-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcan_receiver.py
More file actions
46 lines (41 loc) · 1.46 KB
/
can_receiver.py
File metadata and controls
46 lines (41 loc) · 1.46 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
import can
import re
def get_data_bus():
try:
# Get and bind the CAN network on the usb port
bus = can.interface.Bus(channel='can0', bustype='socketcan')
return bus
except OSError as e:
if e.errno != 19:
print(f"CAN_RECEIVER::get_data_bus::Unknown error: {e.errno}")
print("CAN_RECEIVER::get_data_bus::can network not found")
except Exception as e:
print(f"CAN_RECEIVER::get_data_bus::unknown exception: {e}")
return None
# Get and return a CAN message
def get_can_line(bus):
try:
# Message format is different from can-utils candump can0 (the log file we tested on)
return bus.recv(timeout=1.0)
except AttributeError as e:
print(f"Error: {e}")
return None
# Simply detect if the network has been found and has been bound to an address
def get_status():
try:
bus = can.Bus(channel='can0', interface='socketcan')
print("First")
return True
except Exception as e:
print("CAN_RECEIVER::get_status::CAN network not found")
return False
# Clean the data given by python-can
def clean_message(message):
# Extract information using regular expressions
timestamp = re.search(r'Timestamp:\s*([\d.]+)', str(message)).group(1)
id_value = re.search(r'ID:\s*(\d+)', str(message)).group(1)
data = re.search(r'DL:\s*\d+\s*((?:[a-f0-9]{2}\s*)+)', str(message)).group(1)
channel = re.search(r'Channel:\s*(\w+)', str(message)).group(1)
# Format the output
formatted_output = f"({timestamp}) {channel} {id_value}#{data.replace(' ', '')}"
return formatted_output