I am trying to connect to the CAN bus of my car. The connection is working and the data is printing to the terminal without any problems.
bus = can.interface.Bus("can0", bustype="socketcan")
notifier = can.Notifier(bus, [can.Printer()])
I am using Python Can 2.2 and Python 3.7.
I want to add a new listener with some sort of switch-case statement on the can.dlc. Would the pseudocode below be the best way to do that?
import can
def parse_data(can):
SingleCanFrame = can.Message
print(SingleCanFrame)
if SingleCanFrame.arbitration_id == 304: # Car voltage
# Convert data
# Save to DB table 1
elif SingleCanFrame.arbitration_id == 400: # Car speed
# Convert data
# Save to DB table 2
elif SingleCanFrame.arbitration_id == 401: # Car tachometer
# Convert data
# Save to DB table 3
else:
# Save to DB errorlog
bus = can.interface.Bus("can0", bustype="socketcan")
notifier = can.Notifier(bus, [parse_data(can)])
Essentially, that would be a fine way to do that.
However, if you would like to express your intent more clearly, a dictionary would be helpful:
CAR = {"voltage": 304, "speed": 400, "tachometer": 401} # Capital variable name, as this is a constant variable
Then you could just refer to the values as if SingleCanFrame.dlc == CAR["voltage"]: which is less error-prone.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With