Files
ch32v203-eth-node/include/modbus.h
2024-11-12 00:55:52 +06:00

57 lines
1.9 KiB
C

#ifndef MODBUS_H
#define MODBUS_H
#include <MQTT/MQTTClient.h>
#include <stdbool.h>
#include <stdint.h>
#include "config.h"
// Function codes
#define MODBUS_FC_READ_HOLDING_REGISTERS 0x03
#define MODBUS_FC_WRITE_SINGLE_REGISTER 0x06
#define MODBUS_FC_WRITE_MULTIPLE_REGISTERS 0x10
// Modbus protocol exception codes
#define MODBUS_ERROR_NONE 0x00
#define MODBUS_ERROR_ILLEGAL_FUNCTION 0x01
#define MODBUS_ERROR_ILLEGAL_ADDRESS 0x02
#define MODBUS_ERROR_ILLEGAL_VALUE 0x03
#define MODBUS_ERROR_DEVICE_FAILURE 0x04
#define MODBUS_ERROR_ACKNOWLEDGE 0x05
#define MODBUS_ERROR_DEVICE_BUSY 0x06
#define MODBUS_ERROR_MEMORY_PARITY 0x08
#define MODBUS_ERROR_TIMEOUT 0x0B // No response received
#define MODBUS_ERROR_CRC 0x0C // CRC check failed
// Frame length
#define MB_MIN_LEN 4
#define MB_CRC_LEN 2
#define MB_WREG_LEN 8
#define MB_MAX_BUFFER 32
// States for the Modbus protocol state machine
typedef enum {
MODBUS_IDLE, // Ready to send new request
MODBUS_WAITING_RESPONSE, // Request sent, waiting for slave response
MODBUS_PROCESS_RESPONSE // Response received, processing data
} modbus_state_t;
// Callback function type for handling received Modbus register values
typedef void (*modbus_value_cb)(uint8_t device_idx, const char* property,
uint16_t value);
// Initialize the Modbus protocol handler with callback for received values
void modbus_handler_init(modbus_value_cb value_callback);
void modbus_handler_process(void);
// Send a Modbus read or write request to a slave device
// Returns true if request was queued successfully
bool modbus_handler_send_request(uint8_t device_idx, const char* property,
bool is_write, uint16_t value);
// Publish a Modbus register value to MQTT broker
// Formats topic as device_name/property
void modbus_publish_value(MQTTClient* client, const char* device_name,
const char* property, uint16_t value);
#endif // MODBUS_H