Files
jarvis-home/skills/python/unifi-protect/main.py
T
2026-08-29 17:02:35 +02:00

51 lines
3.6 KiB
Python

import json, os, ssl, sys
from urllib.request import Request, urlopen
from urllib.error import HTTPError, URLError
PROTO='jarvis.skill.invoke.v1'
def truthy(v): return str(v or '').strip().lower() in ('1','true','yes','on')
def fail(c,m): return {'protocol':PROTO,'success':False,'error':{'code':c,'message':m}}
def ok(d,m='OK',mut=False): return {'protocol':PROTO,'success':True,'data':d,'message':m,'mutated':mut}
def cfg():
b=os.getenv('UNIFI_PROTECT_URL','').strip().rstrip('/'); k=os.getenv('UNIFI_API_KEY','').strip()
if not b or not k: raise RuntimeError('UNIFI_PROTECT_URL und UNIFI_API_KEY müssen gesetzt sein')
if not b.startswith(('http://','https://')): b='https://'+b
return b,k,truthy(os.getenv('UNIFI_VERIFY_TLS','false'))
def request(method,path,body=None):
b,k,verify=cfg(); data=None; h={'Accept':'application/json','X-API-Key':k}
if body is not None: data=json.dumps(body).encode(); h['Content-Type']='application/json'
ctx=ssl._create_unverified_context() if b.startswith('https://') and not verify else None
try:
with urlopen(Request(b+path,data=data,headers=h,method=method),timeout=8,context=ctx) as r:
raw=r.read(); return json.loads(raw.decode()) if raw else {}
except HTTPError as e: raise RuntimeError(f'UniFi Protect HTTP {e.code}: {e.read().decode(errors="replace")[:1000]}')
except URLError as e: raise RuntimeError(f'UniFi Protect nicht erreichbar: {e.reason}')
def name(v):
n=v.get('name','') if isinstance(v,dict) else ''
if isinstance(n,dict): return n.get('name') or n.get('value') or str(n)
return n or ''
def list_norm(path,kind):
raw=request('GET',path); vals=raw if isinstance(raw,list) else raw.get('data',[]) if isinstance(raw,dict) else []
out=[]
for v in vals:
base={'id':v.get('id',''),'name':name(v),'model':v.get('modelKey',''),'state':v.get('state',''),'mac':v.get('mac','')}
if kind=='camera':
f=v.get('featureFlags') or {}; base.update({'video_mode':v.get('videoMode',''),'hdr':v.get('hdrType',''),'has_mic':f.get('hasMic'),'has_speaker':f.get('hasSpeaker'),'smart_detect_types':f.get('smartDetectTypes') or []})
out.append(base)
return out
def main(inv):
a=inv.get('action'); x=inv.get('input') or {}
if a=='info': return ok(request('GET','/v1/meta/info'),'Protect API erreichbar.')
if a in ('list_cameras','list_sensors','list_lights'):
typ={'list_cameras':('cameras','camera'),'list_sensors':('sensors','sensor'),'list_lights':('lights','light')}[a]
vals=list_norm('/v1/'+typ[0],typ[1]); return ok({typ[0]:vals,'count':len(vals)},'Protect-Geräte geladen.')
if a=='get_camera':
raw=request('GET',f"/v1/cameras/{x['camera_id']}"); return ok(raw if isinstance(raw,dict) else {'camera':raw},'Kamera geladen.')
if a=='ptz_goto': request('POST',f"/v1/cameras/{x['camera_id']}/ptz/goto/{int(x['slot'])}"); return ok({'accepted':True},'PTZ-Preset angefahren.',True)
if a=='ptz_patrol_start': request('POST',f"/v1/cameras/{x['camera_id']}/ptz/patrol/start/{int(x['slot'])}"); return ok({'accepted':True},'PTZ-Patrouille gestartet.',True)
if a=='ptz_patrol_stop': request('POST',f"/v1/cameras/{x['camera_id']}/ptz/patrol/stop"); return ok({'accepted':True},'PTZ-Patrouille gestoppt.',True)
if a=='trigger_alarm_webhook': request('POST',f"/v1/alarm-manager/webhook/{x['trigger_id']}"); return ok({'accepted':True},'Protect-Alarm-Webhook ausgelöst.',True)
return fail('UNKNOWN_ACTION',f'Unbekannte Aktion: {a}')
try: res=main(json.load(sys.stdin))
except Exception as e: res=fail('UNIFI_PROTECT_ERROR',str(e))
json.dump(res,sys.stdout,ensure_ascii=False)