forked from srinathava/raspberry-pi-sleep-monitor
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathInfluxDbLogger.py
94 lines (76 loc) · 2.44 KB
/
InfluxDbLogger.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
#!/usr/bin/env python
from twisted.internet import reactor, stdio
from twisted.protocols import basic
from datetime import datetime, timedelta
from influxdb import InfluxDBClient
HOST = "localhost"
PORT = 9001
USER = "pi"
PASSWORD = "pi"
DB_NAME = "sleep_monitor"
class ProcessInput(basic.LineReceiver):
# This seemingly unused line is necessary to over-ride the delimiter
# property of basic.LineReceiver which by default is '\r\n'. Do not
# remove this!
from os import linesep as delimiter
def __init__(self, client):
self.client = client
self.session = 'production'
self.runNo = datetime.utcnow().strftime('%Y%m%d%H%M')
self.lastLogTime = datetime.min
self.lastSpo2 = -1
self.lastBpm = -1
self.lastMotion = 0
self.lastAlarm = 0
def shouldLog(self, time, spo2, bpm, motion, alarm):
if spo2 != self.lastSpo2:
return True
if bpm != self.lastBpm:
return True
if motion != self.lastMotion:
return True
if alarm != self.lastAlarm:
return True
if (time - self.lastLogTime) > timedelta(minutes=10):
return True
return False
def lineReceived(self, line):
nums = [int(s) for s in line.split()]
(spo2, bpm, motion, alarm) = nums
time = datetime.utcnow()
if self.shouldLog(time, spo2, bpm, motion, alarm):
json_body = [{
"measurement": self.session,
"tags": {
"run": self.runNo,
},
"time": time.ctime(),
"fields": {
"spo2": spo2,
"bpm": bpm,
"motion": motion,
"alarm": alarm
}
}]
# Write JSON to InfluxDB
self.client.write_points(json_body)
self.lastLogTime = time
self.lastSpo2 = spo2
self.lastBpm = bpm
self.lastMotion = motion
self.lastAlarm = alarm
def createInfluxClient():
client = InfluxDBClient(HOST, PORT, USER, PASSWORD, DB_NAME)
dbs = client.get_list_database()
for db in dbs:
if db['name'] == DB_NAME:
break
else:
client.create_database(DB_NAME)
return client
def main():
client = createInfluxClient()
stdio.StandardIO(ProcessInput(client))
reactor.run()
if __name__ == "__main__":
main()