new can interface mb_test
authorkyz <kyz@kyz.pub>
Wed, 12 Nov 2025 09:23:15 +0000 (17:23 +0800)
committerkyz <kyz@kyz.pub>
Wed, 12 Nov 2025 09:23:15 +0000 (17:23 +0800)
test/Makefile
test/can_driver.c [new file with mode: 0644]
test/can_driver.h [new file with mode: 0644]
test/can_gui.py [new file with mode: 0644]
test/can_test.c [new file with mode: 0644]

index 50c3bc28c0737491d14c37dcbb042ac1c48ac6c3..b24dfe7ec1bec8af1741cde35a69cbac448ce735 100644 (file)
@@ -1,11 +1,30 @@
-all: mb_test
+# Makefile for CAN processor
+
+CC = gcc
+CFLAGS = -Wall -g -std=gnu99
+LDFLAGS = -lpthread
+
+# 目标文件
+TARGETS = can_test
+
+all: $(TARGETS)
+
+# 编译can_test
+can_test: can_test.c can_driver.c
+       $(CC) $(CFLAGS) -o $@ $^ $(LDFLAGS)
+
+# 编译mb_test(保持原有规则)
+mb_test: mb_test.c mb.c
+       $(CC) $(CFLAGS) -o $@ $^ -lmodbus $(LDFLAGS)
+
+clean:
+       rm -f $(TARGETS) *.o
+
+.PHONY: all clean
+
 
 mb_test: mb.o mb_test.o
        gcc -o $@ $^ -lmodbus -lpthread
 
 %.o: %.c
        gcc -o $@ -c $^
-
-clean:
-       rm -f *.o mb_test
-
diff --git a/test/can_driver.c b/test/can_driver.c
new file mode 100644 (file)
index 0000000..817a6e4
--- /dev/null
@@ -0,0 +1,394 @@
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+#include <fcntl.h>
+#include <sys/ioctl.h>
+#include <sys/socket.h>
+#include <net/if.h>
+#include <linux/can.h>
+#include <linux/can/raw.h>
+#include <poll.h>
+#include <errno.h>
+#include "can_driver.h"
+
+// 总线配置信息
+typedef struct {
+    const char *interface_name;
+    uint32_t bitrate;
+} can_bus_config_t;
+
+// 总线配置表
+static can_bus_config_t can_bus_configs[MAX_CAN_BUSES] = {
+    [CAN_BUS_1] = {"vcan0", 250000},  // CAN_BUS_1 对应 can0 接口,250K速率
+    [CAN_BUS_2] = {"can1", 500000}   // CAN_BUS_2 对应 can1 接口,500K速率
+};
+
+// 检查总线ID是否有效
+static int check_bus_id(int bus_id) {
+    if (bus_id < 0 || bus_id >= MAX_CAN_BUSES) {
+        fprintf(stderr, "错误: 无效的总线ID %d\n", bus_id);
+        return -1;
+    }
+    return 0;
+}
+
+// 执行系统命令
+static int execute_system_command(const char *command) {
+    int ret = system(command);
+    if (ret < 0) {
+        fprintf(stderr, "执行命令失败: %s, 错误: %s\n", command, strerror(errno));
+        return -1;
+    }
+    return 0;
+}
+
+// CAN总线初始化函数
+int can_bus_init(int bus_id) {
+    if (check_bus_id(bus_id) < 0) {
+        return -1;
+    }
+
+    const char *ifname = can_bus_configs[bus_id].interface_name;
+    uint32_t bitrate = can_bus_configs[bus_id].bitrate;
+
+    // 设置CAN接口参数
+    char command[256];
+    snprintf(command, sizeof(command), "ip link set %s type can bitrate %u", ifname, bitrate);
+    if (execute_system_command(command) < 0) {
+        return -1;
+    }
+
+    // 启用CAN接口
+    snprintf(command, sizeof(command), "ip link set up %s", ifname);
+    if (execute_system_command(command) < 0) {
+        return -1;
+    }
+
+    printf("CAN总线 %d (%s) 初始化成功,速率: %u bps\n",
+           bus_id, ifname, bitrate);
+
+    return 0;
+}
+
+// CAN总线重置函数
+int can_bus_reset(int bus_id) {
+    if (check_bus_id(bus_id) < 0) {
+        return -1;
+    }
+
+    const char *ifname = can_bus_configs[bus_id].interface_name;
+
+    // 关闭CAN接口
+    char command[256];
+    snprintf(command, sizeof(command), "ip link set down %s", ifname);
+    if (execute_system_command(command) < 0) {
+        return -1;
+    }
+
+    // 重新启用CAN接口
+    snprintf(command, sizeof(command), "ip link set up %s", ifname);
+    if (execute_system_command(command) < 0) {
+        return -1;
+    }
+
+    printf("CAN总线 %d (%s) 重置成功\n", bus_id, ifname);
+
+    return 0;
+}
+
+// 队列操作函数
+static int queue_is_full(can_device_t *device) {
+    return ((device->tx_queue_tail + 1) % device->tx_queue_size) == device->tx_queue_head;
+}
+
+static int queue_is_empty(can_device_t *device) {
+    return device->tx_queue_head == device->tx_queue_tail;
+}
+
+static int queue_push(can_device_t *device, can_frame_t *frame) {
+    pthread_mutex_lock(&device->tx_queue_mutex);
+
+    if (queue_is_full(device)) {
+        pthread_mutex_unlock(&device->tx_queue_mutex);
+        return -1;  // 队列已满
+    }
+
+    memcpy(&device->tx_queue[device->tx_queue_tail], frame, sizeof(can_frame_t));
+    device->tx_queue_tail = (device->tx_queue_tail + 1) % device->tx_queue_size;
+
+    pthread_mutex_unlock(&device->tx_queue_mutex);
+    return 0;
+}
+
+static int queue_pop(can_device_t *device, can_frame_t *frame) {
+    pthread_mutex_lock(&device->tx_queue_mutex);
+
+    if (queue_is_empty(device)) {
+        pthread_mutex_unlock(&device->tx_queue_mutex);
+        return -1;  // 队列为空
+    }
+
+    memcpy(frame, &device->tx_queue[device->tx_queue_head], sizeof(can_frame_t));
+    device->tx_queue_head = (device->tx_queue_head + 1) % device->tx_queue_size;
+
+    pthread_mutex_unlock(&device->tx_queue_mutex);
+    return 0;
+}
+
+// 创建CAN套接字
+static int create_can_socket(const char *ifname) {
+    int s = socket(PF_CAN, SOCK_RAW, CAN_RAW);
+    if (s < 0) {
+        fprintf(stderr, "创建CAN套接字失败: %s\n", strerror(errno));
+        return -1;
+    }
+
+    struct ifreq ifr;
+    strcpy(ifr.ifr_name, ifname);
+    if (ioctl(s, SIOCGIFINDEX, &ifr) < 0) {
+        fprintf(stderr, "获取接口索引失败: %s\n", strerror(errno));
+        close(s);
+        return -1;
+    }
+
+    struct sockaddr_can addr;
+    addr.can_family = AF_CAN;
+    addr.can_ifindex = ifr.ifr_ifindex;
+
+    if (bind(s, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
+        fprintf(stderr, "绑定CAN接口失败: %s\n", strerror(errno));
+        close(s);
+        return -1;
+    }
+
+    return s;
+}
+
+// 设备线程函数
+static void *can_device_thread(void *arg) {
+    can_device_t *device = (can_device_t *)arg;
+    struct pollfd fds[1];
+    can_frame_t frame;
+    struct can_frame canfd_frame;
+
+    fds[0].fd = device->socket_fd;
+    // 初始时只检测POLLIN事件,不检测POLLOUT事件
+    fds[0].events = POLLIN;
+
+    while (device->is_running) {
+        int ret = poll(fds, 1, 100);  // 100ms超时
+
+        if (ret < 0) {
+            if (errno != EINTR) {
+                fprintf(stderr, "Poll错误: %s\n", strerror(errno));
+                break;
+            }
+            continue;
+        }
+
+        // 处理接收事件
+        if (fds[0].revents & POLLIN) {
+            memset(&canfd_frame, 0, sizeof(canfd_frame));
+            ssize_t nbytes = read(device->socket_fd, &canfd_frame, sizeof(canfd_frame));
+
+            if (nbytes < 0) {
+                fprintf(stderr, "读取CAN数据失败: %s\n", strerror(errno));
+                continue;
+            }
+
+            if (nbytes < sizeof(struct can_frame)) {
+                fprintf(stderr, "接收到不完整的CAN帧\n");
+                continue;
+            }
+
+            // 转换为我们定义的帧格式
+            memset(&frame, 0, sizeof(frame));
+            frame.id = canfd_frame.can_id & CAN_EFF_MASK;
+            frame.is_extended = (canfd_frame.can_id & CAN_EFF_FLAG) ? 1 : 0;
+            frame.len = canfd_frame.can_dlc;
+            memcpy(frame.data, canfd_frame.data, frame.len);
+
+            // 调用回调函数处理数据
+            if (device->callback) {
+                device->callback(device, &frame, device->user_data);
+            }
+        }
+
+        // 处理发送事件
+        if (fds[0].revents & POLLOUT) {
+            if (!queue_is_empty(device)) {
+                memset(&frame, 0, sizeof(frame));
+                if (queue_pop(device, &frame) == 0) {
+                    // 转换为Linux CAN帧格式
+                    memset(&canfd_frame, 0, sizeof(canfd_frame));
+                    canfd_frame.can_id = frame.id;
+                    if (frame.is_extended) {
+                        canfd_frame.can_id |= CAN_EFF_FLAG;
+                    }
+                    canfd_frame.can_dlc = frame.len;
+                    memcpy(canfd_frame.data, frame.data, frame.len);
+
+                    // 发送数据
+                    ssize_t nbytes = write(device->socket_fd, &canfd_frame, sizeof(canfd_frame));
+                    if (nbytes < 0) {
+                        fprintf(stderr, "发送CAN数据失败: %s\n", strerror(errno));
+                        // 可以考虑重新入队
+                        queue_push(device, &frame);
+                    }
+                }
+            }
+
+            // 发送完成后,检查队列是否为空,如果为空则移除POLLOUT事件检测
+            if (queue_is_empty(device)) {
+                fds[0].events &= ~POLLOUT;
+            }
+        }
+
+        // 检查发送队列,如果不为空但当前未检测POLLOUT事件,则添加POLLOUT事件检测
+        if (!queue_is_empty(device) && !(fds[0].events & POLLOUT)) {
+            fds[0].events |= POLLOUT;
+        }
+    }
+
+    return NULL;
+}
+
+// 发送CAN数据帧
+int can_device_send(can_device_t *device, can_frame_t *frame) {
+    if (!device || !frame || !device->is_running) {
+        return -1;
+    }
+
+    // 检查数据长度
+    if (frame->len > 8) {
+        fprintf(stderr, "错误: CAN数据长度不能超过8字节\n");
+        return -1;
+    }
+
+    // 将数据帧加入发送队列
+    if (queue_push(device, frame) < 0) {
+        fprintf(stderr, "发送队列已满\n");
+        return -1;
+    }
+
+    // 数据入队后,不需要在这里设置POLLOUT事件,会在线程循环中自动检测
+
+    return 0;
+}
+
+// 创建CAN设备
+can_device_t *can_device_new(int bus_id, can_receive_callback_t callback, void *user_data, int tx_queue_size) {
+    if (check_bus_id(bus_id) < 0) {
+        return NULL;
+    }
+
+    if (tx_queue_size <= 0) {
+        fprintf(stderr, "错误: 发送队列大小必须大于0\n");
+        return NULL;
+    }
+
+    // 分配设备结构内存
+    can_device_t *device = (can_device_t *)malloc(sizeof(can_device_t));
+    if (!device) {
+        fprintf(stderr, "分配设备内存失败\n");
+        return NULL;
+    }
+
+    // 分配发送队列内存
+    device->tx_queue = (can_frame_t *)malloc(sizeof(can_frame_t) * tx_queue_size);
+    if (!device->tx_queue) {
+        fprintf(stderr, "分配发送队列内存失败\n");
+        free(device);
+        return NULL;
+    }
+
+    // 初始化设备结构
+    device->bus_id = bus_id;
+    device->callback = callback;
+    device->user_data = user_data;
+    device->tx_queue_size = tx_queue_size;
+    device->tx_queue_head = 0;
+    device->tx_queue_tail = 0;
+    device->is_running = false;
+
+    // 初始化互斥锁
+    if (pthread_mutex_init(&device->tx_queue_mutex, NULL) != 0) {
+        fprintf(stderr, "初始化互斥锁失败\n");
+        free(device->tx_queue);
+        free(device);
+        return NULL;
+    }
+
+    // 创建CAN套接字
+    const char *ifname = can_bus_configs[bus_id].interface_name;
+    device->socket_fd = create_can_socket(ifname);
+    if (device->socket_fd < 0) {
+        fprintf(stderr, "创建CAN套接字失败\n");
+        pthread_mutex_destroy(&device->tx_queue_mutex);
+        free(device->tx_queue);
+        free(device);
+        return NULL;
+    }
+
+    printf("CAN设备创建成功,总线ID: %d\n", bus_id);
+
+    return device;
+}
+
+// 销毁CAN设备
+void can_device_delete(can_device_t *device) {
+    if (!device) {
+        return;
+    }
+
+    // 确保设备已停止
+    can_device_stop(device);
+
+    // 关闭套接字
+    if (device->socket_fd >= 0) {
+        close(device->socket_fd);
+        device->socket_fd = -1;
+    }
+
+    // 清理资源
+    pthread_mutex_destroy(&device->tx_queue_mutex);
+    free(device->tx_queue);
+    free(device);
+
+    printf("CAN设备已销毁\n");
+}
+
+// 启动CAN设备
+int can_device_start(can_device_t *device) {
+    if (!device || device->is_running) {
+        return -1;
+    }
+
+    device->is_running = true;
+
+    // 创建设备线程
+    if (pthread_create(&device->thread_id, NULL, can_device_thread, device) != 0) {
+        fprintf(stderr, "创建设备线程失败\n");
+        device->is_running = false;
+        return -1;
+    }
+
+    printf("CAN设备已启动\n");
+
+    return 0;
+}
+
+// 停止CAN设备
+void can_device_stop(can_device_t *device) {
+    if (!device || !device->is_running) {
+        return;
+    }
+
+    device->is_running = false;
+
+    // 等待线程结束
+    pthread_join(device->thread_id, NULL);
+
+    printf("CAN设备已停止\n");
+}
diff --git a/test/can_driver.h b/test/can_driver.h
new file mode 100644 (file)
index 0000000..5074fdb
--- /dev/null
@@ -0,0 +1,63 @@
+#ifndef CAN_DRIVER_H
+#define CAN_DRIVER_H
+
+#include <stdint.h>
+#include <pthread.h>
+#include <stdbool.h>
+
+// 总线编号定义
+#define CAN_BUS_1    0
+#define CAN_BUS_2    1
+#define MAX_CAN_BUSES 2
+
+// CAN帧数据结构
+typedef struct {
+    uint32_t id;           // 帧ID
+    uint8_t data[8];       // 数据内容
+    uint8_t len;           // 数据长度
+    uint8_t is_extended;   // 是否为扩展帧
+} can_frame_t;
+
+typedef struct can_device  can_device_t;
+// 数据接收回调函数类型
+typedef void (*can_receive_callback_t)( can_device_t *dev, can_frame_t *frame, void *user_data);
+
+// CAN设备结构
+struct can_device{
+    int bus_id;                     // 所属总线ID
+    int socket_fd;                  // CAN套接字
+    pthread_t thread_id;            // 设备线程ID
+    bool is_running;                // 运行状态
+    can_receive_callback_t callback;// 数据接收回调函数
+    void *user_data;                // 用户数据
+
+    // 发送队列相关
+    can_frame_t *tx_queue;          // 发送队列
+    int tx_queue_size;              // 发送队列大小
+    int tx_queue_head;              // 队列头指针
+    int tx_queue_tail;              // 队列尾指针
+    pthread_mutex_t tx_queue_mutex; // 队列互斥锁
+};
+
+// 总线初始化函数
+extern int can_bus_init(int bus_id);
+
+// 总线重置函数
+extern int can_bus_reset(int bus_id);
+
+// 设备创建函数
+extern can_device_t *can_device_new(int bus_id, can_receive_callback_t callback, void *user_data, int tx_queue_size);
+
+// 设备销毁函数
+extern void can_device_delete(can_device_t *device);
+
+// 设备启动函数
+extern int can_device_start(can_device_t *device);
+
+// 设备停止函数
+extern void can_device_stop(can_device_t *device);
+
+// 发送数据帧函数
+extern int can_device_send(can_device_t *device, can_frame_t *frame);
+
+#endif // CAN_DRIVER_H
diff --git a/test/can_gui.py b/test/can_gui.py
new file mode 100644 (file)
index 0000000..91e3d0a
--- /dev/null
@@ -0,0 +1,296 @@
+#!/usr/bin/env python3
+# -*- coding: utf-8 -*-
+"""
+CAN测试图形界面程序
+功能:加载vcan模块,建立vcan0设备接口,提供CAN数据收发功能
+"""
+
+import tkinter as tk
+from tkinter import ttk, scrolledtext, messagebox
+import subprocess
+import threading
+import time
+import os
+import sys
+# 首先尝试导入socket库来直接使用socketcan
+import socket
+import struct
+
+class CanTestGUI:
+    def __init__(self, root):
+        """初始化CAN测试图形界面"""
+        self.root = root
+        self.root.title("CAN测试工具")
+        self.root.geometry("800x600")
+        self.root.resizable(True, True)
+
+        # 状态变量
+        self.can_socket = None
+        self.running = False
+        self.receive_thread = None
+
+        # 创建UI界面
+        self.create_widgets()
+
+        # 检查并加载vcan模块
+        self.check_and_setup_vcan()
+
+        # 窗口关闭时的处理
+        self.root.protocol("WM_DELETE_WINDOW", self.on_closing)
+
+    def create_widgets(self):
+        """创建界面组件"""
+        # 创建主框架
+        main_frame = ttk.Frame(self.root, padding="10")
+        main_frame.pack(fill=tk.BOTH, expand=True)
+
+        # 状态栏
+        status_frame = ttk.Frame(main_frame, padding="5")
+        status_frame.pack(fill=tk.X, side=tk.TOP)
+
+        self.status_var = tk.StringVar(value="就绪")
+        status_label = ttk.Label(status_frame, textvariable=self.status_var, relief=tk.SUNKEN, anchor=tk.W)
+        status_label.pack(fill=tk.X, expand=True)
+
+        # 接收数据区域
+        receive_frame = ttk.LabelFrame(main_frame, text="接收数据", padding="10")
+        receive_frame.pack(fill=tk.BOTH, expand=True, side=tk.TOP, pady=(0, 10))
+
+        self.receive_text = scrolledtext.ScrolledText(receive_frame, wrap=tk.WORD, width=70, height=15, font=("Courier New", 10))
+        self.receive_text.pack(fill=tk.BOTH, expand=True)
+        self.receive_text.config(state=tk.DISABLED)
+
+        # 控制按钮区域
+        control_frame = ttk.Frame(main_frame, padding="5")
+        control_frame.pack(fill=tk.X, side=tk.TOP)
+
+        self.start_stop_btn = ttk.Button(control_frame, text="开始接收", command=self.toggle_receive)
+        self.start_stop_btn.pack(side=tk.LEFT, padx=5)
+
+        clear_btn = ttk.Button(control_frame, text="清空接收", command=self.clear_receive)
+        clear_btn.pack(side=tk.LEFT, padx=5)
+
+        # 发送数据区域
+        send_frame = ttk.LabelFrame(main_frame, text="发送数据", padding="10")
+        send_frame.pack(fill=tk.X, side=tk.BOTTOM)
+
+        # ID输入
+        ttk.Label(send_frame, text="CAN ID:").grid(row=0, column=0, sticky=tk.W, padx=5, pady=5)
+        self.id_entry = ttk.Entry(send_frame, width=10)
+        self.id_entry.grid(row=0, column=1, sticky=tk.W, padx=5, pady=5)
+        self.id_entry.insert(0, "123")
+
+        # DLC输入
+        ttk.Label(send_frame, text="DLC:").grid(row=0, column=2, sticky=tk.W, padx=5, pady=5)
+        self.dlc_entry = ttk.Entry(send_frame, width=5)
+        self.dlc_entry.grid(row=0, column=3, sticky=tk.W, padx=5, pady=5)
+        self.dlc_entry.insert(0, "8")
+
+        # 数据输入
+        ttk.Label(send_frame, text="数据 (空格分隔的十六进制数):").grid(row=1, column=0, sticky=tk.W, padx=5, pady=5)
+        self.data_entry = ttk.Entry(send_frame, width=50)
+        self.data_entry.grid(row=1, column=1, columnspan=4, sticky=tk.W, padx=5, pady=5)
+        self.data_entry.insert(0, "01 02 03 04 05 06 07 08")
+
+        # 发送按钮
+        send_btn = ttk.Button(send_frame, text="发送数据", command=self.send_can_message)
+        send_btn.grid(row=0, column=4, rowspan=2, padx=10, pady=5, sticky=tk.NS)
+
+    def check_and_setup_vcan(self):
+        """检查并设置vcan接口"""
+        try:
+            # 检查是否以root权限运行
+            if os.geteuid() != 0:
+                messagebox.showwarning("权限警告", "程序需要root权限来设置vcan接口,请使用sudo运行。")
+                return
+
+            # 检查vcan模块是否已加载
+            result = subprocess.run(["lsmod"], capture_output=True, text=True)
+            if "vcan" not in result.stdout:
+                self.update_status("正在加载vcan模块...")
+                subprocess.run(["modprobe", "vcan"], check=True)
+                self.update_status("vcan模块加载成功")
+            else:
+                self.update_status("vcan模块已加载")
+
+            # 检查vcan0接口是否已存在
+            result = subprocess.run(["ip", "link", "show", "vcan0"], capture_output=True, text=True)
+            if "does not exist" in result.stderr:
+                self.update_status("正在创建vcan0接口...")
+                subprocess.run(["ip", "link", "add", "dev", "vcan0", "type", "vcan"], check=True)
+                subprocess.run(["ip", "link", "set", "up", "vcan0"], check=True)
+                self.update_status("vcan0接口创建并启动成功")
+            else:
+                # 确保vcan0接口已启动
+                subprocess.run(["ip", "link", "set", "up", "vcan0"], check=True)
+                self.update_status("vcan0接口已存在并启动")
+
+            # 尝试打开can总线(使用socket直接连接)
+            try:
+                # 创建CAN套接字
+                self.can_socket = socket.socket(socket.PF_CAN, socket.SOCK_RAW, socket.CAN_RAW)
+                # 设置超时,避免recv阻塞
+                self.can_socket.settimeout(1.0)
+
+                # 绑定到vcan0接口(使用元组格式,这是关键修复)
+                self.can_socket.bind(('vcan0',))
+
+                self.update_status("CAN总线连接成功")
+            except Exception as e:
+                print(f"CAN总线连接失败: {str(e)}")
+                self.update_status(f"CAN总线连接失败: {str(e)}")
+                messagebox.showerror("CAN错误", f"无法打开CAN总线: {str(e)}")
+        except subprocess.CalledProcessError as e:
+            self.update_status(f"命令执行失败: {str(e)}")
+            messagebox.showerror("系统错误", f"设置vcan接口失败: {str(e)}")
+        except Exception as e:
+            self.update_status(f"未知错误: {str(e)}")
+            messagebox.showerror("错误", f"程序出错: {str(e)}")
+
+    def update_status(self, message):
+        """更新状态栏消息"""
+        self.status_var.set(f"{time.strftime('%H:%M:%S')} - {message}")
+
+    def append_receive_text(self, message):
+        """向接收区域添加文本"""
+        self.receive_text.config(state=tk.NORMAL)
+        self.receive_text.insert(tk.END, message + "\n")
+        self.receive_text.see(tk.END)
+        self.receive_text.config(state=tk.DISABLED)
+
+    def toggle_receive(self):
+        """切换接收状态"""
+        if not self.can_socket:
+            messagebox.showwarning("警告", "CAN总线未连接,请检查vcan0接口设置")
+            return
+
+        if self.running:
+            self.running = False
+            self.start_stop_btn.config(text="开始接收")
+            self.update_status("接收已停止")
+        else:
+            self.running = True
+            self.start_stop_btn.config(text="停止接收")
+            self.update_status("正在接收CAN数据...")
+            # 启动接收线程
+            self.receive_thread = threading.Thread(target=self.receive_can_messages)
+            self.receive_thread.daemon = True
+            self.receive_thread.start()
+
+    def receive_can_messages(self):
+        """接收CAN消息的线程函数"""
+        # CAN帧结构定义
+        class CanFrame:
+            def __init__(self, data):
+                # 解析CAN帧数据
+                can_id, can_dlc = struct.unpack("=IB3x", data[:8])
+                # 提取标准ID(忽略扩展ID标志)
+                self.arbitration_id = can_id & 0x7FF
+                self.dlc = can_dlc
+                self.data = data[8:8+can_dlc] if can_dlc <=8 else data[8:16]
+
+        while self.running and self.can_socket:
+            try:
+                # 接收CAN帧数据
+                frame_data, addr = self.can_socket.recvfrom(16)
+                if frame_data and self.running:
+                    # 解析CAN帧
+                    msg = CanFrame(frame_data)
+                    timestamp = time.strftime('%H:%M:%S.%f')[:-3]
+                    data_str = " ".join([f"{byte:02X}" for byte in msg.data])
+                    message = f"[{timestamp}] ID: {msg.arbitration_id:03X}, DLC: {msg.dlc}, Data: {data_str}"
+                    self.append_receive_text(message)
+            except socket.timeout:
+                # 超时是正常的,继续等待
+                continue
+            except Exception as e:
+                if self.running:  # 只有在运行时才显示错误
+                    error_msg = f"接收错误: {str(e)}"
+                    self.update_status(error_msg)
+                    self.append_receive_text(error_msg)
+                break
+
+    def send_can_message(self):
+        """发送CAN消息"""
+        if not self.can_socket:
+            messagebox.showwarning("警告", "CAN总线未连接,请检查vcan0接口设置")
+            return
+
+        try:
+            # 获取ID
+            can_id = int(self.id_entry.get(), 10)
+            if can_id < 0 or can_id > 0x7FF:
+                raise ValueError("CAN ID必须在0-0x7FF范围内")
+
+            # 获取DLC
+            dlc = int(self.dlc_entry.get(), 10)
+            if dlc < 0 or dlc > 8:
+                raise ValueError("DLC必须在0-8范围内")
+
+            # 获取数据
+            data_str = self.data_entry.get().strip()
+            data_parts = data_str.split() if data_str else []
+
+            # 验证数据数量
+            if len(data_parts) > dlc:
+                raise ValueError(f"数据数量({len(data_parts)})不能超过DLC({dlc})")
+
+            # 解析数据
+            data = [int(byte, 16) for byte in data_parts]
+            for byte in data:
+                if byte < 0 or byte > 0xFF:
+                    raise ValueError("数据字节必须在0-0xFF范围内")
+
+            # 填充数据到DLC长度
+            while len(data) < dlc:
+                data.append(0)
+
+            # 创建CAN帧
+            # 构建CAN帧头部 (ID和DLC)
+            frame_header = struct.pack("=IB3x", can_id, dlc)
+            # 构建CAN数据部分
+            frame_data = bytes(data)
+            # 组合完整的CAN帧
+            can_frame = frame_header + frame_data
+
+            # 发送CAN帧
+            self.can_socket.send(can_frame)
+
+            # 显示发送成功信息
+            timestamp = time.strftime('%H:%M:%S.%f')[:-3]
+            data_str = " ".join([f"{byte:02X}" for byte in data])
+            message = f"[{timestamp}] TX - ID: {can_id:03X}, DLC: {dlc}, Data: {data_str}"
+            self.append_receive_text(message)
+            self.update_status("CAN消息发送成功")
+
+        except ValueError as e:
+            messagebox.showerror("输入错误", f"无效的输入: {str(e)}")
+        except Exception as e:
+            messagebox.showerror("发送错误", f"发送CAN消息失败: {str(e)}")
+
+    def clear_receive(self):
+        """清空接收区域"""
+        self.receive_text.config(state=tk.NORMAL)
+        self.receive_text.delete(1.0, tk.END)
+        self.receive_text.config(state=tk.DISABLED)
+        self.update_status("接收区域已清空")
+
+    def on_closing(self):
+        """窗口关闭时的处理"""
+        self.running = False
+        if self.receive_thread and self.receive_thread.is_alive():
+            self.receive_thread.join(timeout=1.0)  # 等待接收线程结束
+
+        if self.can_socket:
+            self.can_socket.close()
+
+        self.root.destroy()
+
+def main():
+    """主函数"""
+    root = tk.Tk()
+    app = CanTestGUI(root)
+    root.mainloop()
+
+if __name__ == "__main__":
+    main()
diff --git a/test/can_test.c b/test/can_test.c
new file mode 100644 (file)
index 0000000..23f3a79
--- /dev/null
@@ -0,0 +1,141 @@
+#include <stdio.h>
+#include <stdlib.h>
+#include <signal.h>
+#include <unistd.h>
+#include <time.h>
+#include "can_driver.h"
+
+// 全局变量
+static can_device_t *g_can_device = NULL;
+static volatile int g_running = 1;
+static time_t g_last_send_time = 0;
+static const int SEND_INTERVAL = 10;  // 发送间隔(秒)
+
+// 信号处理函数
+static void signal_handler(int sig) {
+    printf("收到信号 %d,准备退出...\n", sig);
+    g_running = 0;
+}
+
+// CAN数据接收回调函数
+static void can_receive_callback(can_device_t *dev, can_frame_t *frame, void *user_data) {
+    printf("收到CAN数据帧:\n");
+    printf("  ID: 0x%08X\n", frame->id);
+    printf("  类型: %s\n", frame->is_extended ? "扩展帧" : "标准帧");
+    printf("  长度: %d 字节\n", frame->len);
+    printf("  数据: ");
+    for (int i = 0; i < frame->len; i++) {
+        printf("0x%02X ", frame->data[i]);
+    }
+    printf("\n\n");
+    if (can_device_send(g_can_device, frame) == 0) {
+    printf("send echo data...\n");
+    }
+
+}
+
+// 发送测试数据函数
+static void send_test_data() {
+    if (!g_can_device) {
+        return;
+    }
+
+    // 创建测试数据帧
+    can_frame_t frame;
+    memset(&frame, 0, sizeof(frame));
+
+    // 随机生成一些测试数据
+    frame.id = 0x123;  // 测试ID
+    frame.is_extended = 0;  // 标准帧
+    frame.len = 8;  // 8字节数据
+
+    // 填充测试数据
+    time_t now = time(NULL);
+    struct tm *local_time = localtime(&now);
+    frame.data[0] = local_time->tm_hour;    // 小时
+    frame.data[1] = local_time->tm_min;     // 分钟
+    frame.data[2] = local_time->tm_sec;     // 秒
+    frame.data[3] = (unsigned char)(now >> 24);  // 时间戳高位
+    frame.data[4] = (unsigned char)(now >> 16);
+    frame.data[5] = (unsigned char)(now >> 8);
+    frame.data[6] = (unsigned char)(now);        // 时间戳低位
+    frame.data[7] = 0xAA;  // 固定值作为标识
+
+    // 发送数据
+    if (can_device_send(g_can_device, &frame) == 0) {
+        printf("定时测试数据发送成功\n");
+        g_last_send_time = now;
+    } else {
+        printf("定时测试数据发送失败\n");
+    }
+}
+
+int main(int argc, char *argv[]) {
+    // 设置信号处理
+    signal(SIGINT, signal_handler);
+    signal(SIGTERM, signal_handler);
+
+    printf("CAN驱动测试程序启动\n");
+
+    // 1. 初始化CAN总线(CAN_BUS_1对应can0)
+    printf("初始化CAN总线...\n");
+    if (can_bus_init(CAN_BUS_1) < 0) {
+        fprintf(stderr, "CAN总线初始化失败,程序退出\n");
+        return -1;
+    }
+
+    // 2. 创建CAN设备
+    printf("创建CAN设备...\n");
+    g_can_device = can_device_new(
+        CAN_BUS_1,             // 总线ID
+        can_receive_callback,  // 接收回调函数
+        NULL,                  // 用户数据
+        10                     // 发送队列大小
+    );
+
+    if (!g_can_device) {
+        fprintf(stderr, "CAN设备创建失败,程序退出\n");
+        return -1;
+    }
+
+    // 3. 启动CAN设备
+    printf("启动CAN设备...\n");
+    if (can_device_start(g_can_device) < 0) {
+        fprintf(stderr, "CAN设备启动失败,程序退出\n");
+        can_device_delete(g_can_device);
+        g_can_device = NULL;
+        return -1;
+    }
+
+    // 记录初始时间
+    g_last_send_time = time(NULL);
+
+    printf("CAN测试程序已成功启动\n");
+    printf("每10秒将发送一条测试数据\n");
+    printf("按Ctrl+C退出程序\n\n");
+
+    // 4. 主循环:定时发送数据并等待接收
+    while (g_running) {
+        time_t now = time(NULL);
+
+        // 检查是否需要发送定时测试数据
+        if (now - g_last_send_time >= SEND_INTERVAL) {
+            send_test_data();
+        }
+
+        // 短暂休眠,减少CPU占用
+        usleep(100000);  // 100ms
+    }
+
+    // 5. 清理资源
+    printf("清理资源...\n");
+    if (g_can_device) {
+        can_device_stop(g_can_device);
+        can_device_delete(g_can_device);
+        g_can_device = NULL;
+    }
+
+    printf("CAN测试程序已退出\n");
+
+    return 0;
+}