ISO14229-1_2013_03报文解析脚本

个人微信: wzdhh991
邮箱: wzd991@126.com
个人比较懒,CSDN更新缓慢,有相关问题可发邮箱或个人微信交流!

# -*- coding:utf-8 -*-
import sys
import os
import binascii
import struct
import re
import json
import traceback
from tool_base import *
import logging
from ctypes import *
'''
测试
版本:v1.0.0

'''
uds_appp_wdbg = logging.getLogger('UdsApp')
support_psm =1 
u8_lit = struct.Struct('B')
s8_lit = struct.Struct('b')
u16_lit = struct.Struct('<H')
s16_lit = struct.Struct('<h')
u32_lit = struct.Struct('<I')
s32_lit = struct.Struct('<i')
u64_lit = struct.Struct('<Q')
s64_lit = struct.Struct('<q')
double_lit = struct.Struct('<d')
float_lit = struct.Struct('<f')
u16_big = struct.Struct('>H')
s16_big = struct.Struct('>h')
u32_big = struct.Struct('>I')
s32_big = struct.Struct('>i')
u64_big = struct.Struct('>Q')
s64_big = struct.Struct('>q')
double_big = struct.Struct('>d')
float_big = struct.Struct('>f')
(DIRECTION_TX, DIRECTION_RX) = (0, 1) 

Identifier_tab = {
    0xF180: 'BootSoftwareIdentificationDataIdentifier(0xF180)',
    0xF181: 'applicationSoftwareIdentificationDataIdentifier(0xF181)',
    0xF182: 'applicationDataIdentificationDataIdentifier(0xF182)',
    0xF183: 'bootSoftwareFingerprintDataIdentifier(0xF183)',
    0xF184: 'applicationSoftwareFingerprintDataIdentifier(0xF184)',
    0xF185: 'applicationDataFingerprintDataIdentifier(0xF185)',
    0xF186: 'ActiveDiagnosticSessionDataIdentifier(0xF186)',
    0xF187: 'vehicleManufacturerSparePartNumberDataIdentifier(0xF187)',
    0xF188: 'vehicleManufacturerECUSoftwareNumberDataIdentifier(0xF188)',
    0xF189: 'vehicleManufacturerECUSoftwareVersionNumberDataIdentifier(0xF189)',
    0xF18A: 'systemSupplierIdentifierDataIdentifier(0xF18A)',
    0xF18B: 'ECUManufacturingDateDataIdentifier(0xF18B)',
    0xF18C: 'ECUSerialNumberDataIdentifier(0xF18C)',
    0xF18D: 'supportedFunctionalUnitsDataIdentifier(0xF18D)',
    0xF18E: 'VehicleManufacturerKitAssemblyPartNumberDataIdentifier(0xF18E)',
    0xF18F: 'ISOSAEReservedStandardized(0xF18F)',
    0xF190: 'VINDataIdentifier(0xF190)',
    0xF191: 'vehicleManufacturerECUHardwareNumberDataIdentifier(0xF191)',
    0xF192: 'systemSupplierECUHardwareNumberDataIdentifier(0xF192)',
    0xF193: 'systemSupplierECUHardwareVersionNumberDataIdentifier(0xF193)',
    0xF194: 'systemSupplierECUSoftwareNumberDataIdentifier(0xF194)',
    0xF195: 'systemSupplierECUSoftwareVersionNumberDataIdentifier(0xF195)',
    0xF196: 'exhaustRegulationOrTypeApprovalNumberDataIdentifier(0xF196)',
    0xF197: 'systemNameOrEngineTypeDataIdentifier(0xF197)',
    0xF198: 'repairShopCodeOrTesterSerialNumberDataIdentifier(0xF198)',
    0xF199: 'programmingDateDataIdentifier(0xF199)',
    0xF19A: 'calibrationRepairShopCodeOrCalibrationEquipmentSerialNumberDataIdentifier(0xF19A)',
    0xF19B: 'calibrationDateDataIdentifier(0xF19B)',
    0xF19C: 'calibrationEquipmentSoftwareNumberDataIdentifier(0xF19C)',
    0xF19D: 'ECUInstallationDateDataIdentifier(0xF19D)',
    0xF19E: 'ODXFileDataIdentifier(0xF19E)',
    0xF19F: 'EntityDataIdentifier(0xF19F)',
    0xFA10: 'NumberOfEDRDevices(0xFA10)',
    0xFA11: 'EDRIdentification(0xFA11)',
    0xFA12: 'EDRDeviceAddressInformation(0xFA12)',
    0xFF00: 'UDSVersionDataIdentifier(0xFF00)',
    0x8d00: '读历史数据(0x8d00)',
    0x6500: '读实时数据(0x6500)',
    0xd500: '参数操作(0xd500)'
}

negative_response_codes = {
    0x00: 'positiveResponse',
    0x10: 'generalReject',
    0x11: 'serviceNotSupported',
    0x12: 'sub-functionNotSupported',
    0x13: 'incorrectMessageLengthOrInvalidFormat',
    0x14: 'responseTooLong',
    0x21: 'busyRepeatRequest',
    0x22: 'conditionsNotCorrect',
    0x23: 'ISOSAEReserved',
    0x24: 'requestSequenceError',
    0x25: 'noResponseFromSubnetComponent',
    0x26: 'FailurePreventsExecutionOfRequestedAction',
    0x31: 'requestOutOfRange',
    0x32: 'ISOSAEReserved',
    0x33: 'securityAccessDenied',
    0x34: 'ISOSAEReserved',
    0x35: 'invalidKey',
    0x36: 'exceedNumberOfAttempts',
    0x37: 'requiredTimeDelayNotExpired',
    0x70: 'uploadDownloadNotAccepted',
    0x71: 'transferDataSuspended',
    0x72: 'generalProgrammingFailure',
    0x73: 'wrongBlockSequenceCounter',
    0x78: 'requestCorrectlyReceived-ResponsePending',
    0x7E: 'sub-functionNotSupportedInActiveSession',
    0x7F: 'serviceNotSupportedInActiveSession',
    0x80: 'ISOSAEReserved',
    0x81: 'rpmTooHigh',
    0x82: 'rpmTooLow',
    0x83: 'engineIsRunning',
    0x84: 'engineIsNotRunning',
    0x85: 'engineRunTimeTooLow',
    0x86: 'temperatureTooHigh',
    0x87: 'temperatureTooLow',
    0x88: 'vehicleSpeedTooHigh',
    0x89: 'vehicleSpeedTooLow',
    0x8A: 'throttle/PedalTooHigh',
    0x8B: 'throttle/PedalTooLow',
    0x8C: 'transmissionRangeNotInNeutral',
    0x8D: 'transmissionRangeNotInGear',
    0x8E: 'ISOSAEReserved',
    0x8F: 'brakeSwitch(es)NotClosed',
    0x90: 'shifterLeverNotInPark',
    0x91: 'torqueConverterClutchLocked',
    0x92: 'voltageTooHigh',
    0x93: 'voltageTooLow',
    0xFF: 'ISOSAEReserved'
}


def service_0x10_decode(direction, src_data):
    """DiagnosticSessionControl
    """
    (defaultSession, ProgrammingSession, extendedDiagnosticSession, safetySystemDiagnosticSession) = range(1, 5)
    type_name = ('defaultSession', 'ProgrammingSession', 'extendedDiagnosticSession', 'safetySystemDiagnosticSession')
    out_msg = { }

    try:
        if safetySystemDiagnosticSession >= src_data[0] >= defaultSession:
            out_msg['diagnosticSessionType'] = type_name[src_data[0] - 1]
        else:
            out_msg['diagnosticSessionType'] = 'unknown:%d' % src_data[0]

        if direction == DIRECTION_RX:
            if len(src_data) == 5:
                out_msg['p2_server_max(ms)'] = u16_big.unpack_from(src_data, 1)[0]  # 1ms
                out_msg['p2x_server_max(ms)'] = u16_big.unpack_from(src_data, 3)[0]*10  # 10ms

    except Exception as e:
        out_msg['err'] = msg = 'ERROR>>{}:{} {} '.format(e.__traceback__.tb_frame.f_globals["__file__"], e.__traceback__.tb_lineno, e)
    return out_msg


def service_0x11_decode(direction, src_data):
    try:
        (hardReset, keyOffOnReset, softReset, enableRapidPowerShutDown, disableRapidPowerShutDown) = range(1, 6)
        type_name = ('hardReset', 'keyOffOnReset', 'softReset', 'enableRapidPowerShutDown', 'disableRapidPowerShutDown')
        out_msg = { }

        if disableRapidPowerShutDown >= src_data[0] >= hardReset:
            out_msg['resetType'] = type_name[src_data[0] - 1]
        else:
            out_msg['resetType'] = 'unknown:%d' % src_data[0]

        if direction == DIRECTION_RX and len(src_data) == 2:
            if src_data[1] == 0xff:
                out_msg['powerDownTime'] = ' indicates a failure or time not available'
            else:
                out_msg['powerDownTime'] = '%ds' % src_data[1]

    except Exception as e:
        out_msg['err'] = msg = 'ERROR>>{}:{} {} '.format(e.__traceback__.tb_frame.f_globals["__file__"], e.__traceback__.tb_lineno, e)
    return out_msg


def service_0x27_decode(direction, src_data):
    (requestSeed, sendKey) = range(1, 3)
    out_msg = { }
    try:

        if src_data[0] == 5 or src_data[0] == 9:  # requestSeed
            out_msg['securityAccessType'] = 'requestSeed'
            if direction == DIRECTION_RX and len(src_data) > 1:
                out_msg['securityKey'] = '{}'.format(binascii.hexlify(src_data[1:]))
        elif src_data[0] == 6 or src_data[0] == 10:
            out_msg['securityAccessType'] = 'sendKey'
            if direction == DIRECTION_TX and len(src_data) > 1:
                out_msg['securityKey'] = '{}'.format(binascii.hexlify(src_data[1:]))
    except Exception as e:
        out_msg['err'] = msg = 'ERROR>>{}:{} {} '.format(e.__traceback__.tb_frame.f_globals["__file__"], e.__traceback__.tb_lineno, e)
    return out_msg


def service_0x28_decode(direction, src_data):
    try:
        (enableRxAndTx, enableRxAndDisableTx, disableRxAndEnableTx, disableRxAndTx,
         enableRxAndDisableTxWithEnhancedAddressInformation,
         enableRxAndTxWithEnhancedAddressInformation) = range(0, 6)
        src_name = ('enableRxAndTx', 'enableRxAndDisableTx', 'disableRxAndEnableTx', 'disableRxAndTx',
                    'enableRxAndDisableTxWithEnhancedAddressInformation',
                    'enableRxAndTxWithEnhancedAddressInformation')
        out_msg = { }
        if direction == 0:
            if enableRxAndTxWithEnhancedAddressInformation >= src_data[0] >= enableRxAndTx:
                out_msg['controlType'] = src_name[src_data[0]]
            else:
                out_msg['controlType'] = 'unknown:%d' % src_data[0]
            out_msg['communicationType'] = src_data[1]

            if len(src_data) == 4:#WZD-20220805-1
                out_msg['nodeIdentificationNumber'] = u16_big.unpack_from(src_data, 2)[0]
    except Exception as e:
        out_msg['err'] = msg = 'ERROR>>{}:{} {} '.format(e.__traceback__.tb_frame.f_globals["__file__"], e.__traceback__.tb_lineno, e)
    return out_msg


def service_0x3e_decode(direction, src_data):
    out_msg = { }
    try:
        if src_data[0] == 0:
            out_msg['zeroSubFunction'] = 'zeroSubFunction'
        else:
            out_msg['zeroSubFunction'] = 'unknown:0x%x' % src_data[0]
    except Exception as e:
        out_msg['err'] = msg = 'ERROR>>{}:{} {} '.format(e.__traceback__.tb_frame.f_globals["__file__"], e.__traceback__.tb_lineno, e)
    return out_msg


def service_0x83_decode(direction, src_data):
    out_msg = { }
    try:
        (ISOSAEReserved, readExtendedTimingParameterSet,
         setTimingParametersToDefaultValues, readCurrentlyActiveTimingParameters, setTimingParametersToGivenValues) = (0, 1, 2, 3, 4)
        name = ('ISOSAEReserved', 'readExtendedTimingParameterSet',
                'setTimingParametersToDefaultValues', 'readCurrentlyActiveTimingParameters',
                'setTimingParametersToGivenValues')
        if setTimingParametersToGivenValues >= src_data[0] >= ISOSAEReserved:
            out_msg['timingParameterAccessType'] = name[src_data[0]]
        else:
            out_msg['timingParameterAccessType'] = 'unknown:0x%x' % src_data[0]
    except Exception as e:
        out_msg['err'] = msg = 'ERROR>>{}:{} {} '.format(e.__traceback__.tb_frame.f_globals["__file__"], e.__traceback__.tb_lineno, e)
    return out_msg


def service_0x84_decode(direction, src_data):
    out_msg = { }
    try:
        pass
    except Exception as e:
        out_msg['err'] = msg = 'ERROR>>{}:{} {} '.format(e.__traceback__.tb_frame.f_globals["__file__"], e.__traceback__.tb_lineno, e)
    return out_msg


def service_0x85_decode(direction, src_data):
    out_msg = { }
    try:
        if direction == 0:
            (ISOSAEReserved, on, off) = (0, 1, 2)
            name = ('ISOSAEReserved', 'on', 'off')
            if off >= src_data[0] >= ISOSAEReserved:
                out_msg['DTCSettingType'] = name[src_data[0]]
            else:
                out_msg['DTCSettingType'] = '0x%x' % src_data[0]
            pass
    except Exception as e:
        out_msg['err'] = msg = 'ERROR>>{}:{} {} '.format(e.__traceback__.tb_frame.f_globals["__file__"], e.__traceback__.tb_lineno, e)
    return out_msg


def service_0x86_decode(direction, src_data):
    out_msg = { }
    try:
        if direction == 0:
            if src_data[0] & 0x40:
                out_msg['tStoreEvent'] = 'storeEvent'
            else:
                out_msg['tStoreEvent'] = 'doNotStoreEvent'
            typex = src_data[0] & 0x3f
            eventWindowTime_offset = 1
            if typex == 0:
                out_msg['eventType'] = 'stopResponseOnEvent'
            elif typex == 1:
                out_msg['eventType'] = 'onDTCStatusChange'
                eventWindowTime_offset = 2
                out_msg['DTCStatusMask'] = '{}'.format(bin(src_data[1]))
            elif typex == 2:
                out_msg['eventType'] = 'onTimerInterrupt'
                out_msg['eventTypeRecord'] = '{}'.format(bin(src_data[1]))
                eventWindowTime_offset = 2
            elif typex == 3:
                out_msg['eventType'] = 'onChangeOfDataIdentifier'
                out_msg['eventTypeRecord'] = '{}'.format(binascii.hexlify(src_data[1:]))
                eventWindowTime_offset = 3
            elif typex == 4:
                out_msg['eventType'] = 'reportActivatedEvents'
            elif typex == 5:
                out_msg['eventType'] = 'startResponseOnEvent'
            elif typex == 6:
                out_msg['eventType'] = 'clearResponseOnEvent'
            elif typex == 7:
                out_msg['eventType'] = 'onComparisonOfValues'
                eventWindowTime_offset = 11
                out_msg['eventTypeRecord'] = '{}'.format(binascii.hexlify(src_data[1:]))

                out_msg['eventWindowTime'] = '0x%x'%src_data[2]
                out_msg['did'] = '0x%x' % u16_big.unpack_from(src_data, 3)[0]
                if src_data[6] == 1:
                    out_msg['Comparison logic'] = 'Comparison Parameter < Measured Value'
                elif src_data[6] == 2:
                    out_msg['Comparison logic'] = 'Comparison Parameter > Measured Value'
                elif src_data[6] == 3:
                    out_msg['Comparison logic'] = 'Comparison Parameter = Measured Value'
                elif src_data[6] == 4:
                    out_msg['Comparison logic'] = 'Comparison Parameter <> Measured Value'
                out_msg['Raw reference '] = u32_big.unpack_from(src_data, 7)[0]
                out_msg['hysteresis value'] = '%d%%'%src_data[11]
                tempx = u16_big.unpack_from(src_data, 12)[0]

                if tempx & 0x8000:
                    out_msg['comparison'] = 'comparison with sig'
                else:
                    out_msg['comparison'] = 'comparison without sign'
                out_msg['Localization'] = u16_big.unpack_from(src_data, 12)[0]
                out_msg['did_len'] = tempx>>10 & 0x1f
                out_msg['offset'] = tempx & 0x3f
        else:
            pass
    except Exception as e:
        out_msg['err'] = msg = 'ERROR>>{}:{} {} '.format(e.__traceback__.tb_frame.f_globals["__file__"], e.__traceback__.tb_lineno, e)
    # eventWindowTime
    return out_msg


def service_0x87_decode(direction, src_data):
    out_msg = { }
    try:
        pass
    except Exception as e:
        out_msg['err'] = msg = 'ERROR>>{}:{} {} '.format(e.__traceback__.tb_frame.f_globals["__file__"], e.__traceback__.tb_lineno, e)
    return out_msg


def service_0x22_decode(direction, src_data):
    out_msg = { }
    try:
        identifier = u16_big.unpack_from(src_data, 0)[0]

        out_msg['Identifier_src'] = '0x%04x' % identifier
        if identifier in Identifier_tab.keys():
            out_msg['Identifier'] = Identifier_tab[identifier]
        if direction > 0:
            out_msg['dataRecord'] = binascii.hexlify(src_data[2:])
    except Exception as e:
        out_msg['err'] = msg = 'ERROR>>{}:{} {} '.format(e.__traceback__.tb_frame.f_globals["__file__"], e.__traceback__.tb_lineno, e)
    return out_msg

class ReadMemFrame1(BigEndianStructure):
    _pack_ = 1
    _fields_ = [
        ('sid',c_ubyte),
        ('format',c_ubyte),
        ('addr', c_uint),
        ('len',c_short)
    ]

def service_0x23_decode(direction, src_data):
    out_msg = { }
    try:
        if direction == DIRECTION_TX:
            cmd = bytearray(1)
            cmd[0] = 0x23
            if len(src_data) == 7:
                cmd.extend(src_data)
                msg = ReadMemFrame1.from_buffer(cmd)
                out_msg['memoryAddress'] =  msg.addr
                out_msg['memorySize'] =  msg.len
        else:
            out_msg['dataRecord'] = src_data
            pass
        
    except Exception as e:
        out_msg['err'] = msg = 'ERROR>>{}:{} {} '.format(e.__traceback__.tb_frame.f_globals["__file__"], e.__traceback__.tb_lineno, e)
    return out_msg


def service_0x24_decode(direction, src_data):
    out_msg = { }
    try:
        pass
    except Exception as e:
        out_msg['err'] = msg = 'ERROR>>{}:{} {} '.format(e.__traceback__.tb_frame.f_globals["__file__"], e.__traceback__.tb_lineno, e)
    return out_msg


def service_0x2a_decode(direction, src_data):
    out_msg = { }
    try:
        pass
    except Exception as e:
        out_msg['err'] = msg = 'ERROR>>{}:{} {} '.format(e.__traceback__.tb_frame.f_globals["__file__"], e.__traceback__.tb_lineno, e)
    return out_msg


def service_0x2c_decode(direction, src_data):
    out_msg = { }
    try:
        pass
    except Exception as e:
        out_msg['err'] = msg = 'ERROR>>{}:{} {} '.format(e.__traceback__.tb_frame.f_globals["__file__"], e.__traceback__.tb_lineno, e)
    return out_msg


def service_0x2e_decode(direction, src_data):
    out_msg = { }
    try:
        identifier = u16_big.unpack_from(src_data, 0)[0]

        out_msg['Identifier_src'] = '0x%04x' % identifier

        if identifier in Identifier_tab.keys():
            out_msg['Identifier'] = Identifier_tab[identifier]

        if direction == 0:
            out_msg['dataRecord'] = binascii.hexlify(src_data[2:])
    except Exception as e:
        out_msg['err'] = msg = 'ERROR>>{}:{} {} '.format(e.__traceback__.tb_frame.f_globals["__file__"], e.__traceback__.tb_lineno, e)
    return out_msg


def service_0x3d_decode(direction, src_data):
    out_msg = { }
    try:
        pass
    except Exception as e:
        out_msg['err'] = msg = 'ERROR>>{}:{} {} '.format(e.__traceback__.tb_frame.f_globals["__file__"], e.__traceback__.tb_lineno, e)
    return out_msg


def service_0x14_decode(direction, src_data):
    out_msg = { }
    try:
        if len(src_data) == 3:
            out_msg['groupOfDTC'] = binascii.hexlify(src_data)
    except Exception as e:
        out_msg['err'] = msg = 'ERROR>>{}:{} {} '.format(e.__traceback__.tb_frame.f_globals["__file__"], e.__traceback__.tb_lineno, e)
    return out_msg


def service_0x19_decode(direction, src_data):
    out_msg = { }
    try:
        pass
    except Exception as e:
        out_msg['err'] = msg = 'ERROR>>{}:{} {} '.format(e.__traceback__.tb_frame.f_globals["__file__"], e.__traceback__.tb_lineno, e)
    return out_msg


def service_0x2f_decode(direction, src_data):
    out_msg = { }
    try:
        pass
    except Exception as e:
        out_msg['err'] = msg = 'ERROR>>{}:{} {} '.format(e.__traceback__.tb_frame.f_globals["__file__"], e.__traceback__.tb_lineno, e)
    return out_msg


def service_0x31_decode(direction, src_data):
    out_msg = { }
    try:
        (ISOSAEReserved, startRoutine, stopRoutine, requestRoutineResults) = (0, 1, 2, 3)
        name = ('ISOSAEReserved', 'startRoutine', 'stopRoutine', 'requestRoutineResults')

        if requestRoutineResults >= src_data[0] >= ISOSAEReserved:
            out_msg['sub-function'] = name[src_data[0]]
        else:
            out_msg['sub-function'] = '0x%x' % src_data[0]

        if len(src_data) >= 3:
            routineIdentifier = {
                0xf001:'完整性校验',
                0xff00:'擦除内存',
                0x0203:'预编译条件检测',
                0xff01:'编译依赖性检测',
                }
            val = u16_big.unpack_from(src_data, 1)[0]

            out_msg['routineIdentifier'] =  '0x%04x'%val
            if val in routineIdentifier.keys():
                out_msg['routineIdentifier name'] = routineIdentifier[val]

            if len(src_data) > 3:
                out_msg['routineControlOptionRecord'] = binascii.hexlify(src_data[3:])
    except Exception as e:
        out_msg['err'] = msg = 'ERROR>>{}:{} {} '.format(e.__traceback__.tb_frame.f_globals["__file__"], e.__traceback__.tb_lineno, e)
    return out_msg


def service_0x34_decode(direction, src_data):
    out_msg = { }
    try:
        if direction == 0:
            out_msg['dataFormatIdentifier'] = src_data[0]
            out_msg['addr_bytes'] = src_data[1] & 0xf
            out_msg['size_bytes'] = src_data[1] >> 4
            size_offset = 2
            if out_msg['addr_bytes'] == 4:
                out_msg['addr'] = '0x%08x' % (u32_big.unpack_from(src_data, 2)[0])
                size_offset = 6
            elif out_msg['addr_bytes'] == 1:
                out_msg['addr'] = '0x%02x' % (src_data[2])
                size_offset = 3
            elif out_msg['addr_bytes'] == 2:
                out_msg['addr'] = '0x%04x' % (u16_big.unpack_from(src_data, 2)[0])
                size_offset = 4
            else:
                size_offset = 2

            if out_msg['size_bytes'] == 4:
                out_msg['size'] = u32_big.unpack_from(src_data, size_offset)[0]
                size_offset = 6
            elif out_msg['size_bytes'] == 1:
                out_msg['size'] = src_data[3]
            elif out_msg['size_bytes'] == 2:
                out_msg['size'] = u16_big.unpack_from(src_data, size_offset)[0]
        elif direction > 0:
            lenx = src_data[0] >> 4

            if lenx == 2:
                out_msg['maxNumberOfBlockLength'] = u16_big.unpack_from(src_data, 1)[0]
            elif lenx == 4:
                out_msg['maxNumberOfBlockLength'] = u32_big.unpack_from(src_data, 1)[0]
            elif lenx == 1:
                out_msg['maxNumberOfBlockLength'] = src_data[1]
            else:
                out_msg['maxNumberOfBlockLength'] = 'unknown'
    except Exception as e:
        out_msg['err'] = msg = 'ERROR>>{}:{} {} '.format(e.__traceback__.tb_frame.f_globals["__file__"], e.__traceback__.tb_lineno, e)
    return out_msg


def service_0x35_decode(direction, src_data):
    out_msg = { }
    try:
        pass
    except Exception as e:
        out_msg['err'] = msg = 'ERROR>>{}:{} {} '.format(e.__traceback__.tb_frame.f_globals["__file__"], e.__traceback__.tb_lineno, e)
    return out_msg


def service_0x36_decode(direction, src_data):
    out_msg = { }
    try:
        if len(src_data) >= 1:
            out_msg['blockSequenceCounter'] = src_data[0]
            if len(src_data) > 1:
                out_msg['transferResponseParameterRecord'] = binascii.hexlify(src_data[1:])
        pass
    except Exception as e:
        out_msg['err'] = msg = 'ERROR>>{}:{} {} '.format(e.__traceback__.tb_frame.f_globals["__file__"], e.__traceback__.tb_lineno, e)
    return out_msg


def service_0x37_decode(direction, src_data):
    out_msg = { }
    try:
        pass
    except Exception as e:
        out_msg['err'] = msg = 'ERROR>>{}:{} {} '.format(e.__traceback__.tb_frame.f_globals["__file__"], e.__traceback__.tb_lineno, e)
    return out_msg


def service_0x38_decode(direction, src_data):
    out_msg = { }
    try:
        pass
    except Exception as e:
        out_msg['err'] = msg = 'ERROR>>{}:{} {} '.format(e.__traceback__.tb_frame.f_globals["__file__"], e.__traceback__.tb_lineno, e)
    return out_msg


def service_0x7f_decode(direction, src_data):
    out_msg = { }
    try:
        if src_data[0] in service.keys():
            out_msg['negative sid'] = service[src_data[0]]['name']
            if src_data[1] in negative_response_codes.keys():
                out_msg['negative reason'] = negative_response_codes[src_data[1]]
            else:
                out_msg['negative sid'] = 'unknown:0x%x' % src_data[1]
        else:
            out_msg['negative sid'] = '0x%x'%(src_data[0])
    except Exception as e:
        out_msg['err'] = msg = 'ERROR>>{}:{} {} '.format(e.__traceback__.tb_frame.f_globals["__file__"], e.__traceback__.tb_lineno, e)
    return out_msg

service = {
    0x10: {
        'name': 'DiagnosticSessionControl',
        'decode': service_0x10_decode,
        'nrc': {0x12: 'sub-functionNotSupported ',
                0x13: 'incorrectMessageLengthOrInvalidFormat',
                0x22: 'conditionsNotCorrect'}

    },
    0x11: {
        'name': 'ECUReset',
        'decode': service_0x11_decode,
        'nrc': {0x12: 'sub-functionNotSupported ',
                0x13: 'incorrectMessageLengthOrInvalidFormat',
                0x22: 'conditionsNotCorrect',
                0x33: 'securityAccessDenied'}
    },
    0x27: {
        'name': 'securityAccess',
        'decode': service_0x27_decode,
        'nrc': {0x12: 'sub-functionNotSupported ',
                0x13: 'incorrectMessageLengthOrInvalidFormat',
                0x22: 'conditionsNotCorrect',
                0x24: 'requestSequenceError',
                0x31: 'requestOutOfRange',
                0x35: 'invalidKey',
                0x36: 'exceededNumberOfAttempts',
                0x37: 'requiredTimeDelayNotExpired'
                }
    },
    0x28: {
        'name': 'CommunicationControl',
        'decode': service_0x28_decode,
        'nrc': {0x12: 'sub-functionNotSupported ',
                0x13: 'incorrectMessageLengthOrInvalidFormat',
                0x22: 'conditionsNotCorrect',
                0x31: 'requestOutOfRange'
                }
    },
    0x3e: {
        'name': 'TesterPresent',
        'decode': service_0x3e_decode,
        'nrc': {0x12: 'sub-functionNotSupported ',
                0x13: 'incorrectMessageLengthOrInvalidFormat'
                }
    },
    0x83: {
        'name': 'AccessTimingParameter',
        'decode': service_0x83_decode,
        'nrc': {0x12: 'sub-functionNotSupported ',
                0x13: 'incorrectMessageLengthOrInvalidFormat',
                0x22: 'conditionsNotCorrect',
                0x31: 'requestOutOfRange'
                }
    },
    0x84: {
        'name': 'SecuredDataTransmission',
        'decode': service_0x84_decode,
        'nrc': {
            0x13: 'incorrectMessageLengthOrInvalidFormat',
        }
    },
    0x85: {
        'name': 'ControlDTCSetting',
        'decode': service_0x85_decode,
        'nrc': {0x12: 'sub-functionNotSupported ',
                0x13: 'incorrectMessageLengthOrInvalidFormat',
                0x22: 'conditionsNotCorrect',
                0x31: 'requestOutOfRange'
                }
    },
    0x86: {
        'name': 'ResponseOnEvent',
        'decode': service_0x86_decode,
        'nrc': {0x12: 'sub-functionNotSupported ',
                0x13: 'incorrectMessageLengthOrInvalidFormat',
                0x22: 'conditionsNotCorrect',
                0x31: 'requestOutOfRange'
                }
    },
    0x87: {
        'name': 'LinkControl',
        'decode': service_0x87_decode,
        'nrc': {0x12: 'sub-functionNotSupported ',
                0x13: 'incorrectMessageLengthOrInvalidFormat',
                0x22: 'conditionsNotCorrect',
                0x24: 'requestSequenceError',
                0x31: 'requestOutOfRange'
                }
    },
    0x22: {
        'name': 'ReadDataByIdentifier',
        'decode': service_0x22_decode,
        'nrc': {
            0x13: 'incorrectMessageLengthOrInvalidFormat',
            0x14: 'responseTooLong',
            0x22: 'conditionsNotCorrect',
            0x33: 'securityAccessDenied',
            0x31: 'requestOutOfRange'
        }
    },
    0x23: {
        'name': 'ReadMemoryByAddress',
        'decode': service_0x23_decode,
        'nrc': {
            0x13: 'incorrectMessageLengthOrInvalidFormat',
            0x33: 'securityAccessDenied',
            0x31: 'requestOutOfRange'
        }
    },
    0x24: {
        'name': 'ReadScalingDataByIdentifier',
        'decode': service_0x24_decode,
        'nrc': {
            0x13: 'incorrectMessageLengthOrInvalidFormat',
            0x22: 'conditionsNotCorrect',
            0x33: 'securityAccessDenied',
            0x31: 'requestOutOfRange'
        }
    },
    0x2a: {
        'name': 'ReadDataByPeriodicIdentifier',
        'decode': service_0x2a_decode,
        'nrc': {
            0x13: 'incorrectMessageLengthOrInvalidFormat',
            0x22: 'conditionsNotCorrect',
            0x33: 'securityAccessDenied',
            0x31: 'requestOutOfRange'
        }
    },
    0x2c: {
        'name': 'DynamicallyDefineDataIdentifier',
        'decode': service_0x2c_decode,
        'nrc': {
            0x12: 'sub-functionNotSupported',
            0x13: 'incorrectMessageLengthOrInvalidFormat',
            0x22: 'conditionsNotCorrect',
            0x33: 'securityAccessDenied',
            0x31: 'requestOutOfRange'
        }
    },
    0x2e: {
        'name': 'WriteDataByIdentifier',
        'decode': service_0x2e_decode,
        'nrc': {
            0x13: 'incorrectMessageLengthOrInvalidFormat',
            0x22: 'conditionsNotCorrect',
            0x33: 'securityAccessDenied',
            0x31: 'requestOutOfRange'
        }
    },
    0x3d: {
        'name': 'WriteMemoryByAddress',
        'decode': service_0x3d_decode,
        'nrc': {
            0x13: 'incorrectMessageLengthOrInvalidFormat',
            0x22: 'conditionsNotCorrect',
            0x33: 'securityAccessDenied',
            0x31: 'requestOutOfRange'
        }
    },
    0x14: {
        'name': 'ClearDiagnosticInformation',
        'decode': service_0x14_decode,
        'nrc': {
            0x12: 'sub-functionNotSupported',
            0x13: 'incorrectMessageLengthOrInvalidFormat',
            0x31: 'requestOutOfRange'
        }
    },
    0x19: {
        'name': 'ReadDTCInformation',
        'decode': service_0x19_decode,
        'nrc': {
            0x13: 'incorrectMessageLengthOrInvalidFormat',
            0x22: 'conditionsNotCorrect',
            0x72: 'generalProgrammingFailure',
            0x31: 'requestOutOfRange'
        }
    },
    0x2f: {
        'name': 'InputOutputControlByIdentifier',
        'decode': service_0x2f_decode,
        'nrc': {
            0x13: 'incorrectMessageLengthOrInvalidFormat',
            0x22: 'conditionsNotCorrect',
            0x31: 'requestOutOfRange'
        }
    },
    0x31: {
        'name': 'RoutineControl',
        'decode': service_0x31_decode,
        'nrc': {
            0x12: 'sub-functionNotSupported',
            0x13: 'incorrectMessageLengthOrInvalidFormat',
            0x22: 'conditionsNotCorrect',
            0x24: 'requestSequenceError',
            0x31: 'requestOutOfRange',
            0x33: 'securityAccessDenied',
            0x72: 'GeneralProgrammingFailure'
        }
    },
    0x34: {
        'name': 'RequestDownload',
        'decode': service_0x34_decode,
        'nrc': {
            0x13: 'incorrectMessageLengthOrInvalidFormat',
            0x22: 'conditionsNotCorrect',
            0x31: 'requestOutOfRange',
            0x33: 'securityAccessDenied',
            0x70: 'uploadDownloadNotAccepted'
        }
    },
    0x35: {
        'name': 'RequestUpload',
        'decode': service_0x35_decode,
        'nrc': {
            0x13: 'incorrectMessageLengthOrInvalidFormat',
            0x22: 'conditionsNotCorrect',
            0x31: 'requestOutOfRange',
            0x33: 'securityAccessDenied',
            0x70: 'uploadDownloadNotAccepted'
        }
    },
    0x36: {
        'name': 'TransferData',
        'decode': service_0x36_decode,
        'nrc': {
            0x13: 'incorrectMessageLengthOrInvalidFormat',
            0x24: 'requestSequenceError',
            0x31: 'requestOutOfRange',
            0x71: 'transferDataSuspended',
            0x72: 'generalProgrammingFailure',
            0x73: 'wrongBlockSequenceCounter',
            0x92: 'voltageTooHigh',
            0x93: 'voltageTooLow',
        }
    },
    0x37: {
        'name': 'RequestTransferExit',
        'decode': service_0x37_decode,
        'nrc': {
            0x13: 'incorrectMessageLengthOrInvalidFormat',
            0x24: 'requestSequenceError',
            0x31: 'requestOutOfRange',
            0x72: 'generalProgrammingFailure'
        }
    },
    0x38: {
        'name': 'RequestFileTransfer',
        'decode': service_0x38_decode,
        'nrc': {
            0x13: 'incorrectMessageLengthOrInvalidFormat',
            0x22: 'conditionsNotCorrect',
            0x31: 'requestOutOfRange',
            0x33: 'securityAccessDenied',
            0x70: 'uploadDownloadNotAccepted'
        }
    },
    0x3f: {
        'name': 'Negative response service identifier',
        'decode': service_0x7f_decode,
        'nrc': {}
    }
}

def decode_app(data):
    out_msg = {}
    try:
        
        si = data[0]
        did_st = struct.Struct('>H')
        msg = ''
        tx_mark = si & 0x40
        si &= 0xbf
        uds_appp_wdbg.info('tx mark:%x si:0x%x',tx_mark,si)
        out_msg = {'time':get_time_str()}
        
        direction = DIRECTION_RX
        if tx_mark:
            if data[0] == 0x7f:
                out_msg['direction'] = 'negative response codes'
            else:
                out_msg['direction'] = 'Positive response message'
        else:
            direction = DIRECTION_TX
            out_msg['direction'] = 'Request message'

        if si in service.keys():
            out_msg['Service Identifier'] = service[si]['name']
        else:
            out_msg['Service Identifier'] = '%x'%si

        if si in service.keys():
            if 'decode' in service[si].keys():
                # out_msg['src data'] = get_hex_data(data[1:])
                out_msg_temp = (service[si]['decode'])(direction, data[1:])
                out_msg.update(out_msg_temp)
                

        
        
        
    except Exception as e:
        printf_except_info(e)
    return out_msg
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

魏振东991

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值