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]
def __init__(self): gpsd.connect() self.errors = [] self.latitude = [] self.longitude = [] self.tempo = [] self.historico_tempo = [] self.x = [] self.y = [] self.historico_diff_ang = [] self.distancia_prox_cone = [] self.historico_y = [] self.historico_x = [] self.instante_inicial = time.time() self.angulo_primeiro_cone = 24.676863170337057 #(np.arctan((17/37))/(np.pi))*180 self.angulo_segundo_cone = 29.054604099077146 #(np.arctan((10/18))/(np.pi))*180 self.angulo_terceiro_cone = 33.690067525979785 #(np.arctan((16/24))/(np.pi))*180 self.distancia_primeiro_cone = 40.718546143004666 #np.sqrt(17**2+37**2) self.distancia_segundo_cone = 20.591260281974 #np.sqrt(18**2+10**2) self.distancia_terceiro_cone = 28.844410203711913 #np.sqrt(16**2+24**2) self.cone_atual = 1 # primeiro cone self.primeiro_cone_xy = [ 19.706534, -39.04558 ] # mudar aqui dependendo da convencao lat long self.segundo_cone_xy = [ -11.29724, 10.991958 ] # mudar aqui dependendo da convencao lat long self.terceiro_cone_xy = [ 16.121901, 24.63018 ] # mudar aqui dependendo da convencao lat long self.distancia_rel_inicial = [] self.historico_diff_ang.append(0) self.distancia_prox_cone.append(0) #gambiarra
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 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 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 start_GPSD(): output = subprocess.Popen(bashCommand_startGPSD1 + sys.argv[3] + bashCommand_startGPSD2, shell=True, stdout=subprocess.PIPE) output.wait() print("--GPSD START: " + str(output.stdout.read())) time.sleep(2) # GPSD verbinden gpsd.connect()
def __init__(self): super(self.__class__, self).__init__() self.setupUi(self) self.schedule = schedule self.frame.installEventFilter(self) self.modules={} self.fakeModules={} self.tasks=[] self.modules["pyCAR"]={} self.modules["pyCAR"]["deck"]=0 self.modules["pyCAR"]["instance"]=self self.volume = volume self.volume.parent = self self.player = None self.active = None self.mobile=mobile() self.mobile.parent = self gpsd.connect() self.volumeViewSetup() self.readConfig() self.home.setStyleSheet("background-color: #000000;") self.btnVolumeUp.clicked.connect(lambda: self.volumeUp()) self.btnVolumeDown.clicked.connect(lambda: self.volumeDown()) self.btnMute.clicked.connect(lambda: self.volume.mute()) self.btnHome.clicked.connect(lambda: self.switchModule(0)) self.timer = QtCore.QTimer() #self.timer.timeout.connect(lambda: self.timefunctions()) self.timer.timeout.connect(lambda: self.schedule.run_pending()) self.timer.start(1000) self.schedule.every().second.do(self.timefunctions).tag("primary")
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_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 main(): #process_id1 = os.getpid() """Main Function""" print(BANNER + "\n\n") args = parse_arguments() # Start the channel hopper, creates a new process p = Process(target=channel_hop, args=(args.interface, )) p.start() # To do: create new process for gpsd #open newfile or existing file exists = os.path.isfile(filename) if not exists: # if new file create fieldnames in csv file with open(filename, mode='w') as new_file: CSV_FIELDNAME = [ 'SSID', 'BSSID', 'channel', 'signal strength', 'latitude', 'longlitude' ] CSV_WRITER = csv.DictWriter(new_file, fieldnames=CSV_FIELDNAME, delimiter=",") CSV_WRITER.writeheader() new_file.close() # connect to the local gpsd . gpsd -N -n -D2 /dev/ttyACM0 #start_gpsd = 'gpsd -N -n /dev/ttyACM0' #os.system(start_gpsd) if (args.gps): gpsd.connect() power.value = args.power # used in check() function sniff(iface=args.interface, count=args.count, prn=PacketHandler)
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 __init__(self): print("gps: starting up") connect() self.cached_position = None self.is_fresh()
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 __init__(self, message_server): Thread.__init__(self) self.setName('GpsReader') gpsd.connect() self.gps_reader = None self.point_list = [] self.active = True self.message_server = message_server
def configgps(self): while not self.gpsconnected: try: gpsd.connect() self.gpsconnected = True except: logging.critical('No GPS connection present. TIME NOT SET.') time.sleep(0.5)
def __init__(self, gpsdhost, gpsdport): gpsd.connect(host=gpsdhost, port=gpsdport) self.running = True self.coords = { "Latitude": None, "Longitude": None, "Altitude": None }
def connect(self): while not self.connected: try: gpsd.connect() # Connect to the local gpsd self.connected = True except: print('Could not connect to gpsd socket') time.sleep(5)
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 __init__(self): gpsd.connect() GPIO.setmode(GPIO.BCM) GPIO.setup(18, GPIO.IN, pull_up_down=GPIO.PUD_UP) GPIO.setup(3, GPIO.IN) #physical pull up resistor is fitted on this channel GPIO.add_event_detect(18, GPIO.RISING, callback=self.button_callback, bouncetime=300) GPIO.add_event_detect(3, GPIO.FALLING, callback=self.button_callback, bouncetime=300) self.distance = 0 self.running = True self.last_packet = None
def setup_gps(): killall = "sudo killall gpsd" stop = "sudo systemctl stop gpsd.socket" disable = "sudo systemctl disable gpsd.socket" start = "sudo gpsd /dev/ttyUSB-GPS -F /var/run/gpsd.sock" c = killall + "; " + stop + "; " + disable + "; " + start process = subprocess.Popen(c, stdout=subprocess.PIPE, shell=True) proc = process.communicate() gpsd.connect()
def connectAttempt(): global connectSuccess try: gpsd.connect() connectSuccess = True print "successfully connected to gps service" except Exception as e: print "failed to connect to gps service" connectSuccess = False print e
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): STEP = 5 * 60 #5min #STEP = 50 while True: try: print("Connecting on GPSD...") gpsd.connect() except: print( "Could not connect to GPSD.\nThis script is persistent and will try to reconnect to GPSD in 10 sec.", sys.exc_info()[0]) time.sleep(10) else: print("GPSD connected!") break while True: str_out = "" try: packet = gpsd.get_current() if packet.mode > 1: if packet.mode >= 2: str_out = str_out + "Latitude: " + str( packet.lat) + "\n" str_out = str_out + "Longitude: " + str( packet.lon) + "\n" str_out = str_out + "Track: " + str( packet.track) + "\n" str_out = str_out + "Horizontal Speed: " + str( packet.hspeed) + "\n" str_out = str_out + "Time: " + str(packet.time) + "\n" str_out = str_out + "Error: " + str( packet.error) + "\n" if packet.mode == 3: str_out = str_out + "Altitude: " + str( packet.alt) + "\n" str_out = str_out + "Climb: " + str( packet.climb) + "\n" print("We have a fix!:#" + str_out + "#\nSending email.") send_email(str_out) print("script sleeps for " + str(STEP)) time.sleep(STEP) else: print("There is no GPS FIX yet. Packet mode 0.") time.sleep(3) except: print(sys.exc_info()[0]) time.sleep(3)
def GPSInit(): gps_ok = 1 while gps_ok: gps_ok = 0 try: gpsd.connect() #Koble til gpsd journal.write("myGps: GPS connected") except: #print("gpsd error") journal.write("myGps: No GPS") gps_ok = 1
def record(verbose): SENSE.show_message("Picycle") # Connect to the GPS device. gpsd.connect() # Run the session, consisting of asynchronous tasks. asyncio.run(session(verbose)) # Clear the SenseHAT LED matrix. SENSE.clear()
def gnss_fix(): gpsd.connect() mode = 0 while mode < 3: try: packet = gpsd.get_current() mode = packet.mode except: pass print("Gnss Fix") time.sleep(10)
def GetGPSPosition(): gpsd.connect( ) # verbindet zu lokalem GPSD-Dienst (muss installiert und konfiguriert sein) gpsdata = gpsd.get_current() current_position = [0, 0, 0] if gpsdata.mode >= 2: # nur bei diesem und hoeherem Modus ist der Fix da current_position[0] = gpsdata.lat current_position[1] = gpsdata.lon current_position[2] = gpsdata.hspeed return current_position else: return False
def gpsInit(): # Starter kobling til gpsd, vil forsøke til koblingen er oppe gps_ok = 1 while gps_ok: gps_ok = 0 try: gpsd.connect() #Koble til gpsd journal.write("pyMon: GPS init ok") except: #print("gpsd error") journal.write("pyMon: GPS init Error") gps_ok = 1
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) path_output = sys.argv[1] 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() print("SVO is Recording, use q to stop.") frames_recorded = 0 while True: if cam.grab(runtime) == sl.ERROR_CODE.SUCCESS: frames_recorded += 1 file.write( str(packet.lat) + " " + str(packet.lon) + " " + str(packet.track) + "\n") # print("Frame count: " + str(frames_recorded), end="\r") print( str(packet.lat) + " " + str(packet.lon) + " " + str(packet.track) + "\n") if cv2.waitKey(20) & 0xFF == ord('q'): break file.close()
def get_gps_data(): if config['sensors']['gps_enable']: try: # Reinitialise gpsd connection if it's broken for some reason if not gps_data['mode']: gpsd.connect() # Read some data packet = gpsd.get_current() # Deposit it into the global dict gps_data['mode'] = packet.mode gps_data['mode_text'] = gps_mode_text[gps_data['mode']] gps_data['sats'] = packet.sats gps_data['sats_valid'] = packet.sats_valid # Present some information if we have a fix if (gps_data['mode'] >= 2): gps_data['time'] = packet.get_time().replace( tzinfo=None, microsecond=0).isoformat() gps_data['time_local'] = packet.get_time( local_time=True).replace(tzinfo=None, microsecond=0).isoformat() gps_data['timezone'] = TimezoneFinder().timezone_at( lng=packet.lon, lat=packet.lat) gps_data['latitude'] = round(packet.lat, 4) gps_data['longitude'] = round(packet.lon, 4) gps_data['speed'] = int(packet.speed()) else: gps_data['time'] = None gps_data['time_local'] = None gps_data['timezone'] = None gps_data['latitude'] = None gps_data['longitude'] = None gps_data['speed'] = None # Information below is only obtainable from a 3D fix if (gps_data['mode'] >= 3): gps_data['altitude'] = int(packet.alt) else: gps_data['altitude'] = None except Exception as e: # Error has occurred, log it logger.error("Failed to get GPS data: " + str(e)) gps_data.clear() gps_data['enabled'] = True gps_data['mode'] = 0 gps_data['mode_text'] = gps_mode_text[gps_data['mode']] else: logger.warn('Request to read GPS data, but not enabled in config')
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 __init__(self): threading.Thread.__init__(self) self.daemon = True for i in ["sats", "mode", "lat", "long", "alt", "accx", "accy", "accz"]: self.__setattr__(i, 0) try: gpsd.connect() except: os.popen("sudo gpsd /dev/ttyUSB0") time.sleep(1) try: gpsd.connect() except: raise EnvironmentError("GPS server not available, " + "restart gpsd")
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
def connect(self): gpsd.connect()
#!/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")