def get_gps(self): if self.disable_gps: packet = self.get_ocid_location() if packet: return packet Packet = namedtuple("Packet", ("lat", "lon")) gps = self.config['general']['gps_default'].split(',') packet = Packet(float(gps[0]), float(gps[1])) else: gpsd.logger.setLevel("WARNING") try: gpsd.connect(**self.gpsd_args) except (ConnectionRefusedError, ConnectionResetError): raise RuntimeError("Connection to GPSD failed. Please ensure GPSD is set up as " \ "described in the \"Configuring GPSD\" section of README.md and is running.") packet = gpsd.get_current() tries = 1 while packet.mode < 2: # After every 10 tries try to get a packet from ocid if not tries % 10: packet = self.get_ocid_location() if packet: return packet tries += 1 packet = gpsd.get_current() return packet
def get_gps(): gpsd.get_current() latitude, longitude = gpsd.position() return jsonify({ "latitude": latitude, "longitude": longitude, })
def get_MGRS(): location = gpsd.get_current() m = mgrs.MGRS() while location.mode <= 1: location = gpsd.get_current() display.fill(0) display.text('- Waiting for GPS -', 15, 20, 1) display.show() coords_MGRS = m.toMGRS(location.lat, location.lon) coords_MGRS = str(coords_MGRS.decode("ascii")) return coords_MGRS
def get_MGRS(): # Get the location from the GPS. Outputs the MGRS Grid ref as a string. location = gpsd.get_current() m = mgrs.MGRS() # Mode checking (https://github.com/MartijnBraam/gpsd-py3/blob/master/DOCS.md) while location.mode <= 1: location = gpsd.get_current() display.fill(0) display.text('- Waiting for GPS -', 15, 20, 1) display.show() coords_MGRS = m.toMGRS(location.lat, location.lon) coords_MGRS = str(coords_MGRS.decode("ascii")) return coords_MGRS
def __init__(self): threading.Thread.__init__(self) self.daemon = True try: gpsd.connect() gpsd.get_current() except: os.popen("sudo killall gpsd") os.popen("sudo gpsd /dev/ttyUSB0") time.sleep(2) gpsd.connect() gpsd.get_current() for i in ["latitude", "longitude", "altitude", "accuracy"]: object.__setattr__(self, i, 0)
def handle(self, *args, **kwargs): gpsd.connect() packet = gpsd.get_current() last_lat = None last_lon = None while True: current_position = packet.position() # position = lat x lon print(current_position) if last_lat is not None and last_lon is not None: current_lat = current_position[0] current_lon = current_position[1] if random.randrange(0, 100) > 80: current_lat += 10 current_lon += 8 diff_lat = abs(current_lat - last_lat) diff_lon = abs(current_lon - last_lon) print(diff_lat, diff_lon) if diff_lat >= 5: if diff_lon >= 5: g = GpsScan() g.created_at = datetime.now() g.lat = current_position[0] g.lon = current_position[1] g.save() last_lat = current_position[0] last_lon = current_position[1]
async def loop_track_satellites(): global LED_MATRIX global PICYCLE_STATE while PICYCLE_STATE == PicycleState.RUNNING: for x in range(gpsd.get_current().sats): if x % 2 == 0: idx = 0 else: idx = 8 idx = idx + (x // 2) if 0 <= x <= 3: LED_MATRIX[idx] = (255, 0, 0) elif 3 < x < 8: LED_MATRIX[idx] = (255, 255, 0) elif 8 <= x <= 16: LED_MATRIX[idx] = (0, 255, 0) await asyncio.sleep(1) click.echo("Stopping tracking satellites...")
def on_request(ch, method, props, body): global latitude global longitude jsonReply = {} try: packet = gpsd.get_current() # latitude = latitude + .0005 # longitude = longitude + .0005 # print(packet.position()) jsonReply['position'] = packet.position() jsonReply['time'] = packet.time() jsonReply['mapURL'] = packet.map_url() # jsonReply['time'] = str(datetime.now()) # jsonReply['longitude'] = longitude # jsonReply['latitude'] = latitude reply = json.dumps(jsonReply) except Exception as e: print("Except: " + str(e)) reply = "error" print(reply) ch.basic_publish(exchange='', routing_key=props.reply_to, properties=pika.BasicProperties(correlation_id = \ props.correlation_id), body=reply) ch.basic_ack(delivery_tag=method.delivery_tag)
def poll(self): try: packet = gpsd.get_current() self.beetle.state.set('lat', '%.6f' % packet.lat) self.beetle.state.set('lon', '%.9f' % packet.lon) speed_str = '%.0f' % (packet.speed() * 2.237) self.beetle.state.set('speed', speed_str) new_position = packet.position() ignition = self.beetle.state.get('ignition') if ignition and self.prev_ignition and int(ignition) == 1: if int(self.prev_ignition) == 0: self.trip = float(self.beetle.state.get('trip_odometer')) self.charge = float( self.beetle.state.get('charge_odometer')) if self.position != None: d = distance(new_position, self.position).miles self.trip += d self.charge += d self.beetle.state.set('trip_odometer', '%.1f' % self.trip) self.beetle.state.set('charge_odometer', '%.1f' % self.charge) self.prev_ignition = ignition self.position = new_position except gpsd.NoFixError: self.beetle.logger.error('gps signal too low')
def __get_gps_location(self): """ Get a GPS location from GPSD. """ pos = { 'alt_ft': None, 'error': False, 'lat': None, 'lon': None, 'lock': False } gpsd.connect(host=self.__gpsd_host, port=self.__gpsd_port) try: packet = gpsd.get_current() if packet.mode >= 2: pos['lock'] = True pos['lat'] = packet.lat pos['lon'] = packet.lon if packet.mode >= 3: pos['alt_ft'] = packet.alt except UserWarning: pos['error'] = True pos['lock'] = False return pos
def run(self): status = self.get_status() self.__try_connect() while status in [WorkerStatus.ERROR]: self.__try_connect() if status in [WorkerStatus.ERROR]: logger.warning("Trying reconnect to GPSd server...") sleep(10) status = self.get_status() print(f"status: {status}") while status in [WorkerStatus.WORKING]: try: self.current = gpsd.get_current() except UserWarning as e: logger.warning(f"{e}") gps_status, position = self.get_position() mgr = self.storage.get(CommandHandler.WORKER_NAME) if position != DEFAULT_POSITION: mgr.put( commands.CmdSetPositionToDataManager( self.storage, position)) else: logger.warning("No correct geo position.") mgr.put(commands.CmdGpsStatus(self.storage, gps_status)) sleep(1)
def getPositionFromGpsd(self): import gpsd gpsd.connect() try: packet = gpsd.get_current() except KeyError as e: return try: pos = packet.position() except gpsd.NoFixError: raise NoFixError else: precision = packet.position_precision() time = packet.get_time() try: alt = packet.altitude() movement = packet.movement() except gpsd.NoFixError: alt, speed, track, climb = ['n/a'] * 4 else: speed, track, climb = movement['speed'], movement[ 'track'], movement['climb'] return { 'latitude': pos[0], 'longitude': pos[1], 'altitude': alt, 'speed': speed, 'track': track, 'climb': climb, 'time': time, 'error_horizontal': precision[0], 'error_vertical': precision[1], }
def setup_GPS(): gpsd.connect() packet = gpsd.get_current() if (packet.mode < 2): logging.warning("GPS does not have a fix!") counter = 0 while (packet.mode < 2): if (counter > (150)): logging.error("GPS cannot get a fix!") return False packet = gpsd.get_current() logging.warning("GPS still does not have a fix.") counter += 1 time.sleep(.2) logging.debug("GPS has fix.") return True
def get_position_and_direction(): got_current_position = False global current_latitude, current_longitude, current_direction_degrees gps_packet = gpsd.get_current() print("Latitude: " + str(gps_packet.lat) + " Longitude: " + str(gps_packet.lon)) return got_current_position
def main(bind, port, debug, speedunit, gpsd_host, gpsd_port): logging.basicConfig( format="%(asctime)s.%(msecs)03d %(levelname)-8s %(message)s", level=logging.INFO, datefmt="%Y-%m-%d %H:%M:%S", ) set_speed_units(speedunit) logging.info(f"Listening on http://{bind}:{port}") logging.info(f"Reporting speed in {speedunit}") if not gpsd_host is None: logging.info(f"GPSD Host: {gpsd_host}:{gpsd_port}") gpsd.connect(host=gpsd_host, port=gpsd_port) else: gpsd.connect() start_http_server(addr=bind, port=port) while True: data = gpsd.get_current() get_gpsd_data(speedunit, data) time.sleep(1) if debug: logging.info(f"Sensor data: {make_json()}")
def updateClock(): gpsd.connect() ready = False while not ready: try: packet = gpsd.get_current() pos = packet.position() gpsTime = packet.get_time() ready = True except Exception: print("No signal") time.sleep(1) acceptable = datetime.timedelta(seconds=1) cpuTime = datetime.datetime.now() print(gpsTime) print(cpuTime) print("") diff = abs(gpsTime - cpuTime) print(diff) if diff > acceptable: print("changing date") code = 'sudo timedatectl set-time \"' + str(gpsTime) + '\"' print(code) os.system(code) os.system('sudo hwclock -s') print("done") return (gpsTime)
def getLoc2D(): """Get 2D location (lat/long) from GPS returns: (latitude, longitude), DD.DDDD format (truncated) """ gpsd.connect() myloc = gpsd.get_current() return ((float(round(decimal.Decimal(myloc.lat), 4)), float(round(decimal.Decimal(myloc.lon), 4))))
def stream(self): self.connect() while True: try: pkt = gpsd.get_current() az = pkt.track*pi/180 vx = pkt.speed()*cos(az) vy = pkt.speed()*sin(az) self.pos = toVector(pkt.lat*pi/180, pkt.lon*pi/180, pkt.altitude()) self.vel = toVector(vx, vy, pkt.climb) self.PDOP = toVector(pkt.error['x'], pkt.error['y'], pkt.error['v']) self.sats = pkt.sats self.time = time.time() self.new = True if __name__ == '__main__': print("%.1f, %3.7f, %3.7f, %4.1f, %3.3f, %3.3f, %3.3f, %.2f, %.2f, %.2f, %2i" % (time.time(), pkt.lat, pkt.lon, pkt.altitude(), vx, vy, pkt.climb, pkt.error['x'], pkt.error['y'], pkt.error['v'], pkt.sats)) except : #raise if __name__ == '__main__': print("No 3D fix available") self.PDOP = toVector(1e6, 1e6,1e6) self.sats = 0 else: pass time.sleep(1)
def track(self): while True: pack = gpsd.get_current() payload: str = str(pack.lat) + "," + str(pack.lon) print(payload) self.dust_agent._sent_gps_data_to_server(payload) time.sleep(1)
def gps_init_fix(): gpsd.connect() __init_status__ = False __lat__ = np.nan __lon__ = np.nan __start_time__ = time.time() while not __init_status__ and ( (time.time() - __start_time__) < max_timeout_poll): try: gps_packet = gpsd.get_current() __lat__ = gps_packet.lat __lon__ = gps_packet.lon __init_status__ = True print(datetime.datetime.now().strftime('%b-%d_%H:%M') + ': First GPS fix: ' + str(__lat__) + ' N' + str(__lon__) + ' E') except gpsd.NoFixError: __lat__ = np.nan __lon__ = np.nan __init_status__ = False print(datetime.datetime.now().strftime('%b-%d_%H:%M') + ': No first GPS fix.') _gps_status = [__lat__, __lon__, __init_status__] return _gps_status
def get_gpsloc(self): try: gpsd.connect() packet = gpsd.get_current() print(packet) return packet.lat, packet.lon except Exception as e: print(e) pass
def get_location(): packet = gpsd.get_current() lat = packet.lat lon = packet.lon alt = packet.alt nSat = packet.sats_valid return {'lat': lat, 'lon': lon, 'alt': alt, 'nSat': nSat}
def GetGPSPacket(): while True: try: Gps_packet = gpsd.get_current() #Hent gps data if Gps_packet.mode > 1: #Sjekk om fix er minst 2D return Gps_packet except: #hvis ikke prøv igjen journal.write("myGps: Bad gps packet, retrying in 5 sec") time.sleep(5)
def gpsCheck(): gps = gpsd.get_current() lat = gps.lat lon = gps.lon alt = gps.alt if math.trunc(lat) == 0.0 or math.trunc(lon) == 0.0 or math.trunc(alt) == 0.0: time.sleep(.1) lat, lon, alt = gpsCheck() return lat, lon, alt
def update_gps(self): if self.running: packet = gpsd.get_current() if packet.mode >= 2: self.coords = { "Latitude": packet.lat, "Longitude": packet.lon, "Altitude": packet.alt if packet.mode > 2 else None } return self.coords
def get_speed(): if debug: speed = input("Enter a debug speed (m/s)") else: packet = gpsd.get_current() speed = packet.speed() speed = float(speed) * 2.237 speed = round(speed) return speed
def get_loc(max_tries=None): p = None i = 0 while p is None and (max_tries is None or i < max_tries): try: p = gpsd.get_current() except (IndexError, KeyError): #gpsd sometimes chokes on the parsing and throws IndexError - don't know why. pass return p
def getPositionData(gps): try: p = gpsd.get_current() pos = "{\"mode\":"+str(p.mode)+",\"sats\":"+str(p.sats)+",\"lat\":"+str(p.lat)+",\"lng\":"+str(p.lon)+",\"alt\":"+str(p.alt)+",\"speed\":"+str(p.speed())+",\"track\":"+str(p.track)+",\"climb\":"+str(p.climb)+",\"precision\":\""+str(p.position_precision())+"\"}" return str(pos) except gpsd.NoFixError: print("GPS NO FIX!") return "-1" except: return "-2"
def send_update(): sensor_read(acc, mag, 'single', kill, nav_data) json_data = '{"command": "refreshSensorData", "nav":' + json.dumps(nav_data) + ', "gps":' + json.dumps( get_gps_data(gpsd.get_current())) + '}' async_to_sync(channel_layer.group_send)( "sensor-data", { "type": "sensor.refresh", "text": json_data } )
def main(): if not sys.argv or len(sys.argv) != 2: exit(1) init = sl.InitParameters() init.camera_resolution = sl.RESOLUTION.HD720 init.camera_fps = 30 init.depth_mode = sl.DEPTH_MODE.ULTRA # Use ULTRA depth mode init.coordinate_units = sl.UNIT.METER init.depth_minimum_distance = 0.15 gpsd.connect() packet = gpsd.get_current() print(" Mode: " + str(packet.mode)) cont = 0 status = cam.open(init) if status != sl.ERROR_CODE.SUCCESS: print(repr(status)) exit(1) ######## while True: t = 0 t0 = time.time() name = datetime.datetime.now() path_output = name.strftime("%d_%m_%Y__%H_%M_") + str(cont) + ".svo" path_output = sys.argv[1] + path_output recording_param = sl.RecordingParameters( path_output, sl.SVO_COMPRESSION_MODE.LOSSLESS) err = cam.enable_recording(recording_param) if err != sl.ERROR_CODE.SUCCESS: print(repr(status)) exit(1) file = open(path_output.split('.')[0] + ".txt", 'w') runtime = sl.RuntimeParameters() while t < 60: if cam.grab(runtime) == sl.ERROR_CODE.SUCCESS: file.write( str(packet.lat) + " " + str(packet.lon) + " " + str(packet.track) + "\n") print( str(packet.lat) + " " + str(packet.lon) + " " + str(packet.track) + "\n") t = time.time() - t0 print(str(t)) file.close() cont = cont + 1
def run(self): while 1: try: data = gpsd.get_current() self.latitude = data.lat self.longitude = data.lon self.altitude = data.alt self.latitude = data.lat self.accuracy = data.position_precision()[0] time.sleep(1) except: pass
def run(self): while 1: try: data = gpsd.get_current() self.sats = data.sats self.mode = data.mode if self.mode > 1: self.lat = data.lat self.long = data.lon if self.mode > 2: self.alt = data.alt self.accx = data.error["x"] # values given in Minecraft format self.accy = data.error["v"] # (X/Z axes horizontal, self.accz = data.error["y"] # Y axis vertical) time.sleep(1) except IndexError: self.restart()
def initialize_gps(): global packet init_complete = False read_attempts = 0 # Connect to the local gpsd gpsd.connect() while (read_attempts < 5 and init_complete == False): valid_read = False # Get gps position try: packet = gpsd.get_current() init_complete = True except Exception as e: valid_read = False read_attempts = read_attempts + 1 time.sleep(0.25) # Delay for 250 milliseconds return init_complete
#!/usr/bin/env python3 import gpsd import sys # Connect to the local gpsd gpsd.connect() # Connect somewhere else gpsd.connect() # Get gps position try: packet = gpsd.get_current() except Exception as e: print("ERROR: Error occured while parsing JSON or expected key or attribute missing") sys.exit() # See the inline docs for GpsResponse for the available data print(" ************ PROPERTIES ************* ") print(" Mode: {}".format(packet.mode)) print(" Satellites: {}".format(packet.sats)) if packet.mode >= 2: print(" Latitude: {}".format(packet.lat)) print(" Longitude: {}".format(packet.lon)) print(" Track: {}".format(packet.track)) print(" Horizontal Speed: {}".format(packet.hspeed)) print(" Time: {}".format(packet.time_iso)) print(" Error: {}".format(packet.error)) else: print(" Latitude: NOT AVAILABLE")