|
EnigmaIOT
0.9.8
Secure sensor and gateway platform based on ESP8266 and ESP32
|
Go to the documentation of this file.
9 #ifndef _ENIGMAIOTNODE_h
10 #define _ENIGMAIOTNODE_h
13 #if defined(ARDUINO) && ARDUINO >= 100
26 #include <ESPAsyncWebServer.h>
27 #include <ESPAsyncWiFiManager.h>
30 #define LED_OFF !LED_ON
105 bool broadcastKeyValid ;
106 bool broadcastKeyRequested ;
115 #if defined ARDUINO_ARCH_ESP8266 || defined ARDUINO_ARCH_ESP32
116 #include <functional>
182 bool checkCRC (
const uint8_t* buf,
size_t count, uint32_t* crc);
324 bool processDownstreamData (
const uint8_t* mac,
const uint8_t* buf,
size_t count,
bool control =
false);
334 void manageMessage (
const uint8_t* mac,
const uint8_t* buf, uint8_t count);
349 static void rx_cb (uint8_t* mac_addr, uint8_t*
data, uint8_t len);
357 static void tx_cb (uint8_t* mac_addr, uint8_t
status);
567 #ifndef DISABLE_BRCAST
806 #endif // _ENIGMAIOTNODE_h
bool otaRunning
True if OTA update has started.
onWiFiManagerExit_t notifyWiFiManagerExit
Function called when configuration portal exits.
bool otaError
True if OTA update has failed. This normally produces a restart.
onNodeDataRx_t notifyData
Callback that will be called on every message reception.
time_t unixtime()
Gets current time in seconds from 1970, if time is synchronized.
void(* onDisconnected_t)(nodeInvalidateReason_t reason)
bool protectOTA
True if OTA update was launched. OTA flag is stored on RTC so this disables writting.
nodeMessageType nodeMessageType_t
bool hasClockSync()
Checks if internal clock is synchronized to gateway.
void enableClockSync(bool clockSync=true)
Controls clock synchronization function.
static const size_t ENIGMAIOT_ADDR_LEN
Address size. Mac address = 6 bytes.
Crypto library that implements EnigmaIoT encryption, decryption and key agreement fuctions.
EnigmaIoT sensor node management structures.
bool clientHello()
Build a ClientHello messange and send it to gateway.
nodeMessageType
Message code definition.
static const uint8_t MAX_MESSAGE_LENGTH
Maximum payload size on ESP-NOW.
bool searchForGateway(rtcmem_data_t *data, bool shouldStoreData=false)
Starts searching for a gateway that it using configured Network Name as WiFi AP. Stores this info for...
static const uint8_t NODE_NAME_LENGTH
Maximum number of characters of node name.
void setResetPin(int pin)
Sets a pin to be used to reset configuration it it is connected to ground during startup.
int8_t led
IO Pin that corresponds to Tx LED. Default value disables LED. It is initialized with setLed method.
bool checkCRC(const uint8_t *buf, size_t count, uint32_t *crc)
Check that a given CRC matches to calulated value from a buffer.
bool sendData(const uint8_t *data, size_t len, nodePayloadEncoding_t payloadEncoding=CAYENNELPP)
Starts a data message transmission.
bool broadcastIsEnabled()
Returns if node broadcast mode is enabled. In that case, node is able to send and receive encrypted b...
static void rx_cb(uint8_t *mac_addr, uint8_t *data, uint8_t len)
Function that will be called anytime this node receives a message.
bool processOTACommand(const uint8_t *mac, const uint8_t *data, uint8_t len)
Processes a single OTA update command or data.
bool dataMessage(const uint8_t *data, size_t len, dataMessageType_t dataMsgType=DATA_TYPE, bool encrypt=true, nodePayloadEncoding_t payloadEncoding=CAYENNELPP)
Builds, encrypts and sends a Data message.
void setSleepTime(uint32_t sleepTime, bool forceSleepForever=false)
Allows to configure a new sleep time period from user code.
bool processSetSleepTimeCommand(const uint8_t *mac, const uint8_t *buf, uint8_t len)
Processes a request to set new sleep time configuration.
bool processGetNameCommand(const uint8_t *mac, const uint8_t *data, uint8_t len)
Processes a request to get Node name and address.
void clearRTC()
Clears configuration stored in RTC memory to recover factory state.
void handle()
This method should be called periodically for instance inside loop() function. It is used for interna...
void sendRestart()
Sends a restart notification control message.
EnigmaIOTNodeClass EnigmaIOTNode
void checkResetButton()
Checks reset button status during startup.
static const uint8_t NETWORK_NAME_LENGTH
Maximum number of characters of network name.
int resetPin
Pin used to reset configuration if it is connected to ground during startup.
uint16_t lastDownlinkMsgCounter
simpleEventHandler_t notifyWiFiManagerStarted
Function called when configuration portal is started.
bool getOTArunning()
Checks if OTA is running.
bool requestReportRSSI
Flag to control RSSI reporting.
restartReason_t restartReason
Reason of restart (OTA, restart requested, configuration reset)
boolean indentifying
True if node has its led flashing to be identified.
bool processSetNameResponse(const uint8_t *mac, const uint8_t *data, uint8_t len)
Processes a response to set Node name.
enum node_status status_t
Node state.
bool flashBlue
If true Tx LED will be flashed.
uint32_t getSleepTime()
Returns sleep period in seconds.
bool sendUnencryptedData(const uint8_t *data, size_t len, nodePayloadEncoding_t payloadEncoding=CAYENNELPP)
Starts a data message transmission.
bool broadcastIsEnabled()
Returns if node broadcast mode is enabled. In that case, node is able to send and receive encrypted b...
Comms_halClass * comm
Comms abstraction layer.
@ DOWNSTREAM_BRCAST_CTRL_DATA
uint8_t dataMessageSent[MAX_MESSAGE_LENGTH]
Buffer where sent message is stored in case of retransmission is needed.
bool processSetIdentifyCommand(const uint8_t *mac, const uint8_t *buf, uint8_t len)
Processes a request to start indicate to identify a node visually.
clock_t timeSyncPeriod
Clock synchronization period.
bool clockRequest()
Build a ClockRequest messange and send it to gateway.
void enableBroadcast(bool broadcast=true)
Enables node broadcast mode. Node will request broadcast key to Gateway. When it is received node wil...
void sleep()
Requests transition to sleep mode (low energy state)
void(* simpleEventHandler_t)(void)
bool processSetResetConfigCommand(const uint8_t *mac, const uint8_t *buf, uint8_t len)
Processes a request to reset node configuration.
static void tx_cb(uint8_t *mac_addr, uint8_t status)
Function that will be called anytime this node sends a message to indicate status result of sending p...
bool processServerHello(const uint8_t *mac, const uint8_t *buf, size_t count)
Gets a buffer containing a ServerHello message and process it. It uses that message to calculate a sh...
static const unsigned int QUICK_SYNC_TIME
Period of clock synchronization request in case of resync is needed.
void onWiFiManagerExit(onWiFiManagerExit_t handle)
Register callback to be called on wifi manager exit.
uint16_t lastMessageCounter
void clearFlash()
Clears configuration stored in flash to recover factory state.
int16_t lastBroadcastMsgCounter
Counter for broadcast messages from gateway */.
@ DOWNSTREAM_BRCAST_DATA_GET
void restart(restartReason_t reason, bool reboot=true)
Sets connection as unregistered to force a resyncrhonisation after boot.
void onDisconnected(onDisconnected_t handler)
Defines a function callback that will be called everytime node is disconnected from gateway.
bool configWiFiManager(rtcmem_data_t *data)
Starts configuration AP and web server and gets settings from it.
void resetConfig()
Deletes configuration file stored on flash. It makes neccessary to configure it again using WiFi Port...
uint64_t sleepTime
Time in microseconds that this node will be slept between measurements.
void stopIdentifying()
Stops node identification.
bool dataMessageSendPending
True in case of message retransmission is needed.
onConnected_t notifyConnection
Callback that will be called anytime a new node is registered.
bool useCounter
true means that data message counter will be used to mark message order
bool sendData(const uint8_t *data, size_t len, dataMessageType_t dataMsgType, bool encrypt=true, nodePayloadEncoding_t payloadEncoding=CAYENNELPP)
Initiades data transmission distinguissing if it is payload or control data.
bool processControlCommand(const uint8_t *mac, const uint8_t *data, size_t len, bool broadcast)
Processes a control command. Does not propagate to user code.
void onWiFiManagerStarted(simpleEventHandler_t handle)
Register callback to be called on wifi manager start.
bool processSetNameCommand(const uint8_t *mac, const uint8_t *data, uint8_t len)
Processes a request to set Node name.
uint16_t lastControlCounter
bool isRegistered()
Checks if node is registered.
unsigned int ledOnTime
Time that LED is On during flash. Initalized on setLed
Node node
Node abstraction to store context.
bool sendNodeNameSet(const char *name)
Informs Gateway about custom node name.
void addWiFiManagerParameter(AsyncWiFiManagerParameter *p)
Adds a parameter to configuration portal.
bool processSetRestartCommand(const uint8_t *mac, const uint8_t *buf, uint8_t len)
Processes a request to restar node mcu.
nodeInvalidateReason_t invalidateReason
Last key invalidation reason.
rtcmem_data_t rtcmem_data
Context data to be stored on persistent storage.
bool loadRTCData()
Loads configuration from RTC data. Uses a CRC to check data integrity.
bool clockSyncEnabled
If true clock is synchronized with Gateway.
const uint8_t KEY_LENGTH
Key length used by selected crypto algorythm. The only tested value is 32. Change it only if you know...
bool processBroadcastKeyMessage(const uint8_t *mac, const uint8_t *buf, size_t count)
Gets a buffer containing a BroadcastKey message and process it. This key is used to send and receive ...
bool sleepRequested
true means that this node will sleep as soon a message is sent and downlink wait time has passed
bool processVersionCommand(const uint8_t *mac, const uint8_t *buf, uint8_t len)
Processes a request firmware version.
bool processDownstreamData(const uint8_t *mac, const uint8_t *buf, size_t count, bool control=false)
Processes downstream data from gateway.
AsyncWiFiManager * wifiManager
Wifi configuration portal.
bool processClockResponse(const uint8_t *mac, const uint8_t *buf, size_t count)
Gets a buffer containing a ClockResponse message and process it. It uses that message to calculate cl...
bool sendHADiscoveryMessage(const uint8_t *data, size_t len)
Builds, encrypts and sends a HomeAssistant discovery message.
bool broadcastKeyRequested
bool dataMessageEncrypt
Message encryption enabled. Stored for use in case of message retransmission is needed.
void onConnected(onConnected_t handler)
Defines a function callback that will be called everytime node is registered on gateway.
Class definition for a single sensor Node.
time_t lastOTAmsg
Time when last OTA update message has received. This is used to control timeout.
void begin(Comms_halClass *comm, uint8_t *gateway=NULL, uint8_t *networkKey=NULL, bool useCounter=true, bool sleepy=true)
Initalizes communication basic data and starts node registration.
void enableBroadcast(bool broadcast)
Enables node broadcast mode. Node will request broadcast key to Gateway. When it is received node wil...
onDisconnected_t notifyDisconnection
Callback that will be called anytime a node is disconnected.
bool isRegistered()
Gets registration state of this node.
time_t identifyStart
Time when identification started flashing. Used to control identification timeout.
nodeInvalidateReason_t processInvalidateKey(const uint8_t *mac, const uint8_t *buf, size_t count)
Gets a buffer containing an InvalidateKey message and process it. This trigger a new key agreement to...
void setLed(uint8_t led, time_t onTime=FLASH_LED_TIME)
Sets a LED to be flashed every time a message is transmitted.
bool saveRTCData()
Save configuration to RTC to store current status and recover it after deep sleep.
bool loadFlashData()
Loads configuration from flash memory.
bool unencryptedDataMessage(const uint8_t *data, size_t len, dataMessageType_t dataMsgType=DATA_TYPE, nodePayloadEncoding_t payloadEncoding=CAYENNELPP)
Builds and sends a Data message without encryption. Not recommended, use it only if you absolutely ne...
bool reportRSSI()
Sends RSSI value and channel to Gateway.
bool shouldRestart
Triggers a restart if true.
void getStatus(uint8_t *mac_addr, uint8_t status)
Functrion to debug send status.
Main node class. Manages communication with gateway and allows sending and receiving user data.
bool processGetSleepTimeCommand(const uint8_t *mac, const uint8_t *buf, uint8_t len)
Processes a request of sleep time configuration.
Auxiliary function definition.
void stop()
Stops EnigmaIoT protocol.
bool processGetRSSICommand(const uint8_t *mac, const uint8_t *data, uint8_t len)
Processes a request to measure RSSI.
bool setNodeAddress(uint8_t address[ENIGMAIOT_ADDR_LEN])
Set node address to be used in EnigmaIOT communication.
bool requestSearchGateway
Flag to control updating gateway address, RSSI and channel.
nodeInvalidateReason_t
Key invalidation reason definition.
bool saveFlashData(bool fsOpen=false)
Saves configuration to flash memory.
void(* onWiFiManagerExit_t)(bool status)
static const uint32_t FLASH_LED_TIME
Time that led keeps on during flash in ms.
int64_t clock()
Gets current clock counter. millis() + offset.
nodePayloadEncoding_t dataMessageSendEncoding
Encoding of the message pending to be sent.
void manageMessage(const uint8_t *mac, const uint8_t *buf, uint8_t count)
Process every received message.
void(* onNodeDataRx_t)(const uint8_t *mac, const uint8_t *buf, uint8_t len, nodeMessageType_t command, nodePayloadEncoding_t payloadEncoding)
time_t cycleStartedTime
Used to calculate exact sleep time by substracting awake time.
Generic communication system abstraction layer.
bool gatewaySearchStarted
Avoids start a new gateway scan if it already started.
bool configCleared
This flag disables asy configuration save after triggering a factory reset.
Context data to be stored con persistent storage to be used after wake from sleep mode.
void(* onWiFiManagerStarted_t)(void)
int8_t getRSSI()
Gets latest RSSI measurement. It is updated during start up or in case of transmission errors.
void startIdentifying(time_t period)
Starts node identification by flashing led.
Node * getNode()
Gets Node instance.
Interface for communication subsystem abstraction layer definition.
uint8_t dataMessageSentLength
Message length stored for use in case of message retransmission is needed.
@ DOWNSTREAM_BRCAST_DATA_SET
void onDataRx(onNodeDataRx_t handler)
Defines a function callback that will be called on every downlink data message that is received from ...