-
Daalen, Tim van authoredDaalen, Tim van authored
GPS_receiver.py 2.34 KiB
import socket
import socketserver
import logging
import threading
import pynmea2 #nmea message parser
import sys
from datetime import datetime
from global_vars import *
#if we have not had a GPS signal yet the coordates are set to 0,0.
#once we have a signal and lose it again we keep sending the same coordinates.
#(lozing the signal means GPS_FIX == 0)
TCPServerInstance = None #link to the TCPserver thread so we can stop it
#RUTX11 NMEA string receiver
class TCPReceiver(socketserver.StreamRequestHandler):
#receive the NMEA messages
def handle(self):
global GPS_lock, GPS_ringbuf
msg = self.request.recv(1024).strip().decode('ascii')
msgList = msg.split("\x00")
#on startup we get a lot of qued messages, we only look at the latest compleet request:
if len(msgList) > 1:
nmea_msg = pynmea2.parse(msgList[-2])
else:
nmea_msg = pynmea2.parse(msgList[0])
#print(repr(nmea_msg)) #prints everything compactly.
if type(nmea_msg).__name__ != "GGA":
raise Exception("wrong data type received!")
with GPS_lock:
if nmea_msg.gps_qual != 0:
GPS_ringbuf.put(nmea_msg, datetime.utcnow())
#start TCP server which receives the messages from the RUTX11
def start_GPSthread(CONFIG):
global TCPServerInstance, GPS_Ringbuffer
GPS_ringbuf.set_min_frame_movement(CONFIG['min-movement-frame'])
GPS_poort = 8500 #port to which the TCP nmea string is send
for _ in range(0,5):
ip_address = get_ip_address()
if ip_address != None: break
if ip_address == None:
raise Exception("Router not connected, shutting down!")
ServerAddress = (ip_address, GPS_poort)
TCPServerInstance = socketserver.ThreadingTCPServer(ServerAddress, TCPReceiver)
threading.Thread(target=TCPServerInstance.serve_forever).start()
def stop_GPSthread():
global TCPServerInstance
if TCPServerInstance != None:
TCPServerInstance.server_close()
#get own ip_address
def get_ip_address():
try:
test_IP = "8.8.8.8"
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect((test_IP, 0))
ipaddres = s.getsockname()[0]
except Exception as e:
print("tried to connect before the networkdriver and router are online: %s" %e)
return None
return str(ipaddres)