代码示例
#include <future>
#include <iostream>
#include <thread>
#include <modbus.h>
#define TEST_MAX_REGISTERS 100
#define TEST_MAX_READ 5
int main()
{
auto&& f1 = std::async(std::launch::async, []() {
std::this_thread::sleep_for(std::chrono::seconds(1));
uint16_t tab_reg[TEST_MAX_REGISTERS] = { 0 };
modbus_t* ctx = modbus_new_rtu("COM2", 9600, 'N', 8, 1);
modbus_set_slave(ctx, 1);
modbus_rtu_set_serial_mode(ctx, MODBUS_RTU_RS232);
modbus_rtu_set_rts(ctx, MODBUS_RTU_RTS_UP);
if (modbus_connect(ctx) == -1) {
fprintf(stderr, "Connection failed: %s\n", modbus_strerror(errno));
modbus_free(ctx);
return;
}
modbus_set_response_timeout(ctx, 0, 1000000);
while (true) {
int rc = modbus_read_registers(ctx, 0, TEST_MAX_READ, tab_reg);
if (rc == -1) {
fprintf(stderr, "%s\n", modbus_strerror(errno));
continue;
}
for (int i = 0; i < TEST_MAX_READ; ++i) {
printf("<%#x>", tab_reg[i]);
}
printf("\n");
std::this_thread::sleep_for(std::chrono::seconds(1));
}
});
auto&& f2 = std::async(std::launch::async, []() {
modbus_t* ctx = modbus_new_rtu("COM3", 9600, 'N', 8, 1);
modbus_set_slave(ctx, 1);
modbus_rtu_set_serial_mode(ctx, MODBUS_RTU_RS232);
modbus_rtu_set_rts(ctx, MODBUS_RTU_RTS_UP);
if (modbus_connect(ctx) == -1) {
fprintf(stderr, "Connection failed: %s\n", modbus_strerror(errno));
modbus_free(ctx);
return;
}
modbus_mapping_t* mb_mapping = modbus_mapping_new(MODBUS_MAX_READ_BITS, 0, MODBUS_MAX_READ_REGISTERS, 0);
if (mb_mapping == NULL) {
fprintf(stderr, "Failed to allocate the mapping: %s\n", modbus_strerror(errno));
modbus_free(ctx);
return;
}
uint8_t query[MODBUS_TCP_MAX_ADU_LENGTH];
while (true) {
for (size_t i = 0; i < TEST_MAX_REGISTERS; i++) {
mb_mapping->tab_registers[i] = rand() % 100;
}
memset(query, 0, sizeof(query));
int rc = modbus_receive(ctx, query);
if (rc == -1) {
continue;
}
modbus_reply(ctx, query, rc, mb_mapping);
}
});
while (true) {
std::this_thread::sleep_for(std::chrono::seconds(1));
}
return 0;
}
效果