-
Notifications
You must be signed in to change notification settings - Fork 0
/
watch_garage_door.py
executable file
·189 lines (151 loc) · 5.27 KB
/
watch_garage_door.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import humanize
import json
import pytz
import requests
import smtplib
import sys
import time
import traceback
from email.message import EmailMessage
from datetime import datetime
from secrets import (
DELAY_MINUTES,
EUFY_EMAIL,
EUFY_PASSWORD,
TO_EMAILS,
SMTP_HOST,
SMTP_PORT,
SMTP_USERNAME,
SMTP_PASSWORD,
TIMEZONE,
)
API_BASE: str = "https://mysecurity.eufylife.com/api/v1"
SENSORS_FILE: str = ".sensors.json"
SECRET_FILE: str = ".secret-api-token"
def main() -> int:
token = get_token()
if not token:
error('Missing api token, exiting.')
return 1
resp = None
try:
resp = requests.post(API_BASE + '/app/get_devs_list', headers={'x-auth-token': token})
sensors = door_sensors(resp.json()['data'])
except:
error(f'Error response from Eufy API devices list {resp.status_code if resp else ""}:\n{resp.text if resp else traceback.format_exc()}')
token = get_token(fresh=True)
if not token:
error('Missing api token, exiting.')
return 1
try:
resp = requests.post(API_BASE + '/app/get_devs_list', headers={'x-auth-token': token})
sensors = door_sensors(resp.json()['data'])
except:
error(f'Error response from Eufy API devices list {resp.status_code if resp else ""}:\n{resp.text if resp else traceback.format_exc()}')
return 1
# Eufy's api sometimes gives stale update_time timestamp, so we make sure
# it's sane by comparing with the previous sensor state
try:
with open(SENSORS_FILE) as fh:
previous = json.loads(fh.read())
except:
previous = []
for sensor in sensors:
state = door_sensor_state(sensor)
updated_at = datetime.utcfromtimestamp(sensor['update_time'])
prev_state = prev_sensor_state(sensor, previous)
print(f'{sensor["device_name"]} is {state}.')
if state == 'open' and open_longer_than_delay(updated_at, prev_state):
send_email(sensor['device_name'], state, updated_at)
with open(SENSORS_FILE, 'w') as fh:
fh.write(json.dumps(sensors))
return 0
def get_token(fresh: bool = False) -> str:
if not fresh:
try:
with open(SECRET_FILE) as fh:
token = fh.readline().strip()
expires_at = fh.readline().strip()
if token and int(expires_at or 0) > int(time.time() + 120):
return token
except:
pass
payload = {
'email': EUFY_EMAIL,
'password': EUFY_PASSWORD,
}
resp = requests.post(API_BASE + '/passport/login', json=payload)
try:
token = resp.json()['data']['auth_token']
expires_at = resp.json()['data']['token_expires_at']
except:
error(f'Error response from login to Eufy API {resp.status_code}:\n{resp.text}')
return ''
with open(SECRET_FILE, 'w') as fh:
fh.write(f'{token}\n{expires_at}')
return token
def door_sensors(devices):
sensors = []
for device in devices:
if device['device_type'] == 2:
sensors.append(device)
return sensors
def find_device(devices, sn):
for device in devices:
if device['device_sn'] == sn:
return device
return None
def door_sensor_state(device) -> str:
param = next(filter(lambda p: p['param_type'] == 1550, device['params']), None)
if param is None:
return 'unknown'
return 'open' if param['param_value'] == '1' else 'closed'
def prev_sensor_state(sensor, previous_sensors) -> str:
prev = find_device(previous_sensors, sensor['device_sn'])
if not prev:
return None
return door_sensor_state(prev)
def open_longer_than_delay(updated_at, prev_state) -> bool:
minutes_open = (datetime.utcnow() - updated_at).total_seconds() / 60
return minutes_open > DELAY_MINUTES and (minutes_open < DELAY_MINUTES * 2 or prev_state == 'open')
def send_email(device, state, updated_at) -> None:
duration = humanize.naturaldelta(datetime.utcnow() - updated_at)
since = format_time(updated_at)
server = smtplib.SMTP(SMTP_HOST, SMTP_PORT)
server.starttls()
server.login(SMTP_USERNAME, SMTP_PASSWORD)
msg = EmailMessage()
message = f'{device} has been {state} for {duration} since {since}.\n'
msg.set_content(message)
msg['Subject'] = f'{device} {state} for {duration}'
msg['From'] = SMTP_USERNAME
msg['To'] = ', '.join(TO_EMAILS)
server.send_message(msg)
def format_time(dt) -> str:
"""Formats datetime like `3pm`."""
if not dt:
return ''
if dt.tzinfo is None:
dt = dt.replace(tzinfo=pytz.utc)
tz = pytz.timezone(TIMEZONE)
dt = dt.astimezone(tz)
hour = dt.strftime('%H')
minute = dt.strftime('%M')
if hour == '00':
return dt.strftime('12{minute}am').format(
minute=':' + minute if minute != '00' else '',
)
hour = int(hour.lstrip('0'))
if hour > 12:
hour -= 12
return dt.strftime('{hour}{minute}{ampm}').format(
hour=hour,
minute=':' + minute if minute != '00' else '',
ampm=dt.strftime('%p').lower(),
)
def error(msg: str):
sys.stderr.write(f'{msg}\n')
if __name__ == '__main__':
sys.exit(main())