使用python执行uds诊断

这篇具有很好参考价值的文章主要介绍了使用python执行uds诊断。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

        主要是通过python-can模块与pcan等支持的硬件通讯,uds协议层使用udsoncan模块和can-isotp模块实现uds诊断。

1、模块安装及相关文档

        python-can模块

        pip install python-can

        相关文档链接:Installation - python-can 4.1.0 documentation

        

        udsoncan模块

        pip install udsoncan

        相关文档链接:Python implementation of UDS standard (ISO-14229) — udsoncan 0 documentation

        can-isotp模块

        pip install can-isotp

        相关文档链接:Python support for IsoTP Transport protocol (ISO-15765) — isotp 0 documentation

2、相关示例

        下面示例展示了如何将PythonIsoTpConnection与Vector接口一起使用。

from can.interfaces.vector import VectorBus
from udsoncan.connections import PythonIsoTpConnection
from udsoncan.client import Client
import isotp

# Refer to isotp documentation for full details about parameters
isotp_params = {
   'stmin' : 32,                          # Will request the sender to wait 32ms between consecutive frame. 0-127ms or 100-900ns with values from 0xF1-0xF9
   'blocksize' : 8,                       # Request the sender to send 8 consecutives frames before sending a new flow control message
   'wftmax' : 0,                          # Number of wait frame allowed before triggering an error
   'tx_data_length' : 8,                  # Link layer (CAN layer) works with 8 byte payload (CAN 2.0)
   'tx_data_min_length' : None,           # Minimum length of CAN messages. When different from None, messages are padded to meet this length. Works with CAN 2.0 and CAN FD.
   'tx_padding' : 0,                      # Will pad all transmitted CAN messages with byte 0x00.
   'rx_flowcontrol_timeout' : 1000,       # Triggers a timeout if a flow control is awaited for more than 1000 milliseconds
   'rx_consecutive_frame_timeout' : 1000, # Triggers a timeout if a consecutive frame is awaited for more than 1000 milliseconds
   'squash_stmin_requirement' : False,    # When sending, respect the stmin requirement of the receiver. If set to True, go as fast as possible.
   'max_frame_size' : 4095                # Limit the size of receive frame.
}

bus = VectorBus(channel=0, bitrate=500000)                                          # Link Layer (CAN protocol)
tp_addr = isotp.Address(isotp.AddressingMode.Normal_11bits, txid=0x123, rxid=0x456) # Network layer addressing scheme
stack = isotp.CanStack(bus=bus, address=tp_addr, params=isotp_params)               # Network/Transport layer (IsoTP protocol)
stack.set_sleep_timing(0, 0)                                                        # Speed First (do not sleep)
conn = PythonIsoTpConnection(stack)                                                 # interface between Application and Transport layer
with Client(conn, request_timeout=1) as client:                                     # Application layer (UDS protocol)
   client.change_session(1)
   # ...

        其他uds服务相关使用示例:

import udsoncan
from udsoncan.connections import IsoTPSocketConnection
from udsoncan.client import Client
from udsoncan.exceptions import *
from udsoncan.services import *

udsoncan.setup_logging()

conn = IsoTPSocketConnection('can0', rxid=0x123, txid=0x456)
with Client(conn,  request_timeout=2, config=MyCar.config) as client:
   try:
      client.change_session(DiagnosticSessionControl.Session.extendedDiagnosticSession)  # integer with value of 3
      client.unlock_security_access(MyCar.debug_level)   # Fictive security level. Integer coming from fictive lib, let's say its value is 5
      client.write_data_by_identifier(udsoncan.DataIdentifier.VIN, 'ABC123456789')       # Standard ID for VIN is 0xF190. Codec is set in the client configuration
      print('Vehicle Identification Number successfully changed.')
      client.ecu_reset(ECUReset.ResetType.hardReset)  # HardReset = 0x01
   except NegativeResponseException as e:
      print('Server refused our request for service %s with code "%s" (0x%02x)' % (e.response.service.get_name(), e.response.code_name, e.response.code))
   except InvalidResponseException, UnexpectedResponseException as e:
      print('Server sent an invalid payload : %s' % e.response.original_payload)

安全算法示例,需要实现myalgo函数,并且uds的configs中的security_algo配置为myalgo,同时配置security_algo_params。

def myalgo(level, seed, params):
"""
Builds the security key to unlock a security level. Returns the seed xor'ed with pre-shared key.
"""
   output_key = bytearray(seed)
   xorkey = bytearray(params['xorkey'])

   for i in range(len(seed)):
      output_key[i] = seed[i] ^ xorkey[i%len(xorkey)]
   return bytes(output_key)

client.config['security_algo'] = myalgo
client.config['security_algo_params'] = dict(xorkey=b'\x12\x34\x56\x78')

使用DID配置配置客户端,并使用ReadDataByIdentifier请求服务器文章来源地址https://www.toymoban.com/news/detail-491330.html

import udsoncan
from udsoncan.connections import IsoTPSocketConnection
from udsoncan.client import Client
import udsoncan.configs
import struct

class MyCustomCodecThatShiftBy4(udsoncan.DidCodec):
   def encode(self, val):
      val = (val << 4) & 0xFFFFFFFF # Do some stuff
      return struct.pack('<L', val) # Little endian, 32 bit value

   def decode(self, payload):
      val = struct.unpack('<L', payload)[0]  # decode the 32 bits value
      return val >> 4                        # Do some stuff (reversed)

   def __len__(self):
      return 4    # encoded payload is 4 byte long.


config = dict(udsoncan.configs.default_client_config)
config['data_identifiers'] = {
   0x1234 : MyCustomCodecThatShiftBy4,    # Uses own custom defined codec. Giving the class is ok
   0x1235 : MyCustomCodecThatShiftBy4(),  # Same as 0x1234, giving an instance is good also
   0xF190 : udsoncan.AsciiCodec(15)       # Codec that read ASCII string. We must tell the length of the string
   }

# IsoTPSocketconnection only works with SocketCAN under Linux. Use another connection if needed.
conn = IsoTPSocketConnection('vcan0', rxid=0x123, txid=0x456)
with Client(conn,  request_timeout=2, config=config) as client:
   response = client.read_data_by_identifier([0xF190])
   print(response.service_data.values[0xF190]) # This is a dict of DID:Value

   # Or, if a single DID is expected, a shortcut to read the value of the first DID
   vin = client.read_data_by_identifier_first(0xF190)
   print(vin)  # 'ABCDE0123456789' (15 chars)

到了这里,关于使用python执行uds诊断的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • UDS诊断协议——网络层协议

     UDS(unified Diagnostic Service, 统一诊断服务)是一个在整个汽车系统上经常使用的设备维护协议。其主要遵循: ISO-15765、ISO-14229,其ISO-15765协议是适用于网络层的协议,主要规范了“传输协议和网络层服务”, ISO-14229协议对应用层、会话层做出了定义。 协议功能        UDS网络

    2024年02月04日
    浏览(42)
  • UDS诊断之负响应码

    否定响应码(NRC) 定义(Defination) 0x12 服务器支持诊断请求中的服务标识符(Service ID),但不支持收到的子功能参数时,回复此编码。 0x13 请求服务的诊断报文中的数据长度与定义不一致时,回复此编码。请求服务中参数的格式与定义不一致时也会回复此编码。 0x22 请求的诊断服务的执

    2024年02月11日
    浏览(36)
  • UDS统一诊断服务【一】诊断会话控制0X10服务

    最近在做诊断相关的开发工作,将自己接触到的知识点记录下来。前面的文章已经介绍过UDS的一些基础知识,和基本的一些概念,不清楚的可以查看之前的文章:UDS基础知识介绍 诊断会话控制服务 DiagnosticSessionControl ,SID是0X10,主要功能是控制服务端的会话模式切换。一般默

    2024年02月03日
    浏览(53)
  • 【车载开发系列】UDS诊断---读取数据($0x22)

    该服务的英文简称为ReadDataByIdentifier 。 根据ISO14119-1标准中所述,诊断服务22主要用于Client向Server(ECU)通过DID的方式读取相关的数据。这些数据可以输入输出的数字信号,模拟信号,内部数据以及其他的系统状态信息。作为诊断服务种的基础服务,可以简单理解为就是一个用于

    2023年04月19日
    浏览(38)
  • 【车载开发系列】UDS诊断---安全访问服务($0x27)

    该服务提供了一种保护机制,该机制用来保护访问限制的诊断服务。 加密策略采用种子和密钥相关联的方法。采用随机产生的种子,通过安全算法得到唯一的秘钥。 若秘钥匹配正确则可以调用受到保护的诊断服务。这个服务解锁的是处在某个安全等级下的服务。 诊断工具请

    2024年02月03日
    浏览(45)
  • 【车载开发系列】UDS诊断---动态定义DID($0x2C)

    动态定义数据标识符 DynamicallyDefineDataIdentifier(2Ch) 此服务允许诊断工具在ECU的内部动态定义一个数据标识符,一个临时的DID,可以通过这个DID读取一段内存的数据,也可以通过改DID一次性读取多个原有DID的数据。 该数据标识符还可以被读取数据服务22h或读取数据(周期标识

    2024年02月02日
    浏览(40)
  • 汽车诊断之UDS入门-0x27(SecurityAccess)安全访问

    安全访问服务 0x27 用来解锁 ECU 对应的安全等级 , 一般处在非默认会话 下 进行解锁,这个服务解锁的是 处在某个安全等级下的服务 。 服务格式   安全等级解闭锁   需要注意的是: 1.P owerOn 或者 R eset 后, ECU 处在 locked 状态; 2.同一时刻只有 1 个安全等级是 active ,与这个

    2024年02月08日
    浏览(37)
  • 【车载开发系列】UDS诊断---读取DTC信息($0x19)

    UDS可以简单理解为一套完整的通讯协议框架,其目的在于规范各种行车电脑和ECU之间的通讯。0x19服务其实是读取DTC信息的服务。 1)DTC概念 故障存储相关的0x19和0x14服务。 当系统检测到了一个错误或者是一个故障发生的时候,会将相对应的数值故障码进行存储,那么这个对应

    2024年01月15日
    浏览(34)
  • 车载诊断NRC - UDS Negative Response Code

    下表中列出了ISO14229-1:2013(E)中定义的否定响应码及其使用条件: 否定响应码的取值范围为0x00 - 0xFF,被分为三组: 0x00:服务器内部实现否定响应码判断逻辑时使用,表示要给出肯定响应。 0x01 – 0x7F:诊断通信相关的否定响应码。 0x80 – 0xFF:服务器收到诊断服务请求时,由

    2023年04月08日
    浏览(27)
  • UDS诊断系列之七 安全访问(27)服务(番外)附录I

    附录I的主要内容是通过一个状态图来描述ECU在安全访问的各状态之间的切换条件,以及如何进行状态切换即切换过程中都需要执行哪些操作。 下面直接先上图。 图看起来流程很多,但实际上很简单,先说图中的四个状态: A - ECU没有接收过任何安全访问的请求,或者刚刚接

    2024年02月10日
    浏览(26)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包