EnigmaIOT  0.9.8
Secure sensor and gateway platform based on ESP8266 and ESP32
enigmaiot_node_nonsleepy.cpp
Go to the documentation of this file.
1 
11 #if !defined ESP8266 && !defined ESP32
12 #error Node only supports ESP8266 or ESP32 platform
13 #endif
14 
15 #include <Arduino.h>
16 #include <EnigmaIOTNode.h>
17 #include <espnow_hal.h>
18 #include <CayenneLPP.h>
19 
20 #ifdef ESP8266
21 #include <ESP8266WiFi.h>
22 #include <ESP8266HTTPClient.h>
23 #include <ESP8266httpUpdate.h>
24 #include <ESPAsyncTCP.h> // Comment to compile for ESP32
25 #include <Hash.h>
26 #elif defined ESP32
27 #include <WiFi.h>
28 #include <AsyncTCP.h> // Comment to compile for ESP8266
29 #include <Update.h>
30 #include <driver/adc.h>
31 #include "esp_wifi.h"
32 #include "soc/soc.h" // Disable brownout problems
33 #include "soc/rtc_cntl_reg.h" // Disable brownout problems
34 #endif
35 #include <ArduinoJson.h>
36 #include <Curve25519.h>
37 #include <ESPAsyncWebServer.h>
38 #include <ESPAsyncWiFiManager.h>
39 #include <DNSServer.h>
40 #include <FS.h>
41 
42 #ifndef LED_BUILTIN
43 #ifdef ESP8266
44 #define LED_BUILTIN 2 // ESP8266 boards normally have a LED in GPIO2
45 #else
46 #define LED_BUILTIN 5 // ESP32 boards normally have a LED in GPIO2 or GPIO5
47 #endif
48 #endif // !LED_BUILTIN
49 
50 #define BLUE_LED LED_BUILTIN
51 constexpr auto RESET_PIN = -1;
52 
53 #ifdef ESP8266
54 ADC_MODE (ADC_VCC);
55 #endif
56 
58  Serial.println ("Connected");
59 }
60 
62  Serial.printf ("Unregistered. Reason: %d\n", reason);
63 }
64 
65 void processRxData (const uint8_t* mac, const uint8_t* buffer, uint8_t length, nodeMessageType_t command, nodePayloadEncoding_t payloadEncoding) {
66  char macstr[ENIGMAIOT_ADDR_LEN * 3];
67  String commandStr;
68  uint8_t tempBuffer[MAX_MESSAGE_LENGTH];
69  bool broadcast = false;
70  uint8_t _command = command;
71 
72  if (_command & 0x80)
73  broadcast = true;
74 
75  _command = (_command & 0x7F);
76 
77  mac2str (mac, macstr);
78  Serial.println ();
79  Serial.printf ("Data from %s --> %s\n", macstr, printHexBuffer (buffer, length));
81  commandStr = "GET";
82  else if (_command == nodeMessageType_t::DOWNSTREAM_DATA_SET)
83  commandStr = "SET";
84  else
85  return;
86 
87  Serial.printf ("%s Command %s\n", broadcast ? "Broadcast" : "Unicast", commandStr.c_str ());
88  Serial.printf ("Data: %s\n", printHexBuffer (buffer, length));
89  Serial.printf ("Encoding: 0x%02X\n", payloadEncoding);
90 
91  CayenneLPP lpp (MAX_DATA_PAYLOAD_SIZE);
92  DynamicJsonDocument doc (1000);
93  JsonArray root;
94  memcpy (tempBuffer, buffer, length);
95 
96  switch (payloadEncoding) {
97  case CAYENNELPP:
98  root = doc.createNestedArray ();
99  lpp.decode (tempBuffer, length, root);
100  serializeJsonPretty (doc, Serial);
101  break;
102  case MSG_PACK:
103  deserializeMsgPack (doc, tempBuffer, length);
104  serializeJsonPretty (doc, Serial);
105  Serial.println ();
106  break;
107  default:
108  DEBUG_WARN ("Payload encoding %d is not (yet) supported", payloadEncoding);
109  }
110 }
111 
112 void setup () {
113 
114  Serial.begin (115200); Serial.println (); Serial.println ();
115 
116 #ifdef ESP32
117  // Turn-off the 'brownout detector' to avoid random restarts during wake up,
118  // normally due to bad quality regulator on board
119  WRITE_PERI_REG (RTC_CNTL_BROWN_OUT_REG, 0);
120 #endif
121 
123  //pinMode (BLUE_LED, OUTPUT);
124  //digitalWrite (BLUE_LED, HIGH); // Turn on LED
131 
132  EnigmaIOTNode.begin (&Espnow_hal, NULL, NULL, true, false);
133 
134  uint8_t macAddress[ENIGMAIOT_ADDR_LEN];
135 #ifdef ESP8266
136  if (wifi_get_macaddr (STATION_IF, macAddress))
137 #elif defined ESP32
138  if ((esp_wifi_get_mac (WIFI_IF_STA, macAddress) == ESP_OK))
139 #endif
140  {
141  EnigmaIOTNode.setNodeAddress (macAddress);
142  DEBUG_WARN ("Node address set to %s", mac2str (macAddress));
143  } else {
144  DEBUG_WARN ("Node address error");
145  }
146 }
147 
148 void showTime () {
149  //const int time_freq = 10000;
150 
151 
152  if (EnigmaIOTNode.hasClockSync ()) {
153  //static time_t displayTime;
154  tm timeinfo;
155 
156  //displayTime = millis ();
157  //time_t local_time_ms = EnigmaIOTNode.clock ();
158  //local_time_ms /= 1000;
159  time_t local_time = EnigmaIOTNode.unixtime ();
160  localtime_r (&local_time, &timeinfo);
161  //Serial.printf ("Timestamp ms: %lld\n", local_time_ms);
162  //Serial.printf ("Timestamp sec: %ld\n", local_time);
163  Serial.printf ("%02d/%02d/%04d %02d:%02d:%02d\n",
164  timeinfo.tm_mday,
165  timeinfo.tm_mon + 1,
166  timeinfo.tm_year + 1900,
167  timeinfo.tm_hour,
168  timeinfo.tm_min,
169  timeinfo.tm_sec);
170  } else {
171  Serial.printf ("Time not sync'ed\n");
172  }
173 
174 }
175 
176 void loop () {
177 
179 
180  CayenneLPP msg (20);
181 
182  static time_t lastSensorData;
183  static const time_t SENSOR_PERIOD = 10000;
184  if (millis () - lastSensorData > SENSOR_PERIOD) {
185  lastSensorData = millis ();
186  showTime ();
187  // Read sensor data
188 #ifdef ESP8266
189  msg.addAnalogInput (0, (float)(ESP.getVcc ()) / 1000);
190  Serial.printf ("Vcc: %f\n", (float)(ESP.getVcc ()) / 1000);
191 #elif defined ESP32
192  msg.addAnalogInput (0, (float)(analogRead (ADC1_CHANNEL_0_GPIO_NUM) * 3.6 / 4096));
193  Serial.printf ("Vcc: %f V\n", (float)(analogRead (ADC1_CHANNEL_0_GPIO_NUM) * 3.6 / 4096));
194 #endif
195  msg.addTemperature (1, 20.34);
196  // Read sensor data
197 
198  Serial.printf ("Trying to send: %s\n", printHexBuffer (msg.getBuffer (), msg.getSize ()));
199 
200  if (!EnigmaIOTNode.sendData (msg.getBuffer (), msg.getSize ())) {
201  Serial.println ("---- Error sending data");
202  } else {
203  Serial.println ("---- Data sent");
204  }
205 
206  }
207 }
EnigmaIOTNodeClass::unixtime
time_t unixtime()
Gets current time in seconds from 1970, if time is synchronized.
Definition: EnigmaIOTNode.cpp:1460
EnigmaIOTNodeClass::hasClockSync
bool hasClockSync()
Checks if internal clock is synchronized to gateway.
Definition: EnigmaIOTNode.cpp:1464
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
MAX_MESSAGE_LENGTH
static const uint8_t MAX_MESSAGE_LENGTH
Maximum payload size on ESP-NOW.
Definition: EnigmaIoTconfigAdvanced.h:21
MAX_DATA_PAYLOAD_SIZE
static const int MAX_DATA_PAYLOAD_SIZE
Maximun payload size for data packets.
Definition: EnigmaIoTconfigAdvanced.h:48
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
EnigmaIOTNodeClass::handle
void handle()
This method should be called periodically for instance inside loop() function. It is used for interna...
Definition: EnigmaIOTNode.cpp:1003
DOWNSTREAM_DATA_GET
@ DOWNSTREAM_DATA_GET
Definition: EnigmaIOTGateway.h:44
printHexBuffer
char * printHexBuffer(const uint8_t *buffer, uint16_t len)
Debug helper function that generates a string that represent a buffer hexadecimal values.
Definition: helperFunctions.cpp:16
DOWNSTREAM_DATA_SET
@ DOWNSTREAM_DATA_SET
Definition: EnigmaIOTGateway.h:42
EnigmaIOTNode
EnigmaIOTNodeClass EnigmaIOTNode
Definition: EnigmaIOTNode.cpp:2719
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
connectEventHandler
void connectEventHandler()
Definition: enigmaiot_node_nonsleepy.cpp:57
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
setup
void setup()
Definition: enigmaiot_node_nonsleepy.cpp:112
processRxData
void processRxData(const uint8_t *mac, const uint8_t *buffer, uint8_t length, nodeMessageType_t command, nodePayloadEncoding_t payloadEncoding)
Definition: enigmaiot_node_nonsleepy.cpp:65
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
RESET_PIN
constexpr auto RESET_PIN
Definition: enigmaiot_node_nonsleepy.cpp:51
disconnectEventHandler
void disconnectEventHandler(nodeInvalidateReason_t reason)
Definition: enigmaiot_node_nonsleepy.cpp:61
EnigmaIOTNode.h
Library to build a node for EnigmaIoT system.
MSG_PACK
@ MSG_PACK
Definition: EnigmaIOTGateway.h:65
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
showTime
void showTime()
Definition: enigmaiot_node_nonsleepy.cpp:148
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
Espnow_hal
Espnow_halClass Espnow_hal
Singleton instance of ESP-NOW class.
Definition: espnow_hal.cpp:20
loop
void loop()
Definition: enigmaiot_node_nonsleepy.cpp:176
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
BLUE_LED
#define BLUE_LED
Definition: enigmaiot_node_nonsleepy.cpp:50
CAYENNELPP
@ CAYENNELPP
Definition: EnigmaIOTGateway.h:63
espnow_hal.h
ESP-NOW communication system abstraction layer. To be used on ESP8266 or ESP32 platforms.
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