-
Notifications
You must be signed in to change notification settings - Fork 0
/
j.py
254 lines (201 loc) · 8.24 KB
/
j.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
#!/usr/bin/python
import os
import sys
import datetime
import commands
import math
import requests
import serial
import argparse
import logging
import struct
from string import split
from smbus import SMBus
from time import sleep
#class for GPS breakout
from GPS_Controller import GpsController
#class for MinIMU-9 V2 (L3GD20, GYRO)
#from warnings import filterwarnings
#filterwarnings('ignore', category = MySQLdb.Warning)
#set devide ID
deviceID = 1
#enable the GPS socket
os.system('sudo gpsd /dev/ttyAMA0 -F /var/run/gpsd.sock')
sleep(0.5)
#create the gps controller object
gpsc = GpsController()
#start gps controller
gpsc.start()
#access the MySQL databse
def bytes2int(bytes):
return struct.unpack("B", bytes)[0]
def init_usb(sysnode):
return os.system("echo disabled > %s/power/wakeup"%sysnode)
def turn_on_usb(sysnode):
return os.system("echo on > %s/power/level"%sysnode)
def turn_off_usb(sysnode):
return os.system("echo on > %s/power/level"%sysnode)
def setup_args():
parser = argparse.ArgumentParser()
parser.add_argument("-d", "--device", help="device node",
default="/dev/ttyUSB0")
parser.add_argument("-u", "--url",
help="POST to this url. If empty, the script will only print out the values")
parser.add_argument("-l", "--loglevel", help="Log level",
choices=["DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"],
default="INFO")
parser.add_argument("-p", "--powersaving", help="Powersaving",
action="store_true")
parser.add_argument("-s", "--sysnode", help="System node for the usb - for powersaving",
default="/sys/bus/usb/devices/usb1")
return parser.parse_args()
def readGPS():
#fetch GPS data from Ultimate GPS Breakout
latitude = gpsc.fix.latitude
longitude = gpsc.fix.longitude
timeUtc = gpsc.utc
timeFix = ''
if isinstance(gpsc.fix.time, str):
timeFix = gpsc.fix.time
altitude2 = gpsc.fix.altitude
eps = gpsc.fix.eps #speed error estimate in meter/sec
epx = gpsc.fix.epx #estimated Longitude error in meters
epv = gpsc.fix.epv #estimated vertical error in meters
ept = gpsc.gpsd.fix.ept #estimated timestamp error
speed = gpsc.fix.speed
climb = gpsc.fix.climb #climb (positive) or sink (negative rate, meters per second
track = gpsc.fix.track #course over ground, degrees from true north
mode = gpsc.fix.mode #NMEA mode: %d, 0=no mode value yet seen, 1=no fix, 2=2D, 3=3D
satellites = len(gpsc.satellites)
#make sure that the database tables get no input for as long as there is no GPS signal
if (math.isnan(latitude) or not latitude):
gpsSignal = 0
elif (math.isnan(longitude) or not longitude):
gpsSignal = 0
elif (timeUtc is None or "nan" in timeUtc or not timeUtc):
gpsSignal = 0
elif (math.isnan(altitude2)):
gpsSignal = 0
elif (math.isnan(eps)):
gpsSignal = 0
elif (math.isnan(epx)):
gpsSignal = 0
elif (math.isnan(epv)):
gpsSignal = 0
elif (math.isnan(ept)):
gpsSignal = 0
elif (math.isnan(speed)):
gpsSignal = 0
elif (math.isnan(climb)):
gpsSignal = 0
elif (math.isnan(track)):
gpsSignal = 0
else:
gpsSignal = 1
return {'gpsSignal':gpsSignal, 'latitude':latitude, 'longitude':longitude, 'timeUtc':timeUtc, 'timeFix':timeFix, 'altitude2':altitude2, 'eps':eps, 'epx':epx, 'epv':epv, 'ept':ept, 'speed':speed, 'climb':climb, 'track':track, 'mode':mode, 'satellites':satellites}
def printValues(sysDate, sysTime, latitude, longitude, timeUtc, timeFix, altitude2, eps, epx, epv, ept, speed, climb, track, mode, satellites):
#print data to screen
print "Date: {0}".format(sysDate)
print "Time: {0}".format(sysTime)
print "Latitude: {0}".format(latitude)
print "Longitude: {0}".format(longitude)
print "Time-Utc: {0}".format(timeUtc)
print "Time-Fix: {0}".format(timeFix)
print "Altitude-GPS: {0}".format(altitude2)
print "EPS: {0}".format(eps)
print "EPX: {0}".format(epx)
print "EPV: {0}".format(epv)
print "EPT: {0}".format(ept)
print "Speed: {0} m/s".format(speed)
print "Climb: {0}".format(climb)
print "Track: {0}".format(track)
print "Mode: {0}".format(mode)
print "Satellites: {0}".format(satellites)
def main():
try:
#continuously append data
while(True):
#current Date and Time
sysDate = datetime.datetime.now().date().strftime('%Y-%m-%d')
sysTime = datetime.datetime.now().time().strftime('%H:%m:%S')
#printValues(sysDate, sysTime, readGPS().get('latitude'), readGPS().get('longitude'), readGPS().get('timeUtc'), readGPS().get('timeFix'), readGPS().get('altitude2'), readGPS().get('eps'), readGPS().get('epx'), readGPS().get('epv'), readGPS().get('ept'), readGPS().get('speed'), readGPS().get('climb'), readGPS().get('track'), readGPS().get('mode'), readGPS().get('satellites'))
#only write Dataset to table if the GPS signal is fully valid
sleep(0.01)
#clear terminal screen
sys.stdout.flush()
#Ctrl C user interrupt
except KeyboardInterrupt:
print 'User cancelled...'
#name is not defined
except NameError as e:
print 'Name is not defined: %s on Line number: %s' % (e.message.split("'")[1], sys.exc_traceback.tb_lineno)
raise
#type error
except TypeError as e:
print 'Type Error: %s on Line number: %s' % (e, sys.exc_traceback.tb_lineno)
raise
#attribute error
except AttributeError as e:
print 'Attribute Error: %s on Line number: %s' % (e, sys.exc_traceback.tb_lineno)
raise
#unexpected error
except:
print 'Unexpected error:', sys.exc_info()[0]
raise
finally:
#current Date and Time
sysDate = datetime.datetime.now().date().strftime('%Y-%m-%d')
sysTime = datetime.datetime.now().time().strftime('%H:%m:%S')
gpsc.stopController()
#wait for the thread to finish
gpsc.join()
print 'Done'
sys.exit(0)
if __name__ == '__main__':
args = setup_args()
logging.basicConfig(format='%(levelname)s:%(message)s', level=getattr(logging, args.loglevel.upper()))
if args.powersaving and args.sysnode:
logging.debug("Init Powersaving")
logging.debug(init_usb(args.sysnode))
logging.debug("Turning USB ON")
logging.debug(turn_on_usb(args.sysnode))
try:
with serial.Serial(args.device, baudrate=9600) as ser:
logging.info("Serial device initialized")
read_full = False
pm25 = 0
pm10 = 0
data = []
while not read_full:
if ser.read() == b'\xaa':
logging.debug("FIRST HEADER GOOD")
# FIRST HEADER IS GOOD
if ser.read() == b'\xc0':
# SECOND HEADER IS GOOD
logging.debug("SECOND HEADER GOOD")
for i in range(8):
byte = ser.read()
data.append(bytes2int(byte))
if data[-1] == 171:
# END BYTE IS GOOD. DO CRC AND CALCULATE
logging.debug("END BYTE GOOD")
if data[6] == sum(data[0:6])%256:
logging.debug("CRC GOOD")
pm25 = (data[0]+data[1]*256)/10
pm10 = (data[4]+data[3]*256)/10
read_full = True
if args.url:
logging.info("Posting to %s" % args.url)
gps_data = readGPS()
r = requests.post(args.url, data={"pm10": pm10, "pm2.5": pm25, "lat": gps_data.get('latitude'), "lon": gps_data.get('longitude'), "alt": gps_data.get('speed'), "spd": gps_data.get('altitude2'), "time": gps_data.get('timeUtc'), "satt": gps_data.get('satellites')})
logging.debug(r)
logging.info("PM 10: %s" % pm10)
logging.info("PM 2.5: %s" % pm25)
logging.info("Latitude: %s" % gps_data.get('latitude'))
logging.info("longitude: %s" % gps_data.get('longitude'))
except serial.SerialException as e:
logging.critical(e)
if args.powersaving and args.sysnode:
logging.debug("Turning USB OFF")
logging.debug(turn_off_usb())
# main()