EnigmaIOT  0.9.8
Secure sensor and gateway platform based on ESP8266 and ESP32
EnigmaIOT-Led-Controller.cpp
Go to the documentation of this file.
1 
9 #if !defined ESP8266 && !defined ESP32
10 #error Node only supports ESP8266 or ESP32 platform
11 #endif
12 
13 #include <Arduino.h>
15 #include <FailSafe.h>
16 #include "LedController.h" // <-- Include here your controller class header
17 
18 #include <EnigmaIOTNode.h>
19 #include <espnow_hal.h>
20 #include <CayenneLPP.h>
21 #include <ArduinoJson.h>
22 
23 #ifdef ESP8266
24 #include <ESP8266WiFi.h>
25 #include <ESP8266HTTPClient.h>
26 #include <ESP8266httpUpdate.h>
27 #include <ESPAsyncTCP.h> // Comment to compile for ESP32
28 #include <Hash.h>
29 #elif defined ESP32
30 #include <WiFi.h>
31 #include <SPIFFS.h>
32 #include <AsyncTCP.h> // Comment to compile for ESP8266
33 #include <SPIFFS.h>
34 #include <Update.h>
35 #include <driver/adc.h>
36 #include "esp_wifi.h"
37 #endif
38 #include <ArduinoJson.h>
39 #include <Curve25519.h>
40 #include <ESPAsyncWebServer.h>
41 #include <ESPAsyncWiFiManager.h>
42 #include <DNSServer.h>
43 #include <FS.h>
44 
45 #define SLEEPY 0 // Set it to 1 if your node should sleep after sending data
46 
47 #ifndef LED_BUILTIN
48 #define LED_BUILTIN 2 // ESP32 boards normally have a LED in GPIO3 or GPIO5
49 #endif // !LED_BUILTIN
50 
51 // If you do need serial for your project you must disable serial debug by commenting next line
52 #define USE_SERIAL // Don't forget to set DEBUG_LEVEL to NONE if serial is disabled
53 
54 #define BLUE_LED LED_BUILTIN // You can set a different LED pin here. -1 means disabled
55 
56 EnigmaIOTjsonController* controller; // Generic controller is refferenced here. You do not need to modify it
57 
58 #define RESET_PIN 13 // You can set a different configuration reset pin here. Check for conflicts with used pins.
59 
60 const time_t BOOT_FLAG_TIMEOUT = 10000; // Time in ms to reset flag
61 const int MAX_CONSECUTIVE_BOOT = 3; // Number of rapid boot cycles before enabling fail safe mode
62 const int LED = LED_BUILTIN; // Number of rapid boot cycles before enabling fail safe mode
63 const int FAILSAFE_RTC_ADDRESS = 0; // If you use RTC memory adjust offset to not overwrite other data
64 #if SLEEPY
65 const int SLEEP_TIME = 10; // Sleep time time in secons.
66 #endif
67 
68 // Called when node is connected to gateway. You don't need to do anything here usually
71  DEBUG_WARN ("Connected");
72 }
73 
74 // Called when node is unregistered from gateway. You don't need to do anything here usually
76  DEBUG_WARN ("Disconnected. Reason %d", reason);
77 }
78 
79 // Called to route messages to EnitmaIOTNode class. Do not modify
80 bool sendUplinkData (const uint8_t* data, size_t len, nodePayloadEncoding_t payloadEncoding, dataMessageType_t dataMsgType) {
81  if (dataMsgType == DATA_TYPE) {
82  return EnigmaIOTNode.sendData (data, len, payloadEncoding);
83  } else if (dataMsgType == HA_DISC_TYPE) {
85  } else {
86  return false;
87  }
88 }
89 
90 // Called to route incoming messages to your code. Do not modify
91 void processRxData (const uint8_t* mac, const uint8_t* buffer, uint8_t length, nodeMessageType_t command, nodePayloadEncoding_t payloadEncoding) {
92  if (controller->processRxCommand (mac, buffer, length, command, payloadEncoding)) {
93  DEBUG_INFO ("Command processed");
94  } else {
95  DEBUG_WARN ("Command error");
96  }
97 }
98 
99 // Do not modify
100 void wifiManagerExit (boolean status) {
102 }
103 
104 // Do not modify
107 }
108 
109 void setup () {
110 
111 #ifdef USE_SERIAL
112  Serial.begin (921600);
113  //delay (1000);
114  Serial.println ();
115 #endif
116  FailSafe.checkBoot (MAX_CONSECUTIVE_BOOT, LED, FAILSAFE_RTC_ADDRESS); // Parameters are optional
117  if (FailSafe.isActive ()) { // Skip all user setup if fail safe mode is activated
118  return;
119  }
120 
121  controller = (EnigmaIOTjsonController*)new CONTROLLER_CLASS_NAME (); // Use your class name here
122 
123  //EnigmaIOTNode.setLed (BLUE_LED); // Set communication LED
124  EnigmaIOTNode.setResetPin (RESET_PIN); // Set reset pin
125  EnigmaIOTNode.onConnected (connectEventHandler); // Configure registration handler
126  EnigmaIOTNode.onDisconnected (disconnectEventHandler); // Configure unregistration handler
127  EnigmaIOTNode.onDataRx (processRxData); // Configure incoming data handler
128  EnigmaIOTNode.enableClockSync (true); // Set to true if you need this node to get its clock syncronized with gateway
129  // You should enable it if your node noes not send any periodic data
132 
133  if (!controller->loadConfig ()) { // Trigger custom configuration loading
134  DEBUG_WARN ("Error reading config file");
135  if (FILESYSTEM.format ())
136  DEBUG_WARN ("SPIFFS Formatted");
137  }
138 
139  EnigmaIOTNode.begin (&Espnow_hal, NULL, NULL, true, SLEEPY == 1); // Start EnigmaIOT communication
140 #if SLEEPY
142 #endif
143 
144  uint8_t macAddress[ENIGMAIOT_ADDR_LEN];
145  // Set Address using internal MAC Address. Do not modify
146 #ifdef ESP8266
147  if (wifi_get_macaddr (STATION_IF, macAddress))
148 #elif defined ESP32
149  if ((esp_wifi_get_mac (WIFI_IF_STA, macAddress) == ESP_OK))
150 #endif
151  {
152  EnigmaIOTNode.setNodeAddress (macAddress);
153  char macStr[ENIGMAIOT_ADDR_LEN * 3];
154  DEBUG_DBG ("Node address set to %s", mac2str (macAddress, macStr));
155  } else {
156  DEBUG_WARN ("Node address error");
157  }
158 
159  controller->sendDataCallback (sendUplinkData); // Listen for data from controller class
160  controller->setup (&EnigmaIOTNode); // Start controller class
161 
162 #if SLEEPY
163  EnigmaIOTNode.sleep ();
164 #endif
165 
166  DEBUG_DBG ("END setup");
167 }
168 
169 void loop () {
170  FailSafe.loop (BOOT_FLAG_TIMEOUT); // Use always this line
171 
172  if (FailSafe.isActive ()) { // Skip all user loop code if Fail Safe mode is active
173  return;
174  }
175 
176  controller->loop (); // Loop controller class
177 #if SUPPORT_HA_DISCOVERY
178  controller->callHAdiscoveryCalls (); // Send HA registration messages
179 #endif // SUPPORT_HA_DISCOVERY
180  EnigmaIOTNode.handle (); // Mantain EnigmaIOT connection
181 }
EnigmaIOTjsonController::loop
virtual void loop()=0
This should be called periodically for module handling.
EnigmaIOTjsonController::configManagerStart
virtual void configManagerStart()=0
Called when wifi manager starts config portal.
EnigmaIOTjsonController::configManagerExit
virtual void configManagerExit(bool status)=0
Called when wifi manager exits config portal.
connectEventHandler
void connectEventHandler()
Definition: EnigmaIOT-Led-Controller.cpp:69
EnigmaIOTNodeClass::enableClockSync
void enableClockSync(bool clockSync=true)
Controls clock synchronization function.
Definition: EnigmaIOTNode.h:584
ENIGMAIOT_ADDR_LEN
static const size_t ENIGMAIOT_ADDR_LEN
Address size. Mac address = 6 bytes.
Definition: EnigmaIoTconfigAdvanced.h:23
nodeMessageType
nodeMessageType
Message code definition.
Definition: EnigmaIOTNode.h:35
EnigmaIOTNodeClass::setResetPin
void setResetPin(int pin)
Sets a pin to be used to reset configuration it it is connected to ground during startup.
Definition: EnigmaIOTNode.cpp:94
LED_BUILTIN
#define LED_BUILTIN
Definition: EnigmaIOT-Led-Controller.cpp:48
EnigmaIOTjsonController::connectInform
virtual void connectInform()
Used to notify controller that it is registered on EnigmaIOT network.
Definition: EnigmaIOTjsonController.h:81
EnigmaIOTNodeClass::setSleepTime
void setSleepTime(uint32_t sleepTime, bool forceSleepForever=false)
Allows to configure a new sleep time period from user code.
Definition: EnigmaIOTNode.cpp:948
EnigmaIOTNodeClass::handle
void handle()
This method should be called periodically for instance inside loop() function. It is used for interna...
Definition: EnigmaIOTNode.cpp:1003
EnigmaIOTjsonController::sendDataCallback
void sendDataCallback(sendData_cb cb)
Register send data callback to run when module needs to send a message.
Definition: EnigmaIOTjsonController.h:74
BOOT_FLAG_TIMEOUT
const time_t BOOT_FLAG_TIMEOUT
Definition: EnigmaIOT-Led-Controller.cpp:60
CONTROLLER_CLASS_NAME
Definition: ButtonController.h:27
SLEEP_TIME
const int SLEEP_TIME
Definition: EnigmaIOT-Sensor-Controller.cpp:69
dataMessageType_t
dataMessageType_t
Definition: EnigmaIOTNode.h:68
MAX_CONSECUTIVE_BOOT
const int MAX_CONSECUTIVE_BOOT
Definition: EnigmaIOT-Led-Controller.cpp:61
EnigmaIOTjsonController::loadConfig
virtual bool loadConfig()=0
Loads output module configuration.
controller
EnigmaIOTjsonController * controller
Definition: EnigmaIOT-Led-Controller.cpp:56
DATA_TYPE
@ DATA_TYPE
Definition: EnigmaIOTNode.h:69
setup
void setup()
Definition: EnigmaIOT-Led-Controller.cpp:109
EnigmaIOTNode
EnigmaIOTNodeClass EnigmaIOTNode
Definition: EnigmaIOTNode.cpp:2719
EnigmaIOTNodeClass::sleep
void sleep()
Requests transition to sleep mode (low energy state)
Definition: EnigmaIOTNode.cpp:1564
EnigmaIOTNodeClass::onWiFiManagerExit
void onWiFiManagerExit(onWiFiManagerExit_t handle)
Register callback to be called on wifi manager exit.
Definition: EnigmaIOTNode.h:719
EnigmaIOTNodeClass::onDisconnected
void onDisconnected(onDisconnected_t handler)
Defines a function callback that will be called everytime node is disconnected from gateway.
Definition: EnigmaIOTNode.h:711
disconnectEventHandler
void disconnectEventHandler(nodeInvalidateReason_t reason)
Definition: EnigmaIOT-Led-Controller.cpp:75
nodePayloadEncoding_t
nodePayloadEncoding_t
Definition: EnigmaIOTNode.h:58
EnigmaIOTNodeClass::sendData
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.
Definition: EnigmaIOTNode.cpp:1535
EnigmaIOTNodeClass::onWiFiManagerStarted
void onWiFiManagerStarted(simpleEventHandler_t handle)
Register callback to be called on wifi manager start.
Definition: EnigmaIOTNode.h:727
loop
void loop()
Definition: EnigmaIOT-Led-Controller.cpp:169
EnigmaIOTjsonController::processRxCommand
virtual bool processRxCommand(const uint8_t *mac, const uint8_t *buffer, uint8_t length, nodeMessageType_t command, nodePayloadEncoding_t payloadEncoding)=0
Called to process a downlink command.
EnigmaIOTNode.h
Library to build a node for EnigmaIoT system.
EnigmaIOTNodeClass::sendHADiscoveryMessage
bool sendHADiscoveryMessage(const uint8_t *data, size_t len)
Builds, encrypts and sends a HomeAssistant discovery message.
Definition: EnigmaIOTNode.cpp:1764
EnigmaIOTNodeClass::onConnected
void onConnected(onConnected_t handler)
Defines a function callback that will be called everytime node is registered on gateway.
Definition: EnigmaIOTNode.h:682
EnigmaIOTjsonController::setup
virtual void setup(EnigmaIOTNodeClass *node, void *config=NULL)=0
Initialize data structures.
RESET_PIN
#define RESET_PIN
Definition: EnigmaIOT-Led-Controller.cpp:58
EnigmaIOTNodeClass::begin
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.
Definition: EnigmaIOTNode.cpp:696
FAILSAFE_RTC_ADDRESS
const int FAILSAFE_RTC_ADDRESS
Definition: EnigmaIOT-Led-Controller.cpp:63
LedController.h
data
@ data
Definition: GwOutput_generic.h:23
Espnow_hal
Espnow_halClass Espnow_hal
Singleton instance of ESP-NOW class.
Definition: espnow_hal.cpp:20
SLEEPY
#define SLEEPY
Definition: EnigmaIOT-Led-Controller.cpp:45
wifiManagerExit
void wifiManagerExit(boolean status)
Definition: EnigmaIOT-Led-Controller.cpp:100
mac2str
char * mac2str(const uint8_t *mac, char *extBuffer)
Debug helper function that generates a string that represent a MAC address.
Definition: helperFunctions.cpp:85
processRxData
void processRxData(const uint8_t *mac, const uint8_t *buffer, uint8_t length, nodeMessageType_t command, nodePayloadEncoding_t payloadEncoding)
Definition: EnigmaIOT-Led-Controller.cpp:91
EnigmaIOTNodeClass::setNodeAddress
bool setNodeAddress(uint8_t address[ENIGMAIOT_ADDR_LEN])
Set node address to be used in EnigmaIOT communication.
Definition: EnigmaIOTNode.cpp:943
nodeInvalidateReason_t
nodeInvalidateReason_t
Key invalidation reason definition.
Definition: EnigmaIOTNode.h:78
EnigmaIOTjsonController.h
Prototype for JSON/MSGPACK based controller node.
HA_DISC_TYPE
@ HA_DISC_TYPE
Definition: EnigmaIOTNode.h:71
wifiManagerStarted
void wifiManagerStarted()
Definition: EnigmaIOT-Led-Controller.cpp:105
LED
const int LED
Definition: EnigmaIOT-Led-Controller.cpp:62
espnow_hal.h
ESP-NOW communication system abstraction layer. To be used on ESP8266 or ESP32 platforms.
status
@ status
Definition: GwOutput_generic.h:25
sendUplinkData
bool sendUplinkData(const uint8_t *data, size_t len, nodePayloadEncoding_t payloadEncoding, dataMessageType_t dataMsgType)
Definition: EnigmaIOT-Led-Controller.cpp:80
EnigmaIOTNodeClass::onDataRx
void onDataRx(onNodeDataRx_t handler)
Defines a function callback that will be called on every downlink data message that is received from ...
Definition: EnigmaIOTNode.h:655
EnigmaIOTjsonController
Definition: EnigmaIOTjsonController.h:34