2021-10-15 20:31:17 +00:00
|
|
|
import os
|
|
|
|
import sys
|
|
|
|
import asyncio
|
|
|
|
import aiohttp
|
2021-10-15 21:07:28 +00:00
|
|
|
import RPi.GPIO as GPIO
|
|
|
|
import time
|
2021-10-15 20:31:17 +00:00
|
|
|
from aiohttp import ClientSession, CookieJar
|
|
|
|
|
2021-10-15 19:47:23 +00:00
|
|
|
import settings
|
|
|
|
|
2021-10-15 20:31:17 +00:00
|
|
|
from pyunifiprotect.unifi_protect_server import UpvServer
|
2021-10-15 19:47:23 +00:00
|
|
|
|
2021-10-15 20:31:17 +00:00
|
|
|
import logging
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
2021-10-15 21:07:28 +00:00
|
|
|
RELAY_ON = False
|
|
|
|
RELAY_OFF = True
|
|
|
|
|
|
|
|
def ring_bell(mac):
|
|
|
|
try:
|
|
|
|
doorbell = settings.DOORBELLS[mac]
|
|
|
|
GPIO.output(doorbell['gpio'], RELAY_ON)
|
|
|
|
time.sleep(0.5)
|
|
|
|
GPIO.output(doorbell['gpio'], RELAY_OFF)
|
|
|
|
except KeyError:
|
|
|
|
logger.error('Doorbell %s not found!', mac)
|
|
|
|
|
2021-10-15 20:31:17 +00:00
|
|
|
def subscriber(updated):
|
|
|
|
logger.debug('Subscription: updated=%s', updated)
|
|
|
|
|
|
|
|
for _, data in updated.items():
|
|
|
|
if data['event_type'] == 'ring' and data['event_ring_on']:
|
2021-10-15 21:07:28 +00:00
|
|
|
logger.info('%s: %s is ringing!', data['mac'], data['name'])
|
|
|
|
ring_bell(data['mac'])
|
2021-10-15 20:31:17 +00:00
|
|
|
|
|
|
|
async def ws_listener():
|
|
|
|
session = ClientSession(cookie_jar=CookieJar(unsafe=True))
|
|
|
|
|
|
|
|
unifiprotect = UpvServer(
|
|
|
|
session,
|
2021-10-15 19:47:23 +00:00
|
|
|
settings.UFP_ADDRESS,
|
|
|
|
settings.UFP_PORT,
|
2021-10-15 20:31:17 +00:00
|
|
|
settings.UFP_USERNAME,
|
|
|
|
settings.UFP_PASSWORD,
|
2021-10-15 19:47:23 +00:00
|
|
|
)
|
|
|
|
|
2021-10-15 20:31:17 +00:00
|
|
|
await unifiprotect.check_unifi_os()
|
|
|
|
await unifiprotect.update()
|
|
|
|
|
|
|
|
unsub = unifiprotect.subscribe_websocket(subscriber)
|
|
|
|
|
|
|
|
for i in range(15000):
|
|
|
|
await asyncio.sleep(1)
|
|
|
|
|
|
|
|
await session.close()
|
|
|
|
unsub()
|
|
|
|
|
2021-10-15 21:07:28 +00:00
|
|
|
def init_relays():
|
|
|
|
GPIO.setmode(GPIO.BCM)
|
|
|
|
GPIO.setwarnings(False)
|
|
|
|
|
|
|
|
for _, doorbell in settings.DOORBELLS.items():
|
|
|
|
GPIO.setup(doorbell['gpio'], GPIO.OUT)
|
|
|
|
GPIO.output(doorbell['gpio'], RELAY_OFF)
|
|
|
|
|
2021-10-15 20:31:17 +00:00
|
|
|
if __name__ == '__main__':
|
|
|
|
logging.basicConfig(level=logging.INFO)
|
|
|
|
loop = asyncio.get_event_loop()
|
|
|
|
loop.run_until_complete(ws_listener())
|
|
|
|
loop.close()
|