def connect_bluetooth(): show_message(INFO_007) global connection retries = 0 connection = obd.OBD() # auto-connects to USB or RF port while ((connection.status() != OBDStatus.CAR_CONNECTED) and retries < OBD_RETRIES): if connection.status() == OBDStatus.ELM_CONNECTED: show_message(INFO_001) time.sleep(5) connection = obd.OBD() # auto-connects to USB or RF port if connection.status() != OBDStatus.CAR_CONNECTED: show_message(ERROR_005) time.sleep(5) print(retries) retries = retries + 1 if connection.status() != OBDStatus.CAR_CONNECTED: show_message(ERROR_005) ports = obd.scan_serial() # return list of valid USB or RF ports logging.info("Ports found:") logging.info(ports) for x in ports: connection = obd.OBD(x) if connection.status() == OBDStatus.CAR_CONNECTED: show_message(INFO_008.format(connection.port_name())) break show_message(ERROR_006) sys.exit(0) else: show_message(INFO_008.format(connection.port_name()))
def connect(): connection = obd.OBD() print connection.status() while connection.status() != OBDStatus.CAR_CONNECTED: connection = obd.OBD() print connection.status() time.sleep(5) return connection
def __init__(self): self.connection = obd.OBD() while self.connection.status() == OBDStatus.NOT_CONNECTED: print("<{0}> Waiting for OBD Connection...".format( datetime.datetime.now().time())) time.sleep(10) self.connection = obd.OBD() if self.connection.status() == OBDStatus.CAR_CONNECTED: print("OBD Connected")
def connectToPort(portNumber=0): """ Connect to selected port, by default port 0""" ports = scanDevices() print(ports) portNumber = int(input("number: ")) if (obd.OBD(ports[portNumber])): return obd.OBD(ports[portNumber]) else: raise Exception("Unable to connect to port " + portNumber)
def __init__(self, port): if port=="": self.conn = obd.OBD() else: self.conn = obd.OBD(portstr=port) self.cmdSpeed = obd.commands.SPEED self.cmdRPM = obd.commands.RPM self.cmdPos = obd.commands.THROTTLE_POS self.cmdTemp = obd.commands.COOLANT_TEMP
def getVehicleTelemtries(deviceId): global connection if (not connection.is_connected()): print("No connecting to the car, reconnecting...") connection = obd.OBD(fast=True) try: telemtryDic = {} # allCommands = connection.supported_commands allCommands = [ obd.commands.RUN_TIME, obd.commands.RPM, obd.commands.SPEED, obd.commands.MAF, obd.commands.THROTTLE_POS, obd.commands.COOLANT_TEMP, obd.commands.ENGINE_LOAD, obd.commands.SHORT_FUEL_TRIM_1, obd.commands.LONG_FUEL_TRIM_1, #obd.commands.SHORT_FUEL_TRIM_2, #obd.commands.LONG_FUEL_TRIM_2, #obd.commands.FUEL_PRESSURE, obd.commands.INTAKE_PRESSURE, obd.commands.TIMING_ADVANCE, obd.commands.INTAKE_TEMP, obd.commands.RELATIVE_THROTTLE_POS, #obd.commands.AMBIANT_AIR_TEMP, #obd.commands.FUEL_LEVEL, obd.commands.ABSOLUTE_LOAD, obd.commands.OIL_TEMP ] for command in allCommands: try: response = connection.query(obd.commands[command.name]) telemetryValue = getValue(response) telemtryDic[command.name] = telemetryValue except Exception as e: print("Error querying OBDII entry: " + command.name + ", error: " + str(e)) if (telemtryDic["RPM"] == 0): print("Cannot read RPM, reconnecting...") connection = obd.OBD(fast=True) return None else: return buildJsonPayload(deviceId, telemtryDic) except Exception as e: print("Error with OBDII, error: " + str(e) + ". Reconnecting...") connection = obd.OBD(fast=True) return None
def get_speed(): connection = obd.OBD() #may be changed to specify the interface # get the speed cmd = obd.commands.SPEED speed = connection.query(cmd) # add this value to the list of speeds files.write_value(speed.value.magnitude)
def __connect(self): logger.debug('ELM device on {}'.format(self.__port)) self.__supported_commands = [] if self.__testing: logger.info('Worker connection status = Fake OBD') self.__supported_commands.append('RPM') self.__supported_commands.append('SPEED') self.__supported_commands.append('MAF') self.__supported_commands.append('BAROMETRIC_PRESSURE') self.__supported_commands.append('COOLANT_TEMP') self.__supported_commands.append('INTAKE_PRESSURE') self.__supported_commands.append('DISTANCE_SINCE_DTC_CLEAR') self.__supported_commands.append('DISTANCE_W_MIL') self.__supported_commands.append('WARMUPS_SINCE_DTC_CLEAR') self.__supported_commands.append('ENGINE_LOAD') self.__supported_commands.append('EGR_ERROR') self.__supported_commands.append('COMMANDED_EGR') self.__supported_commands.append('FUEL_RAIL_PRESSURE_DIRECT') self.__supported_commands.append('CONTROL_MODULE_VOLTAGE') self.__supported_commands.append('AMBIANT_AIR_TEMP') self.__supported_commands.append('INTAKE_TEMP') else: if self.__port is None: #logger.error('Could not find ELM device. Check connection and settings.') self.__interface = None sleep(0.1) return self.__interface = obd.OBD('/dev/' + self.__port, self.__baud) logger.debug('Worker connection status = {}'.format( self.__interface.status())) if self.__interface.status() == 'Car Connected': for c in self.__interface.supported_commands: if c.mode == 1 and c.name[:4] != 'PIDS': self.__supported_commands.append(c.name)
def __init__(self): # initialize game window, etc pygame.init() self.screen = pygame.display.set_mode((WIDTH, HEIGHT)) pygame.display.set_caption(TITLE) self.clock = pygame.time.Clock() self.running = True self.connection = obd.OBD() self.command = obd.commands.RPM self.response = self.connection.query(self.command) self.mph = 0 self.rpm = 0 self.throttle_position = 0 self.temp = 0 self.fuel = 100 self.oil_pressure = 0 self.fuel_pressure = 0 self.test_module_1 = HudModule("MPH", 0) self.test_module_2 = HudModule("RPM", 1) self.test_module_3 = HudModule("THROTTLE POS", 2) self.test_module_4 = HudModule("TEMP", 3) self.test_module_5 = HudModule("FUEL", 4) self.test_module_6 = HudModule("OIL PRESSURE", 5) self.test_module_7 = HudModule("FUEL PRESSURE", 6)
def init_obd : ArrayOBDRPM = [''] * 300 ArrayOBDSpeed = [''] * 300 ArrayOBDThrottle = [''] * 300 ArrayOBDLoad = [''] * 300 ArrayOBDCoolant = [''] * 300 connection = obd.OBD()
def loopOBD2(num, sheet): print("Starting OBD2 Reading.. ") connection = obd.OBD("/dev/ttyUSB1") carCommands = [ obd.commands.ENGINE_LOAD, # obd.commands.COOLANT_TEMP, # obd.commands.FUEL_PRESSURE, obd.commands.RPM, obd.commands.SPEED, # obd.commands.INTAKE_TEMP, # obd.commands.MAF, obd.commands.THROTTLE_POS ] while (connection.is_connected() and num > 0): respCommands = [] for c in carCommands: respCommands.append(str(connection.query(c).value)) global buffer for i, val in enumerate(respCommands): buffer[13 + i] = struct.pack("if", 13 + i + 1, val) # buffer[13:17] = respCommands global row sheet.write(row, 6, str(respCommands[0])) sheet.write(row, 7, str(respCommands[1])) sheet.write(row, 8, str(respCommands[2])) sheet.write(row, 9, str(respCommands[3])) num -= 1 time.sleep(0.01) global isFinished isFinished[3] = True
def pid_scan(self): """This option MUST BE selected for the first time a new car is added to the pid_list.cfg configuration file. Using the obd library's current PID database a list of all supported PID is requested and (over)written to the corresponding section in the pid_list.cfg configuration file.""" self.data.pid_list[self.cindex].clear() #old PID values are cleared connection = obd.OBD( self.obd_path) #new obd connection to query new car. #--------------------------------------------------------------- config = ConfigParser.SafeConfigParser() #reads pid_list.cfg config.read('data/pid_list.cfg') car = u'car' + unicode(self.cindex + 1) #--------------------------------------------------------------- for c in connection.supported_commands: #loops through supported command list mp = str(c) mode_pid = mp[0:4] #stores pid number self.data.pid_list[ self.cindex][mode_pid] = c.name #stores pid name #----------------------------------------------------------- config.set(car, unicode(mode_pid), unicode(c.name)) #adds new pid to list #--------------------------------------------------------------- with open('data/pid_list.cfg', 'r+') as configfile: config.write(configfile) #writes all new pids to corresponding
def main(port_name, MAF=True): connection = obd.OBD(port_name) start_time = time.strftime("%d%H%M%S", time.localtime()) print(start_time) outputfile = open('output' + start_time + '.csv', 'w', newline='') csvwriter = csv.writer(outputfile) print("Writing OBD-II csv file...\n") while True: try: t = time.time() OBD_speed = connection.query(obd.commands.SPEED).value.magnitude if MAF: OBD_max_air_flow = connection.query( obd.commands.MAF).value.magnitude csvwriter.writerow([ t, #time from record start OBD_max_air_flow, #gram/sec OBD_speed #m/s ]) else: csvwriter.writerow([ t, # time from record start OBD_speed # m/s ]) except KeyboardInterrupt: outputfile.close()
def main(): con = obd.OBD("/dev/serial0", 115200) now = dt.datetime.now() file_name = dt.datetime.strftime(now, "%Y%m%d_%H%M%S.dat") print(file_name) dafi = open(file_name, "w+") counter = 0 while (counter < 2): #status = "200" status = [] status.append(con.status()) status.append(get_speed(con)) status.append(get_RPM(con)) status.append(get_FUEL_STATUS(con)) status.append(get_ENGINE_LOAD(con)) status.append(get_COOLANT_TEMP(con)) status.append(get_THROTTLE_POS(con)) status.append(get_DISTANCE_W_MIL(con)) status.append(get_FUEL_LEVEL(con)) status.append(get_DISTANCE_SINCE_DTC_CLEAR(con)) status.append(get_FUEL_RATE(con)) status.append(get_OIL_TEMP(con)) status.append(get_ELM_VOLTAGE(con)) print(status) dafi.write("".join(status)) time.sleep(1) counter = counter + 1 dafi.close()
def textbox(self): connection = obd.OBD() alertcmd = obd.commands.GET_DTC alert_resp = connection.query(alertcmd) alert_str = str(alert_resp.value) self.textEdit.setText(alert_str)
def __init__(self): try: self.OBD_conn = obd.OBD(obd.scan_serial()[0]) self.connected = True print(self.OBD_conn.status()) except: self.connected = False
def connect(): global timer global connection try: ports = obd.scan_serial() # return list of valid ports except (Exception) as error: print(error) try: connection = obd.OBD(ports[0], baudrate=38400, protocol=None, fast=True) # auto-connects to USB or RF port except (Exception) as error: print(error) # # BUZZER # if timer > 20: sys.exit("Too many attempts") timer += 1 connect() finally: read_data()
def addVehicleInfo(): global messageToSend, sequence, bootTime try: connection = obd.OBD() # auto-connects to USB or RF port try: c = obd.OBDCommand("VIN", "Get Vehicle Identification Number", b"0902", 20, raw_string, ECU.ENGINE, True) connection.supported_commands.add(c) VIN = str(connection.query(c).value) except: VIN = 'None' message = { 'type': 'vehicleData', 'bootTime': bootTime, 'sequence': sequence, 'currentTime': str(datetime.now().isoformat()), 'VIN': VIN } allCommands = connection.supported_commands for command in allCommands: try: response = connection.query(obd.commands[command.name]) message[command.name] = str(response.value) except: print("for command in allCommands: Error: " + str(sys.exc_info()[0])) #print message addMessage(str(message)) except: print("addVehicleInfo() Error: " + str(sys.exc_info()[0]))
def test_fast(): o = obd.OBD("/dev/null", fast=False) o.interface = FakeELM("/dev/null") assert command.fast o.query(command, force=True) # force since this command isn't in the tables
def test_is_connected(): o = obd.OBD("/dev/null") assert not o.is_connected() # our fake ELM class always returns success for connections o.interface = FakeELM("/dev/null") assert o.is_connected()
def connectToOBD(self): self._logger.info('VEHICLE_SERVICE: connecting to port:' + self._port) self._connected = False # print ("OBD serial port:",port) try: self.odb_connection = obd.OBD(portstr=self._port) except Exception as err: self._error = "Cannot connect to OBD:" + str(err) self._logger.error(self._error) return False self._connected = self.odb_connection.is_connected() self._obd_status = self.odb_connection.status() if self._connected: self._all_cmds = self.odb_connection.supported_commands self.setActualCommands(self._all_cmds) self._request_commands = self._actual_commands # self._logger.debug("OBD connection:"+self._obd_status+' protocol ' + self.odb_connection.protocol_name()) self._error = 'CONNECTED! Protocol ' + self.odb_connection.protocol_name( ) + ' #CMDS:' + str(len(self._all_cmds)) self._logger.info('VEHICLE_SERVICE: ' + self._error) self.read_elm327() self.engine_on = True return True else: self._error = 'Device (' + self._port + ' ' + self.MAC_ADDRESS + ') status:' + self._obd_status self._logger.error(self._error) self._logger.info('VEHICLE_SERVICE NOT CONNECTED (ENGINE OFF): ' + self._port) self.engine_on = False #exit(1) return False
def instrument_readings(self): connection = obd.OBD() rpmCmd = obd.commands.RPM speedCmd = obd.commands.SPEED fuelCmd = obd.commands.FUEL_LEVEL while 1: fuelResponse = connection.query(fuelCmd) rpmResponse = connection.query(rpmCmd) speedResponse = connection.query(speedCmd) fuelString = str(fuelResponse.value).split() rpmString = str(rpmResponse.value).split() speedString = str(speedResponse.value).split() if fuelString[0] != "None": fuel = float(fuelString[0]) self.fuel_val.setValue(fuel) if speedString[0] != "None": speed = float( speedString[0] ) * 0.62137119223733 # convert Kilometers per hour to MPH self.speed_val.setText(str(speed)) if rpmString[0] != "None": rpm = float(rpmString[0]) self.rpm_val.setText(str(rpm))
def open(self, force=False): if self.is_permanently_closed and not force: raise Warning( "OBD connection is no longer available as it has been permanently closed" ) # Reset flag self.is_permanently_closed = False log.debug("Opening OBD connection") try: self._obd = obd.OBD( portstr=self._device, baudrate=self._baudrate, timeout=self._timeout, protocol={ "id": self._protocol_id if self._protocol_id != "AUTO" else None, # None value will result in autodetection "baudrate": self._protocol_baudrate, "verify": self._protocol_verify }, load_commands=self. _protocol_verify, # Only load supported commands when protocol is verified interface_cls=STN11XX, status_callback=self._status_callback, fast=False) return self except Exception: log.exception("Failed to open OBD connection") raise
def test_protocol_id(): o = obd.OBD("/dev/null") o.port = None assert o.protocol_id() == "" o.port = FakeELM("/dev/null") assert o.protocol_id() == o.port.protocol_id()
def establish_obd_connection(self, baud, port, debug=False): if debug: obd.logger.setLevel(obd.logging.DEBUG) ports = obd.scan_serial() print(ports) connection = obd.OBD(port, baud) while connection.query(obd.commands.SPEED).value is None: time.sleep(1) print('Retrying Connection') connection = obd.OBD(port, baud) print('Connection Established') return connection
def retry_connection(self): if self.connection is not None and self.connection.is_connected( ) == obd.OBDStatus.NOT_CONNECTED: self.connection.close() try: self.connection = obd.OBD() except SerialException: print("No OBD device found")
def test_protocol_id(): o = obd.OBD("/dev/null") o.interface = None assert o.protocol_id() == "" o.interface = FakeELM("/dev/null") assert o.protocol_id() == o.interface.protocol_id()
def main(): # See https://github.com/brendan-w/python-OBD/issues/93 # Note, for FiXD device, the pin code is 1234 try: connection = obd.OBD('/dev/rfcomm1') # auto-connects to USB or RF port valid_pids = [] cmd = obd.commands.PIDS_A response = connection.query(cmd) print(f'PIDS_A: {response.value}') for i in range(32): pid_num = i + 1 if response.value[i] == 1 and i != 31: valid_pids.append(pid_num) print(f'PID {hex(pid_num)} Supported: {response.value[i]}') cmd = obd.commands.PIDS_B response = connection.query(cmd) print(f'PIDS_B: {response.value}') for i in range(32): pid_num = 32 + i + 1 if response.value[i] == 1 and i != 31: valid_pids.append(pid_num) print(f'PID {hex(pid_num)} Supported: {response.value[i]}') cmd = obd.commands.PIDS_C response = connection.query(cmd) print(f'PIDS_C: {response.value}') for i in range(32): pid_num = 64 + i + 1 if response.value[i] == 1 and i != 31: valid_pids.append(pid_num) print(f'PID {hex(pid_num)} Supported: {response.value[i]}') blacklist_pids = [ obd.commands.FUEL_STATUS.pid, obd.commands.O2_SENSORS.pid, obd.commands.OBD_COMPLIANCE.pid, obd.commands.STATUS.pid, obd.commands.STATUS_DRIVE_CYCLE.pid, ] scan_pids = [p for p in valid_pids if p not in blacklist_pids] start_time = time.time() LOOP_TIME_GOAL = 2.0 # seconds while True: spin_pid_list(connection, scan_pids) spin_time = time.time() - start_time print(f'Loop took {spin_time:.3f} seconds') print() print() print() time.sleep(max(0, LOOP_TIME_GOAL - spin_time)) start_time = time.time() finally: connection.close()
def get_error_codes(self): #try catch? # The specific location of the usb port will probably need to be configurable -- it'll be different for different folk connection = obd.OBD("/dev/tty.usbserial-146220") dtc_codes = connection.query(obd.commands.GET_DTC) if dtc_codes: for dtc_code in dtc_codes.value: return dtc_code else: return 'no error codes found'
def getData(): connection = obd.OBD() start = time.time() r = connection.query( obd.commands.SPEED) # returns the response from the car end = time.time() elapsed = end - start print(r) print(elapsed)