Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
python-can help
#1
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,
Reply
#2
(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')
Reply
#3
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
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#4
Thank you for the explain and exmaple :-)
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020