-
Notifications
You must be signed in to change notification settings - Fork 0
/
ublox.py
executable file
·204 lines (167 loc) · 5.75 KB
/
ublox.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
#!/usr/bin/env python
import sys, os, time
import serial
import serial.rfc2217
import threading
from datetime import datetime
from helper import *
# This is a class to handle the serial port comms.
# It supports 2 main API types:
# - Always on logging to a file
# - Command / response request from a host (including filtering the received data to look for a specific string)
# It does not support:
# - random data from the device being received and understood
class SerialPort():
def __init__( self, uartPort, baudrate, lineEndings, caseSensitive=False, verbose=False ):
if verbose:
print "SerialPort: ", uartPort, str(baudrate)
try:
self.serial_port = serial.Serial(port=uartPort, baudrate=baudrate, bytesize=serial.EIGHTBITS, parity=serial.PARITY_NONE, stopbits=serial.STOPBITS_ONE, timeout=0, xonxoff=False, rtscts=False, writeTimeout=None, dsrdtr=False, interCharTimeout=1 )
self.dummyFile = False
except Exception:
#try as a normal file instead
self.serial_port = open(uartPort, "rw")
self.dummyFile = True
pass
self.lineEndings = lineEndings
self.event = threading.Event()
self.event.clear()
self.responseFilter = None
self.readLine = ""
self.verbose = verbose
self.caseSensitive = caseSensitive
self.openLogFiles = {}
#start the thread automatically
def read_from_port(self, ser):
exitThread = False
readLine = ""
while not exitThread:
try:
# print "logLine:",
self.readLine = ser.readline()
logLine = self.readLine
# print logLine
if len(self.readLine) != 0:
if self.caseSensitive:
self.readLine = self.readLine.upper().lstrip().rstrip()
self.readLine = self.readLine.lstrip().rstrip()
lines = self.readLine.splitlines()
for l in lines:
if( self.verbose ):
print datetime.now().strftime("%H:%M:%S.%f"), " R:", l
if( len(l) ):
if( self.responseFilter != None and l.find(self.responseFilter) != -1):
self.response = l
#trigger the event!
self.event.set()
#always write to the output logs
for key in self.openLogFiles:
self.openLogFiles[key].write( logLine )
except Exception, err:
print Exception, err
exitThread = True
#print "SerialPort Thread exit!"
if self.serial_port != None:
if self.dummyFile == False:
self.thread = threading.Thread(target=read_from_port, args=(self, self.serial_port))
self.thread.start()
# print "Created thread: ", self.thread, self.serial_port
else:
raise Exception("Failed to connect to serial port: ", uartPort)
def shutdown(self):
#print "shutDown!: ", self.thread, self.serial_port
#close the logs
for key in self.openLogFiles.items():
self.stopLogging(key[0])
if self.serial_port != None:
self.serial_port.close()
self.serial_port = None
if self.dummyFile == False:
self.thread.join()
def __del__( self ):
self.shutdown()
#Global logging start / stop commands
def startLogging( self, logFileName ):
outfile = open(logFileName,"w")
if outfile != None:
#print "startLogging:", logFileName, outfile
self.openLogFiles[logFileName] = outfile
def stopLogging( self, logFileName ):
if self.openLogFiles.has_key(logFileName):
outfile = self.openLogFiles[logFileName]
del self.openLogFiles[logFileName]
outfile.close()
#command / pair
#responseFilter is a very basic strstr
#returns the response or throws an exception
def doCommandResponse( self, cmd, responseFilter, timeout ):
self.responseFilter = responseFilter
if self.dummyFile == False:
self.serial_port.write(cmd)
self.serial_port.write(self.lineEndings)
ok = self.event.wait( timeout )
self.event.clear()
if ok:
print datetime.now().strftime("%H:%M:%S.%f"), "ok"
return self.response
else:
print datetime.now().strftime("%H:%M:%S.%f"), "serial timeout"
return None
else:
return None
def waitResponse(self, responseFilter, timeout):
self.responseFilter = responseFilter
if self.dummyFile == False:
ok = self.event.wait( timeout )
self.event.clear()
if ok:
if self.verbose:
print datetime.now().strftime("%H:%M:%S.%f"), "ok"
return self.response
elif self.verbose:
print datetime.now().strftime("%H:%M:%S.%f"), "serial timeout"
#send a blind command
def sendCommand(self, cmd):
if self.dummyFile == False:
self.serial_port.write(cmd)
self.serial_port.write(self.lineEndings)
def attach_checksum(data):
checksum = 0
for byte in data:
checksum += byte
checksum_msb = checksum >> 8
checksum_lsb = checksum & 0xFF
data.append(checksum_msb)
data.append(checksum_lsb)
def set_standard_datum(serial, datumNum):
data = bytearray([0xB5, 0x62, 0x06, 0x06, 0x02, datumNum])
attach_checksum(data)
serial.sendCommand(data)
def get_standard_datum(serial, datumNum):
data = bytearray([0xB5, 0x62, 0x06, 0x06, 0x02, datumNum])
attach_checksum(data)
serial.sendCommand(data)
def get_lonlat(serial, timeout):
gll = serial.waitResponse("GNGLL", timeout)
tokens = gll.split(",")
longitude = tokens[1]
lon_degrees = longitude[:longitude.index('.')-2]
lon_minutes = longitude[longitude.index('.')-2:]
longitude = lon_degrees + " " + lon_minutes
if tokens[2] == "S":
longitude = "-" + longitude
latitude = tokens[3]
lon_degrees = latitude[:latitude.index('.')-2]
lon_minutes = latitude[latitude.index('.')-2:]
latitude = lon_degrees + " " + lon_minutes
if tokens[4] == "W":
latitude = "-" + latitude
return (longitude, latitude)
if __name__ == "__main__":
ublox_serial = SerialPort("/dev/ttyACM0", 115200, "\r\n")
ublox_serial.startLogging("ublox.log")
while True:
(longitude, latitude) = get_lonlat(ublox_serial, 10000)
print("LON/LAT: " + longitude + ", " + latitude)
raw_input("Press Enter to shutdown...")
ublox_serial.shutdown()