Пример #1
0
class Info(object):
    def __init__(self, port, baudrate, reconnattempts, sertimeout, lazy):
        self.connector = None

        self.port = port
        self.baudrate = baudrate
        self.reconnattempts = reconnattempts
        self.sertimeout = sertimeout
        self.lazy = lazy

        self.commands = [
            '0100',  # PIDs supported [01 - 20]  n: 0
            '0120',  # PIDs supported [21 - 40]  n: 20
            '0140',  # PIDs supported [41 - 60]  n: 40
            '0160',  # PIDs supported [61 - 80]  n: 60
            '0180',  # PIDs supported [81 - A0]  n: 80
            '01A0',  # PIDs supported [A1 - C0]  n: A0
            '01C0',  # PIDs supported [C1 - E0]  n: C0
            '050100',  # OBD Monitor IDs supported ($01 – $20)
            '0900',  # mode 9 supported PIDs 01 to 20  n: 0
        ]

    def add_hex(self, n1, n2):
        integer = int('0x' + n1, 16) + int('0x' + n2, 16)
        hexa = hex(integer).upper()[2:]
        return hexa

    def check_supported_pids(self, answer, command):
        n = command[2:]
        mode = command[:2]

        hexa = ''
        for s in answer:
            hexa += hex_to_bin(s)

        pids = [
            '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D',
            'E', 'F', '10', '11', '12', '13', '14', '15', '16', '17', '18',
            '19', '1A', '1B', '1C', '1D', '1E', '1F', '20'
        ]

        supported_pids = []
        for i, bit in enumerate(hexa):
            if bit == '1':
                pid = self.add_hex(n, pids[i])
                if len(pid) == 1:
                    pid = '0' + pid
                supported_pids.append(mode + pid)

        return supported_pids

    def connect(self):
        self.connector = OBDConnector(self.port, self.baudrate,
                                      self.reconnattempts, self.sertimeout)
        logging.info('Connecting...')
        success = self.connector.initCommunication()
        if success != 1:
            logging.error('Connection error...')
            sys.exit(1)
        logging.info('Connected')

    def get_supported_pids(self):
        if self.connector is None:
            logging.error('You should connect to the port first.')
            sys.exit(1)

        supported_pids = []

        # check which commands are supported by this car
        for command in self.commands:
            result, validation = self.connector.run_OBD_command(command)
            if validation == 'Y':
                value, unit = decode_answer(command, result)
                supported_pids += self.check_supported_pids(value, command)

        return supported_pids

    def run(self):
        if self.connector is None:
            logging.error('You should connect to the port first.')
            sys.exit(1)

        print('INFORMATION FETCHED FROM THE CAR')
        print('--------------------------------\n\n')

        supported_pids = self.get_supported_pids()

        # use the supported commands to get some info
        for command in supported_pids:
            # do not run check (supported pids) commands
            if command in self.commands:
                continue

            result, validation = self.connector.run_OBD_command(command)
            if validation == 'Y':
                if self.lazy:
                    value, unit = decode_answer(command, result)
                    print(
                        'Command: {0}\nDescription: {1}\nValue: {2}\nUnit: {3}\n\n'
                        .format(command, ELMdb[command]['description'], value,
                                unit))
                else:
                    print('Command: {0}\nResult: {1}'.format(command, result))
            else:
                logging.warning(
                    'Something wrong happened with "{0}" command'.format(
                        command))

        self.disconnect()

    def disconnect(self):
        self.connector.run_OBD_command('END')
        logging.info('Disconnected')
Пример #2
0
class ExpertMode(object):

    def __init__(self, port, baudrate, reconnattempts, sertimeout, lazy_mode):
        self.connector = None
        self.keep_going = True

        self.port = port
        self.baudrate = baudrate
        self.reconnattempts = reconnattempts
        self.sertimeout = sertimeout

        self.lazy_mode = lazy_mode

    def connect(self):
        self.connector = OBDConnector(
            self.port, self.baudrate, self.reconnattempts, self.sertimeout)
        logging.info('Connecting...')
        success = self.connector.initCommunication()
        if success != 1:
            logging.error('Connection error...')
            sys.exit(1)
        logging.info('Connected')

    def run(self):
        if self.connector is None:
            logging.error('You should connect to the port first.')
            sys.exit(1)

        logging.info('Launching Expert Mode console...')
        choice = ''
        valid_answers = ['Y', 'N']
        while choice not in valid_answers:
            choice = raw_input(MSG_WARNING)
        if choice.upper() == 'Y':
            logging.warning(MSG_DISCLAIMER)
            print('Type "quit" or CTRL-C to exit')

            while self.keep_going is True:
                try:
                    user_command = raw_input('ROOT@KT-OBD> ').upper()
                    if re.search('\AAT', user_command):
                        print('Wrong command, ELM configuration is not '
                              'allowed')
                    elif re.search('QUIT', user_command):
                        raise KeyboardInterrupt
                    elif user_command == '':
                        pass
                    else:
                        result, validation = self.connector.run_OBD_command(
                            user_command, expert=True)

                        if re.search('ERROR', result) or \
                                re.search('DATA', result):
                            print('ERROR: Wrong command or not supported, '
                                  'type another one')
                        elif re.search('BUSY', result):
                            print('ERROR: Bus busy, try again')
                        elif re.search('UNABLE', result):
                            print('ERROR: Communication lost, shutting '
                                  'down app!')
                            break
                        else:
                            if self.lazy_mode:
                                value, unit = decode_answer(
                                    user_command, result)
                                print('{0} {1}'.format(value, unit))
                            else:
                                print(result)
                except KeyboardInterrupt:
                        break
        logging.info('Expert mode aborted by user, finishing...')
        self.connector.run_OBD_command('END', expert=True)
Пример #3
0
class CollectData(object):

    def __init__(self, port, baudrate, reconnattempts,
                 sertimeout, logfile, commands,
                 command_attempts, interval, server):

        self.commands = commands
        self.command_attempts = command_attempts
        self.invalid_commands = {}
        self.logfile = logfile
        self.keep_going = True
        self.connector = None
        self.interval = interval
        self.server = server
        self.server_post_url = 'http://127.0.0.1:5000/post'

        self.port = port
        self.baudrate = baudrate
        self.reconnattempts = reconnattempts
        self.sertimeout = sertimeout

    def connect(self):
        self.connector = OBDConnector(
            self.port, self.baudrate, self.reconnattempts, self.sertimeout)
        logging.info('Connecting...')
        success = self.connector.initCommunication()
        if success != 1:
            logging.error('Connection error...')
            sys.exit(1)
        logging.info('Connected')

    def collect(self):
        if self.connector is None:
            logging.error('You should connect to the port first.')
            sys.exit(1)
        for i, command in enumerate(self.commands):
            if command in self.invalid_commands and \
                    self.invalid_commands[command] == self.command_attempts:
                logging.info('Skipping command "{0}" ({1}/{2})...'
                             .format(command, i, len(self.commands)))
                continue

            logging.info('Excecuting command "{0}" ({1}/{2})...'
                         .format(command, i, len(self.commands)))
            answer, valid = self.connector.run_OBD_command(command)
            timestamp = time.time()
            if valid == 'N':
                # do not call this command again after
                # "self.command_attempt" times
                if command in self.invalid_commands:
                    self.invalid_commands[command] += 1
                else:
                    self.invalid_commands[command] = 1

            with open(self.logfile, 'ab') as csvfile:
                writer = csv.writer(csvfile, delimiter=',',
                                    quoting=csv.QUOTE_ALL)
                row = (command, answer, valid, timestamp)
                writer.writerow(row)

            if self.server:
                data = json.dumps({
                        'answer': answer,
                        'command': command,
                        'timestamp': timestamp,
                        })
                requests.post(url=self.server_post_url, data=data)

    def disconnect(self):
        self.connector.run_OBD_command('END')
        logging.info('Disconnected')

    def run(self):
        while self.keep_going:
            try:
                self.collect()
                logging.info('Waiting %s seconds before continue',
                             self.interval)
                time.sleep(self.interval)
            except KeyboardInterrupt:
                self.keep_going = False
        self.disconnect()
Пример #4
0
class Info(object):

    def __init__(self, port, baudrate, reconnattempts, sertimeout, lazy):
        self.connector = None

        self.port = port
        self.baudrate = baudrate
        self.reconnattempts = reconnattempts
        self.sertimeout = sertimeout
        self.lazy = lazy

        self.commands = [
            '0100',  # PIDs supported [01 - 20]  n: 0
            '0120',  # PIDs supported [21 - 40]  n: 20
            '0140',  # PIDs supported [41 - 60]  n: 40
            '0160',  # PIDs supported [61 - 80]  n: 60
            '0180',  # PIDs supported [81 - A0]  n: 80
            '01A0',  # PIDs supported [A1 - C0]  n: A0
            '01C0',  # PIDs supported [C1 - E0]  n: C0
            '050100',  # OBD Monitor IDs supported ($01 – $20)
            '0900',  # mode 9 supported PIDs 01 to 20  n: 0
            ]

    def add_hex(self, n1, n2):
        integer = int('0x' + n1, 16) + int('0x' + n2, 16)
        hexa = hex(integer).upper()[2:]
        return hexa

    def check_supported_pids(self, answer, command):
        n = command[2:]
        mode = command[:2]

        hexa = ''
        for s in answer:
            hexa += hex_to_bin(s)

        pids = ['1', '2', '3', '4', '5', '6', '7', '8', '9', 'A',
                'B', 'C', 'D', 'E', 'F', '10', '11', '12', '13', '14',
                '15', '16', '17', '18', '19', '1A', '1B', '1C', '1D', '1E',
                '1F', '20']

        supported_pids = []
        for i, bit in enumerate(hexa):
            if bit == '1':
                pid = self.add_hex(n, pids[i])
                if len(pid) == 1:
                    pid = '0' + pid
                supported_pids.append(mode + pid)

        return supported_pids

    def connect(self):
        self.connector = OBDConnector(
            self.port, self.baudrate, self.reconnattempts, self.sertimeout)
        logging.info('Connecting...')
        success = self.connector.initCommunication()
        if success != 1:
            logging.error('Connection error...')
            sys.exit(1)
        logging.info('Connected')

    def get_supported_pids(self):
        if self.connector is None:
            logging.error('You should connect to the port first.')
            sys.exit(1)

        supported_pids = []

        # check which commands are supported by this car
        for command in self.commands:
            result, validation = self.connector.run_OBD_command(command)
            if validation == 'Y':
                value, unit = decode_answer(command, result)
                supported_pids += self.check_supported_pids(value, command)

        return supported_pids

    def run(self):
        if self.connector is None:
            logging.error('You should connect to the port first.')
            sys.exit(1)

        print('INFORMATION FETCHED FROM THE CAR')
        print('--------------------------------\n\n')

        supported_pids = self.get_supported_pids()

        # use the supported commands to get some info
        for command in supported_pids:
            # do not run check (supported pids) commands
            if command in self.commands:
                continue

            result, validation = self.connector.run_OBD_command(command)
            if validation == 'Y':
                if self.lazy:
                    value, unit = decode_answer(command, result)
                    print('Command: {0}\nDescription: {1}\nValue: {2}\nUnit: {3}\n\n'
                          .format(command, ELMdb[command]['description'], value, unit))
                else:
                    print('Command: {0}\nResult: {1}'.format(command, result))
            else:
                logging.warning('Something wrong happened with "{0}" command'
                                .format(command))

        self.disconnect()

    def disconnect(self):
        self.connector.run_OBD_command('END')
        logging.info('Disconnected')
Пример #5
0
class ExpertMode(object):
    def __init__(self, port, baudrate, reconnattempts, sertimeout, lazy_mode):
        self.connector = None
        self.keep_going = True

        self.port = port
        self.baudrate = baudrate
        self.reconnattempts = reconnattempts
        self.sertimeout = sertimeout

        self.lazy_mode = lazy_mode

    def connect(self):
        self.connector = OBDConnector(self.port, self.baudrate,
                                      self.reconnattempts, self.sertimeout)
        logging.info('Connecting...')
        success = self.connector.initCommunication()
        if success != 1:
            logging.error('Connection error...')
            sys.exit(1)
        logging.info('Connected')

    def run(self):
        if self.connector is None:
            logging.error('You should connect to the port first.')
            sys.exit(1)

        logging.info('Launching Expert Mode console...')
        choice = ''
        valid_answers = ['Y', 'N']
        while choice not in valid_answers:
            choice = raw_input(MSG_WARNING)
        if choice.upper() == 'Y':
            logging.warning(MSG_DISCLAIMER)
            print('Type "quit" or CTRL-C to exit')

            while self.keep_going is True:
                try:
                    user_command = raw_input('ROOT@KT-OBD> ').upper()
                    if re.search('\AAT', user_command):
                        print('Wrong command, ELM configuration is not '
                              'allowed')
                    elif re.search('QUIT', user_command):
                        raise KeyboardInterrupt
                    elif user_command == '':
                        pass
                    else:
                        result, validation = self.connector.run_OBD_command(
                            user_command, expert=True)

                        if re.search('ERROR', result) or \
                                re.search('DATA', result):
                            print('ERROR: Wrong command or not supported, '
                                  'type another one')
                        elif re.search('BUSY', result):
                            print('ERROR: Bus busy, try again')
                        elif re.search('UNABLE', result):
                            print('ERROR: Communication lost, shutting '
                                  'down app!')
                            break
                        else:
                            if self.lazy_mode:
                                value, unit = decode_answer(
                                    user_command, result)
                                print('{0} {1}'.format(value, unit))
                            else:
                                print(result)
                except KeyboardInterrupt:
                    break
        logging.info('Expert mode aborted by user, finishing...')
        self.connector.run_OBD_command('END', expert=True)