add new mb interface
authorkyz <kyz@kyz.pub>
Thu, 6 Nov 2025 09:44:29 +0000 (17:44 +0800)
committerkyz <kyz@kyz.pub>
Thu, 6 Nov 2025 09:44:29 +0000 (17:44 +0800)
test/Makefile [new file with mode: 0644]
test/mb.c [new file with mode: 0644]
test/mb.h [new file with mode: 0644]
test/mb_test.c [new file with mode: 0644]

diff --git a/test/Makefile b/test/Makefile
new file mode 100644 (file)
index 0000000..50c3bc2
--- /dev/null
@@ -0,0 +1,11 @@
+all: mb_test
+
+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/mb.c b/test/mb.c
new file mode 100644 (file)
index 0000000..26c4b53
--- /dev/null
+++ b/test/mb.c
@@ -0,0 +1,349 @@
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+#include <time.h>
+#include <errno.h>
+
+#include "mb.h"
+
+// 全局总线列表
+
+mb_port_cfg_t mb_port[  ] = {
+    {"/dev/ttyUSB0",  9600, 'N', 8, 1, MODBUS_RTU_RS232 },
+    {"/dev/ttyUSB1", 19200, 'N', 8, 1, MODBUS_RTU_RS232 },
+    {"/dev/ttyUSB2", 38400, 'N', 8, 1, MODBUS_RTU_RS485 },
+};
+
+mb_bus_t g_mb_bus[MB_BUS_MAX];
+
+// 获取当前时间戳(毫秒)
+static uint64_t get_current_time_ms(void)
+{
+    struct timespec ts;
+    clock_gettime(CLOCK_MONOTONIC, &ts);
+    return (uint64_t)ts.tv_sec * 1000 + ts.tv_nsec / 1000000;
+}
+
+// 初始化写入队列
+static void write_queue_init(mb_write_queue_t *queue)
+{
+    queue->head = NULL;
+    queue->tail = NULL;
+    pthread_mutex_init(&queue->lock, NULL);
+}
+
+// 销毁写入队列
+static void write_queue_destroy(mb_write_queue_t *queue)
+{
+    mb_write_message_node_t *node = NULL;
+    mb_write_message_node_t *next = NULL;
+
+    pthread_mutex_lock(&queue->lock);
+    node = queue->head;
+    while (node != NULL) {
+        next = node->next;
+        free(node);
+        node = next;
+    }
+    queue->head = NULL;
+    queue->tail = NULL;
+    pthread_mutex_unlock(&queue->lock);
+
+    pthread_mutex_destroy(&queue->lock);
+}
+
+// 向写入队列添加消息
+static int write_queue_push(mb_write_queue_t *queue, const mb_write_message_t *msg)
+{
+    mb_write_message_node_t *node = (mb_write_message_node_t *)malloc(sizeof(mb_write_message_node_t));
+    if (node == NULL) {
+        return -1;
+    }
+
+    node->msg = *msg;
+    node->next = NULL;
+
+    pthread_mutex_lock(&queue->lock);
+    if (queue->tail == NULL) {
+        queue->head = node;
+        queue->tail = node;
+    } else {
+        queue->tail->next = node;
+        queue->tail = node;
+    }
+    pthread_mutex_unlock(&queue->lock);
+
+    return 0;
+}
+
+// 从写入队列取出消息
+static int write_queue_pop(mb_write_queue_t *queue, mb_write_message_t *msg)
+{
+    int ret = -1;
+    mb_write_message_node_t *node = NULL;
+
+    pthread_mutex_lock(&queue->lock);
+    if (queue->head != NULL) {
+        node = queue->head;
+        *msg = node->msg;
+        queue->head = node->next;
+        if (queue->head == NULL) {
+            queue->tail = NULL;
+        }
+        free(node);
+        ret = 0;
+    }
+    pthread_mutex_unlock(&queue->lock);
+
+    return ret;
+}
+
+// 总线线程函数
+static void *bus_thread_func(void *arg)
+{
+    mb_bus_t *bus = (mb_bus_t *)arg;
+    mb_device_t *device = NULL;
+    mb_write_message_t write_msg;
+    uint64_t current_time;
+    int i, j;
+    bus->running = 1;
+    while (bus->running) {
+        current_time = get_current_time_ms();
+
+        pthread_mutex_lock(&bus->devices_lock);
+        device = bus->devices;
+        while (device != NULL) {
+            // 检查是否需要读取数据
+            if (current_time - device->last_read_time >= device->read_interval) {
+                //printf( "to read device %d on bus[%s]\n", device->slave_id, device->bus->port_cfg.port );
+                // 设置从机ID
+                modbus_set_slave(bus->modbus_ctx, device->slave_id);
+
+                // 读取所有寄存器区域
+                for (i = 0; i < device->register_area_count; i++) {
+                    mb_register_area_t *area = &device->register_areas[i];
+
+                    // 读取寄存器
+                    if (modbus_read_registers(bus->modbus_ctx, area->start_addr, area->count, area->data) == -1) {
+                        fprintf(stderr, "%s read error: %s\n", device->name, modbus_strerror(errno));
+                        device->read_err_count++;
+                        if( device->read_err_count >= 5 ){
+                            if( device->connected == 1 ){
+                                device->connected = 0;
+                                printf( "%s on bus[%s] ----------------> disconnected\n", device->name, bus->port_cfg.port );
+                            }
+                        }
+                    }else{
+                        device->read_err_count = 0;
+                        if( device->connected == 0 ){
+                            device->connected = 1;
+                            printf( "%s on bus[%s] ----------------> connected\n", device->name, bus->port_cfg.port );
+                        }
+                    }
+                }
+
+                device->last_read_time = current_time;
+
+                // 处理写入队列
+                while (write_queue_pop(&device->write_queue, &write_msg) == 0) {
+                    modbus_set_slave(bus->modbus_ctx, device->slave_id);
+                    if (modbus_write_register(bus->modbus_ctx, write_msg.addr, write_msg.value) == -1) {
+                        fprintf(stderr, "Modbus write error: %s\n", modbus_strerror(errno));
+                    }
+                }
+            }
+
+            device = device->next;
+        }
+        pthread_mutex_unlock(&bus->devices_lock);
+
+        // 短暂休眠,避免占用过多CPU
+        usleep(1000);
+    }
+
+    return NULL;
+}
+
+static int mb_bus_create( mb_bus_t *bus, mb_port_cfg_t *cfg ) ;
+// 模块初始化
+int mb_bus_init(void)
+{
+    int ret = 0;
+    for( int i = 0; i < MB_BUS_MAX; i++)
+    {
+        if( mb_bus_create(&g_mb_bus[i], &mb_port[i]) == 0 ){
+            printf( "creat mb bus [%d][%s] ... OK!\n", i, mb_port[i].port );
+        }else{
+            ret--;
+            printf( "creat mb bus [%d][%s] ... Failed!\n", i, mb_port[i].port );
+        }
+    }
+
+    return ret;
+}
+
+// 创建Modbus总线
+static int mb_bus_create( mb_bus_t *bus, mb_port_cfg_t *cfg )
+{
+    modbus_t *modbus_ctx = NULL;
+
+    if( !cfg || !bus )
+    {
+        return -1;
+    }
+
+    // 创建Modbus上下文
+    modbus_ctx = modbus_new_rtu(cfg->port, cfg->baudrate, cfg->parity, cfg->data_bit, cfg->stop_bit);
+    if (modbus_ctx == NULL) {
+        fprintf(stderr, "Unable to create the libmodbus context\n");
+        return -1;
+    }
+
+    // 设置Modbus模式
+    modbus_rtu_set_serial_mode(modbus_ctx, cfg->mb_mode);
+
+    // 打开串口
+    if (modbus_connect(modbus_ctx) == -1) {
+        fprintf(stderr, "Connection failed: %s\n", modbus_strerror(errno));
+        modbus_free(modbus_ctx);
+        return -1;
+    }
+    memcpy( &bus->port_cfg, cfg, sizeof(mb_port_cfg_t) );
+    bus->modbus_ctx = modbus_ctx;
+    bus->devices = NULL;
+    bus->running = 0;
+    pthread_mutex_init(&bus->devices_lock, NULL);
+
+    return 0;
+}
+
+// 注册Modbus设备
+mb_device_t * mb_device_new( const char * name, mb_bus_id_t bus_id, uint8_t slave_id,
+                          mb_register_area_t *register_areas, int register_area_count,
+                          int read_interval)
+{
+    mb_bus_t *bus = NULL;
+    mb_device_t *device = NULL;
+    int i;
+    int ret = 0;
+
+    if( bus_id >= MB_BUS_MAX ){
+        return NULL;
+    }
+
+    bus = &g_mb_bus[bus_id];
+
+    // 创建设备结构体
+    device = (mb_device_t *)malloc(sizeof(mb_device_t));
+    if (device == NULL) {
+        return NULL;
+    }
+    device->name = name;
+    device->slave_id = slave_id;
+    device->bus = bus;
+    device->read_interval = read_interval;
+    device->last_read_time = 0;
+
+    // 复制寄存器区域信息
+    device->register_area_count = register_area_count;
+    device->register_areas = (mb_register_area_t *)malloc(sizeof(mb_register_area_t) * register_area_count);
+    if (device->register_areas == NULL) {
+        free(device);
+        return NULL;
+    }
+
+    for (i = 0; i < register_area_count; i++) {
+        device->register_areas[i].start_addr = register_areas[i].start_addr;
+        device->register_areas[i].count = register_areas[i].count;
+        device->register_areas[i].data = (uint16_t *)malloc(sizeof(uint16_t) * register_areas[i].count);
+        if (device->register_areas[i].data == NULL) {
+            // 释放已分配的内存
+            for (int j = 0; j < i; j++) {
+                free(device->register_areas[j].data);
+            }
+            free(device->register_areas);
+            free(device);
+            return NULL;
+        }
+        memset(device->register_areas[i].data, 0, sizeof(uint16_t) * register_areas[i].count);
+    }
+
+    // 初始化写入队列
+    write_queue_init(&device->write_queue);
+
+    // 初始化互斥锁
+    pthread_mutex_init(&device->data_lock, NULL);
+
+    // 将设备添加到总线
+    pthread_mutex_lock(&bus->devices_lock);
+    device->next = bus->devices;
+    bus->devices = device;
+    pthread_mutex_unlock(&bus->devices_lock);
+
+    return device;
+}
+
+// 读取寄存器值
+int mb_register_read( mb_device_t *dev, uint16_t addr, uint16_t *value)
+{
+    int i, j;
+
+    if( !dev ){
+        return -1;
+    }
+
+
+    // 在设备的寄存器区域中查找地址
+    pthread_mutex_lock(&dev->data_lock);
+    for (i = 0; i < dev->register_area_count; i++) {
+        mb_register_area_t *area = &dev->register_areas[i];
+        if (addr >= area->start_addr && addr < area->start_addr + area->count) {
+            j = addr - area->start_addr;
+            *value = area->data[j];
+            pthread_mutex_unlock(&dev->data_lock);
+            return 0;
+        }
+    }
+    pthread_mutex_unlock(&dev->data_lock);
+
+    return -1; // 未找到地址
+}
+
+// 写入寄存器值
+int mb_register_write( mb_device_t *dev, uint16_t addr, uint16_t value)
+{
+    mb_write_message_t msg;
+
+    // 检查地址是否在设备的寄存器区域中
+    pthread_mutex_lock(&dev->data_lock);
+    for (int i = 0; i < dev->register_area_count; i++) {
+        mb_register_area_t *area = &dev->register_areas[i];
+        if (addr >= area->start_addr && addr < area->start_addr + area->count) {
+            // 添加到写入队列
+            msg.addr = addr;
+            msg.value = value;
+            pthread_mutex_unlock(&dev->data_lock);
+            return write_queue_push(&dev->write_queue, &msg);
+        }
+    }
+    pthread_mutex_unlock(&dev->data_lock);
+
+    return -1; // 未找到地址
+}
+
+// 启动Modbus模块
+int mb_bus_start(void)
+{
+    mb_bus_t *bus;
+
+    for( int i=0; i<MB_BUS_MAX; i++){
+        bus = &g_mb_bus[i];
+        if (pthread_create(&bus->thread, NULL, bus_thread_func, bus) != 0) {
+                fprintf(stderr, "Failed to create bus thread\n");
+                return -1;
+        }
+    }
+    return 0;
+}
+
diff --git a/test/mb.h b/test/mb.h
new file mode 100644 (file)
index 0000000..9abffa6
--- /dev/null
+++ b/test/mb.h
@@ -0,0 +1,95 @@
+#ifndef __MB_H__
+#define __MB_H__
+
+#include <stdint.h>
+#include <pthread.h>
+#include <modbus/modbus.h>
+
+// 寄存器区域类型定义
+typedef struct {
+    uint16_t start_addr;    // 起始地址
+    uint16_t count;         // 寄存器数量
+    uint16_t *data;         // 数据缓冲区指针
+} mb_register_area_t;
+
+// 写入消息结构体
+typedef struct {
+    uint16_t addr;          // 寄存器地址
+    uint16_t value;         // 写入值
+} mb_write_message_t;
+
+// 写入消息队列节点
+typedef struct write_message_node {
+    mb_write_message_t msg;
+    struct write_message_node *next;
+} mb_write_message_node_t;
+
+// 写入消息队列
+typedef struct {
+    mb_write_message_node_t *head;
+    mb_write_message_node_t *tail;
+    pthread_mutex_t lock;
+} mb_write_queue_t;
+
+struct modbus_bus;
+// 设备结构体
+typedef struct modbus_device {
+    uint8_t slave_id;                           // 从机ID
+    int read_interval;                          // 读取周期(ms)
+    uint64_t last_read_time;                    // 上次读取时间
+    mb_register_area_t *register_areas;     // 寄存器区域数组
+    int register_area_count;                    // 寄存器区域数量
+    mb_write_queue_t write_queue;           // 写入消息队列
+    pthread_mutex_t data_lock;                  // 数据访问互斥锁
+    struct modbus_device *next;                 // 指向下一个设备
+    struct modbus_bus *bus;
+    int connected;
+    int read_err_count;
+    const char *name;
+} mb_device_t;
+
+typedef enum{
+    MB_BUS_1 = 0,
+//    MB_BUS_2 = 1,
+//    MB_BUS_3 = 2,
+    MB_BUS_MAX,
+} mb_bus_id_t;
+
+typedef struct{
+    char *port;                             // 串口设备路径
+    int baudrate;                           // 波特率
+    char parity;                            // 校验位
+    int data_bit;                           // 数据位
+    int stop_bit;                           // 停止位
+    int mb_mode;                            // MB模式  MODBUS_RTU_RS232/MODBUS_RTU_RS485
+}mb_port_cfg_t;
+
+// 总线结构体
+typedef struct modbus_bus {
+    mb_bus_id_t id;                         // 总线ID
+    mb_port_cfg_t port_cfg;                 // 端口配置
+    modbus_t *modbus_ctx;                   // libmodbus上下文
+    mb_device_t *devices;                   // 设备链表
+    pthread_t thread;                       // 总线线程
+    pthread_mutex_t devices_lock;           // 设备列表互斥锁
+    int running;                            // 运行状态
+} mb_bus_t;
+
+// 模块初始化
+int mb_bus_init(void);
+
+// 注册Modbus设备
+mb_device_t * mb_device_new( const char * name, mb_bus_id_t bus_id, uint8_t slave_id,
+                          mb_register_area_t *register_areas, int register_area_count,
+                          int read_interval);
+
+// 读取寄存器值
+int mb_register_read( mb_device_t *dev, uint16_t addr, uint16_t *value);
+
+// 写入寄存器值
+int mb_register_write( mb_device_t *dev, uint16_t addr, uint16_t value);
+
+// 启动Modbus模块
+int mb_bus_start(void);
+
+#endif /* __MB_H__ */
diff --git a/test/mb_test.c b/test/mb_test.c
new file mode 100644 (file)
index 0000000..d77e21f
--- /dev/null
@@ -0,0 +1,71 @@
+#include <stdio.h>
+#include <unistd.h>
+
+#include "mb.h"
+
+int main(void)
+{
+    mb_device_t *pcs, *bms;
+    mb_register_area_t register_areas[2];
+
+    // 初始化Modbus总线
+    if (mb_bus_init() != 0) {
+        fprintf(stderr, "Failed to initialize modbus access module\n");
+        return -1;
+    }
+
+    // 定义寄存器区域
+    register_areas[0].start_addr = 0;
+    register_areas[0].count = 10;
+    register_areas[1].start_addr = 20;
+    register_areas[1].count = 5;
+
+    // 注册Modbus设备
+    pcs = mb_device_new( "PCS", MB_BUS_1, 1, register_areas, 2, 1000 );
+    if( !pcs ){
+        fprintf(stderr, "Failed to register modbus device\n");
+        return -1;
+    }
+    bms = mb_device_new( "BMS", MB_BUS_1, 2, register_areas, 2, 1000 );
+    if( !bms ){
+        fprintf(stderr, "Failed to register modbus device\n");
+        return -1;
+    }
+
+    // 启动Modbus模块
+    if (mb_bus_start() != 0) {
+        fprintf(stderr, "Failed to start modbus access module\n");
+        return -1;
+    }
+
+    // 主循环:读取并打印寄存器值
+    uint16_t value;
+    while (1) {
+        // 读取寄存器值
+        if (mb_register_read( pcs, 2, &value) == 0) {
+            printf("PCS Register 2 value: %d\n", value);
+        }
+        if (mb_register_read( bms, 3, &value) == 0) {
+            printf("BMS Register 3 value: %d\n", value);
+        }
+
+        // 每5秒写入一个测试值到寄存器1
+        static int count = 0;
+        count++;
+        if (count % 5 == 0) {
+            printf("Writing value %d to register 1\n", count);
+            mb_register_write( pcs, 1, count);
+            mb_register_write( bms, 5, count);
+        }
+
+        sleep(1);
+    }
+
+    // 停止Modbus模块
+
+
+    // 退出Modbus访问模块
+
+
+    return 0;
+}