def do_log(): try: if log_bluetooth: logging.warning("Starting BT") btl = BluetoothLogger(fields=all_fields, bt_commands=bt_commands, password=args.bluetooth_pass) btl.start() logging.warning("Waiting for CAN Bus channel={} interface={}".format( args.channel, args.interface)) led1(1) led2(1) if is_fms: baud = 250000 else: baud = 500000 # Reset the CAN interface just in case it doesn't come up reset_can_interface(args.channel) bus = can.interface.Bus(channel=args.channel, bustype=args.interface, bitrate=baud) if not disable_gps: gps = GPS(args.gps_port, args.gps_baud) led2(0) led1(0) logging.warning("Connected CAN Bus and GPS") except can.CanError as err: logging.error('Failed to initialise CAN BUS: ' + str(err)) return if is_tesla: logging.warning("Using TeslaSnifferLogger") logger_c = TeslaSniffingLogger elif is_bustech: logger_c = BustechLogger elif is_obd_query: logging.warning("Using QueryingOBDLogger") logger_c = QueryingOBDLogger init_sniff(bus) elif is_fms: logging.warning("Using FMSLogger") logger_c = FMSLogger else: logging.warning("Using SnifferLogger") logger_c = SniffingOBDLogger logger = logger_c(bus, pid_ids, pids, log_trigger) responds_to.update(logger.responds_to) trip_sequence = 0 vid = args.vehicle_id json_writer = JSONLogRotator(log_folder=log_folder, maxbytes=bytes_per_log, fieldnames=all_fields, vin=vid, pid_file=log_pid_location) path = pathlib.Path(json_writer._out_fh.name) writing_to['name'] = path.name trip_id = '{}_{}'.format(path.stem, vid) def make_buff(): return {'vid': vid, 'trip_id': trip_id, 'trip_sequence': trip_sequence} while 1: buff = make_buff() led1(1) new_log = logger.log() if GPIO.input(35) == 1: shutdown_msg = "$status=Received shutdown signal" logging.warning(shutdown_msg) if log_bluetooth: btl.send(shutdown_msg) sudo('shutdown -h 0') buff.update(new_log) for k, v in buff.items(): if type(v) is float: buff[k] = round(v, 2) led1(0) if not args.disable_gps: led2(1) gps_data = gps.read() if gps_data is not None: buff.update(gps_data) led2(0) if args.verbose: print(buff) # put the buffer into the logs row_txt = json_writer.writerow(buff) trip_sequence += 1 if log_bluetooth: led2(1) if bt_log and btl.identified: btl.send(row_txt) led2(0)
def reset_can_interface(interface): sudo('ifdown ' + interface) sudo('ifup ' + interface)
def reset_wifi(): for cmd in ['ifdown', 'ifup']: sudo('/sbin/{} wlan0'.format(cmd))
def reset(): return sudo('shutdown -r now')
def shutdown(): GPIO.cleanup() atexit.register(shutdown) if __name__ == "__main__": # start logging loop import time setup_GPIO() sleep_time = 10 log_err_count = 0 logging.warning("Starting logging") while 1: try: do_log() except Exception as e: logging.error(e, exc_info=True) led1(1) led2(1) logging.warning("Sleeping for {}s".format(sleep_time)) time.sleep(sleep_time) led2(0) led1(0) log_err_count += 1 if log_err_count == 3: sudo('reboot')
def log(self): # send a message asking for those requested pids out = {} time.sleep(0.5) pids_responded = [] for m in self.pids2log: if m in outlander_pids: outlander_data = self._log_outlander(m) if outlander_data != {}: pids_responded.append(m) out.update(outlander_data) else: self.bus.set_filters([{'can_id': 0x07e8, 'can_mask': 0xffff}]) # if self.responds_to is not None and m in self.responds_to: out_msg = self.make_msg(m) # logging.warning("S> {}".format(out_msg)) # self.bus.send(out_msg) # receive the pid back, (hoping it's the right one) # count = 0 start = datetime.now() while count < 5: count += 1 self.bus.send(out_msg) msg = self.bus.recv(0.4) # logging.warning(self.pids[m]['name']+str(msg)) if msg is None: # logging.warning("No message") if (datetime.now() - start).total_seconds() > self.log_timeout: print("Query timeout") break continue if msg.arbitration_id == OBD_RESPONSE: # logging.warning("R> {}".format(msg)) pid, obd_data = self.separate_can_msg(msg) # logging.warning("PID={}, pids2log={}, pid in?={}".format(pid, self.pids2log, pid in self.pids2log)) # try and receive if pid in self.pids2log: out.update(self.pids[pid]['parse'](obd_data)) pids_responded.append(pid) break # logging.warning(out) if len(out) == len(self.pids2log): logging.debug("got all PIDs") break # logging.warning(out) # logging.warning("finished log loop") if self.first_log: # only log those that get a response the first time around # self.pids2log = set(pids_responded) logging.warning("Setting PIDs to {}".format(",".join(self.pids[p]['name'] for p in self.pids2log))) self.first_log = False self.log_timeout = self.log_timeout_tail # print(out) if out == {}: self.errors += 1 if self.errors == 5: logging.warning("Shutting down after failing to receive CAN data") sudo("shutdown -h 0") else: self.errors = 0 return out