forked from rekab/py-airvision-nvr
-
Notifications
You must be signed in to change notification settings - Fork 0
/
motion.py
70 lines (59 loc) · 2.18 KB
/
motion.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
import argparse
import airvision
import os
import time
def SetupFlags():
parser = argparse.ArgumentParser(
description='Connects to a v2.0.0 Airvision NVR and '
'runs a command when motion is detected.')
parser.add_argument('--server',
help='NVR server URL (e.g. https://server:port/).',
default='https://airvision-nvr:7443/', required=True)
parser.add_argument('--user', help='NVR username/email address.',
required=True)
parser.add_argument('--password', help='NVR password.', required=True)
parser.add_argument('--cooldown',
help='Number of seconds to wait before running the command '
'again for the same zone(s)', default=60)
parser.add_argument('--command',
help='Command to run. Can take python formatted strings '
'%%(zone)s for the zone name and %%(time)s for the time',
default='espeak "motion detected in %(zones)s at %(time)s"')
return parser.parse_args()
class Cooldown(object):
def __init__(self):
self._times = {}
def Update(self, key, duration):
"""Update a cooldown timer.
Args:
key: string
duration: integer, number of seconds to wait.
Returns:
True if sufficient time has passed since the key was last seen.
"""
prev = self._times.get(key, 0)
self._times[key] = time.time()
return int(duration) <= (time.time() - prev)
def main():
flags = SetupFlags()
if not flags.server.endswith('/'):
flags.server += '/'
server = airvision.Server(flags.server, flags.user, flags.password)
conn = airvision.CreateAirvisionNVRConnection(server)
conn.Subscribe(['camera', 'motion'])
state = airvision.State()
cooldown = Cooldown()
while True:
msg = conn.Read()
print 'ServerMessage: %s' % msg
state.UpdateFromServerMessage(msg)
for motion_event in airvision.GetMotionEvents(state, msg):
if cooldown.Update(motion_event.zones, flags.cooldown):
command = flags.command % motion_event.__dict__
print 'Running command: %s' % command
status = os.system(command)
print 'Command exit status: %d' % status
else:
print 'Cooldown still active for "%s".' % motion_event.zones
if __name__ == '__main__':
main()