LightHub 4.6.0
Open-source smart home controller firmware
Loading...
Searching...
No Matches
main.h File Reference

Main controller interface of LightHub. More...

#include "options.h"
#include "streamlog.h"
#include "DallasTemperature.h"
#include <ModbusMaster.h>
#include "owTerm.h"
#include "dmx.h"
#include <Ethernet.h>
#include "Arduino.h"
#include "utils.h"
#include "textconst.h"
#include <PubSubClient.h>
#include <SPI.h>
#include <string.h>
#include "aJSON.h"
#include <Cmd.h>
#include "stdarg.h"
#include "item.h"
#include "inputs.h"

Go to the source code of this file.

Classes

union  UID
 Chip unique ID (20 bytes), viewable as 5 longs or 20 bytes. More...

Enumerations

enum  lan_status {
  INITIAL_STATE = 0 , AWAITING_ADDRESS = 1 , HAVE_IP_ADDRESS = 2 , LIBS_INITIALIZED = 3 ,
  IP_READY_CONFIG_LOADED_CONNECTING_TO_BROKER = 4 , RETAINING_COLLECTING = 5 , OPERATION = 6 , OPERATION_NO_MQTT = 7 ,
  DO_REINIT = -10 , REINIT = - 11 , DO_RECONNECT = 12 , RECONNECT = 13 ,
  READ_RE_CONFIG = 14 , DO_READ_RE_CONFIG = 15 , DO_NOTHING = -15 , DO_GET = -16 ,
  GET = -17 , GET_IN_PROGRESS = 18 , AWAITING_CONFIG = 19
}
 LAN/MQTT boot-up and runtime state machine states. More...

Functions

bool isNotRetainingStatus ()
 Checks whether the controller is not in the retain/collecting phase.
void mqttCallback (char *topic, byte *payload, unsigned int length)
 MQTT receive callback: dispatches incoming messages to item command processing or config handling.
lan_status lanLoop ()
 One iteration of the LAN/MQTT state machine; advances the ethernet/WiFi/MQTT boot sequence and returns the new state.
int loadConfigFromHttp ()
 Downloads the device JSON config from the config server (HTTP GET with If-None-Match ETag), parses and applies it.
void onInitialStateInitLAN ()
 Initial LAN setup: initializes ethernet/WiFi and starts the address acquisition sequence.
void onMQTTConnect ()
 Called on (re)connect to the MQTT broker: sets up topics, subscribes and publishes retained states.
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 setupMacAddress ()
 Resolves the controller MAC address (from flash or chip UID) and stores it in the system config.
void printMACAddress ()
 Prints the current MAC address to the info log.
void Changed (int i, DeviceAddress addr, float currentTemp)
 1-Wire temperature change callback.
void modbusIdle (void)
 Idle hook invoked by the Modbus code between serial operations to let the main system breathe.
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.
bool applyConfig ()
 Applies the loaded JSON config tree to the running system (items, inputs, topics, drivers).
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 cmdFunctionSetMac (int arg_cnt, char **args)
 CLI command "mac": changes the controller MAC address.
int cmdFunctionGet (int arg_cnt, char **args)
 CLI command "get": re-downloads the config from the portal.
int cmdFunctionLoglevel (int arg_cnt, char **args)
 CLI command "log": changes serial/UDP log levels.
void printBool (bool arg)
 Prints a bool as "+" or "-" to the info log.
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 setup_main ()
 Application setup: init serial, flash config, MAC, LAN, HTTP/CLI listeners and all drivers (runs once at boot).
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 inputLoop (short)
 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 thermoLoop (void)
 Thermostat control loop: checks temperature readings and drives heater relays (on/off/error bypass) with overheat alarms.
short thermoSetCurTemp (char *name, float t)
 Updates the current-temperature store of a thermostat by name.
void printConfigSummary ()
 Prints a summary of the current network/system config.
void setupCmdArduino ()
 Registers the serial CLI commands (help, save, load, get, mac, ip, kill, reboot, log, ...) with the Cmd library.
void printFirmwareVersionAndBuildOptions ()
 Prints firmware version, revision and build options at boot.
bool IsThermostat (const aJsonObject *item)
 Checks whether a config array entry is a thermostat item.
bool disabledDisconnected (const aJsonObject *thermoExtensionArray, int thermoLatestCommand)
 Checks whether a thermostat must be stopped (disabled or its temperature sensor disconnected for too long).
void resetHard ()
 Hard-resets the board (watchdog or MCU reset).
bool cleanConf (short locksAlowed=0)
 Frees the current config tree and its driver resources.
void printCurentLanConfig ()
 Prints the current LAN configuration to the serial port.
int16_t attachMaturaTimer ()
 Attaches the Matura timer (interrupt-based timing helper).
void setFirstBroker ()
 Selects the first configured MQTT broker for connection.
void setNextBroker ()
 Moves to the next configured MQTT broker (failover).

Variables

Streamlog debugSerial
Streamlog infoSerial
Streamlog errorSerial
lan_status lanStatus
 Current state of the LAN/MQTT state machine.

Detailed Description

Main controller interface of LightHub.

Declares the application entry points (setup_main/loop_main), the LAN/MQTT state machine (lan_status, lanLoop) and its initialization routines (onInitialStateInitLAN, onMQTTConnect, ip_ready_config_loaded_connecting_to_broker), remote config handling (loadConfigFromHttp, loadConfigFromEEPROM, applyConfig), the serial CLI command handlers (cmdFunction*) and the periodic polling loops (pollingLoop, thermoLoop, inputLoop) that drive items, thermostats and inputs.

Enumeration Type Documentation

◆ lan_status

enum lan_status

LAN/MQTT boot-up and runtime state machine states.

Positive values are boot/operation states; negative and high values are transient actions requested by loop_main (reinit, reconnect, config re-read, get).

Enumerator
INITIAL_STATE 
AWAITING_ADDRESS 
HAVE_IP_ADDRESS 
LIBS_INITIALIZED 
IP_READY_CONFIG_LOADED_CONNECTING_TO_BROKER 
RETAINING_COLLECTING 
OPERATION 
OPERATION_NO_MQTT 
DO_REINIT 
REINIT 
DO_RECONNECT 
RECONNECT 
READ_RE_CONFIG 
DO_READ_RE_CONFIG 
DO_NOTHING 
DO_GET 
GET 
GET_IN_PROGRESS 
AWAITING_CONFIG 

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.

◆ Changed()

void Changed ( int i,
DeviceAddress addr,
float currentTemp )

1-Wire temperature change callback.

Parameters
iSensor index.
addrDeviceAddress of the sensor.
currentTempNewly read temperature in Celsius.

◆ 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.

◆ 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.

◆ 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.

◆ 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.

◆ 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.

◆ disabledDisconnected()

bool disabledDisconnected ( const aJsonObject * thermoExtensionArray,
int thermoLatestCommand )

Checks whether a thermostat must be stopped (disabled or its temperature sensor disconnected for too long).

Parameters
thermoExtensionArrayThermostat extension array from config.
thermoLatestCommandLast received thermostat command.
Returns
true if the thermostat should be disabled.

◆ 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.

◆ 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.

◆ IsThermostat()

bool IsThermostat ( const aJsonObject * item)

Checks whether a config array entry is a thermostat item.

Parameters
itemaJsonObject config array to check.
Returns
true if the entry is a CH_THERMO item.

◆ 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.

◆ 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.

◆ 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.

◆ thermoLoop()

void thermoLoop ( void )

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

◆ thermoSetCurTemp()

short thermoSetCurTemp ( char * name,
float t )

Updates the current-temperature store of a thermostat by name.

Parameters
nameName of the thermostat item.
tNew temperature in Celsius.
Returns
0 on success, nonzero if the item was not found.

Variable Documentation

◆ debugSerial

Streamlog debugSerial
extern

◆ errorSerial

Streamlog errorSerial
extern

◆ infoSerial

Streamlog infoSerial
extern

◆ lanStatus

lan_status lanStatus
extern

Current state of the LAN/MQTT state machine.