-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.py
140 lines (114 loc) · 4.21 KB
/
main.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
from datetime import datetime
from datetime import timedelta
import pytz
import os
from influxdb import InfluxDBClient
from apscheduler.schedulers.blocking import BlockingScheduler
# Load Environmental Variables
TZ = os.environ.get('TZ', 'America/Chicago')
API = os.environ.get('API')
PORTAL = os.environ.get('PORTAL')
ZMAPIUSER = os.environ.get('ZMAPIUSER')
ZMAPIPASS = os.environ.get('ZMAPIPASS')
INFLUXHOST = os.environ.get('INFLUXHOST', 'localhost')
INFLUXDB = os.environ.get('INFLUXDB', 'zoneminder')
INFLUXPORT = os.environ.get('INFLUXPORT', '8086')
INFLUXUSER = os.environ.get('INFLUXUSER')
INFLUXPASS = os.environ.get('INFLUXPASS')
# Set up a Dumb logger to suppress the built-in pyzm logger that's super chatty.
class NonLogger:
' console based logging function that is used if no logging handler is passed'
def __init__(self):
self.dtformat = "%b %d %Y %H:%M:%S.%f"
def Debug (self,level, message, caller=None):
dt = datetime.now().strftime(self.dtformat)
def Info (self,message, caller=None):
dt = datetime.now().strftime(self.dtformat)
def Warning (self,message, caller=None):
dt = datetime.now().strftime(self.dtformat)
def Error (self,message, caller=None):
dt = datetime.now().strftime(self.dtformat)
def Fatal (self,message, caller=None):
dt = datetime.now().strftime(self.dtformat)
exit(-1)
def Panic (self,message, caller=None):
dt = datetime.now().strftime(self.dtformat)
exit(-2)
# Set pyzm API Options
api_options = {
'apiurl': API,
'portalurl': PORTAL,
'user': ZMAPIUSER,
'password': ZMAPIPASS,
# 'logger': zmlog # We connect the API to zmlog
'logger': NonLogger(), # use none if you don't want to log to ZM,
# 'disable_ssl_cert_check': True
}
print("Firing up, stats will be sent to " + INFLUXHOST + ":" + INFLUXPORT + " every 1 minute.")
# Main function.
def grab_events():
import pyzm.api as zmapi
# Set the Time
timenow = datetime.today() - timedelta(minutes=10)
timeminus9 = datetime.today() - timedelta(minutes=9)
timezone = pytz.timezone(TZ)
time = timenow.astimezone(timezone).isoformat()
time9 = timeminus9.astimezone(timezone).isoformat()
# Init ZM API
try:
zmapi = zmapi.ZMApi(options=api_options)
except Exception as e:
print('Error: {}'.format(str(e)))
exit(1)
# Now we connect to InfluxDB
# Connect
client = InfluxDBClient(host=INFLUXHOST, port=INFLUXPORT, username=INFLUXUSER, password=INFLUXPASS, ssl=False, verify_ssl=False)
# Switch to zm database
client.switch_database(INFLUXDB)
# Loop through monitors, grab events for the last N minutes.
ms = zmapi.monitors()
pushev = []
for m in ms.list():
pushev = []
event_filter = {
'mid': m.id(),
'from': '10 minutes ago', # Events must start after this... and....
'object_only': False,
'min_alarmed_frames': 1,
'max_events': 500,
}
es = zmapi.events(event_filter)
for i in range(0, len(es.list())):
ev_start = datetime.strptime(es.list()[i].event['Event']['StartTime'], '%Y-%m-%d %H:%M:%S').isoformat()
if ev_start < time9:
pushev.append(es.list()[i])
frames = 0
totscore = 0
for events in range(0, len(pushev)):
frames = pushev[events].alarmed_frames() + frames
totscore = pushev[events].score()['total'] + totscore
json_body = [
{
"measurement": "monitorEvents",
"tags": {
"monitor": m.name(),
"monitorId": m.id()
},
"time": time,
"fields": {
"events": len(pushev),
"frames": frames,
"totscore": int(totscore)
}
}
]
# Write to InfluxDB
client.write_points(json_body)
print("Stats pushed for " + time)
if __name__ == '__main__':
scheduler = BlockingScheduler()
scheduler.add_job(grab_events, 'cron', minute='*')
try:
scheduler.start()
except (KeyboardInterrupt, SystemExit):
pass