Code Monkey home page Code Monkey logo

python-udsoncan's People

Contributors

amrobidoux avatar bollenn avatar eranzim avatar fbagagli avatar guigor avatar hugga avatar jacobschaer avatar jmoren13 avatar joefischetti avatar kenjo avatar kirya-dev avatar kloolk avatar lumagi avatar martinjthompson avatar martonmiklos avatar mikisama avatar nbusser avatar pierreluctg avatar pylessard avatar shutingrz avatar speedy-h avatar trivialpursuer avatar venden avatar wanam avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

python-udsoncan's Issues

During handling of the above exception, another exception occurred:

this is part of the code that I writed.

class UdsApp(object):
def init(self):
self.__bitrates = {
'500K': 500000,
'250K': 250000,
'125K': 125000,
}

def usd_app_deal(self,channel,bitrate,isotp_params,PhyID,ResponID):
    # 自定义logging.conf配置文件
    udslog_config_file = path.join(path.dirname(path.abspath(__file__)), 'logging.conf')
    # 开始起动udslogging
    udsoncan.setup_logging(config_file = udslog_config_file)

    thread = Thread(target=self.uds_app, args=(channel,bitrate,isotp_params,PhyID,ResponID))
    thread.start()

def uds_app(self,channel,bitrate,isotp_params,PhyID,ResponID):
    # Link Layer (CAN protocol)
    bus = KvaserBus(channel=int(channel),bitrate=self.__bitrates[bitrate])
    # Network layer addr

essing scheme
tp_addr = isotp.Address(isotp.AddressingMode.Normal_11bits, txid=eval(PhyID), rxid=eval(ResponID))
# Network/Transport layer (IsoTP protocol)
stack = isotp.CanStack(bus=bus, address=tp_addr, params=isotp_params)
# interface between Application and Transport layer
conn = PythonIsoTpConnection(stack)
# Application layer (UDS protocol)

    with Client(conn, request_timeout=1) as client:
        try:
            client.change_session(DiagnosticSessionControl.Session.defaultSession)
            # client.read_data_by_identifier_first(0xF190)
            # res_f193 = client.read_data_by_identifier(0xF193)
            # print(res_f193.service_data.values[0xF190])  # This is a dict of DID:Value
            # res_f195 = client.read_data_by_identifier(0xF195)
            # print(res_f195.service_data.values[0xF190])  # This is a dict of DID:Value
            # 
            # client.change_session(DiagnosticSessionControl.Session.extendedDiagnosticSession)
            # client.control_dtc_setting(ControlDTCSetting.SettingType.off)
            # client.communication_control(0x01,CommunicationControl.ControlType.disableRxAndTx)
            # 
            # client.change_session(DiagnosticSessionControl.Session.programmingSession)
            # client.request_seed(0x11)
        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 or UnexpectedResponseException as e:
        #     print('Server sent an invalid payload : %s' % e.response.original_payload)
        # # except UnexpectedResponseException as e:
        # #     print('Server sent an invalid payload : %s' % e.response.original_payload)
        finally:
            print('其他错误')

In fact, the can bus donot response [client.change_session], But the program reported the following error:

2020-07-08 14:49:30 [INFO] Connection: Connection opened
2020-07-08 14:58:58 [INFO] UdsClient: DiagnosticSessionControl<0x10> - Switching session to defaultSession (0x01)
2020-07-08 14:58:58 [DEBUG] Connection: Sending 2 bytes : [b'1001']
2020-07-08 14:58:59 [DEBUG] Connection: No data received: [TimeoutException] - Did not receive frame IsoTP Transport layer in time (timeout=0.9980063438415527 sec)
2020-07-08 14:58:59 [ERROR] UdsClient: [TimeoutException] : Did not receive response in time. Global request timeout time has expired (timeout=0.998 sec)
其他错误
2020-07-08 15:02:10 [INFO] Connection: Connection closed
Traceback (most recent call last):
File "C:\Users\Gary\AppData\Local\Programs\Python\Python38\lib\site-packages\udsoncan-1.12.2-py3.8.egg\udsoncan\client.py", line 1631, in send_request
payload = self.conn.wait_frame(timeout=timeout_value, exception=True)
File "C:\Users\Gary\AppData\Local\Programs\Python\Python38\lib\site-packages\udsoncan-1.12.2-py3.8.egg\udsoncan\connections.py", line 68, in wait_frame
frame = self.specific_wait_frame(timeout=timeout)
File "C:\Users\Gary\AppData\Local\Programs\Python\Python38\lib\site-packages\udsoncan-1.12.2-py3.8.egg\udsoncan\connections.py", line 490, in specific_wait_frame
raise TimeoutException("Did not receive frame IsoTP Transport layer in time (timeout=%s sec)" % timeout)
udsoncan.exceptions.TimeoutException: Did not receive frame IsoTP Transport layer in time (timeout=0.9980063438415527 sec)

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "C:\Users\Gary\AppData\Local\Programs\Python\Python38\lib\threading.py", line 870, in run
self._target(*self._args, **self._kwargs)
File "D:\01 工作\13 软件开发\04 Python\02 Bootload tool\02 py\V1_2\APP1\UdsApp.py", line 44, in uds_app
client.change_session(DiagnosticSessionControl.Session.defaultSession)
File "C:\Users\Gary\AppData\Local\Programs\Python\Python38\lib\site-packages\udsoncan-1.12.2-py3.8.egg\udsoncan\client.py", line 123, in decorated
return func(self, *args, **kwargs)
File "C:\Users\Gary\AppData\Local\Programs\Python\Python38\lib\site-packages\udsoncan-1.12.2-py3.8.egg\udsoncan\client.py", line 181, in change_session
response = self.send_request(req)
File "C:\Users\Gary\AppData\Local\Programs\Python\Python38\lib\site-packages\udsoncan-1.12.2-py3.8.egg\udsoncan\client.py", line 1639, in send_request
raise TimeoutException('Did not receive response in time. %s time has expired (timeout=%.3f sec)' % (timeout_name_to_report, timeout_value))
udsoncan.exceptions.TimeoutException: Did not receive response in time. Global request timeout time has expired (timeout=0.998 sec)

my question:
1、why isoIsoTP and cilent all reported timeout errors?
2、 why prompt error "During handling of the above exception, another exception occurred:"?

Cannot pass Single Value to InputOutputControlByIdentifier

Unable to pass a single integer value to InputOutputControlByIdentifier service for overwriting a field represented by a Data Identifier. The service only accepts the following inputs:

  • A list for positional arguments
  • A dict for named arguments
  • An instance of :ref:IOValues<IOValues> for mixed arguments

but not a single argument such as

udsoncan.services.InputOutputControlByIdentifier.make_request(
            did=0xFFF,
            control_param=1,
            values=10,
            ioconfig={0xFFFF: ChildDidCodec()},
        )

Getting the following error from this block of code: https://github.com/pylessard/python-udsoncan/blob/master/udsoncan/services/InputOutputControlByIdentifier.py#L76

        if values is not None:
            if isinstance(values, list):
                values = IOValues(*values)
            if isinstance(values, dict):
                values = IOValues(**values)
    
            if not isinstance(values, IOValues):
>               raise ValueError("values must be an instance of IOValues")
E               ValueError: values must be an instance of IOValues

problem with multiple PythonIsoTpConnection open

I'm seeing a problem when having multiple PythonIsoTpConnection objects open() at the same time. Sending a read_data_by_identifier() hangs most of the time, but not always, statistically more often the more connections are open. They seem to interfere / block each other.
Symptom is, the ECU sends back the FirstFrame of the answer, but the host is not replying with a FlowControlFrame. Communication ceases at this point, in consequence no ConsecutiveFrames get sent by the ECU, the request finally times out.
I've observed this with v1.8 and v1.9, on different hosts (ARM and Intel) and different Python versions (3.55 and 3.74)
When using the kernel native IsoTPSocketConnection instead, it works fine. However, I can't use this since it requires Python3.7.

Messages using 'suppress_positive_response' are not sent.

First, I want you to know that I am not good at English.
so, I ask you a little patience.

I wanted to change the diagSession using the following code.
image

But, the message was not sent. I attached logs below.
image

As you already know, IsoTP did not work at all.
So, I tried to debug this.

When I set a breakpoint at the location shown in the picture below of 'client.py', a message was sent.
image

If I do not set a breakpoint, the message will not be sent.

I use vector hardware in Windows environment.

Am I misusing the API?

Thank you.

MemoryLocation memorysize_format

Running udsoncan==1.5

I found that the memorysize_format param of MemoryLocation doesn't change the format of the data sent on the bus, the only way to get the format to change is by defining it in the config before hand.

Looking into the issue, you may have quick fix though?

Appropriate failure response to send on timeout?

If the 1-2s second timeout to wait for consecutive frames in a multi-frame message is met, what is the correct behavior:

  1. send nothing, wait for device to retry
  2. send 7F failure... with what value for "timeout response"?

Do you have an example of SomeLib

Not really an issue as much as a question. I would like to use your tool to help test a UDS server on a unit we're building. I'm new to UDS but familiar with CAN and J1939.

I'll pre-apologize and admit that my python is intermediate at best.

In your example code you pull in the MyCar config object from the SomeLib.SomeCar.SomeModel. Do you have an example (even a small one) of this module.. Currently I'm only trying to query data by identifier on my server..

DTC cannot be read by valuecan

hello Mr. Pier
from the issue :#12, i guess udsoncan can supprot the ValueCAN.
now when i read the DTC by ValueCAN, uedoncan can not get the response:
the interface is :
bus = NeoViBus(bustype='neovi', channel=1, bitrate=500000) # value can / 581

udsoncan can sent the "19022F" to the ECU successful, and ECU responsed "[11 53]59 02 FF 06 07 41……" , but udsoncan reported an error "raise TimeoutException('Did not receive response in time. %s time has expired (timeout=%.3f sec)' % (timeout_name_to_report, timeout_value))
udsoncan.exceptions.TimeoutException: Did not receive response in time. P2 timeout time has expired (timeout=5.000 sec)"

image
the snapshot when read the DTC by ValueCAN

if i try to read the DTC by canaylzer, it works fine;

image
the snapshot when read the DTC by canaylzer

read to DTC.zip

could you please help me to check mine code where is wrong? thanks very much!

Documentation is incomplete regarding how DTC are reported

i used the following code to read the DTC:
with Client(conn, request_timeout=10) as client:
DTC_list = client.get_dtc_by_status_mask(status_mask)
print("DTC list:", DTC_list)

but i didn't get the DTC code, i got :
DTC list :<PositiveResponse:[ReadDTCInformation]-61 data bytes at 0x0322ff0>;

could you please tell me how can i get the DTC code?

RuntimeException is not defined in connections.py

Hello, I encountered this message while sending request:
File "/usr/local/lib/python3.5/dist-packages/udsoncan-1.7-py3.5.egg/udsoncan/connections.py", line 68, in wait_frame frame = self.specific_wait_frame(timeout=timeout) NameError: name 'RuntimeException' is not defined
I am still looking for root cause on my side but I wanted to ask if this exception is correct.
Btw. thanks for very nice lib ;)

Support for ETAS CAN dongle

Hi,
I wanted to know if it is possible to add support for ETAS CAN dongle?
I have used the PeakCAN and Kvaser interfaces and they work a treat.

I did not see much information online for the ETAS Python interface. I currently hanging on a ETAS ES581.4 dongle without Python support.

Any chance any one has already come across this? Any fix to use it with Python UDSonCAN ?

Many thanks,
Anil

Configure issue : stmin

hello,
I am trying to configure the parameter stmin to 1miliseconds for my connection. but getting the following error.

connection :
my_connection = IsoTPSocketConnection('vcan0', rxid=0x74F, txid=0x74E,stmin =1000)

Error :
Could not import vxlapi: module 'ctypes' has no attribute 'windll'
Let me know whether I am doing it correctly or is there any way to configure it.
so kindly help here, I am new to these things.
thanks in advance.

How to get the Reading DID Response by my custom formula

Hi Friends,
I want to use this library to get the Reading DID response by my custom formula.
for example, I want to send 0x03 0x22 0x01 0x9E, and the response will be like: 0x05 0x62 0x01 0x9E 0x03 0x1F, and the formula is to convert 0x03 and 0x1F from hex to dec then multiply by 0.1544, so I want to get the result is 799(0x031F)*0.01544=12.33656.
I have checked the official example, but I still don't understand well. so sorry...
I don't know how to define the detail config, If you know about this, could you please help me on this. Thank you very much.
below is my original code, but it can't be run correctly...

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

class MyCustomCode:
def encode(byte_1, byte_2):
cal_value = (((byte_1 << 8) + byte_2) * 0.01544)
return cal_value

isotp_params = {
'stmin': 32,
'blocksize': 8,
'wftmax': 0,
'll_data_length': 8,
'tx_padding': 0,
'rx_flowcontrol_timeout': 1000,
'rx_consecutive_frame_timeout': 1000,
'squash_stmin_requirement': False
}
bus = VectorBus(bustype='vector', app_name='CANalyzer', channel=[0])
ecu_address = isotp.Address(isotp.AddressingMode.Normal_29bits, txid=0x18DA10F1, rxid=0x18DAF110)
stack = isotp.CanStack(bus=bus, address=ecu_address, params=isotp_params)
conn = PythonIsoTpConnection(stack)
config = dict(udsoncan.configs.default_client_config)
config['data_identifiers'] = {0x019E: MyCustomCode.encode()}
with Client(conn, request_timeout=2, config=config) as client:
ecu_did_response = client.read_data_by_identifier_first(0x019E)
print(ecu_did_response) `

Problemi installing package from pip

Hi,
first of all thanks for the huge work on this module, especially for the complete test suite that came with it.

Installing the module on a clean environment with python 3.7 on Ubunt 18.04, i've found that the module came installed without the udsoncan/services directory, and also the logging.conf file is missing.
So if you run "import udsoncan" from an interactive python session, an exception is raised

These are the steps to reproduce:

$ pipenv --python 3.7
$ pipenv shell
$ pip install udsoncan
$ python (to enter interactive session)
import udsoncan (<- this raise the exception)

I've modified the setup.py that seems to resolve this problem, and i've created this pull request ( #4 )

Thanks

can't get the response.service_data.values

Hello, friends,
Recently I just found this UDS library and it's very useful for me.
But i am not yet familiar with it.
I tried to follow the example in the document to read the$F190.
But i can't print the correct response and the error as below. and i confirm the actual request and response are correct on CAN BUS.

raise UnexpectedResponseException(response, "Server returned values for data identifier 0x%04x that was not requested and no Codec was defined for it. Parsing must be stopped." % (e.key))
udsoncan.exceptions.UnexpectedResponseException: ReadDataByIdentifier service execution returned a valid response but unexpected. Details : Server returned values for data identifier 0x3933 that was not requested and no Codec was defined for it. Parsing must be stopped.

thank you for your help.
the code as below :
`
from can.interfaces.vector import VectorBus
from udsoncan.connections import PythonIsoTpConnection
from udsoncan.client import Client
import isotp
import udsoncan
import struct

class MyCustomCodecThatShiftBy4(udsoncan.DidCodec):
def encode(self, val):
val = (val << 4) & 0xFFFFFFFF
return struct.pack('<L', val)

def decode(self, payload):
    val = struct.unpack('<L', payload)[0]
    return val >> 4

def __len__(self):
    return 4

isotp_params = {
'stmin': 32,
'blocksize': 8,
'wftmax': 0,
'll_data_length': 8,
'tx_padding': 0,
'rx_flowcontrol_timeout': 1000,
'rx_consecutive_frame_timeout': 1000,
'squash_stmin_requirement': False
}

bus = VectorBus(bustype='vector', app_name='CANoe', channel=[0])
tp_addr = isotp.Address(isotp.AddressingMode.Normal_11bits, txid=0x123, rxid=0x456)
stack = isotp.CanStack(bus=bus, address=tp_addr, params=isotp_params)
conn = PythonIsoTpConnection(stack)
config = dict(udsoncan.configs.default_client_config)
config['data_identifiers'] = {
0xF190: udsoncan.AsciiCodec(15)} # Codec that read ASCII string. We must tell the length of }
with Client(conn, request_timeout=2, config=config) as client:
response = client.read_data_by_identifier(0xF190)
print(response.service_data.values[0xF190])
vin = client.read_data_by_identifier_first(0xF190)
print(vin)

`

Use spaces instead of tabs

Hello Pier,

first thank you for your work on this package!

I noticed that you use tabs instead of spaces for indentation throughout the codebase. Is it possible to switch to spaces?

CAN-FD using Kvaser interface

Not sure if this should be addressed here or in python-can but using Kvaser and CAN-FD the messages are are send as regular CAN not CAN-FD.

I've created the bus with fd=True but this was not used when sending the final message; the transport layer created regular CAN messages that get passed lower to the interface driver.

SecurityAccess does not handle already-unlocked server

If a UDS server is already unlocked for a given security level, then it responds to subsequent requestSeed requests for that security level with an all-zero seed value (see ISO 14229-1:2020 Section 10.4.1).

However, udsoncan doesn't appear to handle this case and attempts to send a key value based on this zero value. This causes the server to respond with NRC requestSequenceError. Instead, if the client receives securitySeed == 0, then it should early return with success without sending a sendKey request.

P2* timeout not used after RequestCorrectlyReceived_ResponsePending

The single-response timeout is correctly set to P2* after the RequestCorrectlyReceived_ResponsePending (0x78 NRC) is received. However, the overall_timeout_time is not updated and so the overall timeout is selected on the next pass through the while not done_receiving: loop. Selecting the single_request_timeout would correctly extend the timeout period to P2*.

Source: Figure 10 in ISO14229-2:2013 shows that the client timer is reloaded with P2* after the 0x78 NRC is received. With this note: "transport/network layer issues to diagnostic application the reception of a response message. Client stops the P Client timer and reloads the P Client timer with the value of P2* Client = P2* Client_max (default enhanced timing)."

Is it possible to send a invalid request

Sometimes you want to test the NRC code for UDS service, like for $22, normally the did length is 2, like 03 22 01 01 xx xx xx xx.
if you want to test the NRC 0x13(incorrect message length), you have to send something like 02 22 01 xx xx xx xx xx, and you expect a NRC 0x13.

Is it possible to add this kind of feature?

Example uses wrong import

Hi there,

in your example code you import ISOTPConnection and use ISOTPSocketConnection.
This gave me an error using your example code.

Changing the import from

import from udsoncan.connections import IsoTPConnection

to

import from udsoncan.connections import IsoTPSocketConnection

resolves the issue.

Scapy with UDS and ISO-TP support

Hi @pylessard
I just found your repos.
You did a very similar thing, like I do at the moment.
I'm trying to bring ISOTP, UDS and many more automotive protocols into Scapy mainline.

Would be great, if we could collaborate on this task in Scapy mainline.

Here is an example branch of my implementations:
https://github.com/polybassa/scapy-1/tree/isotp
It't not mainline, but I'm working with the maintainers on Scapy on bringing it there.

Greetings Nils

Usage on windows with any hardware

I want to use this library to talk to an ECU.I saw on the examples that its using can0 (that means it is used on linux where you will setup a can device as can0)
But I want to use it in windows.what should i use instead of can0 ? And which hardware to use ? Can i use an arduino for example with a particular sketch or use a J2534 device ...
I don't know what to do i can't use it on linux since the software that talk to the ECU is windows. And i can't switch back and forward between linux and windows
Any idea on how to get up and running on windows?

TimeoutException from client.read_data_by_id() and client.clear_dtc()

Hi!

I am having a problem where I get TimeoutExceptions when I'm trying to test my small client program against an UDS-server. Both read_data_by_identifier() and clear_dtc() gets the TimeoutException. I know that the UDS-server is working since another program can send and receive UDS messages, so I must be doing something wrong.

The log gave me the following output from three UDS requests I sent, but every other UDS request gave me similar output, sometimes with "[ERROR] Connection: The receive queue was read too late" and sometimes without it.

2020-05-05 15:01:14 [INFO] Connection: Connection opened
2020-05-05 15:01:14 [INFO] UdsClient: ReadDataByIdentifier<0x22> - Reading data identifier : 0x2b12 (VehicleManufacturerSpecific)
2020-05-05 15:01:14 [DEBUG] Connection: Sending 3 bytes : [b'222b12']
2020-05-05 15:01:15 [DEBUG] Connection: No data received: [TimeoutException] - Did not receive frame IsoTP Transport layer in time (timeout=1 sec)
2020-05-05 15:01:15 [ERROR] UdsClient: [TimeoutException] : Did not receive response in time. P2 timeout time has expired (timeout=1.000 sec)
Did not receive response in time. P2 timeout time has expired (timeout=1.000 sec)
2020-05-05 15:01:15 [INFO] Connection: Connection closed

2020-05-05 15:01:32 [INFO] Connection: Connection opened
2020-05-05 15:01:32 [INFO] UdsClient: ClearDiagnosticInformation<0x14> - Clearing all DTCs (group mask : 0xFFFFFF)
2020-05-05 15:01:32 [DEBUG] Connection: Sending 4 bytes : [b'14ffffff']
2020-05-05 15:01:33 [DEBUG] Connection: No data received: [TimeoutException] - Did not receive frame IsoTP Transport layer in time (timeout=1 sec)
2020-05-05 15:01:33 [ERROR] UdsClient: [TimeoutException] : Did not receive response in time. P2 timeout time has expired (timeout=1.000 sec)
2020-05-05 15:01:33 [INFO] Connection: Connection closed

2020-05-05 15:02:16 [INFO] Connection: Connection opened
2020-05-05 15:02:16 [INFO] UdsClient: ClearDiagnosticInformation<0x14> - Clearing all DTCs (group mask : 0xFFFFFF)
2020-05-05 15:02:16 [DEBUG] Connection: Sending 4 bytes : [b'14ffffff']
2020-05-05 15:02:17 [DEBUG] Connection: No data received: [TimeoutException] - Did not receive frame IsoTP Transport layer in time (timeout=1 sec)
2020-05-05 15:02:17 [ERROR] UdsClient: [TimeoutException] : Did not receive response in time. P2 timeout time has expired (timeout=1.000 sec)
2020-05-05 15:02:18 [ERROR] Connection: The receive queue was read too late
2020-05-05 15:02:18 [INFO] Connection: Connection closed

I was using the PCAN-USB FD interface with the following configuration:

in backend.py

 bus = can.interface.Bus(bustype='pcan', channel='PCAN_USBBUS1', bitrate=500000)
 config = dict(configs.client_config)

 isotp_params = {
   'stmin' : 32,                      
   'blocksize' : 8,                       
   'wftmax' : 0,                          
   'll_data_length' : 8,                 
   'tx_padding' : 0,                     
   'rx_flowcontrol_timeout' : 10000,       
   'rx_consecutive_frame_timeout' : 10000, 
   'squash_stmin_requirement' : False     

  addr = isotp.Address(isotp.AddressingMode.Normal_11bits, rxid=id, txid=interface_ID) 
  stack = isotp.CanStack(bus=bus, address=addr, params=isotp_params) 
  conn = PythonIsoTpConnection(stack) 

  with Client(conn, config=config) as client: 
        try:
            response = uds_requests.chosen_service(client, input_dict)
            if response != None:
                msg_queue.put(response)

        except Exception as e:
            print(e)

In uds_requests.py

def chosen_service(client, dict):
     sid = dict.get("SID") #saved as string in dict
    
     if sid == "22":

        did = int(dict.get("DID), 16) #saved as string in dict
        try:
            response = client.read_data_by_identifier(did)
        except Exception as e:
            print(str(e))
        return response

    elif sid == "14":

         data = int(dict.get("DATA"), 16)
          try:
                response = client.clear_dtc(data)
           except Exception as e:
                print(str(e))
                response = None
          return response

In configs.py:

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 paylaod is 4 byte long.



client_config  = {
        'exception_on_negative_response'	: False,
        'exception_on_invalid_response'		: False,
        'exception_on_unexpected_response'	: False,
        'security_algo'				: None,
        'security_algo_params'		: None,
        'tolerate_zero_padding' 	: True,
        'ignore_all_zero_dtc' 		: True,
        'dtc_snapshot_did_size' 	: 2,		# Not specified in standard. 2 bytes matches other services format.
        'server_address_format'		: None,		# 8,16,24,32,40
        'server_memorysize_format'	: None,		# 8,16,24,32,40
        'data_identifiers' 			: {
                                        0x2b12 : MyCustomCodecThatShiftBy4(),    
                                        },
        'input_output' 				: {},
        'request_timeout'			: 10,
        'p2_timeout'				: 2,
        'p2_star_timeout'			: 5,
}

Also, I am having trouble to grasp what the DidCodec is supposed to do, I have read the documents and the examples, but I don't get what it is supposed to do. MyCustomCodecThatShiftBy4() does a logical shift left 4 times in encode and then a logical and with 0xFFFFFFFF to keep all 1's. And the decode shifts the response 4 positions to the right. Whats the point of doing this? What am I missing?

Timeout issue

Please check below issue, let me know if you need more information.
the log:
2019-11-06 09:31:10,654 - UdsClient - ERROR - [TimeoutException] : Did not receive response in time. Global request timeout time has expired (timeout=0.978 sec)
The trace:
image
The config:
image

exception in threading

hi all,
I'm using the lib with vn1610 vector hardware , during a scan of service 22 xx yy I got this exception:
self.__recvBuffer.append(msg.data[self.__pduStartIndex:])
AttributeError: 'CanTp' object has no attribute '_CanTp__recvBuffer'
in file ....python_uds-1.0.2-py3.7.egg\uds\uds_communications\TransportProtocols\Can\CanTp.py

My script continue to run, but slowly: it sends 1 msg per second and not every 10 msec

InputOutputControlByIdentifier does not handle udsoncan.DidCodec.ReadAllRemainingData

The InputOutputControlByIdentifier does not handle udsoncan.DidCodec.ReadAllRemaining exception which is raised when the length of a Codec is requested.
https://github.com/pylessard/python-udsoncan/blob/master/udsoncan/services/InputOutputControlByIdentifier.py#L186

This should be handled the same way as in the ReadDataByIdentifier: https://github.com/pylessard/python-udsoncan/blob/master/udsoncan/services/ReadDataByIdentifier.py#L65

Work to support for Intrepid's CAN interfaces?

The python-ics interface (provided by Intrepid Control Systems) handles ISO-TP timing, but in Windows it does not provide a socketcan type interface.

How realistic would it be to add support for these ValueCAN/neo* devices under Windows?
Sample API snippets:
device = ics.find_devices()[0]
ics.open_device(device)
ics.iso15765_enable_networks(device, ics.NETID_HSCAN)

I've written some small helpers to work with exchanges but I would love to leverage your service definitions.

    def iso_exchange(self, req_address, rsp_address, message):
        ics.iso15765_enable_networks(self.device, ics.NETID_HSCAN)
        self.rx_iso_setup(req_address, rsp_address)
        self.tx_iso(req_address, message)
        ret = self.rx(rsp_address)
        ics.iso15765_disable_networks(self.device)
        return ret```

How to get the response of reading DTC(18$)

Dear friend,
I want to read the DTC list. but my diagnostic protocol is not UDS, that's KWP2000 based on CAN.
So, when I send the command to ECU, I want to get the response from ECU and print the DTC list.
below picture is the communication with tester and ECU.
the length is 140 bytes(0x8c), and the DTC list is below read box, Actually, it's very similar with UDS DTC reading.
But it seems that I can't use this library directly.
So, My question is whether there is a function or method can extract theses data then print them.
Can I do this by import Response from udsoncan.Response?
if you have a good idea, please share me.
thanks in advance. :)

image

Cannot use communication_control by specifiying communication_type as int

comunication type
from byte

It will execute from_byte if the communication_type is int type. But it will judge if communication_type is bytes type in from_byte function. Variable val in from_byte function does not be assigned a value if the communication_type is not a bytes type. It causes an error when I run client.communication_control function.

Client throws an exception for response pending responses

Code in question:

if not response.positive:
if not request.service.is_supported_negative_response(response.code):
self.logger.warning('Given response code "%s" (0x%02x) is not a supported negative response code according to UDS standard.' % (response.code_name, response.code))
raise NegativeResponseException(response)

How would you like to handle 'ResponsePending (0x78)' handling by the client?

In my instance, I am entering a programming session:

conn = IcsNeoVIConnection(serial=None, rxid=0x7E9, txid=0x7E1)
with Client(conn,  request_timeout=2, config=config) as client:
    client.change_session(udsoncan.services.DiagnosticSessionControl.Session.programmingSession)

image

Who/What should be responsible for handling these "response pending" scenarios?

Passing Security Access level to security_algo

In order to handle the case when a project has different algos for different levels, I need to be able to pass which access level is being unlocked to my security_algo.

It seems that I cannot currently do that, is that correct? Or have I missed how to do this through the params parameter?

Send uds command byte 0 padded with 00

While sending UDS service with udsoncan library, is CAN tools is vector it worked fine, but if CAN tools is PCAN, first bytes will padded with 00, see below message information.
Time Diff Time Chn ID Name Event Type Dir DLC Data length Data
[-] 16.733302 0.000000 CAN 1 700 reqUDS SF Rx 0 8 [00] [02 3E 00 55 55 55 55]
UDS protocol is based on CAN not CANFD.
So how to fix this issue?
Many thanks!

read_data_by_identifier exception

There is source code which I try for test "read_data_by_identifier" feature
uds-test.zip

Log from terminal:

2019-01-16 17:05:52 [INFO] Connection: Connection opened
2019-01-16 17:05:52 [INFO] UdsClient: ReadDataByIdentifier<0x22> - Reading data identifier : 0x210f (VehicleManufacturerSpecific)
2019-01-16 17:05:52 [DEBUG] Connection: Sending 3 bytes : [b'22210f']
2019-01-16 17:05:52 [DEBUG] Connection: Received 7 bytes : [b'62210f00400000']
2019-01-16 17:05:52 [INFO] UdsClient: Received positive response for service ReadDataByIdentifier (0x22) from server.
2019-01-16 17:05:52 [ERROR] UdsClient: [UnexpectedResponseException] : ReadDataByIdentifier service execution returned a valid response but unexpected. Details : Server returned values for data identifier 0x0040 that was not requested and no Codec was defined for it. Parsing must be stopped.
Server sent an invalid payload : b'b!\x0f\x00@\x00\x00'
2019-01-16 17:05:52 [INFO] Connection: Connection closed

Candump output :

$ candump slcan0 | grep "[67]64"
slcan0 764 [4] 03 22 21 0F // TX
slcan0 664 [8] 07 62 21 0F 00 40 00 00 // RX

Say please what I am doing wrong? Why 'udsoncan' think that 0x0040 is new identifier ? Whereas it is a part of payload

filePathAndNameLength shall be encoded on 2 bytes for 0x38 service

Hello @pylessard ,

According to the ISO, in service 0x38, the parameter “filePathAndNameLength” should be encoded on 2 bytes in the Request Message Definition.

image

This is not the case in your implementation, on RequestFileTransfer.py file, here.

        path_ascii = path.encode('ascii')
        if len(path_ascii) > 0xFF:
            raise ValueError('Path length must be smaller or equal than 255 bytes when encoded in ASCII')

Max path length parameter should be 0xFFFF (65535 bytes).

As a consequence here, since our path is encoded in less than 0xFF, we continue to build a corrupted request:

        data += len(path_ascii).to_bytes(1, 'big')
        data += path_ascii](url)

So the first byte of the path will be stripped on the ECU side as the second byte of path length.

I hope the issue is clear, let me know if you need any further information.

Getting timeout while sending 4KB packet over normal CAN

I am using this lib with the can-isotp kernel module, and I try to start a data transfer 0x36 request with max data of 4KB over normal CAN (or with CAN-FD while setting tx_dl to 8 bytes) and STmin = 10.

During my tests, sending this packet of multi-frame takes more than 5 seconds to complete.

So I had to increase the timeout (0.1) set bellow to 10 seconds to avoid a socket timeout:
https://github.com/pylessard/python-udsoncan/blob/master/udsoncan/connections.py#L260

According to UDS standard, there are no limitations for the sending duration, and according to a comment you put here, this timeout was meant for receive only, but I don't understand how it you should be able to do that, the socket's timeout will be triggered for the sending as well if it passes the 100ms.

But increasing this timeout is not enough, because I am getting a P2 timeout, because somehow the socket->send reports (here) completed within 2 or 3 seconds, and it returns the full packet size 4KB, while the sending still continues at kernel module level! this causes the timer to start for the receive and raises a timeout while the ECU is still waiting for the remaining frames of the packet.

I debugged the can-istop kernel module to see if it is reporting a complete status before it ends sending all the consecutive frames of the 4K packet, but it seems the timing seems correct at this module level ( > 5 seconds):

[178158.310957] can-isotp: isotp_sendmsg: starting txtimer for fc
[178159.310929] can-isotp: isotp_tx_timer_tsklet: we did not get FC frame in time.
[178159.310949] can-isotp: isotp_sendmsg: starting txtimer for fc
[178159.312847] can-isotp: isotp_rcv_fc: FC frame: FS 0, BS 0, STmin 0x0A, tx_gap 10000000
[178159.312849] can-isotp: isotp_rcv_fc: starting txtimer for sending
[178159.322853] can-isotp: isotp_tx_timer_tsklet: next pdu to send.
[178159.332868] can-isotp: isotp_tx_timer_tsklet: next pdu to send.
......
[178165.164485] can-isotp: isotp_tx_timer_tsklet: next pdu to send.
[178165.174498] can-isotp: isotp_tx_timer_tsklet: next pdu to send.
[178165.174505] can-isotp: isotp_tx_timer_tsklet: we are done

@pylessard @hartkopp could you help? Being new to Python and have a very limited knowledge on C++, I'm maybe missing something about how the socket works on both layers.

Client not working when decorator module is installed

The decorator module used to autodocument properly the client methods changes the behaviour of the standard_error_management decorator. When the module is not available, a stubbed version of it is defined.

The client works with the stubbed version, but doesn't with the real implementation.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.