MODBUS MASTER MONITOR 1.0
Loading...
Searching...
No Matches
main.cpp File Reference

Modbus RTU Master Firmware over LoRaWAN (ESP32/TTGO). More...

#include <Arduino.h>
#include <SPI.h>
#include <hal/hal.h>
#include <lmic.h>
#include <vector>
#include <cstdint>
#include <map>
#include <ctime>
#include <cstring>
#include <algorithm>
#include "ModbusClientRTU.h"

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...
struct  EventManagerFormat
 Message structure for internal event communication. More...
struct  BitPacker
 Utility for packing arbitrary bits into a byte stream. More...
struct  SensorDataPayload
 Container for processed sensor data, ready for aggregation. More...
struct  Fragmento
 Binary fragment ready for LoRaWAN transmission. 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.
#define MAX_SENSOR_PAYLOAD   128
 Maximum size of an individual sensor payload.
#define AGGREGATION_INTERVAL_MS   6100
 Aggregation interval (ms).
#define AGGREGATION_INTERVAL_MS   6100
 Aggregation interval (ms).

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.
static bool formatAndEnqueueSensorData (const ResponseFormat &response, const ModbusRequestInfo &request, std::vector< uint8_t > &values)
 Extracts and formats data from a sampling Modbus response.
void DataFormatter (void *pvParameters)
 Data Formatter task.
void DataPrinterTask (void *pvParameters)
 Tarea temporal para imprimir los payloads de datos formateados.
std::vector< uint8_t > construirPayloadUnificado (uint8_t id_mensaje, const std::vector< SensorDataPayload > &collectedPayloads)
 Builds a unified payload from a collection of sensor data.
void os_getArtEui (u1_t *buf)
 LMIC configuration functions (placeholders).
void os_getDevEui (u1_t *buf)
void os_getDevKey (u1_t *buf)
void onEvent (ev_t ev)
 LMIC/LoRaWAN event callback.
void initLoRa ()
 Initializes the LMIC stack and configures LoRaWAN (ABP, US915).
void tareaLoRa (void *pvParameters)
 Task dedicated to sending data via LoRaWAN.
void tareaRunLoop (void *pvParameters)
 LMIC runloop task.
void DataAggregatorTask (void *pvParameters)
 Proactive task that collects and packages sensor data at a fixed rate.
void setup ()
void loop ()

Variables

ModbusClientRTU MB
 Global instance of the Modbus RTU client.
std::vector< ModbusSlaveParamslaveList
constexpr size_t MAX_REQUESTS = 16
 Maximum size of the pending requests buffer.
ModbusRequestInfo requestBuffer [MAX_REQUESTS]
 Circular buffer for requests.
size_t requestHead = 0
 Write index of the circular buffer.
QueueHandle_t queueRespuestas
 Queue for received Modbus responses.
QueueHandle_t queueEventos_Peripheral
 Event queues to the EventManager (peripherals and scheduler).
QueueHandle_t queueEventos_Scheduler
QueueHandle_t queueFragmentos
 Queue for binary LoRa messages.
SemaphoreHandle_t semaforoEnvioCompleto
 Semaphore to synchronize the end of a sending cycle.
std::vector< SensorSchedulescheduleList
 Master scheduling list.
SemaphoreHandle_t schedulerMutex
 Mutex to protect concurrent access to scheduleList;.
std::vector< uint8_t > dispositivosAConsultar = {1, 2, 3}
 Predefined list of Modbus IDs to scan at startup.
QueueHandle_t queueSensorDataPayload
 Queue for processed sensor payloads.
const uint8_t SENSOR_ID_BATERIA = 0
 Assigned to Bit 0 of the Activate Byte.
const uint8_t SENSOR_ID_VOLTAJE = 1
 Assigned to Bit 1 of the Activate Byte.
const uint8_t SENSOR_ID_CORRIENTE = 2
 Assigned to Bit 2 of the Activate Byte.
const uint8_t SENSOR_ID_EXT_START = 3
 Start of IDs for external sensors (Bits 3-7).
const int MAX_SENSORES_EXTERNOS = 5
 Number of remaining available bits (3 to 7).
static u1_t NWKSKEY [16]
 ABP keys and device address (DEMO).
static u1_t APPSKEY [16]
static const u4_t DEVADDR = 0x260C691F
const lmic_pinmap lmic_pins
 Pin map for the SX127x radio of the TTGO LoRa32.
constexpr size_t LORA_PAYLOAD_MAX = 220

Detailed Description

Modbus RTU Master Firmware over LoRaWAN (ESP32/TTGO).

This system manages RS485 communication with multiple slaves, schedules periodic readings, formats the data, and transmits it via LoRaWAN.

Date
2025-12-02

Function Documentation

◆ DataPrinterTask()

void DataPrinterTask ( void * pvParameters)

Tarea temporal para imprimir los payloads de datos formateados.

Simula el consumidor final (que será la tarea LoRa) para propósitos de depuración.

Variable Documentation

◆ APPSKEY

u1_t APPSKEY[16]
static
Initial value:
= {
0x42, 0x8F, 0x67, 0xFA, 0xD7, 0xD7, 0x4A, 0x85,
0x3C, 0x10, 0x80, 0x5F, 0x10, 0x1A, 0x0E, 0x14
}