65 lines
1.9 KiB
C
65 lines
1.9 KiB
C
#ifndef MODBUS_TCP_H
|
|
#define MODBUS_TCP_H
|
|
|
|
#include <stdint.h>
|
|
#include <stdbool.h>
|
|
#include <stddef.h>
|
|
|
|
#include "modbus_memory.h"
|
|
|
|
#define MODBUS_TCP_PORT 502
|
|
|
|
/* MBAP header is always 7 bytes */
|
|
#define MODBUS_TCP_MBAP_LEN 7
|
|
|
|
/* Maximum Modbus TCP ADU size:
|
|
* 7-byte MBAP + up to 253-byte PDU = 260 bytes
|
|
*/
|
|
#define MODBUS_TCP_MAX_ADU_LEN 260
|
|
#define MODBUS_TCP_MAX_PDU_LEN 253
|
|
|
|
/* Modbus exception codes */
|
|
#define MODBUS_EX_ILLEGAL_FUNCTION 0x01
|
|
#define MODBUS_EX_ILLEGAL_DATA_ADDRESS 0x02
|
|
#define MODBUS_EX_ILLEGAL_DATA_VALUE 0x03
|
|
#define MODBUS_EX_SERVER_DEVICE_FAILURE 0x04
|
|
|
|
/* Supported function codes */
|
|
#define MODBUS_FC_READ_COILS 0x01
|
|
#define MODBUS_FC_READ_DISCRETE_INPUTS 0x02
|
|
#define MODBUS_FC_READ_HOLDING_REGISTERS 0x03
|
|
#define MODBUS_FC_READ_INPUT_REGISTERS 0x04
|
|
#define MODBUS_FC_WRITE_SINGLE_COIL 0x05
|
|
#define MODBUS_FC_WRITE_SINGLE_REGISTER 0x06
|
|
#define MODBUS_FC_WRITE_MULTIPLE_COILS 0x0F
|
|
#define MODBUS_FC_WRITE_MULTIPLE_REGISTERS 0x10
|
|
|
|
typedef struct
|
|
{
|
|
uint16_t transaction_id;
|
|
uint16_t protocol_id;
|
|
uint16_t length;
|
|
uint8_t unit_id;
|
|
} modbus_mbap_t;
|
|
|
|
/*
|
|
* Process one Modbus TCP request ADU and write the response ADU.
|
|
*
|
|
* mem = target virtual device memory
|
|
* req = incoming request bytes
|
|
* req_len = number of request bytes
|
|
* resp = output response buffer
|
|
* resp_max_len = size of resp buffer
|
|
* resp_len = actual response length written
|
|
*
|
|
* Returns true if a response was built successfully.
|
|
* Returns false on malformed packet / buffer issues.
|
|
*/
|
|
bool modbus_tcp_process_request(modbus_memory_t *mem,
|
|
const uint8_t *req,
|
|
size_t req_len,
|
|
uint8_t *resp,
|
|
size_t resp_max_len,
|
|
size_t *resp_len);
|
|
|
|
#endif /* MODBUS_TCP_H */ |