MODBUS MASTER MONITOR 1.0
Loading...
Searching...
No Matches
Modbus Core

Classes

struct  ModbusSensorParam
 Defines the configuration parameters for an individual sensor. More...
struct  ModbusSlaveParam
 Global vector that stores the configuration and state of all discovered Modbus slaves. More...
struct  ModbusRequestInfo
 Context of an in-flight Modbus request. More...
struct  ResponseFormat
 Intermediate structure to pass data from the Modbus callback to tasks. More...
struct  SensorSchedule
 Planning element for sensor sampling. More...

Macros

#define RX_PIN   13
 < Utilidades de memoria (memcpy).
#define TX_PIN   12
 UART transmission pin for RS485.
#define MAX_MODBUS_RESPONSE_LENGTH   256
 Maximum expected length for a Modbus response.

Enumerations

enum  DiscoveryOrder { DISCOVERY_GET_COUNT = 1 , DISCOVERY_GET_DATA_OFFSET = 255 , DISCOVERY_READ_SENSOR_PARAM = 8 }
 Special commands used during the sensor discovery phase. More...
enum  RequestType { REQUEST_UNKNOWN , REQUEST_DISCOVERY , REQUEST_SAMPLING }
 Classification of the purpose of a Modbus request. More...

Functions

void addRequest (uint32_t token, uint8_t slaveId, uint8_t sensorId, uint8_t functionCode, RequestType type)
 Registers a new request in the circular buffer.
ModbusRequestInfofindRequestByToken (uint32_t token)
 Searches for a pending request by its token.
void initScheduler ()
 Initializes or updates the scheduling list (Scheduler).
void handleData (ModbusMessage response, uint32_t token)
 Callback executed upon receiving valid Modbus data.
void handleError (Error error, uint32_t token)
 Callback executed when a Modbus error occurs.
bool discoverDeviceSensors (uint8_t deviceId)
 Starts the discovery process for a specific device.
void initialDiscoveryTask (void *pvParameters)
 One-shot task for the initial discovery of sensors.
void DataRequestScheduler (void *pvParameters)
 Main task of the Scheduler.
bool getSensorParams (uint8_t slaveId, uint8_t sensorID, uint16_t &startAddr, uint16_t &numRegs)
 Gets the configuration parameters of a specific sensor.
uint8_t getRegistersPerChannel (uint8_t slaveId, uint8_t sensorID)
 Calculates the number of registers per channel for a sensor.
void parseAndStoreDiscoveryResponse (const ResponseFormat &response, uint8_t slaveId)
 Parses the discovery response and updates the slave list.
void EventManager (void *pvParameters)
 Event Manager task.

Variables

ModbusClientRTU MB
 Global instance of the Modbus RTU client.
QueueHandle_t queueRespuestas
 Queue for received Modbus responses.
QueueHandle_t queueEventos_Peripheral
 Event queues to the EventManager (peripherals and scheduler).

Detailed Description

Overview

This module implements the Modbus RTU client (ESP32/TTGO) and the complete flow of:

  • Initial sensor discovery on RS485 slaves.
  • Periodic reading scheduling (Scheduler) based on each sensor's parameters.
  • Response and error management with token correlation.
  • Data formatting in payloads per sensor and aggregation in a LoRaWAN payload.

Structure and components

Main API

Usage

Flow summary:

1) Modbus startup

  • Initializes UART RS485 and ModbusClientRTU (timeout/begin).
  • Registers callbacks: handleData(), handleError().
  • Creates tasks: EventManager and DataRequestScheduler.
  • Launches initialDiscoveryTask with devicesToQuery.

2) Discovery

3) Periodic sampling

  • DataRequestScheduler triggers REQUEST_SAMPLING according to nextSampleTime.
  • EventManager queries getSensorParams() and sends read request with startAddress/numRegs.
  • handleData() delivers registers to the next subsystem.

4) Modbus errors

  • handleError(): handles TIMEOUT, increases consecutiveFails, removes inactive slaves and recalculates scheduler.
  • Tokens are invalidated after processing.

Warnings and best practices:

  • Ensure consistent layout of 8 parameter registers for discovery.
  • Respect offset 3 for register data in Modbus RTU responses.
  • Protect scheduleList access with schedulerMutex.
  • Review MAX_* limits to avoid overflow in queues and tokens.

Macro Definition Documentation

◆ RX_PIN

#define RX_PIN   13

< Utilidades de memoria (memcpy).

< Necesario para definiciones de tipos enteros de tamaño fijo (uint8_t, etc). < Estructura de datos para mapeo de sensores. < Utilizado para la generación de timestamps UNIX.

UART reception pin for RS485.

Enumeration Type Documentation

◆ DiscoveryOrder

Special commands used during the sensor discovery phase.

Enumerator
DISCOVERY_GET_COUNT 

Request item count.

DISCOVERY_GET_DATA_OFFSET 

Offset to get specific data.

DISCOVERY_READ_SENSOR_PARAM 

Command to read sensor parameters (registers 0..7).

◆ RequestType

Classification of the purpose of a Modbus request.

Enumerator
REQUEST_UNKNOWN 

Unidentified request type.

REQUEST_DISCOVERY 

Request related to hardware discovery.

REQUEST_SAMPLING 

Request for periodic data reading.

Function Documentation

◆ addRequest()

void addRequest ( uint32_t token,
uint8_t slaveId,
uint8_t sensorId,
uint8_t functionCode,
RequestType type )

Registers a new request in the circular buffer.

Parameters
tokenUnique identifier.
slaveIdSlave ID.
sensorIdSensor ID.
functionCodeModbus function.
typeRequest type.

◆ DataRequestScheduler()

void DataRequestScheduler ( void * pvParameters)

Main task of the Scheduler.

Periodically checks which sensors should be sampled and generates events for the EventManager.

◆ discoverDeviceSensors()

bool discoverDeviceSensors ( uint8_t deviceId)

Starts the discovery process for a specific device.

Parameters
deviceIdModbus ID of the device to query.
Returns
true if the event was queued correctly, false otherwise.

◆ EventManager()

void EventManager ( void * pvParameters)

Event Manager task.

Centralizes requests from the queues (Scheduler and Peripheral) and converts them into actual Modbus transactions.

◆ findRequestByToken()

ModbusRequestInfo * findRequestByToken ( uint32_t token)

Searches for a pending request by its token.

Parameters
tokenToken to search for.
Returns
Pointer to the ModbusRequestInfo structure or nullptr if it does not exist.

◆ getRegistersPerChannel()

uint8_t getRegistersPerChannel ( uint8_t slaveId,
uint8_t sensorID )

Calculates the number of registers per channel for a sensor.

Returns
Number of registers or 0 if the sensor is not found.

◆ getSensorParams()

bool getSensorParams ( uint8_t slaveId,
uint8_t sensorID,
uint16_t & startAddr,
uint16_t & numRegs )

Gets the configuration parameters of a specific sensor.

Parameters
slaveIdSlave ID.
sensorIDSensor ID.
startAddrReference to return the start address.
numRegsReference to return the number of registers.
Returns
true if the sensor was found, false otherwise.

◆ handleData()

void handleData ( ModbusMessage response,
uint32_t token )

Callback executed upon receiving valid Modbus data.

Parameters
responseObject with the raw response.
tokenToken of the original request.

◆ handleError()

void handleError ( Error error,
uint32_t token )

Callback executed when a Modbus error occurs.

Manages retry logic and removal of inactive slaves (Timeout).

Parameters
errorError code.
tokenToken of the failed request.

◆ initialDiscoveryTask()

void initialDiscoveryTask ( void * pvParameters)

One-shot task for the initial discovery of sensors.

Iterates over dispositivosAConsultar, launches discovery, and then self-deletes.

◆ initScheduler()

void initScheduler ( )

Initializes or updates the scheduling list (Scheduler).

Iterates through slaveList, calculates effective intervals based on channels and registers, and populates scheduleList. It is thread-safe using schedulerMutex.

◆ parseAndStoreDiscoveryResponse()

void parseAndStoreDiscoveryResponse ( const ResponseFormat & response,
uint8_t slaveId )

Parses the discovery response and updates the slave list.

Decodes the 8 parameter registers and creates or updates the entry in slaveList.

Parameters
responseRaw data received.
slaveIdID of the slave that responded.