-
Notifications
You must be signed in to change notification settings - Fork 1
/
cosmicpi-detector.py
257 lines (238 loc) · 10.7 KB
/
cosmicpi-detector.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
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
from influxdb import InfluxDBClient
import requests
import serial
import geohash
import uuid
import random
import time
import datetime
import paho.mqtt.client as paho
#define the versions for earlier units
#version 1.7 and 1.8 are identical, so use 1.8.1 for both
#version 1.6 has a different timing configuration, use 1.6.1
#version 1.5 has a different timing configuration again, use 1.5.1
#this goes in the mqtt channel only.
mqttchannel='cosmicpi/1.8.1'
#do not change these, even if you have an earlier version
#this is because you will need to update your dashboard to read from a different measurement
#not recommended!
hardwareversion='CosmicPiV1.8.1'
hardwareversion_freq='CosmicPiV1.8.1_freq'
broker="cosmicpidata.mooo.com"
port=1883
mqtt_ok=0
def on_publish(client,userdata,result):
print("Data published to MQTT server")
pass
def on_connect(client,userdata,flags,rc):
if rc==0:
print("connected ok")
else:
print("mqtt connection failed")
def on_disconnect(client,userdata,rc):
print("disconnecting reason " + str(rc))
mqttidentstring = str(uuid.getnode())
client1= paho.Client(mqttidentstring)
client1.on_publish = on_publish
client1.username_pw_set(username="cosmicpi",password="MuonsFROMSp8ce")
client1.on_connect=on_connect #binding call
url = "http://www.google.com"
timeout = 10
try:
request = requests.get(url,timeout=timeout)
print("internet ok")
mqtt_ok=1
except (requests.ConnectionError, requests.Timeout) as exception:
print("internet fail")
mqtt_ok=0
dbframe = 0
cosmicdict = {
"DeviceID": 0,
"UTCUnixTime": 0,
"SubSeconds": 0.0,
"TemperatureC": 0.0,
"Humidity": 0.0,
"AccelX": 0.0,
"AccelY": 0.0,
"AccelZ": 0.0,
"MagX": 0.0,
"MagY": 0.0,
"MagZ": 0.0,
"Pressure": 0.0,
"Altitude": 0.0,
"Longitude": 0.0,
"Latitude": 0.0
}
nstimestamp = 0
geohash_pos = 0
eventcount = 0
print("starting")
ser = serial.Serial(port='/dev/serial0', baudrate=115200, parity=serial.PARITY_NONE, stopbits=serial.STOPBITS_ONE, bytesize=serial.EIGHTBITS, timeout=1)
print("connected to: " + ser.portstr)
print ("The device ID using uuid1() is : ",end="")
print (uuid.getnode())
cosmicdict['DeviceID']=uuid.getnode()
print("DB connection")
client = InfluxDBClient(host='localhost', port=8086)
client.create_database('cosmicpilocal')
data=[]
print("MQTT connection")
if mqtt_ok==1:
client1.connect(broker,port)
client1.loop_start()
#return 0
#ser.write("help\n");
while True:
try:
line = ser.readline();
#if line:
#print(line.decode('utf-8'))
line_str = str(line.decode('utf-8'))
data_type = line_str.split(':')[0]
gps_type = line_str.split(',')[0]
#print(data_type)
#print(gps_type)
if data_type in cosmicdict.keys():
data = line_str.split(':')[1].split(';')[0]
cosmicdict[data_type] = float(data)
#if (data_type == "PPS"):
#print("found a pps")
#gps_lock_sting = line_str.split(':')[2]
#gps_lock_sting = gps_lock_sting.split(';')[0]
#if (len(gps_lock_sting) == 1):
#cosmicdict['UTCUnixTime'] += 1
gps_type = line_str.split(',')[0]
if gps_type == "$GPZDA" or gps_type == "$GNZDA":
if (line_str.count(',') == 6):
g_time_string = line_str.split(',')[1].split('.')[0] # has format hhmmss
hour = int(g_time_string[0:2])
minute = int(g_time_string[2:4])
second = int(g_time_string[4:6])
day = int(line_str.split(',')[2])
month = int(line_str.split(',')[3])
year = int(line_str.split(',')[4])
time_from_gps = datetime.datetime(year,month,day,hour,minute,second,tzinfo=None)
cosmicdict['UTCUnixTime'] = (time_from_gps - datetime.datetime(1970, 1, 1)).total_seconds()
cosmicdict['UTCUnixTime'] += 1
if gps_type == "$GPGGA":
# sanity check
if (line_str.count(',') == 14):
# use this as documentation for the string: http://aprs.gids.nl/nmea/#gga
lat = line_str.split(',')[2]
lat = float(lat[0:2])
minutes = line_str.split(',')[2]
minutes = float(minutes[2:len(minutes)])
lat += minutes / 60.
if line_str.split(',')[3] == 'S':
lat = -lat
lon = line_str.split(',')[4]
lon = float(lon[0:3])
minutes = line_str.split(',')[4]
minutes = float(minutes[3:len(minutes)])
lon += minutes / 60.
if line_str.split(',')[5] == 'W':
lon = -lon
cosmicdict['Latitude'] = lat
cosmicdict['Longitude'] = lon
if (eventcount >= 0) :
geohash_pos="\""+geohash.encode(lat,lon)+"\""
data = []
data.append("{measurement},id={DeviceID} geohash={geohash_pos},event_count={event_count} {timestamp}"
.format(measurement=hardwareversion_freq,
DeviceID=cosmicdict['DeviceID'],
geohash_pos=geohash_pos,
event_count=eventcount,
timestamp=int(cosmicdict['UTCUnixTime'])))
print(data)
client.write_points(data, database='cosmicpilocal', time_precision='s', batch_size=1, protocol='line')
eventcount=0
if mqtt_ok==1:
ret = client1.publish("cosmicpi/worldmap",str(data))
if gps_type == "$GPRMC":
# added this type to cope with broken GPS receivers, where the GPGGA and GNZDA strings aren't sent.
# (in fact GPRMC is the default output of 99% of all GPS chipsets, I don't know why we didn't use it from day 1)
# sanity check
if (line_str.count(',') == 12):
# use this as documentation for the string: http://aprs.gids.nl/nmea/#gprmc
g_time_string = line_str.split(',')[1].split('.')[0] # has format hhmmss
hour = int(g_time_string[0:2])
minute = int(g_time_string[2:4])
second = int(g_time_string[4:6])
#time parsed now
lat = line_str.split(',')[3]
lat = float(lat[0:2])
minutes = line_str.split(',')[2]
minutes = float(minutes[2:len(minutes)])
lat += minutes / 60.
if line_str.split(',')[4] == 'S':
lat = -lat
lon = line_str.split(',')[5]
lon = float(lon[0:3])
minutes = line_str.split(',')[5]
minutes = float(minutes[3:len(minutes)])
lon += minutes / 60.
if line_str.split(',')[6] == 'W':
lon = -lon
daycode = (line_str.split(',')[9])
day = int(daycode[0:2])
month = int(daycode[2:4])
year = 2000+int(daycode[4:6])
# Yes, I just introduced a millenium bug for a year 2099 roll over issue...
time_from_gps = datetime.datetime(year,month,day,hour,minute,second,tzinfo=None)
cosmicdict['UTCUnixTime'] = (time_from_gps - datetime.datetime(1970, 1, 1)).total_seconds()
cosmicdict['UTCUnixTime'] += 1
cosmicdict['Latitude'] = lat
cosmicdict['Longitude'] = lon
if (eventcount >= 0) :
geohash_pos="\""+geohash.encode(lat,lon)+"\""
data = []
data.append("{measurement},id={DeviceID} geohash={geohash_pos},event_count={event_count} {timestamp}"
.format(measurement=hardwareversion_freq,
DeviceID=cosmicdict['DeviceID'],
geohash_pos=geohash_pos,
event_count=eventcount,
timestamp=int(cosmicdict['UTCUnixTime'])))
print(data)
client.write_points(data, database='cosmicpilocal', time_precision='s', batch_size=1, protocol='line')
eventcount=0
if mqtt_ok==1:
ret = client1.publish("cosmicpi/worldmap",str(data))
if data_type == "Event":
if ((line_str.count(':') == 3) and (line_str.count(';') == 1)):
sub_sec_string = line_str.split(':')[2]
sub_sec_string = sub_sec_string.split(';')[0]
if sub_sec_string.count('/') == 1:
# this is the newer format and we need to divide the first number by the second one
divisors = sub_sec_string.split('/')
current_subSeconds = float(divisors[0]) / float(divisors[1])
cosmicdict['SubSeconds'] = current_subSeconds
#print(cosmicdict)
#conversion to ns for influx
#add s and ns, then multiply by 1e9
nstimestamp = cosmicdict['UTCUnixTime']+cosmicdict['SubSeconds']
nstimestamp = nstimestamp*1e9
nstimestamp = int(nstimestamp)
eventcount = eventcount + 1
data = []
data.append("{measurement},id={DeviceID} lat={latitude},lon={longitude},Temp={Temp},Hum={Hum},Accelx={Accelx},Accely={Accely},Accelz={Accelz},Magx={Magx},Magy={Magy},Magz={Magz},Press={Pressx},Alt={Altx} {timestamp}"
.format(measurement=hardwareversion,
DeviceID=cosmicdict['DeviceID'],
latitude=cosmicdict['Latitude'],
longitude=cosmicdict['Longitude'],
Temp=cosmicdict['TemperatureC'],
Hum=cosmicdict['Humidity'],
Accelx=cosmicdict['AccelX'],
Accely=cosmicdict['AccelY'],
Accelz=cosmicdict['AccelZ'],
Magx=cosmicdict['MagX'],
Magy=cosmicdict['MagY'],
Magz=cosmicdict['MagZ'],
Pressx=cosmicdict['Pressure'],
Altx=cosmicdict['Altitude'],
timestamp=nstimestamp))
print(data)
client.write_points(data, database='cosmicpilocal', time_precision='n', batch_size=1, protocol='line')
if mqtt_ok==1:
ret = client1.publish(mqttchannel,str(data))
except:
pass