Compare commits

..

5 Commits

Author SHA1 Message Date
a0e0651703 Logging, timeout 2022-04-01 17:53:37 -06:00
8fa91a9c55 Remove watchdog 2022-04-01 17:35:52 -06:00
055b12ee05 Implement our own unifi websocket connection 2022-04-01 17:34:37 -06:00
14051edfc5 Misc 2021-12-19 05:29:10 +00:00
8a05f1aacb Fix update bugs 2021-11-29 06:53:32 +00:00
5 changed files with 103 additions and 94 deletions

View File

@@ -17,6 +17,8 @@ $ sudo raspi-config
- Reboot
```
If wifi doesn't work, you're on your own.
For the watchdog to work, we need write access to `/dev/watchdog/`.
Configure `/etc/udev/rules.d/60-watchdog.rules`:
@@ -25,13 +27,20 @@ Configure `/etc/udev/rules.d/60-watchdog.rules`:
KERNEL=="watchdog", MODE="0666"
```
Change the hostname:
```text
$ sudoedit /etc/hostname
$ sudoedit /etc/hosts
```
### Script
Install dependencies:
```text
$ sudo apt update
$ sudo apt install python3 python3-pip python-virtualenv python3-virtualenv supervisor
$ sudo apt install python3 python3-pip python-virtualenv python3-virtualenv supervisor python3-rpi.gpio
```
**Make sure you have at least Python 3.9 installed.**
@@ -42,7 +51,7 @@ Clone this repo:
$ cd
$ git clone https://tanner@git.tannercollin.com/tanner/doorbelldingdongringringdoorbell.git
$ cd doorbelldingdongringringdoorbell/
$ virtualenv -p python3 env
$ virtualenv --system-site-packages -p python3 env
$ source env/bin/activate
(env) $ pip install -r requirements.txt
```

109
main.py
View File

@@ -5,99 +5,71 @@ logging.basicConfig(
level=logging.DEBUG if DEBUG else logging.INFO)
logging.getLogger('aiohttp').setLevel(logging.DEBUG if DEBUG else logging.WARNING)
import json
import os
import sys
import asyncio
import aiohttp
import RPi.GPIO as GPIO
try:
import RPi.GPIO as GPIO
IS_PI = True
except ModuleNotFoundError:
logging.info('RPi.GPIO not found, running without GPIO.')
IS_PI = False
import time
from signal import *
from aiohttp import ClientSession, CookieJar
import unifi
import settings
from pyunifiprotect.unifi_protect_server import UpvServer
from pyunifiprotect.exceptions import NvrError
RELAY_ON = False
RELAY_OFF = True
allow_watchdog = False
cooldown_time = time.time()
def set_relay(pin, state):
GPIO.output(pin, state)
if IS_PI: GPIO.output(pin, state)
logging.info('Set relay on pin %s to %s', pin, 'ON' if state == RELAY_ON else 'OFF')
def pulse_relay(pin):
set_relay(pin, RELAY_ON)
time.sleep(0.5)
time.sleep(0.25) # atomic
set_relay(pin, RELAY_OFF)
def ring_bell(mac):
global allow_watchdog
if not allow_watchdog and not DEBUG:
logging.info('Enabling watchdog...')
allow_watchdog = True
def ring_bell(camera):
global cooldown_time
if time.time() - cooldown_time < 2:
logging.info('Cooldown skipping.')
return
cooldown_time = time.time()
try:
doorbell = settings.DOORBELLS[mac]
doorbell = settings.DOORBELLS[camera]
pulse_relay(doorbell['gpio'])
except KeyError:
logging.error('Doorbell %s not found!', mac)
logging.error('Doorbell %s not found!', camera)
def subscriber(updates):
logging.debug('Subscription: updates=%s', updates)
for _, data in updates.items():
if data['event_type'] == 'ring' and data['event_ring_on']:
logging.info('%s: %s is ringing!', data['mac'], data['name'])
ring_bell(data['mac'])
async def process_message(msg):
if msg.get('type', '') != 'ring':
return
def feed_watchdog():
with open('/dev/watchdog', 'w') as wdt:
wdt.write('1')
logging.info('Ring message: %s', msg)
async def ws_listener():
ring_bell(msg['camera'])
async def main():
while True:
session = ClientSession(cookie_jar=CookieJar(unsafe=True))
try:
async for msg in unifi.connect():
await process_message(msg)
except BaseException as e:
logging.exception('Error connecting to Unifi Protect: %s. Trying again...', str(e))
await asyncio.sleep(5)
unifiprotect = UpvServer(
session,
settings.UFP_ADDRESS,
settings.UFP_PORT,
settings.UFP_USERNAME,
settings.UFP_PASSWORD,
)
await unifiprotect.check_unifi_os()
await unifiprotect.update()
unsub = unifiprotect.subscribe_websocket(subscriber)
while True:
try:
updates = await unifiprotect.update()
logging.debug('Updates: %s', str(updates))
except NvrError:
logging.error('Problem connecting to Unifi Protect. Reconnecting...')
break
logging.debug('unifiprotect: %s', unifiprotect.__dict__)
logging.debug('ws_session %s', unifiprotect.ws_session.__dict__)
breakpoint()
#active_ws = await unifiprotect.check_ws()
#if not active_ws:
# logging.error('Websocket unactive. Reconnecting...')
if allow_watchdog and not DEBUG:
feed_watchdog()
await asyncio.sleep(1)
await session.close()
unsub()
def disable_relays_on_exit(*args):
logging.info('Exiting, disabling relays...')
@@ -107,11 +79,12 @@ def disable_relays_on_exit(*args):
os._exit(0)
def init():
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
if IS_PI: GPIO.setmode(GPIO.BCM)
if IS_PI: GPIO.setwarnings(False)
for _, doorbell in settings.DOORBELLS.items():
GPIO.setup(doorbell['gpio'], GPIO.OUT)
if IS_PI: GPIO.setup(doorbell['gpio'], GPIO.OUT)
set_relay(doorbell['gpio'], RELAY_OFF)
#pulse_relay(doorbell['gpio'])
time.sleep(1)
logging.info('GPIO initialized')
@@ -127,5 +100,5 @@ if __name__ == '__main__':
init()
loop = asyncio.get_event_loop()
loop.run_until_complete(ws_listener())
loop.run_until_complete(main())
loop.close()

View File

@@ -1,23 +1,9 @@
aiohttp==3.7.4.post0
aioshutil==1.1
async-timeout==3.0.1
asyncio==3.4.3
attrs==21.2.0
chardet==4.0.0
click==8.0.3
aiohttp==3.8.1
aiosignal==1.2.0
async-timeout==4.0.2
attrs==21.4.0
charset-normalizer==2.0.12
frozenlist==1.3.0
idna==3.3
importlib-metadata==4.8.1
multidict==5.2.0
packaging==21.3
Pillow==8.4.0
pydantic==1.8.2
PyJWT==2.2.0
pyparsing==3.0.6
python-dotenv==0.19.1
pytz==2021.3
pyunifiprotect==1.1.0
RPi.GPIO==0.7.0
typer==0.4.0
typing-extensions==3.10.0.2
yarl==1.7.0
zipp==3.6.0
multidict==6.0.2
yarl==1.7.2

View File

@@ -6,10 +6,10 @@ UFP_PORT = 443
DOORBELLS = {
'123456780ABC': {
'name': 'Front Door',
'gpio': 26,
'gpio': 19,
},
'123456780ABC': {
'name': 'Side Door',
'gpio': 19,
'gpio': 26,
},
}

41
unifi.py Normal file
View File

@@ -0,0 +1,41 @@
import asyncio
import aiohttp
import zlib
import struct
import json
import settings
HEADER_LENGTH = 8
async def connect():
data = dict(
username=settings.UFP_USERNAME,
password=settings.UFP_PASSWORD,
rememberMe=True,
)
async with aiohttp.ClientSession() as session:
async with session.post(settings.UFP_ADDRESS + '/api/auth/login', json=data, ssl=False) as resp:
cookie = resp.cookies['TOKEN']
headers = {'cookie': cookie.key + '=' + cookie.value}
async with session.ws_connect(settings.UFP_ADDRESS + '/proxy/protect/ws/updates', headers=headers, ssl=False) as ws:
async for msg in ws:
packet_type, payload_format, deflated, unknown, payload_size = struct.unpack('!bbbbi', msg.data[0:HEADER_LENGTH])
action_start = HEADER_LENGTH
action_packet = zlib.decompress(msg.data[action_start:])
data_start = payload_size + 2*HEADER_LENGTH
data_packet = zlib.decompress(msg.data[data_start:])
yield json.loads(data_packet.decode())
async def test():
async for msg in connect():
print(msg)
if __name__ == '__main__':
loop = asyncio.get_event_loop()
loop.run_until_complete(test())
loop.close()