def recover_lost_connection(connection: obd.OBD, fast: bool,
                            timeout: float) -> obd.OBD:
    """
    Recover lost connection and return a new working connection handle.
    """
    logging.info("recovering lost connection")
    connection.close()
    sleep(CONNECTION_WAIT_DELAY)
    connection = get_obd_connection(fast=fast, timeout=timeout)

    return connection
Example #2
0
def setup():
	adapters = scanner.scan("OBD")
	if len( adapters ) == 0:
		print "[!]\tNo adapters were found that have 'OBD' in their name.\nExiting..."
	else:
		global adapter
		adapter = OBD( type="bluetooth", addr=adapters[0]['addr'], name=adapters[0]['name'], baud=BAUD )
		adapter.bind()
		adapter.connect()
		print(SendOBD("ate0"))
		print(SendOBD("atl0"))
		print(SendOBD("ath0"))
Example #3
0
def bluetooth():
	
	adapters = scanner.scan( "OBD" )

	if len( adapters ) == 0:
		print "[!]\tNo adapters were found that have 'OBD' in their name.\nExiting..."

	# Adapters were found.
	else:
		# Grab the first adapter returned.
		# adapter = OBD( adapters[0]['addr'], adapters[0]['name'], BAUD )
		adapter = OBD( type="bluetooth", addr=adapters[0]['addr'], name=adapters[0]['name'], baud=BAUD )
		adapter.bind()
		adapter.connect()
Example #4
0
 def run(self):
     """
     Main class function
     :return:
     """
     while True:
         if self.connection:
             if not self.connection.status() == OBDStatus.CAR_CONNECTED:
                 self.connection = OBD(self.port, self.baud, self.protocol)
             elif self.connection.status() == OBDStatus.CAR_CONNECTED:
                 self.get_all_pids()
         else:
             self.init_bt()
             self.connection = OBD(self.port, self.baud, self.protocol)
def bluetooth():
	"""Bluetooth OBD-II Range Test

	This method manages all range testing of a bluetooth OBD-II adapter.
	"""

	# Scan for all adapters.
	adapters = scanner.scan( "OBD" )

	# No adapters were found.
	if len( adapters ) == 0:
		print "[!]\tNo adapters were found that have 'OBD' in their name.\nExiting..."

	# Adapters were found.
	else:
		# Grab the first adapter returned.
		# adapter = OBD( adapters[0]['addr'], adapters[0]['name'], BAUD )
		adapter = OBD( type="bluetooth", addr=adapters[0]['addr'], name=adapters[0]['name'], baud=BAUD )
		adapter.bind()
		adapter.connect()

		# Setup the file manager.
		fm = FileManager()

		# Write header to CSV file.
		fm.writeCSV( csvfile, [ "Iteration", "RX/TX Time" ] )

		# Save the starting time.
		starttime = datetime.now()

		###
		# Run the range test.
		###
		test( adapter, fm )

		# Get the time when testing completes.
		finishtime = datetime.now()

		# Create a plot of the values.
		columns = getColumns( fm.readCSV( csvfile ) )

		# Create plot.
		figurename = plotter.generateLinePlot( columns["Iteration"][1:len(columns["Iteration"])], columns["RX/TX Time"][1:len(columns["RX/TX Time"])], "Bluetooth Range Test", "Iteration", "(RX - TX) Time [sec]", ("rangetest_" + finishtime.strftime( "%H_%M_%S" )), "png" )

		# Write ending results.
		print "\tTime to completion: " + str( finishtime - starttime )
		print "\tCSV File: " + csvfile
		print "\tPlot Image: " + figurename
Example #6
0
def wifi():
    """WiFi OBD-II Range Test

	This method manages all range testing of a wifi OBD-II adapter.
	"""
    global IP, PORT

    adapter = OBD(type="wifi", name="OBD", ip=IP, port=PORT)
    adapter.connect()

    # Setup the file manager.
    fm = FileManager()

    # Write header to CSV file.
    fm.writeCSV(csvfile, ["Iteration", "RX/TX Time"])

    # Save the starting time.
    starttime = datetime.now()

    ###
    # Run the range test.
    ###
    test(adapter, fm)

    # Get the time when testing completes.
    finishtime = datetime.now()

    # Create a plot of the values.
    columns = getColumns(fm.readCSV(csvfile))

    # Create plot.
    figurename = plotter.generateLinePlot(
        columns["Iteration"][1 : len(columns["Iteration"])],
        columns["RX/TX Time"][1 : len(columns["RX/TX Time"])],
        "WiFi Range Test",
        "Iteration",
        "(RX - TX) Time [sec]",
        ("rangetest_" + finishtime.strftime("%H_%M_%S")),
        "png",
    )

    # Write ending results.
    print "\tTime to completion: " + str(finishtime - starttime)
    print "\tCSV File: " + csvfile
    print "\tPlot Image: " + figurename
Example #7
0
def speedometer():
    speedData = OBD().query(commands.SPEED).value.to("mph")
    speedText = str(speedData) + " mph"
    speed.config(text=speedText,
                 bg='black',
                 fg='#F4511E',
                 font=("Helvetica", 72, "bold"))
    speed.place(anchor='center', relx=0.5, rely=0.5)
    root.after(1000, speedometer)  # Update speedometer every second
def execute_obd_command(connection: obd.OBD, command_name: str):
    """
    executes OBD interface query given command_name on OBD connection.
    returns list or value
    """
    if obd.commands.has_name(command_name):
        obd_response = connection.query(obd.commands[command_name], force=True)

    elif command_name in local_commands:
        obd_response = connection.query(local_commands[command_name],
                                        force=True)
    else:
        # raise LookupError(f"command <{command_name}> missing from python-obd and custom commands")
        logging.warn(
            f"LookupError: config file has command name <{command_name}> that doesn't exist"
        )
        return None

    return obd_response
Example #9
0
def setup():
	global PRINT_ECHO_ACTIVE
	global adapter
	adapter = OBD()
	adapter.connect()
	ans = adapter.send_obd("ate0")
	if (PRINT_ECHO_ACTIVE):
		print(ans)
	ans = adapter.send_obd("atl0")
	if (PRINT_ECHO_ACTIVE):
		print(ans)
	ans = adapter.send_obd("ath0")
	if (PRINT_ECHO_ACTIVE):
		print(ans)
Example #10
0
    def connect(self, port):

        global connected
        global connOBD

        if port == "":
            self.status["text"] = "Connecting to ELM327..."
            self.update()
            connOBD = ObdData("")

        else:
            self.status["text"] = "Connecting to simulator..."
            self.update()
            connOBD = ObdData(port)

        if OBD.is_connected(connOBD.conn):
            connected = True
            app.show_frame(Dashboard)
        else:
            self.status["text"] = "Error!!"
            self.update()
Example #11
0
    def run(self):
        print "\tOBDReader: connecting..."

        #init
        connection = OBD('/dev/ttyUSB1')
        if not connection.is_connected():
            print "\tOBDReader: Error: could not connecto to vehicle"
            connection = OBD(self.port)
            if not connection.is_connected():
                print "\tOBDReader: Error: could not connect to obdsim"
                return
        self.connected = True

        #print "\treadOBD thread connected. Entering main loop."
        #main loop
        while not self.stopped():
            STATUS = connection.query(commands.STATUS) # MIL: bool, DTC_count int
            MAF = connection.query(commands.MAF) # grams/sec
            SPEED = connection.query(commands.SPEED) # kph
            THROTTLE_POS = connection.query(commands.THROTTLE_POS) # %
            RPM = connection.query(commands.RPM) # rpm
            COOLANT_TEMP = connection.query(commands.COOLANT_TEMP) # deg C
            GET_DTC = connection.query(commands.GET_DTC) # [('code','desc')]
            print "|%s|" % GET_DTC

            SharedData.lock.acquire()
            try:
                SharedData.MIL = STATUS.value.MIL                     if not STATUS.is_null()         else None
                SharedData.DTC_count = STATUS.value.DTC_count         if not STATUS.is_null()         else None
                SharedData.MAF = MAF.value                      if not MAF.is_null()            else None
                SharedData.SPEED = SPEED.value                  if not SPEED.is_null()          else None
                SharedData.THROTTLE_POS = THROTTLE_POS.value    if not THROTTLE_POS.is_null()   else None  
                SharedData.RPM = RPM.value                      if not RPM.is_null()            else None
                SharedData.COOLANT_TEMP = COOLANT_TEMP.value    if not COOLANT_TEMP.is_null()   else None
                SharedData.GET_DTC = GET_DTC.value              if not GET_DTC.is_null          else None  
            finally:
                SharedData.lock.release()

        connection.close()
        print "\tOBDReader: disconnected."
Example #12
0
from obd import OBD
from at_commands import *

HIREKEN_MAC_ADDR = '00:1D:A5:00:03:43'

adapter = OBD()
#adapter.scan()
#adapter.connect_specific(HIREKEN_MAC_ADDR)
adapter.connect()

print adapter.send_obd(DESC_PROTOCOL)
print adapter.send_obd(ECHO_OFF)
print adapter.send_obd(DISP_DEV_ID)
print adapter.send_obd(REPEAT_CMD)
print adapter.send_obd('010C')
print adapter.send_obd(WARM_START)
print adapter.send_obd('010C')

#adapter = OBD_User()
#adapter.connect()

#print adapter.send_obd(WARM_ATART)
Example #13
0
# Weirdly the OBD port doesn't differentiate forward movement from backward movement
class OBDReading():
    def __init__(self, connection):
            self.throttle = connection.query(commands.THROTTLE_ACTUATOR).value.magnitude
            self.rpm = connection.query(commands.RPM).value.magnitude
            self.engineLoad = connection.query(commands.ENGINE_LOAD).value.magnitude
            self.speed = connection.query(commands.SPEED).value.magnitude
            if self.speed == 0 or self.speed is None:
                self.moving = False
            else:
                print('moving')
                self.moving = True
            self.csvstring = "{},{},{},{},".format(self.throttle,self.rpm,self.engineLoad,self.speed)


conn = OBD(portstr='/dev/ttyUSB0',baudrate=38400,fast=False)
with open('/home/stephen/loggeddata.csv', 'w', newline='') as csvfile:
    if conn.status() == OBDStatus.CAR_CONNECTED:
        print(conn.status())
        try:
            while True:
                reading = []
                print('reading reset')
                reading.append(OBDReading(conn))
                if not reading[0].moving:
                    reading.append(OBDReading(conn))
                    if reading[1].moving:
                        print('{},{}'.format(reading[0].moving, reading[0].speed))
                        print('{},{}'.format(reading[1].moving, reading[1].speed))
                        print('beginlogging')
                        for _ in range(0,10):
Example #14
0
# Blink display led 5 times to show device has started
# led will blink at 2500ms intervals while data is uploaded
# to firebase
led = LED(17)
led.off()
for i in range(0, 4):
    led.on()
    sleep(.5)
    led.off()
    sleep(.5)

# Connect to Car ECU
ecuAttempt = 1
try:
    f.write('Attempting Connection to OBD \n')
    connection = OBD()
    f.write(str(connection) + '\n')
except:
    sleep(.25)
    f.write("Connection to ECU #:{} unsuccsesfull, retrying...\n".format(
        str(ecuAttempt)))
    ecuAttempt += 1
    break

# Fetch the service account key for firebase from JSON file contents & initilize
cred = credentials.Certificate('OBDII.json')

initialize_app(
    cred, {'databaseURL': 'https://obdiidata.firebaseio.com/'})

ref = db.reference('/')
Example #15
0
class OBD2(Thread):
    """
    OBD2 Class
    """
    def __init__(self, *args, **kwargs):
        super().__init__()
        self.passkey = kwargs['passkey']
        self.baud = kwargs['baud']
        self.protocol = kwargs['protocol']
        self.vef = kwargs['vef']
        self.eds = kwargs['eds']
        self.parent = kwargs['parent']
        self.port = None
        self.path = os.getcwd() + "/configs/pids.ini"
        self.config = ConfigObj(self.path)
        self.plottime = float(kwargs['time'])
        self.connection = None
        self.mai = 28.97  # Молекуляная масса воздуха
        self.rgas = 8.314  # Газовая постоянная
        self.d_gasoline = 750  # Плотность бензина (АИ-95)
        self.daemon = True
        self.pids = {}
        mypids = list(self.config['PIDS'].sections)
        for pid in mypids:
            gtype = self.config['PIDS'][pid]['type']
            if gtype == 'graph':
                try:
                    color = list(self.config['PIDS'][pid]['color'])
                except:
                    color = [1, 1, 1, 1]
                gauge = GaugeGraph(name=self.config['PIDS'][pid]['name'],
                                   color=color,
                                   grid=True,
                                   gtype=gtype,
                                   parent=self)
                self.pids[pid] = {
                    'values': [],
                    'name': self.config['PIDS'][pid]['name'],
                    'gauge': gauge
                }
            elif gtype == 'label':
                try:
                    color = list(self.config['PIDS'][pid]['color'])
                except:
                    color = [1, 1, 1, 1]
                gauge = GaugeLabel(name=self.config['PIDS'][pid]['name'],
                                   color=color,
                                   gtype=gtype,
                                   parent=self)
                self.pids[pid] = {
                    'value': 0,
                    'name': self.config['PIDS'][pid]['name'],
                    'gauge': gauge
                }

        self.start()
        self._stop_event = Event()

    def init_bt(self):
        """
        Connect to OBDII bt device
        """
        devices = bluetooth.discover_devices(duration=4,
                                             lookup_names=True,
                                             flush_cache=True,
                                             lookup_class=False)
        print(devices)
        for device in devices:
            if device[1] == 'OBDII':
                addr = device[0]
                subprocess.call("kill -9 `pidof bluetooth-agent`", shell=True)
                port = 1
                status = subprocess.call("bluetooth-agent " + self.passkey +
                                         " &",
                                         shell=True)
                try:
                    self.port = bluetooth.BluetoothSocket(bluetooth.RFCOMM)
                    self.port.connect((addr, port))
                except bluetooth.btcommon.BluetoothError as err:
                    print('Bluetooth couldn\'t connect due to error: \n')
                    print(err)
                    pass

    def run(self):
        """
        Main class function
        :return:
        """
        while True:
            if self.connection:
                if not self.connection.status() == OBDStatus.CAR_CONNECTED:
                    self.connection = OBD(self.port, self.baud, self.protocol)
                elif self.connection.status() == OBDStatus.CAR_CONNECTED:
                    self.get_all_pids()
            else:
                self.init_bt()
                self.connection = OBD(self.port, self.baud, self.protocol)

    def get_pid(self, pid):
        """
        Get data for specific PID
        :param pid:
        :return:
        """
        if self.connection.status() == OBDStatus.CAR_CONNECTED:
            cmd = commands[pid]
            response = self.connection.query(cmd)
            if response == "":
                return None
            else:
                res = response.value.magnitude
            return res
        else:
            print("Not connected to OBD2")
            return None

    def get_all_pids(self):
        """
        Get data from all pids from internal list
        :return:
        """
        for pid in self.pids.keys():
            val = self.get_pid(pid)
            gtype = self.pids[pid]['gauge'].gtype
            if gtype == 'graph':
                values_list = self.pids[pid]['values']
                values_list.append(val)
                self.pids[pid]['values'] = values_list[-49:]
            if gtype == 'label':
                self.pids[pid]['value'] = val
            self.pids[pid]['gauge'].update()
            sleep(self.plottime)

    def fuel_consumption(self):
        """
        Calculates fuel consumption based on MAP sensor
        :return:
        """
        rpm = int(self.get_pid("RPM"))
        intake_temp = celsius_to_kelvin(self.get_pid("INTAKE_TEMP"))
        intake_pressure = self.get_pid("INTAKE_PRESSURE")
        speed = self.get_pid("SPEED")
        if speed > 0:
            if (rpm != -999) and (intake_temp != -999) and (intake_pressure !=
                                                            -999):
                vfl = ((((((rpm * intake_pressure / (intake_temp * 2)) / 60) *
                          (self.vef / 100) * self.eds * self.mai / self.rgas) /
                         14.7) / self.d_gasoline) * 3600) * 100 / speed
            else:
                vfl = 0
            units = "LPK"
        else:
            if (rpm != -999) and (intake_temp != -999) and (intake_pressure !=
                                                            -999):
                vfl = (((((rpm * intake_pressure / (intake_temp * 2)) / 60) *
                         (self.vef / 100) * self.eds * self.mai / self.rgas) /
                        14.7) / self.d_gasoline) * 3600
            else:
                vfl = 0
            units = "LPH"
        return (vfl, units)

    def get_available_pids(self):
        """
        Get a list of available PIDS
        :return:
        """
        for command in self.connection.supported_commands:
            try:
                response = self.connection.query(command)
                print("PID : " + str(command) + " ->  " + str(response.value))
                sleep(self.plottime)
            except:
                print("PID : " + str(command) + "said OOPS!")

    def get_errors(self):
        """
        Get the current errors list
        :return:
        """
        try:
            cmd = commands["GET_DTC"]
            response = self.connection.query(cmd)
            if response == "":
                res = "None"
            else:
                res = response.value
            return res
        except Exception as exceptn:
            return exceptn

    def clear_errors(self):
        """
        Clear errors
        :return:
        """
        try:
            cmd = commands["CLEAR_DTC"]
            self.connection.query(cmd)
            return None
        except Exception as exceptn:
            return exceptn
Example #16
0
from obd import OBD

# Create the OBD object - we will leave the port blank so the app will run a port scan and let us know which port
# the OBD connector will be plugged into.  This will be different on each device so this may help debug some initial
# issues when running on the pi for the first time

conn = OBD(portstr=None, baudrate=None, protocol=None, fast=True)