1. 存储区代号
代码号 | 功能 |
---|---|
1区 | 输入线圈 |
0区 | 输出线圈 |
3区 | 输入寄存器 |
4区 | 输出寄存器 |
2. 功能码
代码 | 功能 |
---|---|
0x01 | 读取输出线圈 |
0x02 | 读取输入线圈 |
0x03 | 读取输出寄存器 |
0x04 | 读取输入寄存器 |
0x05 | 写入单个线圈 |
0x06 | 写入单个寄存器 |
0x0F | 写入多个线圈 |
0x10 | 写入多个寄存器 |
3. pymodbus服务器
from pymodbus.server.async_io import StartTcpServer
from pymodbus.datastore import (
ModbusSequentialDataBlock,
ModbusServerContext,
ModbusSlaveContext,
)
datablock = ModbusSequentialDataBlock.create()
context = ModbusSlaveContext(
di=datablock,
co=datablock,
hr=datablock,
ir=datablock,
)
single = True
# Build data storage
store = ModbusServerContext(slaves=context, single=single)
if __name__ == '__main__':
address = ("127.0.0.1", 1502)
StartTcpServer(
context=store, # Data storage
address=address, # listen address
allow_reuse_address=True, # allow the reuse of an address
)
4. libmodbus客户端
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <errno.h>
#include <modbus/modbus.h>
#include <time.h>
// const uint16_t UT_INPUT_REGISTERS_ADDRESS = 0x1;
const uint16_t UT_BITS_ADDRESS = 0x04;
// const uint16_t UT_INPUT_REGISTERS_NB = 0xA;
// const uint16_t UT_INPUT_REGISTERS_TAB[] = { 0x000A };
int main(int argc, char const *argv[])
{
int nb = 0x08;
int rc = 0;
modbus_t *ctx;
uint8_t *tab_rp_bits;
tab_rp_bits = (uint8_t *) malloc(nb * sizeof(uint8_t));
memset(tab_rp_bits, 0, nb * sizeof(uint8_t));
ctx = modbus_new_tcp("127.0.0.1", 1502);
if(ctx == NULL)
{
fprintf(stderr, "Unable to allocate libmodbus context\n");
return -1;
}
if(modbus_connect(ctx) == -1)
{
fprintf(stderr, "Connection failed: %s\n", modbus_strerror(errno));
modbus_free(ctx);
return -1;
}
uint8_t data[8] = {1, 0, 1, 0, 1, 1, 0, 1};
while(1)
{
// rc = modbus_write_bit(ctx, UT_BITS_ADDRESS, 1);
rc = modbus_write_bits(ctx, UT_BITS_ADDRESS, nb, data);
printf("nb points %d : ", rc);
rc = modbus_read_bits(ctx, UT_BITS_ADDRESS, 8, tab_rp_bits);
if (rc != 1)
{
for (size_t i{0}; i < 8; i++)
// printf("FAILED (nb points %d)\n", rc);
printf("%d ", tab_rp_bits[i]);
}
printf("\n");
memset(tab_rp_bits, 0, nb * sizeof(uint8_t));
sleep(1);
}
modbus_close(ctx);
modbus_free(ctx);
return 0;
}