示例#1
0
    def run(self):
        ports = obd.scan_serial()
        print(ports)

        # Enable ECU debugging to show more information from ECU
        obd.logger.setLevel(obd.logging.DEBUG)

        # Connects to the ECU
        ecuConnection = obd.Async("dev/rfcomm1")

        # ECU watchers to detect new values for the setters
        ecuConnection.watch(obd.commands.ENGINE_LOAD,
                            callback=self.getVehicleEngineLoad)

        ecuConnection.watch(obd.commands.THROTTLE_POS,
                            callback=self.getVehicleThrottlePos)

        ecuConnection.watch(obd.commands.MAF, callback=self.getVehicleMAF)

        ecuConnection.watch(obd.commands.SPEED, callback=self.getVehicleSpeed)

        ecuConnection.watch(obd.commands.COOLANT_TEMP,
                            callback=self.getVehicleCoolantTemp)

        ecuConnection.watch(obd.commands.GET_DTC, callback=self.new_dtc)

        ecuConnection.watch(obd.commands.RPM, callback=self.getVehicleRPM)

        ecuConnection.watch(obd.commands.INTAKE_TEMP,
                            callback=self.getVehicleIntakeTemp)

        # Starts the connection to the ECU
        ecuConnection.start()
        # Set ECU Flag to True
        config.ecuFlag = True
示例#2
0
    def __init__(self):
        # obd.logger.setLevel(obd.logging.DEBUG)
        self.fake_speed = 10  # For testing only
        self.up = True  # For testing only

        try:
            self.connection = obd.Async()  # auto-connects to USB or RF port
            self.connection.watch(
                obd.commands.SPEED)  # Watch the speed value from OBD2
            self.connection.start()
            print("Successfully connected to car")

        except:
            try:
                # Try connecting a slightly less automatic way
                self.ports = obd.scan_serial(
                )  # return list of valid USB or RF ports
                print(self.ports)  # ['/dev/ttyUSB0', '/dev/ttyUSB1']
                self.connection = obd.Async(
                    self.ports[0])  # connect to the first port in the list
                self.connection.watch(
                    obd.commands.SPEED)  # Watch the speed value from OBD2
                self.connection.start()
                print("Successfully connected to car, attempt 2")
            except:
                print("No car found")
示例#3
0
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()))
示例#4
0
 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
示例#5
0
def main():
    #obd.logger.setLevel(obd.logging.DEBUG) # enables all debug information

    ports = obd.scan_serial()  # return list of valid USB or RF ports
    log("Ports:" + str(ports))
    log(sys.argv[1])
    connection = obd.Async(portstr=sys.argv[1],
                           baudrate=38400,
                           protocol=None,
                           fast=False)
    speed = obd.commands['SPEED']
    rpm = obd.commands['RPM']
    log("-Connection status" + connection.status())
    log("-Protocol id/name:" + connection.protocol_id() + "/" +
        connection.protocol_name())
    log("-Port:" + connection.port_name())
    log("-ELM voltage:" + str(obd.commands['ELM_VERSION']))
    log("-ELM voltage:" + str(obd.commands['ELM_VOLTAGE']))
    log("-Support speed:" + str(connection.supports(speed)))
    log("-Support RPM:" + str(connection.supports(rpm)))
    log("-Internal cmd speed:" + str(obd.commands.has_command(speed)))
    log("-Internal cmd rpm:" + str(obd.commands.has_command(rpm)))

    connection.watch(speed, callback=new_speed, force=False)
    connection.watch(rpm, callback=new_rpm, force=False)

    connection.start()
    while 1:
        if not connection.is_connected():
            connection.stop()
            unwatch_all()
            connection.close()
            sys.exit("Python script stopped")
        time.sleep(0.3)
示例#6
0
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()
示例#7
0
    def run(self):
        global connection
        ports = obd.scan_serial()
        print(ports)
        # DEBUG: Set debug logging so we can see everything that is happening.
        obd.logger.setLevel(obd.logging.DEBUG)

        # Connect to the ECU.
        connection = obd.Async("/dev/ttyUSB0", 115200, "3", fast=False)
        # Watch everything we care about.
        connection.watch(obd.commands.SPEED, callback=self.new_speed)
        connection.watch(obd.commands.COOLANT_TEMP,\
        callback=self.new_coolant_temp)
        connection.watch(obd.commands.INTAKE_TEMP,\
        callback=self.new_intake_temp)
        connection.watch(obd.commands.MAF, callback=self.new_MAF)
        connection.watch(obd.commands.THROTTLE_POS,\
        callback=self.new_throttle_position)
        connection.watch(obd.commands.ENGINE_LOAD,\
        callback=self.new_engine_load)

        # Start the connection.
        connection.start()

        # Set the ready flag so we can boot the GUI.
        config.ecuReady = True
 def __process_obd(self, protocol, interval):
     """
     Connect to OBDII adapter
     """
     while self.__is_use_obd_port:
         try:
             ports = obd.scan_serial()
             connection = obd.OBD(ports[0], protocol=protocol)
             print('OBD connection status:', connection.status())
             break
         except Exception as e:
             time.sleep(10)
     """
     Update process
     """
     try:
         last_get_time = time.time()
         while True:
             now_time = time.time()
             if (now_time - last_get_time) >= interval:
                 if self.__is_use_obd_port:
                     """
                     Get OBD data
                     """
                     try:
                         self.temp.value = int(
                             connection.query(
                                 obd.commands.COOLANT_TEMP).value.magnitude)
                         self.speed.value = int(
                             connection.query(
                                 obd.commands.SPEED).value.magnitude)
                         self.rpm.value = float(
                             connection.query(
                                 obd.commands.RPM).value.magnitude)
                     except Exception as e:
                         pass
                 # store time
                 last_get_time = now_time
             time.sleep(interval / 10.0)
     except KeyboardInterrupt:
         pass
     except Exception as e:
         import traceback
         traceback.print_exc()
     finally:
         if self.__is_use_obd_port:
             connection.close()
     return
示例#9
0
def main(filename='~/SuperbPi/logs/log00.csv'):
    import os
    import obd
    import time
    from obd import OBD, Async, commands, Unit, OBDStatus
    print('Logging to file: \t', filename)
    ports = obd.scan_serial()
    print("Ports avail:\t", ports)
    if (len(ports) > 0):
        print(ports[0])
        #Default speed set for Freematics OBDII to UART Android v1.
        with obd.Async(ports[0], 115200, None, False, 4) as connection:
            connection.watch(obd.commands.RPM)
            connection.watch(obd.commands.SPEED)
            connection.watch(obd.commands.TIMING_ADVANCE)
            connection.watch(obd.commands.COOLANT_TEMP)
            connection.watch(obd.commands.ENGINE_LOAD)
            connection.watch(obd.commands.LONG_FUEL_TRIM_1)
            connection.watch(obd.commands.SHORT_FUEL_TRIM_1)
            connection.watch(obd.commands.INTAKE_PRESSURE)

            #Start connection and let the games begin...
            connection.start()

            with open(filename, 'a') as file:
                ecua = connection.query(obd.commands.RPM)
                ecub = connection.query(obd.commands.SPEED)
                ecuc = connection.query(obd.commands.TIMING_ADVANCE)
                ecud = connection.query(obd.commands.COOLANT_TEMP)
                ecue = connection.query(obd.commands.ENGINE_LOAD)
                ecuf = connection.query(obd.commands.LONG_FUEL_TRIM_1)
                ecug = connection.query(obd.commands.SHORT_FUEL_TRIM_1)
                ecuh = connection.query(obd.commands.INTAKE_PRESSURE)
                ecui = ""
                ecuj = ""
                ecuk = ""
                ecul = ""
                file.write('\n%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s' %
                           (ecua, ecub, ecuc, ecud, ecue, ecuf, ecug, ecuh,
                            ecui, ecuj, ecuk, ecul))

                #d = integer, f=float, s=string, b=boolean/binary

            time.sleep(120)
            connection.stop()
    else:
        print("F****d op")
示例#10
0
def main():
    # define On Board Diagnostics

    ports = obd.scan_serial()
    connection = obd.OBD(ports[0], baudrate=115200)

    client = MongoClient()
    db = client.selfdrivingcar

    while (True):

	cmd1    = obd.commands.RPM
	cmd2    = obd.commands.THROTTLE_POS
	cmd3    = obd.commands.ENGINE_LOAD
        cmd4    = obd.commands.SPEED

	response1 = connection.query(cmd1)
	response2 = connection.query(cmd2)
	response3 = connection.query(cmd3)
	response4 = connection.query(cmd4)

        print(response1)
        print(response2)
        print(response3)
        print(response4)

        ts = time.time()
	st = datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S')

	result = db.selfdrivingcar.insert_one({
                "drivingparams": {
                    "timestamp": st,
                    "RPM": str(response1.value),
                    "THROTTLE_POS": str(response2.value),
                    "ENGINE_LOAD": str(response3.value),
                    "SPEED": str(response4.value)
                }
            }
	)

	print(st + ' ' + str(result))


    # Release everything if job is finished
    cap.release()
    out.release()
    cv2.destroyAllWindows()
    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 get_obd_connection(fast: bool, timeout: float) -> obd.OBD:
    """
    return an OBD connection instance that connects to the first ELM 327 compatible device
    connected to any of the local serial ports.  If no device found, exit program with error code 1.
    """
    ports = sorted(obd.scan_serial())

    logging.info(f"identified ports {ports}")

    for port in ports:
        logging.info(f"connecting to port {port}")

        try:

            # OBD(portstr=None, baudrate=None, protocol=None, fast=True, timeout=0.1, check_voltage=True)
            connection = obd.OBD(portstr=port, fast=fast, timeout=timeout)
            for t in range(1, CONNECTION_RETRY_COUNT):

                if connection.is_connected():
                    logging.info(
                        f"connected to {port} on try {t} of {CONNECTION_RETRY_COUNT}"
                    )
                    custom_commands = load_custom_commands(connection)
                    return connection

                if connection.status() == obd.OBDStatus.NOT_CONNECTED:
                    logging.warn(
                        f"ELM 327 Adapter Not Found on {port}on try {t} of {CONNECTION_RETRY_COUNT}"
                    )
                    break

                logging.info(
                    f"Waiting for OBD Connection on {port} on try {t} of {CONNECTION_RETRY_COUNT}: {connection.status()}"
                )

                sleep(CONNECTION_WAIT_DELAY)

        except Exception as e:
            logging.exception(
                f"OBD Connection on port {port} unavailable.  Exception: {e}")

    logging.info(f"ELM 327 type device not found in devices: {ports}")
    logging.info("exiting...")

    exit(1)
示例#13
0
    def run(self):
        global ecuReady
        global connection

        ports = obd.scan_serial()
        print ports

        # DEBUG: Set debug logging so we can see everything that is happening.
        obd.logger.setLevel(obd.logging.DEBUG)

        # Connect to the ECU.
        if piTFT:
            connection = obd.Async("/dev/ttyUSB0", 115200, "3", fast=False)
        else:
            connection = obd.Async("/dev/rfcomm0")

        # Watch everything we care about.
        connection.watch(obd.commands.ELM_VOLTAGE,
                         callback=self.new_elm_voltage)
        connection.watch(obd.commands.ELM_VERSION,
                         callback=self.new_elm_version)
        connection.watch(obd.commands.AMBIANT_AIR_TEMP,
                         callback=self.new_ambiant_air_temp)
        connection.watch(obd.commands.OIL_TEMP, callback=self.new_oil_temp)
        connection.watch(obd.commands.FUEL_LEVEL, callback=self.new_fuel_level)
        connection.watch(obd.commands.RPM, callback=self.new_rpm)
        connection.watch(obd.commands.SPEED, callback=self.new_speed)
        connection.watch(obd.commands.COOLANT_TEMP,
                         callback=self.new_coolant_temp)
        connection.watch(obd.commands.INTAKE_TEMP,
                         callback=self.new_intake_temp)
        connection.watch(obd.commands.MAF, callback=self.new_MAF)
        connection.watch(obd.commands.THROTTLE_POS,
                         callback=self.new_throttle_position)
        #connection.watch(obd.commands.TIMING_ADVANCE, callback=self.new_timing_advance)
        connection.watch(obd.commands.ENGINE_LOAD,
                         callback=self.new_engine_load)
        connection.watch(obd.commands.GET_DTC, callback=self.new_dtc)

        # Start the connection.
        connection.start()

        # Set the ready flag so we can boot the GUI.
        ecuReady = True
示例#14
0
    def connect_odb(self):
        # TODO: Add some sort of loading signal
        ports = obd.scan_serial()
        for port in ports:

            passes = True
            try:
                self.connection = obd.OBD(port)
            except serial.serialutil.SerialException:
                passes = False

            if passes:
                break

        if self.connection is not None and self.connection.is_connected():
            self.add_obd_widgets()
        else:
            print("Failed to find OBD2 device! Retrying in 10 seconds")
            self.controller.after(10000, self.connect_odb)
示例#15
0
def main():

    ports = obd.scan_serial()  # return list of valid USB or RF ports

    # print(ports)  # ['/dev/ttyUSB0', '/dev/ttyUSB1']
    # connection = obd.OBD(ports[0])

    count = 0
    for port in ports:
        count = count + 1
        print("[%s] " % count + port)

    if count == 0:
        print("No ports")
        return

    while True and count > 0:
        selection = input("Select OBD port: ")
        if int(selection) > count:
            print("Wrong selection.")
            continue
        obd_port = ports[int(selection - 1)]

        print("Selected port: %s " % obd_port)
        break

    connection = obd.Async(obd_port)  # same constructor as 'obd.OBD()'

    callback_fun = closure('./output.txt')

    connection.watch(obd.commands.RPM,
                     callback=callback_fun)  # keep track of the RPM
    connection.watch(obd.commands.SPEED,
                     callback=callback_fun)  # keep track of the RPM
    try:
        connection.start()  # start the async update loop
    except KeyboardInterrupt:
        pass
    finally:
        connection.close()
示例#16
0
 def _initialize(self):
     '''
     Initialize connection and log file
     '''
     no_ports = True
     while no_ports:
         ports = obd.scan_serial()
         if ports:
             no_ports = False
             try:
                 self.connection = obd.OBD()
                 keep_commands = set(self.connection.supported_commands)
                 for i in self.connection.supported_commands:
                     try:
                         if i.mode != 1:  # keep only mode 1 commands
                             keep_commands.remove(i)
                             print(
                                 "Removing command list index {}".format(i))
                     except ValueError as error:
                         print(
                             "while pruning supported command list, got: {}"
                             .format(error))
                         keep_commands.remove(i)
                 self.connection.supported_commands = set(keep_commands)
                 self.connection.print_commands()  # all supported commands
                 if len(self.connection.supported_commands) == 0:
                     print(
                         "Error - OBD interface claims there are no supported commands"
                     )
                     self.connection.close()
                     no_ports = True
                     time.sleep(5.0)  # try again
             except obd.utils.serial.SerialException:
                 print("Error - serial connection received nothing")
                 sys.exit(-1)
         else:
             print("no ports yet, waiting ...")
             time.sleep(5.0)
     self.log_file = open("./log." + str(self.log_count), "w")
示例#17
0
    def run(self):
        global connection
        # For depugging purposes(shows everything will happend during connection)
        obd.logger.setLevel(obd.logging.DEBUG)
        # Scan for available ports
        ports = obd.scan_serial()
        if (len(ports) > 0):
            #creat connection object with specified properties
            connection = obd.Async(portstr=ports[0], fast=False)
        else:
            print("There is no available serial ports")
            return 0

        # The car parameters that wanted to be monitored
        connection.watch(obd.commands.RPM, callback=self.new_rpm)
        connection.watch(obd.commands.SPEED, callback=self.new_speed)
        connection.watch(obd.commands.INTAKE_TEMP,
                         callback=self.new_intake_temp)
        connection.watch(obd.commands.COOLANT_TEMP,
                         callback=self.new_coolant_temp)
        connection.watch(obd.commands.OIL_TEMP, callback=self.new_oil_temp)
        connection.watch(obd.commands.AMBIANT_AIR_TEMP,
                         callback=self.new_ambiant_temp)
        #connection.watch(obd.commands.DISTANCE_SINCE_DTC_CLEAR, callback = self.new_distance)
        connection.watch(obd.commands.ENGINE_LOAD,
                         callback=self.new_engine_load)
        connection.watch(obd.commands.FUEL_RATE, callback=self.new_fuel_rate)
        connection.watch(obd.commands.THROTTLE_POS,
                         callback=self.new_throttle_position)
        connection.watch(obd.commands.MAF, callback=self.new_MAF)
        connection.watch(obd.commands.RUN_TIME, callback=self.new_run_time)
        #connection.watch(obd.commands.MONITOR_O2_B1S1, callback = self.new_o2Sen_test)
        # The car problems or issues if there are
        connection.watch(obd.commands.GET_DTC, callback=self.new_dtc)
        # Start the Asynchronous connection(threaded updated loop to keep track the subscriped car parameters)
        connection.start()
        # setting this flag to boot GUI
        settings.ecuReady = True
示例#18
0
    def run(self):
        if (self._port == "auto"):
            print("Scanning ports")
            ports = obd.scan_serial()

            print("Found: {0}".format(ports))
            if len(ports) <= 0:
                print("trying simulator on /dev/pts/{0}".format(
                    self._simulator_port))
                self._connection = obd.OBD("/dev/pts/{0}".format(
                    self._simulator_port))
                if self._connection == "":
                    print("failed to find a connection")

                for port in ports:
                    self._connection = obd.OBD(port)
                    if self._connection.status == obd.OBDStatus.NOT_CONNECTED:
                        continue
                    else:
                        break
                if self._connection.status == obd.OBDStatus.NOT_CONNECTED:
                    print("no serial detected.")
                    exit()
                self._available_commands = self._connection.supported_commands
                for command in self._available_commands:
                    print(command)
        else:
            self._connection = obd.OBD(self._port)


# while True:

#     if mode == 1:

#         rpm = connection.query(obd.commands.RPM)
#         env_air_temp = connection.query(obd.commands.AMBIANT_AIR_TEMP)
#         print("{0}, {0}".format(rpm,env_air_temp))
def mainFunction():
  global engineStatus
  global portName
  scanPort = []
  scanPort = obd.scan_serial()
  while True:
    if inAction is False:
      connection = obd.Async(portstr=portName, fast=False, baudrate=115200, protocol="6")
      if obd.OBDStatus.CAR_CONNECTED == "Car Connected":
        dumpObd(connection, 1) 
        portName = portName
        outLog('Connected to '+portName+' successfully')
      elif obd.OBDStatus.CAR_CONNECTED != "Car Connected":
          outLog("Not connected to car yet")
          time.sleep(30)
      elif obd.OBDStatus.ELM_CONNECTED == "ELM Connected":
          outLog("Connected to ELM but not vehicle")
          time.sleep(30)
      else:
          outLog("Not connected to ELM or Car")
          time.sleep(30)
      
      while engineStatus is False:
        if inAction is False:
          connection = obd.OBD(portstr=portName, fast=False, baudrate=115200, protocol="6")
          time.sleep(2)
          outLog('Checking RPM to see if engine is running')
          checkEngineOn = connection.query(obd.commands.RPM)
          outLog('Engine RPM: '+str(checkEngineOn.value))
          if checkEngineOn.is_null():  # Check if we have an RPM value.. if not return false
            outLog('Engine is not running, checking again in 2 minutes') # HAVE TO CHECK SO LONG BECAUSE IT TURNS ON THE CAR LIGHTS BRIEFLY
            engineStatus = False
            connection.close()
            time.sleep(120)
          else:
            connection.close()
            engineStatus = True
      if engineStatus is True:
        connection = obd.Async(portstr=portName, fast=False, baudrate=115200, protocol="6")
        outLog('Engine is started. Kicking off metrics loop..')
        metricsArray = obdWatch(connection, acceptedMetrics)  # Watch all metrics
        connection.start()  # Start async calls now that we're watching PID's
        time.sleep(5)  # Wait for first metrics to come in.
        if os.path.isfile('/opt/influxback'):  # Check for backup file and push it into the queue for upload.
          outLog('Old metric data file found... Processing')
          try:
            with open('/opt/influxback') as f:
              lines = f.readlines()
            for line in lines:
              outLog('Save data found importing...')
              influxQueue.put(line)
            os.remove('/opt/influxback')  # Kill file after we've dumped them all in the backup. 
            outLog('Imported old metric data.')
          except:
            outLog('Failed while importing old queue')

        while engineStatus is True:
          metricDic = {}
          currentTime = time.time()
          for metricName in metricsArray:
            value = str(connection.query(obd.commands[metricName]))
            value = value.split(' ')
            metricDic.update({'time': currentTime})
            if value[0] is not None:
              metricDic.update({metricName: value[0]})
          print connection.query(obd.commands['RPM'])
          if connection.query(obd.commands['RPM']).is_null():  # Dump if RPM is none
            outLog("Engine has stopped. Dropping update")
            dumpObd(connection, 1)
            for metric in metricDic:
              if metric != 'time':
                metricDic.update({metric: 0})
            influxQueue.put(json.dumps(metricDic))
            engineStatus = False  # Kill while above
            if influxQueue.qsize() > 0 and networkStatus is False:
              outLog('Engine off and network down. Saving queue to file.')
              try:
                backupFile = open('/opt/influxback', 'w')
                while influxQueue.qsize() > 0:
                  backupFile.write(influxQueue.get()+"\r\n")
                  influxQueue.task_done()
              except:
                outLog('Failed writing queue to file.')
            break  # break from FOR if engine is no longer running
          else: 
            engineStatus = True  # Stay in While
          influxQueue.put(metricDic)  # Dump metrics to influx queue
          time.sleep(5)
    else:
      if engineStatus is True:
        dumpObd(connection, 1)
      outLog("Skipping metrics and engine check because an action is running")
      time.sleep(5)    
 def getPorts(self):
     ports = scan_serial()
     print(ports)
     return ports
示例#21
0
def scanDevices():
    """ Scan for connected ports """
    return obd.scan_serial()
示例#22
0
""" This program communicates with the OBD adapter present on the vehicle.
    # Add more documentation here.
"""

__author__ = "Dhruv Kool Rajamani"
__email__ = "*****@*****.**"
__copyright__ = "Copyright 2019, The VDAQ Project"
__date__ = "17 May 2019"

import obd
import numpy as np

obd.logger.setLevel(obd.logging.DEBUG)

ports = obd.scan_serial()  # return list of valid USB or RF ports

if len(ports) == 0:
    is_bluetooth_paired = False
else:
    is_bluetooth_paired = True

if is_bluetooth_paired:
    print("{} Port found, connecting to OBD Port ...".format(ports[0]))
    connection = obd.OBD(portstr=ports[0], baudrate=9600)
else:
    print("No port available on the Bluetooth Port")
示例#23
0
    connection.watch(obd.commands.RPM, callback=set_RPM)
    connection.watch(obd.commands.SPEED, callback=set_speed)
    connection.watch(obd.commands.ENGINE_LOAD, callback=set_load)
    connection.watch(obd.commands.COOLANT_TEMP, callback=set_temp)
    connection.watch(obd.commands.SHORT_FUEL_TRIM_1, callback=set_short_fuel)
    connection.watch(obd.commands.LONG_FUEL_TRIM_1, callback=set_long_fuel)
    connection.start()
    # the callback will now be fired upon receipt of new values
    connection.stop()


def test():
    while (True):
        print(str(dashboard.progress_value.get()) + '\n')
        dashboard.progress_value.set(dashboard.progress_value.get() + 1)
        dashboard.load_frame.value.set(str(dashboard.progress_value.get()))
        time.sleep(0.5)


print(obd.scan_serial())

t = threading.Thread(target=connection_thread, name='thread-connection')
t.setDaemon(True)
t.start()

test = threading.Thread(target=test, name='thread-test')
test.setDaemon(True)
test.start()

dashboard.start()
示例#24
0
def serial_port():
    return obd.scan_serial()
示例#25
0
def main():
    # define On Board Diagnostics
    ports = obd.scan_serial()
    connection = obd.OBD(ports[0], baudrate=115200)

    # define camera capture
    cap = cv2.VideoCapture(0)

    #fourcc = cv2.VideoWriter_fourcc(*'XVID')
    #out = cv2.VideoWriter('output.avi', fourcc, 20.0, (640,480))

    out = cv2.VideoWriter('../data/output.avi', -1, 20.0, (640, 480))
    #out = cv2.VideoWriter('..\data\output.avi', -1, 20.0, (640,480))

    # define mongodb database

    client = MongoClient()
    db = client.selfdrivingcar

    # main loop

    #while (cap.isOpened()):
    while (True):
        cmd1 = obd.commands.RPM
        cmd2 = obd.commands.THROTTLE_POS
        cmd3 = obd.commands.ENGINE_LOAD
        cmd4 = obd.commands.SPEED

        response1 = connection.query(cmd1)
        response2 = connection.query(cmd2)
        response3 = connection.query(cmd3)
        response4 = connection.query(cmd4)

        ts = time.time()
        st = datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S')

        result = db.selfdriving.insert_one({
            "drivingparams": {
                "date": st,
                "RPM": str(response1.value),
                "THROTTLE_POS": str(response2.value),
                "ENGINE_LOAD": str(response3.value),
                "SPEED": str(response4.value)
            }
        })

        ret, frame = cap.read()

        frame = cv2.flip(frame, 0)

        # write the flipped frame
        #cv2.imshow('frame',frame)

        out.write(frame)

        print("Getting data for time " + st)

    # Release everything if job is finished
    cap.release()
    out.release()
    cv2.destroyAllWindows()
def mainFunction():
  global engineStatus
  global portName
  scanPort = []
  scanPort = obd.scan_serial()
  while True:
    try:
      if debugOn is True:
        portName = '/dev/pts/21'
        connection = obd.Async(portName)
      else:
        while len(scanPort) == 0:
          outLog('No valid device found. Please ensure ELM327 is connected and on. Looping with 5 seconds pause')
          scanPort = obd.scan_serial()
          time.sleep(2)
        outLog("here")
        tempPortName = scanPort[0]
      portName = scanPort[0] 
      outLog('Connected to '+portName+' successfully')
      connection = obd.Async(portName)  # Auto connect to obd device
      connection.watch(obd.commands.RPM)
      connection.start()
      time.sleep(5)
    
      while engineStatus is False:
        outLog('Watching RPM to see if engine is running')
        checkEngineOn = connection.query(obd.commands.RPM)
        if checkEngineOn.is_null():  # Check if we have an RPM value.. if not return false
          outLog('Engine is not running, checking again')
          engineStatus = False
          time.sleep(5)
        else:
          dumpObd(connection, 1)
          connection = obd.Async(portName)
          outLog('Engine is started. Kicking off metrics loop..')
          metricsArray = obdWatch(connection, acceptedMetrics)  # Watch all metrics
          connection.start()  # Start async calls now that we're watching PID's
          time.sleep(5)  # Wait for first metrics to come in.
          if os.path.isfile('/opt/influxback'):  # Check for backup file and push it into the queue for upload.
            outLog('Old metric data file found... Processing')
            try:
              with open('/opt/influxback') as f:
                lines = f.readlines()
              for line in lines:
                outLog('Save data found importing...')
                influxQueue.put(line)
              os.remove('/opt/influxback')  # Kill file after we've dumped them all in the backup. 
              outLog('Imported old metric data.')
            except:
              outLog('Failed while importing old queue')
          engineStatus = True
          break
  
        while engineStatus is True:
          try:
            metricDic = {}
            currentTime = time.time()
            for metricName in metricsArray:
              value = connection.query(obd.commands[metricName])
              metricDic.update({'time': currentTime})
              # Skip empty values pulled by obd
              if value.value is not None:
                metricDic.update({metricName: value.value})
            if metricDic.get('RPM') is None:  # Dump if RPM is none
              outLog("Engine has stopped. Dropping update")
              dumpObd(connection, 1)
              if influxQueue.qsize() > 0 and networkStatus is False:
                outLog('Engine off and network down. Saving queue to file.')
                try:
                  backupFile = open('/opt/influxback', 'w')
                  while influxQueue.qsize() > 0:
                    backupFile.write(influxQueue.get()+"\r\n")
                    influxQueue.task_done()
                except:
                  outLog('Failed writing queue to file.')
              break  # break from FOR if engine is no longer running
          except:
            outLog("Something happened while pulling metrics.. skipping this run")
          engineStatus = False  # Kill while above
          dumpObd(connection, 1)
          influxQueue.put(metricDic)  # Dump metrics to influx queue
          time.sleep(5)
    except:
      outLog("ERROR: There was an issue with the main loop")
    time.sleep(0.25)
示例#27
0
 def init_obd_connection(self, serial_connection_id):
     if obd.scan_serial():
         if serial_connection_id in obd.scan_serial():
             self.obd_connection = obd.OBD(serial_connection_id)
示例#28
0
import obd  # Potrzebne biblioteki

DISPLAY_PERIOD = 100  # Czas wyświetlania
TIMER_PERIOD = 500  # Zmienna pomocnicza

SERIAL_PORT_NAME = "COM3"  # Ustawienie zmiennej nazwy portu, który chcięlibyśmy, żeby był wybrany
SERIAL_PORT_BAUD = 9600  # Liczba bitów na sekundę w przesyle komunikacji
SERIAL_PORT_TIME_OUT = 60  # Czas, po którym nastąpi poddanie się

ELM_CONNECT_SETTLE_PERIOD = 5  # Czasy do ponownego połączenia
ELM_CONNECT_TRY_COUNT = 5  # Ilość prób do połączenia, póki nie będzie katastrofalnego błędu i nie spali się wszystko

connection = obd.OBD()  # auto connect

ports = obd.scan_serial()  # Próba automatycznego skanowania portu
print(ports)  # Wylistowanie wszystkie porty szeregowe
connection = obd.OBD(ports[0])

if obd.OBD(ports[0]) == SERIAL_PORT_NAME:
    connection == SERIAL_PORT_NAME
else:
    print('Prawdopodonie nie ten port co trzeba :(')

# Czas na wyświetlanie statusów
from obd import OBDStatus

if OBDStatus.NOT_CONNECTED == True:  # Czy jest jakiekolwiek połączenie
    print("Jest polaczenie\n")
else:
    print("NIE MA polaczenia\n")
示例#29
0
def getRefDistance():
    ports = obd.scan_serial()
    connection = obd.OBD(ports[0])
    r = connection.query(obd.commands.DISTANCE_SINCE_DTC_CLEAR)
    settings.refDistance = round(r.value.magnitude, 2)
    connection.close()
示例#30
0
import obd
import time
import json
import serial
import re
from iothub_client import IoTHubClient, IoTHubTransportProvider, IoTHubMessage
# Azure IoT Hub
CONNECTION_STRING = "HostName=OBDLOG.azure-devices.net;DeviceId=RPi1;SharedAccessKey=/uGkNvfJAs//p+57idGGWKGJOY+t8HmfuUQFvda8RhU="
PROTOCOL = IoTHubTransportProvider.MQTT

# confirmation callback
def send_confirmation_callback(message, result, user_context):
    print("Confirmation received for message with result = %s" % (result))

client = IoTHubClient(CONNECTION_STRING, PROTOCOL)
# OBD serial port
devices = obd.scan_serial()
# GPS serial port
gps_ser = serial.Serial("/dev/ttyS0", 115200)
gps_buff = ["AT+CGNSPWR=1\r\n", "AT+CGNSSEQ=\"RMC\"\r\n", "AT+CGNSINF\r\n"]
# Object for JSON.stringify()
prejsonValues = {}
# connect to vehicle
try:
    connection = obd.OBD(devices[0])
    pids = connection.supported_commands
    print(str(devices[0]))
except Exception as ELM_missing:
    print("Chyba pripojenia k vozidlu: " + str(ELM_missing))
    exit()
示例#31
0
文件: blue.py 项目: n8fr8/NTCOBD
#otherwise, setup the rfcomm0 serial device
else:
    getdata = False;
    print '-- begin serial device setup --'
    cmd = 'sudo rfcomm connect hci0 '.split()
    cmd.append(mac)
    subprocess.Popen(cmd)
    ports = []
    cmds_list = []
    trycount = 0
    trymax = 15
    while trycount<trymax:
        print("-- Looking for a serial port, attempt: "+str(trycount))
        time.sleep(.1)
        ports = obd.scan_serial()
        trycount = trycount + 1
        if ports:
            trycount = trymax
    if ports:
        connection = obd.OBD("/dev/rfcomm0")
        getdata = (connection.status() == 'Car Connected')
        print('connection to Car: '+str(getdata))
        if connection:
            print('protocol: '+connection.protocol_name())
            print('supported commands:')
            cmds_text = open("obd_commands.txt", "w")
            for command in connection.supported_commands:
                print(command.name)
                cmds_text.write('{0}\n'.format(command.name) )
                cmds_list.append(command.name)
示例#32
0
import obd

ports = obd.scan_serial()

print(ports)
obd.logger.setLevel(obd.logging.DEBUG)
#connection = obd.OBD(portstr=ports[0], baudrate=10400, fast=False)
connection = obd.OBD('/dev/rfcomm0', baudrate=10400, fast=False)
示例#33
0
import obd
import csv
from datetime import datetime
import time

# obd.logger.setLevel(obd.logging.DEBUG) # Enables Debugger
try:
	print("Connecting with ODB Serial/COM")
	a= obd.scan_serial()
	connection = obd.OBD(a[0],baudrate=10400, fast=False) #Connecting with Serial/COM
except Exception as e:
	print(e)
spd = obd.commands.SPEED
rpm = obd.commands.RPM
thr = obd.commands.THROTTLE_POS
i=0

with open('speed.csv', 'w', newline='') as file:
	writer = csv.writer(file)
	writer.writerow(["Time", "Speed","RPM","Throttle"])
	while(i<100):	
		#speed
		speed = connection.query(spd)
		speed_value=float(speed.replace(' kph', ''))
		#rpms
		rpms  = connection.query(rpm)
		rpms_value =float(rpms.replace(' revolutions_per_minute', ''))
		#throttle
		thrr  = connection.query(thr)
		thrr_value =float(rpms.replace(' percent', ''))
		if(response != None):