Exemplo n.º 1
0
def fixed_xor(s1, s2):
	"""Computes the fixed XOR between two hexadecimal strings."""
	try:
		b1 = utils.hex_to_bin(s1)
		b2 = utils.hex_to_bin(s2)
		res_b = fixed_xor_bins(b1, b2)
	except utils.InvalidArgumentError as err:
		# Raise again as an error of this module for better clarity.
		raise InvalidArgumentError(err)

	return utils.bin_to_hex(res_b)
Exemplo n.º 2
0
def get_disk_repr(key):
    disk = ""
    for i in range(128):
        hash_input = f"{key}-{i}"
        disk += hex_to_bin(knot_hash(hash_input))

    return disk
Exemplo n.º 3
0
def decode(text, polynomial):

    # Quebrar o texto hexadecimal em uma lista de  binario onde cada binario
    # tem 12 bits (3 hexadecimais)
    block_size = 3
    bin_list = [utils.hex_to_bin(text[i:i + block_size], 8) for i in range(0, len(text), block_size)]

    mensagem = ""
    erros = []

    # Calcular o CRC de cada caractere
    for i in range(0, len(bin_list)):
        # se o resultado for igual a zero pega o binario descontando os
        # ultimos 4 bits (o ultimo hexadecimal e converte para ASCII)
        if utils.bin_to_int(calculate_crc(bin_list[i], polynomial)) == 0:
            mensagem += utils.bin_to_ascii(bin_list[i][:-(len(polynomial)-1)])

        # se o resultado for diferente de 0, logo tem erro e deve ser 
        # guardada a posicao.
        else:
            mensagem += "_"
            erros.append(str(i+1))

    # retornar o dict com mensagem e eventuais erros
    return {"message": mensagem, "erros": erros}
Exemplo n.º 4
0
def decode(text):
    # Quebrar o text em strings binarias de 8bits
    block_size = 2
    bin_list = [
        utils.hex_to_bin(text[i:i + block_size], 8)
        for i in range(0, len(text), block_size)
    ]

    # Checar paridade das linhas
    # comparar a paridade de n-1 bits == ao n-ésimo bit, se diferente
    # retorna ERRO
    for b in bin_list:
        if utils.parity(b[:-1]) != b[-1]:
            return "ERRO"

    # Checar paridade das colunas
    # comparar a paridade das colunas para cada coluna comparar n-1 bits == ao
    #  n-ésimo bit, se diferente retorna ERRO
    for i in range(0, 8):
        binary_col = get_col(i, bin_list)
        if utils.parity(binary_col[:-1]) != binary_col[-1]:
            return "ERRO"

    # Não há erros, retornar a mensagem correta
    result_string = ""

    for b in bin_list[:-1]:
        result_string += utils.bin_to_ascii(b[:-1])

    return result_string
Exemplo n.º 5
0
    def DecodeHex(self, encoded_string, frequency_only=False):
        """Decodes a string represented in hexadecimal ASCII format.
		Returns a list of tuple. Each element contains a decoding we detected
		to likely be English plaintext, and the binary key used for that decoding.

		Raises exceptions if the string is not in the expected format.
		"""
        bin_string = utils.hex_to_bin(encoded_string)
        return self.DecodeBin(bin_string, frequency_only)
Exemplo n.º 6
0
        def look_for_issues_check_mode():
            def extract_payload(answer):
                #Delete headers and checksum. Rework for multiple response messages
                test_pattern = string.replace(answer, ' ', '')
                index = string.find(test_pattern, '4101')
                position = index + len('4101')
                return test_pattern[position:-2]

            mil_state = []
            num_dtcs = []
            for i in range(len(self.record)):
                array = self.get_value(i)
                if array[0] == '0101':
                    payload = extract_payload(array[1])
                    while 1:
                        if len(payload) >= 8:
                            #index = string.find(test_pattern,'4101')
                            payload_databyte_1A = payload[0]
                            payload_databyte_2A = payload[1]
                            code = utils.hex_to_bin(payload_databyte_1A)[0]
                            if code:
                                mil_state.append('ON')
                            else:
                                mil_state.append('OFF')
                            partial1 = str(
                                utils.hex_to_bin(payload_databyte_1A[0]))
                            partial2 = str(
                                utils.hex_to_bin(payload_databyte_2A))
                            num_dtcs.append(
                                str(int(partial1[1:] + partial2, 2)))
                        try:
                            payload = payload[
                                16:]  #jump ahead checksum and headers of next frame
                            if payload[
                                    0:
                                    4] != '4101':  #verify answer of next frame
                                break
                            else:
                                payload = payload[4:]
                        except IndexError:
                            break
                    break
            return mil_state, num_dtcs
Exemplo n.º 7
0
 def decode_dtc(self, frame):
     if frame == "0000" or len(frame) != 4:
         return None
     else:
         description = {"00": "P", "01": "C", "10": "B", "11": "U"}
         nibble = frame[0]
         pre_symbol = utils.hex_to_bin(nibble)
         symbol = description[pre_symbol[0:2]]
         first_char = hex(int(pre_symbol[2:], 2))[2:]
         return symbol + first_char + frame[1:]
Exemplo n.º 8
0
def decode_dtc(frame):
    if frame == '0000' or len(frame) != 4:
        return None
    else:
        description = {'00': 'P', '01': 'C', '10': 'B', '11': 'U'}
        nibble = frame[0]
        pre_symbol = utils.hex_to_bin(nibble)
        symbol = description[pre_symbol[0:2]]
        first_char = hex(int(pre_symbol[2:], 2))[2:]
        return symbol + first_char + frame[1:]
Exemplo n.º 9
0
    def get_cb_tx(self, template, mining_address=None):
        orig = hex_to_bin(template['coinbasetxn']['data'])
        if not mining_address:
            return orig

        orig_decoded = self.server.decoderawtransaction(
            template['coinbasetxn']['data'])

        founder_tax_address = orig_decoded['vout'][1]['scriptPubKey'][
            'addresses'][0]
        founder_tax_amount = orig_decoded['vout'][1]['value']
        reward = orig_decoded['vout'][0]['value']

        new_out_tx = hex_to_bin(
            self.server.createrawtransaction(
                [], {
                    mining_address: reward,
                    founder_tax_address: founder_tax_amount
                }))
        return replace_output(orig, new_out_tx)
Exemplo n.º 10
0
def main():
    with open("16/input.txt", encoding="UTF-8") as file:
        content = file.read()

    # hex -> binary. 1 hex char -> 4 bits
    all_bits = [hex_to_bin(char) for char in list(content)]
    message = "".join(all_bits)

    result = parse_packet(message)

    print(result)
Exemplo n.º 11
0
    def get_header_from_templete(t, cb_tx, nonce):
        version = t['version']
        previous_block_hash = hex_to_bin(t['previousblockhash'])

        cb_hash = double_sha256_digest(cb_tx)  #[::-1]
        # cb_hash = hex_to_bin(t['coinbasetxn']['hash'])[::-1]
        hashes = [
            cb_hash,
        ] + txs_hashes(get_txs_from_template(t))
        hash_merkle_root = MerkleTree(hashes).tree_digest()
        time = t['curtime']
        bits = t['bits']

        return ''.join((
            struct.pack("<i", version),
            previous_block_hash[::-1],
            hash_merkle_root,
            '\x00' * 32,
            struct.pack("<I", time),
            hex_to_bin(bits)[::-1],
            nonce,
        ))
Exemplo n.º 12
0
        def look_for_issues_check_mode():

            def extract_payload(answer):
                #Delete headers and checksum. Rework for multiple response messages
                test_pattern = string.replace(answer,' ','')
                index = string.find(test_pattern, '4101')
                position = index+len('4101')
                return test_pattern[position:-2]

            mil_state = []
            num_dtcs = []
            for i in range(len(self.record)):
                array = self.get_value(i)
                if array[0] == '0101':
                    payload = extract_payload(array[1])
                    while 1:
                        if len(payload) >= 8:
                            #index = string.find(test_pattern,'4101')
                            payload_databyte_1A = payload[0]
                            payload_databyte_2A = payload[1]
                            code = utils.hex_to_bin(payload_databyte_1A)[0]
                            if code:
                                mil_state.append('ON')
                            else:
                                mil_state.append('OFF')
                            partial1 = str(utils.hex_to_bin(payload_databyte_1A[0]))
                            partial2 = str(utils.hex_to_bin(payload_databyte_2A))
                            num_dtcs.append(str(int(partial1[1:]+partial2,2)))
                        try:
                            payload = payload[16:]  #jump ahead checksum and headers of next frame
                            if payload[0:4]!='4101':   #verify answer of next frame
                                break
                            else:
                                payload = payload[4:]
                        except IndexError:
                            break
                    break
            return mil_state, num_dtcs
Exemplo n.º 13
0
def decode_dtc(frame):
    if frame == '0000' or len(frame) != 4:
        return None
    else:
        description = {
            '00': 'P',
            '01': 'C',
            '10': 'B',
            '11': 'U'
        }
        nibble = frame[0]
        pre_symbol = utils.hex_to_bin(nibble)
        symbol = description[pre_symbol[0:2]]
        first_char = hex(int(pre_symbol[2:], 2))[2:]
        return symbol + first_char + frame[1:]
Exemplo n.º 14
0
def decode(string):
    # converter cada letra para binario
    bin_list = [
        utils.hex_to_bin(string[i:i + 3], 11)
        for i in range(0, len(string), 3)
    ]
    message = ""
    index_error = []
    for i, binary in enumerate(bin_list):
        # decodifca o binario
        letter, error = decode_calc_hamming(binary)
        message += letter
        if error != 0:
            index_error.append((letter, i + 1))

    return {'message': message, 'index_error': index_error}
Exemplo n.º 15
0
def decode_answer(cmd, answer):
    # TODO: migrate all of these functions to "elmdb.py" dictionary
    # TODO: use elmdb.ELMdb[cmd]['unit']

    # this will receive only valid answers
    value = None
    unit = None
    payload = extract_payload(cmd, answer)
    if cmd in ['0100', '0120', '0140', '0160', '0180', '01A0', '01C0']:
        value = payload

    elif cmd == '0101':
        mil_state = []
        num_dtcs = []
        supported_tests = []
        while 1:
            if len(payload) >= 8:
                # index = string.find(test_pattern,'4101')
                payload_databyte_1A = payload[0]
                payload_databyte_2A = payload[1]
                code = utils.hex_to_bin(payload_databyte_1A)[0]
                if code:
                    mil_state.append('ON')
                else:
                    mil_state.append('OFF')
                partial1 = str(utils.hex_to_bin(payload_databyte_1A[0]))
                partial2 = str(utils.hex_to_bin(payload_databyte_2A))
                num_dtcs.append(str(int(partial1[1:] + partial2, 2)))
                tests = ''
                for i in range(2, 6):
                    tests = tests + utils.hex_to_bin(payload[i])
                supported_tests.append(tests)
            try:
                # jump ahead checksum and headers of next frame
                payload = payload[16:]
                if payload[0:4] != '4101':   # verify answer of next frame
                    break
                else:
                    payload = payload[4:]
            except IndexError:
                break

        value = [mil_state, num_dtcs, supported_tests]

    elif cmd == '0102':
        value = decode_dtc(payload)

    elif cmd == '0103':
        #OL: open loop. CL: closed loop.
        description = {
            '00000000': 'Wrong state',
            '00000001': 'OL',
            '00000010': 'CL',
            '00000100': 'OL-Drive',
            '00001000': 'OL-Fault',
            '00010000': 'CL-Fault',
            '0010000': 'ISO Reserved',
            '01000000': 'ISO Reserved',
            '10000000': 'ISO Reserved'
        }
        fuel_system1_status = utils.hex_to_bin(payload[0]) + \
            utils.hex_to_bin(payload[1])
        fuel_system2_status = utils.hex_to_bin(payload[2]) + \
            utils.hex_to_bin(payload[3])
        try:
            value = [description[fuel_system1_status],
                     description[fuel_system2_status]]
        except KeyError:
            value = 'Unknown'

    elif cmd in ['0104', '012F', '0152']:
        code = utils.hex_to_int(payload)
        value = code * 100.0 / 255.0
        unit = 'Percent scale'

    elif cmd == '0105' or cmd == '010F':
        code = utils.hex_to_int(payload)
        value = code - 40
        unit = 'Degrees Celsius'

    elif cmd in ['0106', '0107', '0108', '0109']:
        code = utils.hex_to_int(payload)
        value = (code - 128.0) * 100.0 / 128
        unit = 'Percent scale'

    elif cmd == '010A':
        code = utils.hex_to_int(payload)
        value = code * 3
        unit = 'KPa'

    elif cmd == '010B':
        value = utils.hex_to_int(payload)
        unit = 'KPa'

    elif cmd == '010C':
        code = utils.hex_to_int(payload)
        value = code / 4
        unit = 'RPM'

    elif cmd == '010D':
        value = utils.hex_to_int(payload)
        unit = 'Km/h'

    elif cmd == '010E':
        code = utils.hex_to_int(payload)
        value = (code - 128) / 2.0
        unit = 'Degrees'

    elif cmd == '0110':
        code = utils.hex_to_int(payload)
        value = code * 0.01
        unit = 'g/s'

    elif cmd == '0111':
        code = utils.hex_to_int(payload)
        value = code * 0.01
        unit = 'Percent scale'

    elif cmd == '0112':
        description = {
            '00000000': 'Wrong state',
            '00000001': 'UPS',
            '00000010': 'DNS',
            '00000100': 'OFF',
            '00001000': 'ISO Reserved',
            '00010000': 'ISO Reserved',
            '0010000': 'ISO Reserved',
            '01000000': 'ISO Reserved',
            '10000000': 'ISO Reserved'
        }
        air_status = utils.hex_to_bin(payload[0]) + \
            utils.hex_to_bin(payload[1])
        try:
            value = description[air_status]
        except KeyError:
            value = 'Unknown'

    elif cmd in ['0113', '011D']:
        value = utils.hex_to_bin(payload[0]) + utils.hex_to_bin(payload[1])

    elif cmd in ['0114', '0115', '0116', '0117', '0118', '0119',
                 '011A', '011B']:
        code = utils.hex_to_int(payload[0:2])
        voltage = code * 0.005
        code2 = utils.hex_to_int(payload[2:4])
        stft = (code2 - 128.0) * 100.0 / 128
        value = [voltage, stft]
        unit = ['V', 'Percent scale']

    elif cmd == '011C':
        description = {
            '01': 'OBD-II',
            '02': 'OBD',
            '03': 'OBD and OBD-II',
            '04': 'OBD-I',
            '05': 'NO OBD',
            '06': 'EOBD',
            '07': 'EOBD and OBD-II',
            '08': 'EOBD and OBD',
            '09': 'EOBD, OBD and OBD-II',
            '0A': 'JOBD',
            '0B': 'JOBD and OBD-II',
            '0C': 'JOBD and OBD',
            '0D': 'JOBD, EOBD and OBD-II',
            '0E': 'EURO IV B1',
            '0F': 'EURO V B2',
            '10': 'EURO C',
            '11': 'EMD'
        }
        try:
            value = description[payload]
        except KeyError:
            value = 'Unknown'

    elif cmd == '011E':
        code = utils.hex_to_bin(payload[1])[3]
        if code:
            value = 'ON'
        else:
            value = 'OFF'

    elif cmd == '011F':
        code = utils.hex_to_int(payload)
        value = code / 60
        unit = 'min'

    elif cmd in ['0121', '0131']:
        value = utils.hex_to_int(payload)
        unit = 'Km'

    elif cmd in ['014D', '014E']:
        value = utils.hex_to_int(payload)
        unit = 'min'

    elif cmd == '0151':
        description = {
            '01': 'GAS',
            '02': 'METH',
            '03': 'ETH',
            '04': 'DSL',
            '05': 'LPG',
            '06': 'CNG',
            '07': 'PROP',
            '08': 'ELEC',
            '09': 'BI_GAS',
            '0A': 'BI_METH',
            '0B': 'BI_ETH',
            '0C': 'BI_LPG',
            '0D': 'BI_CNG',
            '0E': 'BI_PROP',
            '0F': 'BI_ELEC',
        }
        try:
            value = description[payload]
        except KeyError:
            value = 'Unknown'

    elif cmd in ['0901', '0903', '0905', '0909']:
        value = utils.hex_to_int(payload)
        unit = 'Messages'

    elif cmd in ['0902', '0904', '0906', '090A']:
        matrix = []
        while 1:
            # if there is a compliant frame of response
            if len(payload) >= 9:
                index = utils.hex_to_int(payload[0:2])
                frame = binascii.unhexlify(payload[2:10])
                matrix.append([index, frame])
            else:
                break
            try:
                # jump ahead checksum and headers of next frame
                payload = payload[18:]
                # verify answer of next frame
                if payload[0:4] not in ['4902', '4904', '4906', '490A']:
                    break
                else:
                    payload = payload[4:]
            except IndexError:
                break

        # now, order the values gotten
        if len(matrix) > 0:
            value = ''
            for i in range(len(matrix)):
                if matrix[i][0] == i:
                    value = value + matrix[i][1]

    elif cmd in ['03', '07']:
        value = []
        while 1:
            # if there is a compliant frame of dtcs
            if len(payload) >= 12:
                k = 0
                while k != 12:
                    value_k = decode_dtc(payload[k:k+4])
                    if value_k is not None:
                        value.append(value_k)
                    k += 4
            else:
                break
            try:
                # jump ahead checksum and headers of next frame
                payload = payload[20:]
                # verify answer of next frame
                if payload[0:2] not in ['43', '47']:
                    break
                else:
                    payload = payload[2:]
            except IndexError:
                break

    elif cmd == '04':
        if payload == '44':
            value = True
        else:
            value = False
    return value, unit
Exemplo n.º 16
0
def parse_ath_message(mycode, mystr):
		if mycode.startswith(".bf ", 0, 4) == True:
			mycode = mycode.replace(".bf ", "")
			irc.send_msg(bfc.compile_bf(mycode), variables.channel)
			signal.alarm(0)
		elif mycode.startswith(".be ", 0, 4) == True:
			mycode = mycode.replace(".be ", "")
			irc.send_msg(bec.compile_be(mycode), variables.channel)
			signal.alarm(0)
		elif mycode.startswith(".ul ", 0, 4) == True:
			print mycode
			mycode = mycode.replace(".ul ", "")
			irc.send_msg(ulc.compile_ul(mycode), variables.channel)
			signal.alarm(0)
		elif mycode.startswith(".test", 0, 5) == True:
			utils.test()
		elif mycode.startswith(".eval", 0, 5) == True:
			output = "Result: " + utils.evaluate_expression(mycode)
			irc.send_msg(output, variables.channel)
		elif mycode.startswith(".d2h", 0, 4) == True:
			utils.decimal_to_hex(mycode)
		elif mycode.startswith(".h2d", 0, 4) == True:
			utils.hex_to_decimal(mycode)
		elif mycode.startswith(".d2b", 0, 4) == True:
			utils.decimal_to_bin(mycode)
		elif mycode.startswith(".h2b", 0, 4) == True:
			utils.hex_to_bin(mycode)
		elif mycode.startswith(".b2h", 0, 4) == True:
			utils.bin_to_hex(mycode)
		elif mycode.startswith(".b2d", 0, 4) == True:
			utils.bin_to_decimal(mycode)
		elif mycode.startswith(".join", 0, 5) == True:
			user = mystr['PREFIX']
			user = user.split('!')
			if user[0] != variables.head_user:
				irc.send_msg("You need to be: " + variables.head_user + " to make me join a channel", variables.channel)	
			else:
				mychan = mycode.replace(".join", "")
				mychan = mychan.replace(" ", "")
				if mychan == "0":
					irc.send_msg(variables.i_hate_you, variables.channel)
				else:
					irc.join_channel(mychan)

		elif mycode.startswith(".leave", 0, 6):
			user = mystr['PREFIX']
			user = user.split('!')
			if user[0] != variables.head_user:
				irc.send_msg("You need to be: " + variables.head_user + " to make me leave a channel", variables.channel)	
			else:
				mychan = mycode.replace(".leave", "")
				mychan = mychan.replace(" ", "")
				if mychan == "0":
					irc.send_msg(variables.i_hate_you, variables.channel)
				else:
					irc.leave_channel(mychan)
		elif mycode.startswith(".time ", 0, 6) == True:
			utils.get_time(mycode)
		elif mycode.startswith(".ccount ", 0, 8) == True:
			mycode = mycode.replace(".ccount ", "")
			length = 0
			if check_if_unicode(mycode) == True:
				length = unicode_len(mycode)
			else:
				length = len(mycode)
			irc.send_msg("Length: " + str(length), variables.channel)
		elif mycode.startswith(".help", 0, 5) == True:
			irc.send_msg(help.athena_help, variables.channel)
		elif mycode.startswith(".list", 0, 5):
			irc.send_msg("List of modules: " + str(list(imports())), variables.channel)	
		elif mycode.startswith(".xkcd ", 0, 6):
			irc.send_msg(u'\u200b' + xkcd.search_xkcd(mycode.replace(".xkcd ", "")), variables.channel)
		elif mycode.startswith(".tr ", 0, 4):
			mycode = mycode.replace(".tr ", "")
			lang = mycode[:2]
			mycode = mycode.replace(lang, "")
			irc.send_msg(utils.translate_lang(lang, mycode), variables.channel)
		elif mycode.startswith(".bftxt ", 0, 7):
			mycode = mycode.replace(".bftxt ", "")
			irc.send_msg("Output: " + bftxt.bf(mycode), variables.channel)
		elif mycode.startswith(".df ", 0, 4):
			mycode = mycode.replace(".df ", "")
			irc.send_msg("Output: " + deadfish.compile_df(mycode), variables.channel)
		elif mycode.startswith(".source", 0, 7):
			irc.send_msg(u"\u200bhttps://github.com/Benderx2/athena_bot", variables.channel)
Exemplo n.º 17
0
def decode_answer(cmd, answer):
    # TODO: migrate all of these functions to "elmdb.py" dictionary
    # TODO: use elmdb.ELMdb[cmd]['unit']

    # this will receive only valid answers
    value = None
    unit = None
    payload = extract_payload(cmd, answer)
    if cmd in ['0100', '0120', '0140', '0160', '0180', '01A0', '01C0']:
        value = payload

    elif cmd == '0101':
        mil_state = []
        num_dtcs = []
        supported_tests = []
        while 1:
            if len(payload) >= 8:
                # index = string.find(test_pattern,'4101')
                payload_databyte_1A = payload[0]
                payload_databyte_2A = payload[1]
                code = utils.hex_to_bin(payload_databyte_1A)[0]
                if code:
                    mil_state.append('ON')
                else:
                    mil_state.append('OFF')
                partial1 = str(utils.hex_to_bin(payload_databyte_1A[0]))
                partial2 = str(utils.hex_to_bin(payload_databyte_2A))
                num_dtcs.append(str(int(partial1[1:] + partial2, 2)))
                tests = ''
                for i in range(2, 6):
                    tests = tests + utils.hex_to_bin(payload[i])
                supported_tests.append(tests)
            try:
                # jump ahead checksum and headers of next frame
                payload = payload[16:]
                if payload[0:4] != '4101':  # verify answer of next frame
                    break
                else:
                    payload = payload[4:]
            except IndexError:
                break

        value = [mil_state, num_dtcs, supported_tests]

    elif cmd == '0102':
        value = decode_dtc(payload)

    elif cmd == '0103':
        #OL: open loop. CL: closed loop.
        description = {
            '00000000': 'Wrong state',
            '00000001': 'OL',
            '00000010': 'CL',
            '00000100': 'OL-Drive',
            '00001000': 'OL-Fault',
            '00010000': 'CL-Fault',
            '0010000': 'ISO Reserved',
            '01000000': 'ISO Reserved',
            '10000000': 'ISO Reserved'
        }
        fuel_system1_status = utils.hex_to_bin(payload[0]) + \
            utils.hex_to_bin(payload[1])
        fuel_system2_status = utils.hex_to_bin(payload[2]) + \
            utils.hex_to_bin(payload[3])
        try:
            value = [
                description[fuel_system1_status],
                description[fuel_system2_status]
            ]
        except KeyError:
            value = 'Unknown'

    elif cmd in ['0104', '012F', '0152']:
        code = utils.hex_to_int(payload)
        value = code * 100.0 / 255.0
        unit = 'Percent scale'

    elif cmd == '0105' or cmd == '010F':
        code = utils.hex_to_int(payload)
        value = code - 40
        unit = 'Degrees Celsius'

    elif cmd in ['0106', '0107', '0108', '0109']:
        code = utils.hex_to_int(payload)
        value = (code - 128.0) * 100.0 / 128
        unit = 'Percent scale'

    elif cmd == '010A':
        code = utils.hex_to_int(payload)
        value = code * 3
        unit = 'KPa'

    elif cmd == '010B':
        value = utils.hex_to_int(payload)
        unit = 'KPa'

    elif cmd == '010C':
        code = utils.hex_to_int(payload)
        value = code / 4
        unit = 'RPM'

    elif cmd == '010D':
        value = utils.hex_to_int(payload)
        unit = 'Km/h'

    elif cmd == '010E':
        code = utils.hex_to_int(payload)
        value = (code - 128) / 2.0
        unit = 'Degrees'

    elif cmd == '0110':
        code = utils.hex_to_int(payload)
        value = code * 0.01
        unit = 'g/s'

    elif cmd == '0111':
        code = utils.hex_to_int(payload)
        value = code * 0.01
        unit = 'Percent scale'

    elif cmd == '0112':
        description = {
            '00000000': 'Wrong state',
            '00000001': 'UPS',
            '00000010': 'DNS',
            '00000100': 'OFF',
            '00001000': 'ISO Reserved',
            '00010000': 'ISO Reserved',
            '0010000': 'ISO Reserved',
            '01000000': 'ISO Reserved',
            '10000000': 'ISO Reserved'
        }
        air_status = utils.hex_to_bin(payload[0]) + \
            utils.hex_to_bin(payload[1])
        try:
            value = description[air_status]
        except KeyError:
            value = 'Unknown'

    elif cmd in ['0113', '011D']:
        value = utils.hex_to_bin(payload[0]) + utils.hex_to_bin(payload[1])

    elif cmd in [
            '0114', '0115', '0116', '0117', '0118', '0119', '011A', '011B'
    ]:
        code = utils.hex_to_int(payload[0:2])
        voltage = code * 0.005
        code2 = utils.hex_to_int(payload[2:4])
        stft = (code2 - 128.0) * 100.0 / 128
        value = [voltage, stft]
        unit = ['V', 'Percent scale']

    elif cmd == '011C':
        description = {
            '01': 'OBD-II',
            '02': 'OBD',
            '03': 'OBD and OBD-II',
            '04': 'OBD-I',
            '05': 'NO OBD',
            '06': 'EOBD',
            '07': 'EOBD and OBD-II',
            '08': 'EOBD and OBD',
            '09': 'EOBD, OBD and OBD-II',
            '0A': 'JOBD',
            '0B': 'JOBD and OBD-II',
            '0C': 'JOBD and OBD',
            '0D': 'JOBD, EOBD and OBD-II',
            '0E': 'EURO IV B1',
            '0F': 'EURO V B2',
            '10': 'EURO C',
            '11': 'EMD'
        }
        try:
            value = description[payload]
        except KeyError:
            value = 'Unknown'

    elif cmd == '011E':
        code = utils.hex_to_bin(payload[1])[3]
        if code:
            value = 'ON'
        else:
            value = 'OFF'

    elif cmd == '011F':
        code = utils.hex_to_int(payload)
        value = code / 60
        unit = 'min'

    elif cmd in ['0121', '0131']:
        value = utils.hex_to_int(payload)
        unit = 'Km'

    elif cmd in ['014D', '014E']:
        value = utils.hex_to_int(payload)
        unit = 'min'

    elif cmd == '0151':
        description = {
            '01': 'GAS',
            '02': 'METH',
            '03': 'ETH',
            '04': 'DSL',
            '05': 'LPG',
            '06': 'CNG',
            '07': 'PROP',
            '08': 'ELEC',
            '09': 'BI_GAS',
            '0A': 'BI_METH',
            '0B': 'BI_ETH',
            '0C': 'BI_LPG',
            '0D': 'BI_CNG',
            '0E': 'BI_PROP',
            '0F': 'BI_ELEC',
        }
        try:
            value = description[payload]
        except KeyError:
            value = 'Unknown'

    elif cmd in ['0901', '0903', '0905', '0909']:
        value = utils.hex_to_int(payload)
        unit = 'Messages'

    elif cmd in ['0902', '0904', '0906', '090A']:
        matrix = []
        while 1:
            # if there is a compliant frame of response
            if len(payload) >= 9:
                index = utils.hex_to_int(payload[0:2])
                frame = binascii.unhexlify(payload[2:10])
                matrix.append([index, frame])
            else:
                break
            try:
                # jump ahead checksum and headers of next frame
                payload = payload[18:]
                # verify answer of next frame
                if payload[0:4] not in ['4902', '4904', '4906', '490A']:
                    break
                else:
                    payload = payload[4:]
            except IndexError:
                break

        # now, order the values gotten
        if len(matrix) > 0:
            value = ''
            for i in range(len(matrix)):
                if matrix[i][0] == i:
                    value = value + matrix[i][1]

    elif cmd in ['03', '07']:
        value = []
        while 1:
            # if there is a compliant frame of dtcs
            if len(payload) >= 12:
                k = 0
                while k != 12:
                    value_k = decode_dtc(payload[k:k + 4])
                    if value_k is not None:
                        value.append(value_k)
                    k += 4
            else:
                break
            try:
                # jump ahead checksum and headers of next frame
                payload = payload[20:]
                # verify answer of next frame
                if payload[0:2] not in ['43', '47']:
                    break
                else:
                    payload = payload[2:]
            except IndexError:
                break

    elif cmd == '04':
        if payload == '44':
            value = True
        else:
            value = False
    return value, unit
Exemplo n.º 18
0
    def decode_answer(self, cmd, answer):
        # this will receive only valid answers
        value = None
        unit = None
        payload = self.extract_payload(cmd, answer)
        if cmd == "0100":
            value = payload

        elif cmd == "0101":
            mil_state = []
            num_dtcs = []
            supported_tests = []
            while 1:
                if len(payload) >= 8:
                    # index = string.find(test_pattern,'4101')
                    payload_databyte_1A = payload[0]
                    payload_databyte_2A = payload[1]
                    code = utils.hex_to_bin(payload_databyte_1A)[0]
                    if code:
                        mil_state.append("ON")
                    else:
                        mil_state.append("OFF")
                    partial1 = str(utils.hex_to_bin(payload_databyte_1A[0]))
                    partial2 = str(utils.hex_to_bin(payload_databyte_2A))
                    num_dtcs.append(str(int(partial1[1:] + partial2, 2)))
                    tests = ""
                    for i in range(2, 6):
                        tests = tests + utils.hex_to_bin(payload[i])
                    supported_tests.append(tests)
                try:
                    payload = payload[16:]  # jump ahead checksum and headers of next frame
                    if payload[0:4] != "4101":  # verify answer of next frame
                        break
                    else:
                        payload = payload[4:]
                except IndexError:
                    break

            value = [mil_state, num_dtcs, supported_tests]

        elif cmd == "0102":
            value = self.decode_dtc(payload)

        elif cmd == "0103":
            # OL: open loop. CL: closed loop.
            description = {
                "00000000": "Wrong state",
                "00000001": "OL",
                "00000010": "CL",
                "00000100": "OL-Drive",
                "00001000": "OL-Fault",
                "00010000": "CL-Fault",
                "0010000": "ISO Reserved",
                "01000000": "ISO Reserved",
                "10000000": "ISO Reserved",
            }
            fuel_system1_status = utils.hex_to_bin(payload[0]) + utils.hex_to_bin(payload[1])
            fuel_system2_status = utils.hex_to_bin(payload[2]) + utils.hex_to_bin(payload[3])
            try:
                value = [description[fuel_system1_status], description[fuel_system2_status]]
            except KeyError:
                value = "Unknown"

        elif cmd in ["0104", "012F", "0152"]:
            code = utils.hex_to_int(payload)
            value = code * 100.0 / 255.0
            unit = "Percent scale"

        elif cmd == "0105" or cmd == "010F":
            code = utils.hex_to_int(payload)
            value = code - 40
            unit = "Degrees Celsius"

        elif cmd in ["0106", "0107", "0108", "0109"]:
            code = utils.hex_to_int(payload)
            value = (code - 128.0) * 100.0 / 128
            unit = "Percent scale"

        elif cmd == "010A":
            code = utils.hex_to_int(payload)
            value = code * 3
            unit = "KPa"

        elif cmd == "010B":
            value = utils.hex_to_int(payload)
            unit = "KPa"

        elif cmd == "010C":
            code = utils.hex_to_int(payload)
            value = code / 4
            unit = "RPM"

        elif cmd == "010D":
            value = utils.hex_to_int(payload)
            unit = "Km/h"

        elif cmd == "010E":
            code = utils.hex_to_int(payload)
            value = (code - 128) / 2.0
            unit = "Degrees"

        elif cmd == "0110":
            code = utils.hex_to_int(payload)
            value = code * 0.01
            unit = "g/s"

        elif cmd == "0111":
            code = utils.hex_to_int(payload)
            value = code * 0.01
            unit = "Percent scale"

        elif cmd == "0112":
            description = {
                "00000000": "Wrong state",
                "00000001": "UPS",
                "00000010": "DNS",
                "00000100": "OFF",
                "00001000": "ISO Reserved",
                "00010000": "ISO Reserved",
                "0010000": "ISO Reserved",
                "01000000": "ISO Reserved",
                "10000000": "ISO Reserved",
            }
            air_status = utils.hex_to_bin(payload[0]) + utils.hex_to_bin(payload[1])
            try:
                value = description[air_status]
            except KeyError:
                value = "Unknown"

        elif cmd in ["0113", "011D"]:
            value = utils.hex_to_bin(payload[0]) + utils.hex_to_bin(payload[1])

        elif cmd in ["0114", "0115", "0116", "0117", "0118", "0119", "011A", "011B"]:
            code = utils.hex_to_int(payload[0:2])
            voltage = code * 0.005
            code2 = utils.hex_to_int(payload[2:4])
            stft = (code2 - 128.0) * 100.0 / 128
            value = [voltage, stft]
            unit = ["V", "Percent scale"]

        elif cmd == "011C":
            description = {
                "01": "OBD-II",
                "02": "OBD",
                "03": "OBD and OBD-II",
                "04": "OBD-I",
                "05": "NO OBD",
                "06": "EOBD",
                "07": "EOBD and OBD-II",
                "08": "EOBD and OBD",
                "09": "EOBD, OBD and OBD-II",
                "0A": "JOBD",
                "0B": "JOBD and OBD-II",
                "0C": "JOBD and OBD",
                "0D": "JOBD, EOBD and OBD-II",
                "0E": "EURO IV B1",
                "0F": "EURO V B2",
                "10": "EURO C",
                "11": "EMD",
            }
            try:
                value = description[payload]
            except KeyError:
                value = "Unknown"

        elif cmd == "011E":
            code = utils.hex_to_bin(payload[1])[3]
            if code:
                value = "ON"
            else:
                value = "OFF"

        elif cmd == "011F":
            code = utils.hex_to_int(payload)
            value = code / 60
            unit = "min"

        elif cmd in ["0121", "0131"]:
            value = utils.hex_to_int(payload)
            unit = "Km"

        elif cmd in ["014D", "014E"]:
            value = utils.hex_to_int(payload)
            unit = "min"

        elif cmd == "0151":
            description = {
                "01": "GAS",
                "02": "METH",
                "03": "ETH",
                "04": "DSL",
                "05": "LPG",
                "06": "CNG",
                "07": "PROP",
                "08": "ELEC",
                "09": "BI_GAS",
                "0A": "BI_METH",
                "0B": "BI_ETH",
                "0C": "BI_LPG",
                "0D": "BI_CNG",
                "0E": "BI_PROP",
                "0F": "BI_ELEC",
            }
            try:
                value = description[payload]
            except KeyError:
                value = "Unknown"

        elif cmd in ["0901", "0903", "0905", "0909"]:
            value = utils.hex_to_int(payload)
            unit = "Messages"

        elif cmd in ["0902", "0904", "0906", "090A"]:
            matrix = []
            while 1:
                if len(payload) >= 9:  # if there is a compliant frame of response
                    index = utils.hex_to_int(payload[0:2])
                    frame = binascii.unhexlify(payload[2:10])
                    matrix.append([index, frame])
                else:
                    break
                try:
                    payload = payload[18:]  # jump ahead checksum and headers of next frame
                    if payload[0:4] not in ["4902", "4904", "4906", "490A"]:  # verify answer of next frame
                        break
                    else:
                        payload = payload[4:]
                except IndexError:
                    break
            # now, order the values gotten
            if len(matrix) > 0:
                value = ""
                for i in range(len(matrix)):
                    if matrix[i][0] == i:
                        value = value + matrix[i][1]

        elif cmd in ["03", "07"]:
            value = []
            while 1:
                if len(payload) >= 12:  # if there is a compliant frame of dtcs
                    k = 0
                    while k != 12:
                        value_k = self.decode_dtc(payload[k : k + 4])
                        if value_k != None:
                            value.append(value_k)
                        k += 4
                else:
                    break
                try:
                    payload = payload[20:]  # jump ahead checksum and headers of next frame
                    if payload[0:2] not in ["43", "47"]:  # verify answer of next frame
                        break
                    else:
                        payload = payload[2:]
                except IndexError:
                    break

        elif cmd == "04":
            if payload == "44":
                value = True
            else:
                value = False
        return value, unit
Exemplo n.º 19
0
 def testHexToBin(self):
     self.assertEqual('10101011', utils.hex_to_bin('ab'))
Exemplo n.º 20
0
	def testHexToBin(self):
		self.assertEqual('10101011', utils.hex_to_bin('ab'))