EnigmaIOT  0.9.8
Secure sensor and gateway platform based on ESP8266 and ESP32
EnigmaIOT-SmartSwitch-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 "SmartSwitchController.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 4 // 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 
65 // Called when node is connected to gateway. You don't need to do anything here usually
68  DEBUG_WARN ("Connected");
69 }
70 
71 // Called when node is unregistered from gateway. You don't need to do anything here usually
73  DEBUG_WARN ("Disconnected. Reason %d", reason);
74 }
75 
76 // Called to route messages to EnitmaIOTNode class. Do not modify
77 bool sendUplinkData (const uint8_t* data, size_t len, nodePayloadEncoding_t payloadEncoding, dataMessageType_t dataMsgType) {
78  if (dataMsgType == DATA_TYPE) {
79  return EnigmaIOTNode.sendData (data, len, payloadEncoding);
80  } else if (dataMsgType == HA_DISC_TYPE) {
82  } else {
83  return false;
84  }
85 }
86 
87 // Called to route incoming messages to your code. Do not modify
88 void processRxData (const uint8_t* mac, const uint8_t* buffer, uint8_t length, nodeMessageType_t command, nodePayloadEncoding_t payloadEncoding) {
89  if (controller->processRxCommand (mac, buffer, length, command, payloadEncoding)) {
90  DEBUG_INFO ("Command processed");
91  } else {
92  DEBUG_WARN ("Command error");
93  }
94 }
95 
96 // Do not modify
97 void wifiManagerExit (boolean status) {
99 }
100 
101 // Do not modify
104 }
105 
106 void setup () {
107 
108 #ifdef USE_SERIAL
109  Serial.begin (921600);
110  //delay (1000);
111  Serial.println ();
112 #endif
113  FailSafe.checkBoot (MAX_CONSECUTIVE_BOOT, LED, FAILSAFE_RTC_ADDRESS); // Parameters are optional
114  if (FailSafe.isActive ()) { // Skip all user setup if fail safe mode is activated
115  return;
116  }
117 
118  controller = (EnigmaIOTjsonController*)new CONTROLLER_CLASS_NAME (); // Use your class name here
119 
120  EnigmaIOTNode.setLed (BLUE_LED); // Set communication LED
121  EnigmaIOTNode.setResetPin (RESET_PIN); // Set reset pin
122  EnigmaIOTNode.onConnected (connectEventHandler); // Configure registration handler
123  EnigmaIOTNode.onDisconnected (disconnectEventHandler); // Configure unregistration handler
124  EnigmaIOTNode.onDataRx (processRxData); // Configure incoming data handler
125  EnigmaIOTNode.enableClockSync (true); // Set to true if you need this node to get its clock syncronized with gateway
129 
130  if (!controller->loadConfig ()) { // Trigger custom configuration loading
131  DEBUG_WARN ("Error reading config file");
132  if (FILESYSTEM.format ())
133  DEBUG_WARN ("FILESYSTEM Formatted");
134  }
135 
136  EnigmaIOTNode.begin (&Espnow_hal, NULL, NULL, true, SLEEPY == 1); // Start EnigmaIOT communication
137 
138  uint8_t macAddress[ENIGMAIOT_ADDR_LEN];
139  // Set Address using internal MAC Address. Do not modify
140 #ifdef ESP8266
141  if (wifi_get_macaddr (STATION_IF, macAddress))
142 #elif defined ESP32
143  if ((esp_wifi_get_mac (WIFI_IF_STA, macAddress) == ESP_OK))
144 #endif
145  {
146  EnigmaIOTNode.setNodeAddress (macAddress);
147  DEBUG_DBG ("Node address set to %s", mac2str (macAddress));
148  } else {
149  DEBUG_WARN ("Node address error");
150  }
151 
152  controller->sendDataCallback (sendUplinkData); // Listen for data from controller class
153  controller->setup (&EnigmaIOTNode); // Start controller class
154 
155 #if SLEEPY == 1
156  EnigmaIOTNode.sleep ();
157 #endif
158 
159  DEBUG_DBG ("END setup");
160 }
161 
162 void loop () {
163  FailSafe.loop (BOOT_FLAG_TIMEOUT); // Use always this line
164 
165  if (FailSafe.isActive ()) { // Skip all user loop code if Fail Safe mode is active
166  return;
167  }
168 
169  controller->loop (); // Loop controller class
170 #if SUPPORT_HA_DISCOVERY
171  controller->callHAdiscoveryCalls (); // Send HA registration messages
172 #endif // SUPPORT_HA_DISCOVERY
173  EnigmaIOTNode.handle (); // Mantain EnigmaIOT connection
174 
175 #if SLEEPY
176  FailSafe.resetFlag ();
177 #endif
178 }
EnigmaIOTjsonController::loop
virtual void loop()=0
This should be called periodically for module handling.
BLUE_LED
#define BLUE_LED
Definition: EnigmaIOT-SmartSwitch-Controller.cpp:54
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.
LED
const int LED
Definition: EnigmaIOT-SmartSwitch-Controller.cpp:62
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
FAILSAFE_RTC_ADDRESS
const int FAILSAFE_RTC_ADDRESS
Definition: EnigmaIOT-SmartSwitch-Controller.cpp:63
nodeMessageType
nodeMessageType
Message code definition.
Definition: EnigmaIOTNode.h:35
SmartSwitchController.h
loop
void loop()
Definition: EnigmaIOT-SmartSwitch-Controller.cpp:162
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
MAX_CONSECUTIVE_BOOT
const int MAX_CONSECUTIVE_BOOT
Definition: EnigmaIOT-SmartSwitch-Controller.cpp:61
processRxData
void processRxData(const uint8_t *mac, const uint8_t *buffer, uint8_t length, nodeMessageType_t command, nodePayloadEncoding_t payloadEncoding)
Definition: EnigmaIOT-SmartSwitch-Controller.cpp:88
EnigmaIOTjsonController::connectInform
virtual void connectInform()
Used to notify controller that it is registered on EnigmaIOT network.
Definition: EnigmaIOTjsonController.h:81
LED_BUILTIN
#define LED_BUILTIN
Definition: EnigmaIOT-SmartSwitch-Controller.cpp:48
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
CONTROLLER_CLASS_NAME
Definition: ButtonController.h:27
dataMessageType_t
dataMessageType_t
Definition: EnigmaIOTNode.h:68
BOOT_FLAG_TIMEOUT
const time_t BOOT_FLAG_TIMEOUT
Definition: EnigmaIOT-SmartSwitch-Controller.cpp:60
EnigmaIOTjsonController::loadConfig
virtual bool loadConfig()=0
Loads output module configuration.
DATA_TYPE
@ DATA_TYPE
Definition: EnigmaIOTNode.h:69
EnigmaIOTNode
EnigmaIOTNodeClass EnigmaIOTNode
Definition: EnigmaIOTNode.cpp:2719
controller
EnigmaIOTjsonController * controller
Definition: EnigmaIOT-SmartSwitch-Controller.cpp:56
EnigmaIOTNodeClass::enableBroadcast
void enableBroadcast(bool broadcast=true)
Enables node broadcast mode. Node will request broadcast key to Gateway. When it is received node wil...
Definition: EnigmaIOTNode.h:566
wifiManagerExit
void wifiManagerExit(boolean status)
Definition: EnigmaIOT-SmartSwitch-Controller.cpp:97
EnigmaIOTNodeClass::sleep
void sleep()
Requests transition to sleep mode (low energy state)
Definition: EnigmaIOTNode.cpp:1564
wifiManagerStarted
void wifiManagerStarted()
Definition: EnigmaIOT-SmartSwitch-Controller.cpp:102
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
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
SLEEPY
#define SLEEPY
Definition: EnigmaIOT-SmartSwitch-Controller.cpp:45
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
setup
void setup()
Definition: EnigmaIOT-SmartSwitch-Controller.cpp:106
EnigmaIOTjsonController::setup
virtual void setup(EnigmaIOTNodeClass *node, void *config=NULL)=0
Initialize data structures.
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
EnigmaIOTNodeClass::setLed
void setLed(uint8_t led, time_t onTime=FLASH_LED_TIME)
Sets a LED to be flashed every time a message is transmitted.
Definition: EnigmaIOTNode.cpp:89
connectEventHandler
void connectEventHandler()
Definition: EnigmaIOT-SmartSwitch-Controller.cpp:66
data
@ data
Definition: GwOutput_generic.h:23
Espnow_hal
Espnow_halClass Espnow_hal
Singleton instance of ESP-NOW class.
Definition: espnow_hal.cpp:20
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
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
sendUplinkData
bool sendUplinkData(const uint8_t *data, size_t len, nodePayloadEncoding_t payloadEncoding, dataMessageType_t dataMsgType)
Definition: EnigmaIOT-SmartSwitch-Controller.cpp:77
disconnectEventHandler
void disconnectEventHandler(nodeInvalidateReason_t reason)
Definition: EnigmaIOT-SmartSwitch-Controller.cpp:72
EnigmaIOTjsonController.h
Prototype for JSON/MSGPACK based controller node.
HA_DISC_TYPE
@ HA_DISC_TYPE
Definition: EnigmaIOTNode.h:71
RESET_PIN
#define RESET_PIN
Definition: EnigmaIOT-SmartSwitch-Controller.cpp:58
espnow_hal.h
ESP-NOW communication system abstraction layer. To be used on ESP8266 or ESP32 platforms.
status
@ status
Definition: GwOutput_generic.h:25
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