我正在尝试连接到我汽车的CAN总线。连接正常,数据正在打印到终端,没有任何问题。
bus = can.interface.Bus("can0", bustype="socketcan")
notifier = can.Notifier(bus, [can.Printer()])
我正在使用Pyhton Can 2.2和python 3.7。
我想在can.dlc上添加带有某种switch-case语句的新侦听器。下面的伪代码是做到这一点的最佳方法吗?
import can
def parse_data(can):
SingleCanFrame = can.Message
print(SingleCanFrame)
if SingleCanFrame.dlc == 304: #car voltage
#convert data
#save to DB table 1
elif SingleCanFrame.dlc == 400: #car speed
#convert data
#save to DB table 2
elif SingleCanFrame.dlc == 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)])
忘记了参数:def parse_data(可以)
新代码
import can
CAR = {"voltage": 304, "speed": 400, "tachometer": 401}
def cellvoltage(SingleCanFrame, MyDB):
#convert data
#save to DB table 1
def packcurrent(SingleCanFrame, MyDB):
#convert data
#save to DB table 2
def tachometer(SingleCanFrame, MyDB):
#convert data
#save to DB table 3
def parse_data(can):
SingleCanFrame = can.Message
MyDB = SomeDB.Connect()
print(SingleCanFrame)
if SingleCanFrame.dlc == CAR["voltage"]: #car voltage
cellvoltage(SingleCanFrame, MyDB)
elif SingleCanFrame.dlc == CAR["speed"]: #car speed
packcurrent(SingleCanFrame, MyDB)
elif SingleCanFrame.dlc == CAR["tachometer"]: #car tachometer
tachometer(SingleCanFrame, MyDB)
else:
#save to DB errorlog
bus = can.interface.Bus("can0", bustype="socketcan")
notifier = can.Notifier(bus, [parse_data(can)])
答案 0 :(得分:0)
从本质上讲,这是个好方法。
但是,如果您想更清楚地表达自己的意图,那么字典会有所帮助:
CAR = {"voltage": 304, "speed": 400, "tachometer": 401} # capital var name as this a constant var
然后,您可以将这些值简称为if SingleCanFrame.dlc == CAR["voltage"]:
,这样不容易出错。