Python Forum

Full Version: python-can help
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello,
I want to start a project of reading canbus data using python-can.
i want to be able to save the data\pid and analyze it
I took the first example
import can

bus = can.interface.Bus(channel='can0', bustype='socketcan')

while True:
    message = bus.recv(1.0)
    if message is None:
        print('TimeOut!')
    else:
        print(message)
and this is what I got :
Timestamp: 1628595329.976414    ID: 0c00100b    X                DLC:  8    fc ff fa 00 ff ff ff ff     Channel: can0
Timestamp: 1628595329.985834    ID: 0c000027    X                DLC:  8    30 50 14 7d 04 f8 ff 22     Channel: can0
Timestamp: 1628595329.986416    ID: 18fdcd27    X                DLC:  8    00 00 00 00 00 00 00 00     Channel: can0
Timestamp: 1628595329.995918    ID: 0c000027    X                DLC:  8    30 50 14 7d 04 f8 ff 33     Channel: can0
great , now I want to be able to save the ID and the data
I have try this
pid = message.arbitration_id
pid_str = str(pid)
data = message.data
data_str = str(data)
but I get this:
201326631  bytearray(b'0P\x14}\x04\xf8\xff3')
201326631  bytearray(b'0P\x14}\x04\xf8\xffD')
419361063  bytearray(b'\x04\x00\x00\x00\x00\x00\x00\x00')
what do I need to do\change so I can see&save the data as shown in the example ?

Thanks,
(Aug-10-2021, 11:36 AM)korenron Wrote: [ -> ]what do I need to do\change so I can see&save the data as shown in the example ?
Something like this.
file_name = 'data.txt'
with open(file_name, 'w') as f:
    pid = message.arbitration_id
    data = message.data
    f.write(f'{pid}{data}\n')
look at https://github.com/hardbyte/python-can/b...ge.py#L165 and next lines to see Message.__str__ method and how it handles data attribute in string representation
and for ID - https://github.com/hardbyte/python-can/b...ge.py#L148


with your sample, simplified example
pid = 201326631
spam = bytearray(b'0P\x14}\x04\xf8\xff3')
data = [f"{byte:02x}" for byte in spam]
print(f"Data: {' '.join(data)}")
print(f'ID: {pid:08x}')
Output:
Data: 30 50 14 7d 04 f8 ff 33 ID: 0c000027
Thank you for the explain and exmaple :-)