EnigmaIOT  0.9.3
Secure sensor and gateway platform based on ESP8266 and ESP32
enigmaiot_node_nonsleepy.ino
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 <SPIFFS.h>
30 #include <Update.h>
31 #include <driver/adc.h>
32 #include "esp_wifi.h"
33 #include "soc/soc.h" // Disable brownout problems
34 #include "soc/rtc_cntl_reg.h" // Disable brownout problems
35 #endif
36 #include <ArduinoJson.h>
37 #include <Curve25519.h>
38 #include <ESPAsyncWebServer.h>
39 #include <ESPAsyncWiFiManager.h>
40 #include <DNSServer.h>
41 #include <FS.h>
42 
43 #ifndef LED_BUILTIN
44 #define LED_BUILTIN 2 // ESP32 boards normally have a LED in GPIO3 or GPIO5
45 #endif // !LED_BUILTIN
46 
47 #define BLUE_LED LED_BUILTIN
48 constexpr auto RESET_PIN = -1;
49 
50 #ifdef ESP8266
51 ADC_MODE (ADC_VCC);
52 #endif
53 
55  Serial.println ("Connected");
56 }
57 
59  Serial.printf ("Unregistered. Reason: %d\n", reason);
60 }
61 
62 void processRxData (const uint8_t* mac, const uint8_t* buffer, uint8_t length, nodeMessageType_t command, nodePayloadEncoding_t payloadEncoding) {
63  char macstr[ENIGMAIOT_ADDR_LEN * 3];
64  String commandStr;
65  uint8_t tempBuffer[MAX_MESSAGE_LENGTH];
66 
67  mac2str (mac, macstr);
68  Serial.println ();
69  Serial.printf ("Data from %s --> %s\n", macstr, printHexBuffer (buffer, length));
71  commandStr = "GET";
72  else if (command == nodeMessageType_t::DOWNSTREAM_DATA_SET)
73  commandStr = "SET";
74  else
75  return;
76 
77  Serial.printf ("Command %s\n", commandStr.c_str ());
78  Serial.printf ("Data: %s\n", printHexBuffer (buffer, length));
79  Serial.printf ("Encoding: 0x%02X\n", payloadEncoding);
80 
81  CayenneLPP lpp (MAX_DATA_PAYLOAD_SIZE);
82  DynamicJsonDocument doc (1000);
83  JsonArray root;
84  memcpy (tempBuffer, buffer, length);
85 
86  switch (payloadEncoding) {
87  case CAYENNELPP:
88  root = doc.createNestedArray ();
89  lpp.decode (tempBuffer, length, root);
90  serializeJsonPretty (doc, Serial);
91  break;
92  case MSG_PACK:
93  deserializeMsgPack (doc, tempBuffer, length);
94  serializeJsonPretty (doc, Serial);
95  break;
96  default:
97  DEBUG_WARN ("Payload encoding %d is not (yet) supported", payloadEncoding);
98  }
99 }
100 
101 void setup () {
102 
103  Serial.begin (115200); Serial.println (); Serial.println ();
104 
105 #ifdef ESP32
106  // Turn-off the 'brownout detector' to avoid random restarts during wake up,
107  // normally due to bad quality regulator on board
108  WRITE_PERI_REG (RTC_CNTL_BROWN_OUT_REG, 0);
109 #endif
110 
112  //pinMode (BLUE_LED, OUTPUT);
113  //digitalWrite (BLUE_LED, HIGH); // Turn on LED
119 
120  EnigmaIOTNode.begin (&Espnow_hal, NULL, NULL, true, false);
121 
122  uint8_t macAddress[ENIGMAIOT_ADDR_LEN];
123 #ifdef ESP8266
124  if (wifi_get_macaddr (STATION_IF, macAddress))
125 #elif defined ESP32
126  if ((esp_wifi_get_mac (WIFI_IF_STA, macAddress) == ESP_OK))
127 #endif
128  {
129  EnigmaIOTNode.setNodeAddress (macAddress);
130  char macStr[ENIGMAIOT_ADDR_LEN * 3];
131  DEBUG_DBG ("Node address set to %s", mac2str (macAddress, macStr));
132  } else {
133  DEBUG_WARN ("Node address error");
134  }
135 }
136 
137 void showTime () {
138  //const int time_freq = 10000;
139  const char* TZINFO = "CET-1CEST-2,M3.5.0/02:00:00,M10.5.0/03:00:00";
140 
141  tm timeinfo;
142  static time_t displayTime;
143 
144  if (EnigmaIOTNode.hasClockSync()) {
145  setenv ("TZ", TZINFO, 1);
146  displayTime = millis ();
147  time_t local_time_ms = EnigmaIOTNode.clock ();
148  //local_time_ms /= 1000;
149  time_t local_time = EnigmaIOTNode.unixtime ();
150  localtime_r (&local_time, &timeinfo);
151  //Serial.printf ("Timestamp ms: %lld\n", local_time_ms);
152  //Serial.printf ("Timestamp sec: %ld\n", local_time);
153  Serial.printf ("%02d/%02d/%04d %02d:%02d:%02d\n",
154  timeinfo.tm_mday,
155  timeinfo.tm_mon + 1,
156  timeinfo.tm_year + 1900,
157  timeinfo.tm_hour,
158  timeinfo.tm_min,
159  timeinfo.tm_sec);
160  } else {
161  Serial.printf ("Time not sync'ed\n");
162  }
163 
164 }
165 
166 void loop () {
167 
169 
170  CayenneLPP msg (20);
171 
172  static time_t lastSensorData;
173  static const time_t SENSOR_PERIOD = 10000;
174  if (millis () - lastSensorData > SENSOR_PERIOD) {
175  lastSensorData = millis ();
176  showTime ();
177  // Read sensor data
178 #ifdef ESP8266
179  msg.addAnalogInput (0, (float)(ESP.getVcc ()) / 1000);
180  Serial.printf ("Vcc: %f\n", (float)(ESP.getVcc ()) / 1000);
181 #elif defined ESP32
182  msg.addAnalogInput (0, (float)(analogRead (ADC1_CHANNEL_0_GPIO_NUM) * 3.6 / 4096));
183  Serial.printf ("Vcc: %f V\n", (float)(analogRead (ADC1_CHANNEL_0_GPIO_NUM) * 3.6 / 4096));
184 #endif
185  msg.addTemperature (1, 20.34);
186  // Read sensor data
187 
188  Serial.printf ("Trying to send: %s\n", printHexBuffer (msg.getBuffer (), msg.getSize ()));
189 
190  if (!EnigmaIOTNode.sendData (msg.getBuffer (), msg.getSize ())) {
191  Serial.println ("---- Error sending data");
192  } else {
193  Serial.println ("---- Data sent");
194  }
195 
196  }
197 }
EnigmaIOTNodeClass::unixtime
time_t unixtime()
Gets current time in seconds from 1970, if time is synchronized.
Definition: EnigmaIOTNode.cpp:1181
EnigmaIOTNodeClass::hasClockSync
bool hasClockSync()
Checks if internal clock is synchronized to gateway.
Definition: EnigmaIOTNode.cpp:1189
EnigmaIOTNodeClass::enableClockSync
void enableClockSync(bool clockSync=true)
Controls clock synchronization function.
Definition: EnigmaIOTNode.h:511
EnigmaIOTNodeClass::sendData
bool sendData(const uint8_t *data, size_t len, bool controlMessage, bool encrypt=true, nodePayloadEncoding_t payloadEncoding=CAYENNELPP)
Initiades data transmission distinguissing if it is payload or control data.
Definition: EnigmaIOTNode.cpp:1260
nodeMessageType
nodeMessageType
Message code definition.
Definition: EnigmaIOTNode.h:35
MAX_DATA_PAYLOAD_SIZE
static const int MAX_DATA_PAYLOAD_SIZE
Maximun payload size for data packets.
Definition: EnigmaIoTconfig.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:72
BLUE_LED
#define BLUE_LED
Definition: enigmaiot_node_nonsleepy.ino:47
processRxData
void processRxData(const uint8_t *mac, const uint8_t *buffer, uint8_t length, nodeMessageType_t command, nodePayloadEncoding_t payloadEncoding)
Definition: enigmaiot_node_nonsleepy.ino:62
connectEventHandler
void connectEventHandler()
Definition: enigmaiot_node_nonsleepy.ino:54
setup
void setup()
Definition: enigmaiot_node_nonsleepy.ino:101
showTime
void showTime()
Definition: enigmaiot_node_nonsleepy.ino:137
ENIGMAIOT_ADDR_LEN
static const size_t ENIGMAIOT_ADDR_LEN
Address size. Mac address = 6 bytes.
Definition: EnigmaIoTconfig.h:14
EnigmaIOTNodeClass::handle
void handle()
This method should be called periodically for instance inside loop() function. It is used for interna...
Definition: EnigmaIOTNode.cpp:801
DOWNSTREAM_DATA_GET
@ DOWNSTREAM_DATA_GET
Definition: EnigmaIOTGateway.h:38
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:17
DOWNSTREAM_DATA_SET
@ DOWNSTREAM_DATA_SET
Definition: EnigmaIOTGateway.h:37
EnigmaIOTNode
EnigmaIOTNodeClass EnigmaIOTNode
Definition: EnigmaIOTNode.cpp:2229
loop
void loop()
Definition: enigmaiot_node_nonsleepy.ino:166
mac2str
char * mac2str(const uint8_t *mac, char *buffer)
Debug helper function that generates a string that represent a MAC address.
Definition: helperFunctions.cpp:84
EnigmaIOTNodeClass::onDisconnected
void onDisconnected(onDisconnected_t handler)
Defines a function callback that will be called everytime node is disconnected from gateway.
Definition: EnigmaIOTNode.h:627
RESET_PIN
constexpr auto RESET_PIN
Definition: enigmaiot_node_nonsleepy.ino:48
nodePayloadEncoding_t
nodePayloadEncoding_t
Definition: EnigmaIOTNode.h:51
MAX_MESSAGE_LENGTH
static const uint8_t MAX_MESSAGE_LENGTH
Maximum payload size on ESP-NOW.
Definition: EnigmaIoTconfig.h:13
EnigmaIOTNode.h
Library to build a node for EnigmaIoT system.
MSG_PACK
@ MSG_PACK
Definition: EnigmaIOTGateway.h:54
EnigmaIOTNodeClass::onConnected
void onConnected(onConnected_t handler)
Defines a function callback that will be called everytime node is registered on gateway.
Definition: EnigmaIOTNode.h:598
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:510
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:67
Espnow_hal
Espnow_halClass Espnow_hal
Singleton instance of ESP-NOW class.
Definition: espnow_hal.cpp:20
EnigmaIOTNodeClass::setNodeAddress
bool setNodeAddress(uint8_t address[ENIGMAIOT_ADDR_LEN])
Set node address to be used in EnigmaIOT communication.
Definition: EnigmaIOTNode.cpp:741
nodeInvalidateReason_t
nodeInvalidateReason_t
Key invalidation reason definition.
Definition: EnigmaIOTNode.h:65
EnigmaIOTNodeClass::clock
int64_t clock()
Gets current clock counter. millis() + offset.
Definition: EnigmaIOTNode.cpp:1172
disconnectEventHandler
void disconnectEventHandler(nodeInvalidateReason_t reason)
Definition: enigmaiot_node_nonsleepy.ino:58
CAYENNELPP
@ CAYENNELPP
Definition: EnigmaIOTGateway.h:52
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:571