LightHub 4.6.0
Open-source smart home controller firmware
Loading...
Searching...
No Matches
main.cpp File Reference
#include "main.h"
#include "statusled.h"
#include "flashstream.h"
#include "config.h"
#include <Dhcp.h>

Macros

#define ESP_EEPROM_SIZE   4096-10

Enumerations

enum  heaterMode { HEATER_HEAT , HEATER_OFF , HEATER_ERROR }

Functions

PubSubClient mqttClient (ethClient)
bool cleanConf (short locksAlowed)
 Frees the current config tree and its driver resources.
bool isNotRetainingStatus ()
 Checks whether the controller is not in the retain/collecting phase.
uint16_t httpHandler (Client &client, String request, uint8_t method, long contentLength, bool authorized, String &response)
int inTopic (char *topic, topicType tt)
void mqttCallback (char *topic, byte *payload, unsigned int length)
 MQTT receive callback: dispatches incoming messages to item command processing or config handling.
void printMACAddress ()
 Prints the current MAC address to the info log.
void setupOTA (void)
void setupSyslog ()
lan_status lanLoop ()
 One iteration of the LAN/MQTT state machine; advances the ethernet/WiFi/MQTT boot sequence and returns the new state.
void onMQTTConnect ()
 Called on (re)connect to the MQTT broker: sets up topics, subscribes and publishes retained states.
void setFirstBroker ()
 Selects the first configured MQTT broker for connection.
void setNextBroker ()
 Moves to the next configured MQTT broker (failover).
void ip_ready_config_loaded_connecting_to_broker ()
 State handler for IP_READY_CONFIG_LOADED_CONNECTING_TO_BROKER: connects to the configured MQTT broker(s).
void onInitialStateInitLAN ()
 Initial LAN setup: initializes ethernet/WiFi and starts the address acquisition sequence.
void printCurentLanConfig ()
 Prints the current LAN configuration to the serial port.
void resetHard ()
 Hard-resets the board (watchdog or MCU reset).
int cmdFunctionHelp (int arg_cnt, char **args)
 CLI command "help": lists available CLI commands.
int cmdFunctionKill (int arg_cnt, char **args)
 CLI command "kill": aborts the current long operation.
int cmdFunctionReboot (int arg_cnt, char **args)
int cmdFunctionSearch (int arg_cnt, char **args)
bool applyConfig ()
 Applies the loaded JSON config tree to the running system (items, inputs, topics, drivers).
void printConfigSummary ()
 Prints a summary of the current network/system config.
int cmdFunctionLoad (int arg_cnt, char **args)
 CLI command "load": loads the config from the portal or flash.
int loadConfigFromEEPROM ()
 Loads the last saved config from flash into the config tree.
int cmdFunctionSave (int arg_cnt, char **args)
 CLI command "save": persists the current config tree to flash.
int cmdFunctionLoglevel (int arg_cnt, char **args)
 CLI command "log": changes serial/UDP log levels.
int cmdFunctionIp (int arg_cnt, char **args)
int cmdFunctionOTAPwd (int arg_cnt, char **args)
int cmdFunctionGet (int arg_cnt, char **args)
 CLI command "get": re-downloads the config from the portal.
int cmdFunctionSetMac (int arg_cnt, char **args)
 CLI command "mac": changes the controller MAC address.
int cmdFunctionClearEEPROM (int arg_cnt, char **args)
int cmdFunctionPwd (int arg_cnt, char **args)
void printBool (bool arg)
 Prints a bool as "+" or "-" to the info log.
void headerHandlerProc (String header)
int loadConfigFromHttp ()
 Downloads the device JSON config from the config server (HTTP GET with If-None-Match ETag), parses and applies it.
void preTransmission ()
 Marks that an Ethernet transmission is about to happen; disables time-sensitive drivers as needed.
void postTransmission ()
 Marks that an Ethernet transmission has finished; re-enables drivers and handles lost-time compensation.
void TimerHandler (void)
int16_t attachMaturaTimer ()
 Attaches the Matura timer (interrupt-based timing helper).
void setup_main ()
 Application setup: init serial, flash config, MAC, LAN, HTTP/CLI listeners and all drivers (runs once at boot).
void printFirmwareVersionAndBuildOptions ()
 Prints firmware version, revision and build options at boot.
void publishStat ()
void setupMacAddress ()
 Resolves the controller MAC address (from flash or chip UID) and stores it in the system config.
void setupCmdArduino ()
 Registers the serial CLI commands (help, save, load, get, mac, ip, kill, reboot, log, ...) with the Cmd library.
void loop_main ()
 Application main loop: runs the LAN/MQTT state machine, CLI poller, item polling, thermostat, input, DMX and CAN iterations.
void owIdle (void)
 Idle hook invoked by the 1-Wire/DS2482 code between operations.
void ethernetIdle (void)
void modbusIdle (void)
 Idle hook invoked by the Modbus code between serial operations to let the main system breathe.
void inputLoop (short cause)
 Polls digital/analog inputs and processes their events.
void inputSensorsLoop ()
 Polls periodic sensors (DHT, ultrasonic, ...) connected to inputs.
void inputSetup (void)
 Sets up input channels from the loaded config.
void inputStop (void)
 Stops and releases all input channels.
void pollingLoop (void)
 Periodic item polling: refreshes states and publishes changes.
void thermoRelay (int pin, heaterMode on)
void thermoLoop (void)
 Thermostat control loop: checks temperature readings and drives heater relays (on/off/error bypass) with overheat alarms.

Variables

Streamlog debugSerial & debugSerialPort
flashStream sysConfStream
long timer0_overflow_count
EthernetClient ethClient
StatusLED statusLED (ledRED)
lan_status lanStatus = INITIAL_STATE
const char configserver[] PROGMEM = CONFIG_SERVER
uint8_t brokers = 0
char * deviceName = NULL
aJsonObject * topics = NULL
aJsonObject * root = NULL
aJsonObject * items = NULL
aJsonObject * inputs = NULL
aJsonObject * brokersArr = NULL
aJsonObject * mqttArr = NULL
aJsonObject * modbusObj = NULL
aJsonObject * owArr = NULL
aJsonObject * dmxArr = NULL
volatile uint32_t timerPollingCheck = 0
volatile uint32_t timerInputCheck = 0
volatile uint32_t timerLanCheckTime = 0
volatile uint32_t timerThermostatCheck = 0
volatile uint32_t timerSensorCheck =0
volatile unsigned long timerCount =0
volatile int16_t timerNumber =-1
volatile int8_t timerHandlerBusy =0
volatile uint32_t cryptoSalt =0
volatile uint32_t ultrasonicInputCheck =0
aJsonObject * pollingItem = NULL
volatile bool owReady = false
volatile bool configOk = false
volatile bool configLoaded = false
volatile bool initializedListeners = false
volatile uint8_t DHCP_failures = 0
volatile int8_t ethernetIdleCount =0
volatile int8_t configLocked = 0
ModbusMaster node
bool wifiInitialized
int8_t mqttErrorRate =0
const char * headerKeys [] ={"ETag"}
volatile int8_t inputLoopBusy = 0

Macro Definition Documentation

◆ ESP_EEPROM_SIZE

#define ESP_EEPROM_SIZE   4096-10

Enumeration Type Documentation

◆ heaterMode

enum heaterMode
Enumerator
HEATER_HEAT 
HEATER_OFF 
HEATER_ERROR 

Function Documentation

◆ applyConfig()

bool applyConfig ( )

Applies the loaded JSON config tree to the running system (items, inputs, topics, drivers).

Returns
true if the config was applied successfully.

◆ attachMaturaTimer()

int16_t attachMaturaTimer ( )

Attaches the Matura timer (interrupt-based timing helper).

Returns
Attached timer number, or negative on error.

◆ cleanConf()

bool cleanConf ( short locksAlowed = 0)

Frees the current config tree and its driver resources.

Parameters
locksAlowedNumber of config locks that may be active.
Returns
true if the config was successfully released.

◆ cmdFunctionClearEEPROM()

int cmdFunctionClearEEPROM ( int arg_cnt,
char ** args )

◆ cmdFunctionGet()

int cmdFunctionGet ( int arg_cnt,
char ** args )

CLI command "get": re-downloads the config from the portal.

Parameters
arg_cntNumber of arguments.
argsArgument strings.
Returns
Command result code.

◆ cmdFunctionHelp()

int cmdFunctionHelp ( int arg_cnt,
char ** args )

CLI command "help": lists available CLI commands.

Parameters
arg_cntNumber of arguments.
argsArgument strings.
Returns
Command result code.

◆ cmdFunctionIp()

int cmdFunctionIp ( int arg_cnt,
char ** args )

◆ cmdFunctionKill()

int cmdFunctionKill ( int arg_cnt,
char ** args )

CLI command "kill": aborts the current long operation.

Parameters
arg_cntNumber of arguments.
argsArgument strings.
Returns
Command result code.

◆ cmdFunctionLoad()

int cmdFunctionLoad ( int arg_cnt,
char ** args )

CLI command "load": loads the config from the portal or flash.

Parameters
arg_cntNumber of arguments.
argsArgument strings.
Returns
Command result code.

◆ cmdFunctionLoglevel()

int cmdFunctionLoglevel ( int arg_cnt,
char ** args )

CLI command "log": changes serial/UDP log levels.

Parameters
arg_cntNumber of arguments.
argsArgument strings (levels).
Returns
Command result code.

◆ cmdFunctionOTAPwd()

int cmdFunctionOTAPwd ( int arg_cnt,
char ** args )

◆ cmdFunctionPwd()

int cmdFunctionPwd ( int arg_cnt,
char ** args )

◆ cmdFunctionReboot()

int cmdFunctionReboot ( int arg_cnt,
char ** args )

◆ cmdFunctionSave()

int cmdFunctionSave ( int arg_cnt,
char ** args )

CLI command "save": persists the current config tree to flash.

Parameters
arg_cntNumber of arguments.
argsArgument strings.
Returns
Command result code.

◆ cmdFunctionSearch()

int cmdFunctionSearch ( int arg_cnt,
char ** args )

◆ cmdFunctionSetMac()

int cmdFunctionSetMac ( int arg_cnt,
char ** args )

CLI command "mac": changes the controller MAC address.

Parameters
arg_cntNumber of arguments.
argsArgument strings (new MAC).
Returns
Command result code.

◆ ethernetIdle()

void ethernetIdle ( void )

◆ headerHandlerProc()

void headerHandlerProc ( String header)

◆ httpHandler()

uint16_t httpHandler ( Client & client,
String request,
uint8_t method,
long contentLength,
bool authorized,
String & response )

◆ inputLoop()

void inputLoop ( short cause)

Polls digital/analog inputs and processes their events.

Parameters
causeWhy the loop is running (e.g. CHECK_INPUT).

◆ inputSensorsLoop()

void inputSensorsLoop ( )

Polls periodic sensors (DHT, ultrasonic, ...) connected to inputs.

◆ inputSetup()

void inputSetup ( void )

Sets up input channels from the loaded config.

◆ inputStop()

void inputStop ( void )

Stops and releases all input channels.

◆ inTopic()

int inTopic ( char * topic,
topicType tt )

◆ ip_ready_config_loaded_connecting_to_broker()

void ip_ready_config_loaded_connecting_to_broker ( )

State handler for IP_READY_CONFIG_LOADED_CONNECTING_TO_BROKER: connects to the configured MQTT broker(s).

◆ isNotRetainingStatus()

bool isNotRetainingStatus ( )

Checks whether the controller is not in the retain/collecting phase.

Returns
true if lanStatus is not RETAINING_COLLECTING.

◆ lanLoop()

lan_status lanLoop ( )

One iteration of the LAN/MQTT state machine; advances the ethernet/WiFi/MQTT boot sequence and returns the new state.

Returns
Next lan_status for the main loop.

◆ loadConfigFromEEPROM()

int loadConfigFromEEPROM ( )

Loads the last saved config from flash into the config tree.

Returns
0 on success, nonzero on error.

◆ loadConfigFromHttp()

int loadConfigFromHttp ( )

Downloads the device JSON config from the config server (HTTP GET with If-None-Match ETag), parses and applies it.

Returns
HTTP status code (200 on success, 304 if unchanged, negative on error).

◆ loop_main()

void loop_main ( )

Application main loop: runs the LAN/MQTT state machine, CLI poller, item polling, thermostat, input, DMX and CAN iterations.

◆ modbusIdle()

void modbusIdle ( void )

Idle hook invoked by the Modbus code between serial operations to let the main system breathe.

◆ mqttCallback()

void mqttCallback ( char * topic,
byte * payload,
unsigned int length )

MQTT receive callback: dispatches incoming messages to item command processing or config handling.

Parameters
topicMQTT topic of the received message.
payloadMessage payload (not necessarily null-terminated).
lengthPayload length in bytes.

◆ mqttClient()

PubSubClient mqttClient ( ethClient )

◆ onInitialStateInitLAN()

void onInitialStateInitLAN ( )

Initial LAN setup: initializes ethernet/WiFi and starts the address acquisition sequence.

◆ onMQTTConnect()

void onMQTTConnect ( )

Called on (re)connect to the MQTT broker: sets up topics, subscribes and publishes retained states.

strncat(buf,item->name,sizeof(buf)); strncat(buf,",",sizeof(buf));

◆ owIdle()

void owIdle ( void )

Idle hook invoked by the 1-Wire/DS2482 code between operations.

◆ pollingLoop()

void pollingLoop ( void )

Periodic item polling: refreshes states and publishes changes.

◆ postTransmission()

void postTransmission ( )

Marks that an Ethernet transmission has finished; re-enables drivers and handles lost-time compensation.

◆ preTransmission()

void preTransmission ( )

Marks that an Ethernet transmission is about to happen; disables time-sensitive drivers as needed.

◆ printBool()

void printBool ( bool arg)

Prints a bool as "+" or "-" to the info log.

Parameters
argValue to print.

◆ printConfigSummary()

void printConfigSummary ( )

Prints a summary of the current network/system config.

◆ printCurentLanConfig()

void printCurentLanConfig ( )

Prints the current LAN configuration to the serial port.

◆ printFirmwareVersionAndBuildOptions()

void printFirmwareVersionAndBuildOptions ( )

Prints firmware version, revision and build options at boot.

◆ printMACAddress()

void printMACAddress ( )

Prints the current MAC address to the info log.

◆ publishStat()

void publishStat ( )

◆ resetHard()

void resetHard ( )

Hard-resets the board (watchdog or MCU reset).

◆ setFirstBroker()

void setFirstBroker ( )

Selects the first configured MQTT broker for connection.

◆ setNextBroker()

void setNextBroker ( )

Moves to the next configured MQTT broker (failover).

◆ setup_main()

void setup_main ( )

Application setup: init serial, flash config, MAC, LAN, HTTP/CLI listeners and all drivers (runs once at boot).

◆ setupCmdArduino()

void setupCmdArduino ( )

Registers the serial CLI commands (help, save, load, get, mac, ip, kill, reboot, log, ...) with the Cmd library.

◆ setupMacAddress()

void setupMacAddress ( )

Resolves the controller MAC address (from flash or chip UID) and stores it in the system config.

◆ setupOTA()

void setupOTA ( void )

◆ setupSyslog()

void setupSyslog ( )

◆ thermoLoop()

void thermoLoop ( void )

Thermostat control loop: checks temperature readings and drives heater relays (on/off/error bypass) with overheat alarms.

◆ thermoRelay()

void thermoRelay ( int pin,
heaterMode on )

◆ TimerHandler()

void TimerHandler ( void )

Variable Documentation

◆ brokers

uint8_t brokers = 0

◆ brokersArr

aJsonObject* brokersArr = NULL

◆ configLoaded

volatile bool configLoaded = false

◆ configLocked

volatile int8_t configLocked = 0

◆ configOk

volatile bool configOk = false

◆ cryptoSalt

volatile uint32_t cryptoSalt =0

◆ debugSerialPort

Streamlog infoSerial& debugSerialPort

◆ deviceName

char* deviceName = NULL

◆ DHCP_failures

volatile uint8_t DHCP_failures = 0

◆ dmxArr

aJsonObject* dmxArr = NULL

◆ ethClient

EthernetClient ethClient

◆ ethernetIdleCount

volatile int8_t ethernetIdleCount =0

◆ headerKeys

const char* headerKeys[] ={"ETag"}

◆ initializedListeners

volatile bool initializedListeners = false

◆ inputLoopBusy

volatile int8_t inputLoopBusy = 0

◆ inputs

aJsonObject* inputs = NULL

◆ items

aJsonObject* items = NULL

◆ lanStatus

◆ modbusObj

aJsonObject* modbusObj = NULL

◆ mqttArr

aJsonObject* mqttArr = NULL

◆ mqttErrorRate

int8_t mqttErrorRate =0

◆ node

ModbusMaster node

◆ owArr

aJsonObject* owArr = NULL

◆ owReady

volatile bool owReady = false

◆ pollingItem

aJsonObject* pollingItem = NULL

◆ PROGMEM

const char verval_P [] PROGMEM = CONFIG_SERVER

◆ root

aJsonObject* root = NULL

◆ statusLED

StatusLED statusLED(ledRED) ( ledRED )

◆ sysConfStream

systemConfig sysConf & sysConfStream

◆ timer0_overflow_count

long timer0_overflow_count
extern

◆ timerCount

volatile unsigned long timerCount =0

◆ timerHandlerBusy

volatile int8_t timerHandlerBusy =0

◆ timerInputCheck

volatile uint32_t timerInputCheck = 0

◆ timerLanCheckTime

volatile uint32_t timerLanCheckTime = 0

◆ timerNumber

volatile int16_t timerNumber =-1

◆ timerPollingCheck

volatile uint32_t timerPollingCheck = 0

◆ timerSensorCheck

volatile uint32_t timerSensorCheck =0

◆ timerThermostatCheck

volatile uint32_t timerThermostatCheck = 0

◆ topics

aJsonObject* topics = NULL

◆ ultrasonicInputCheck

volatile uint32_t ultrasonicInputCheck =0

◆ wifiInitialized

bool wifiInitialized