#! /usr/bin/env python
'''
Auther      : xiaobaiTser
Email       : 807447312@qq.com
createTime  : 2025/1/14 23:01
fileName    : MonitorCAN.py
'''

# 先安装PCAN的驱动（https://www.peak-system.com/Drivers.523.0.html?&L=1）有也可以淘宝商家给的链接，再安装python-can
# pip install python-can
import can
# pip install cantools
import cantools

# 加载 DBC 文件
db = cantools.database.load_file('xiaobai.dbc')

# 配置 PEAK CAN 接口
bus = can.interface.Bus(channel='PCAN_USBBUS1', bustype='pcan', bitrate=500000)

'''
# 创建 CAN 报文
msg = can.Message(
    arbitration_id=0x123,  # CAN ID
    data=[0x01, 0x02, 0x03, 0x04],  # 数据帧
    is_extended_id=False  # 标准帧
)

try:
    # 发送 CAN 报文
    bus.send(msg)
    print(f"Message sent: {msg}")
except can.CanError:
    print("Message NOT sent")
'''



# 接收 CAN 报文并解析信号
try:
    while True:
        msg = bus.recv(timeout=1.0)  # 设置超时时间为 1 秒
        if msg is not None:
            print(f"Message received: {msg}")

            # 使用 DBC 文件解析信号
            decoded_msg = db.decode_message(msg.arbitration_id, msg.data)
            print(f"Decoded message: {decoded_msg}")
except KeyboardInterrupt:
    print("Stopped receiving messages")

# 关闭总线
bus.shutdown()