11 #include "libb64/cdecode.h"
12 #include <ArduinoJson.h>
35 DEBUG_INFO (
"Configuration saving activated");
46 pinMode (
txled, OUTPUT);
53 pinMode (
rxled, OUTPUT);
57 const void*
memstr (
const void* str,
size_t str_size,
58 const char* target,
size_t target_size) {
59 const uint8_t* pointer = (
const uint8_t*)str;
60 for (
size_t i = 0; i != str_size - target_size; ++i) {
61 if (!memcmp (pointer + i, target, target_size)) {
70 DEBUG_DBG (
"Build 'Get Version' message from: %s",
printHexBuffer (inputData, inputLen));
79 bool buildGetSleep (uint8_t*
data,
size_t& dataLen,
const uint8_t* inputData,
size_t inputLen) {
80 DEBUG_VERBOSE (
"Build 'Get Sleep' message from: %s",
printHexBuffer (inputData, inputLen));
90 DEBUG_VERBOSE (
"Build 'Set Identify' message from: %s",
printHexBuffer (inputData, inputLen));
99 bool buildGetRSSI (uint8_t*
data,
size_t& dataLen,
const uint8_t* inputData,
size_t inputLen) {
100 DEBUG_VERBOSE (
"Build 'Get RSSI' message from: %s",
printHexBuffer (inputData, inputLen));
109 bool buildGetName (uint8_t*
data,
size_t& dataLen,
const uint8_t* inputData,
size_t inputLen) {
110 DEBUG_VERBOSE (
"Build 'Get Node Name and Address' message from: %s",
printHexBuffer (inputData, inputLen));
119 bool buildSetName (uint8_t*
data,
size_t& dataLen,
const uint8_t* inputData,
size_t inputLen) {
120 DEBUG_VERBOSE (
"Build 'Set Node Name' message from: %s",
printHexBuffer (inputData, inputLen));
122 DEBUG_ERROR (
"Not enough space to build message");
126 DEBUG_ERROR (
"Name too short");
130 memcpy (
data + 1, inputData, inputLen);
131 dataLen = 1 + inputLen;
136 DEBUG_VERBOSE (
"Build 'Reset Config' message from: %s",
printHexBuffer (inputData, inputLen));
148 char* tempData =
data;
149 size_t tempLen = len;
151 for (
int i = 0; i < 10; i++) {
153 if (tempData[i] !=
',') {
154 if (tempData[i] >=
'0' && tempData[i] <=
'9') {
155 strNum[i] = tempData[i];
157 DEBUG_ERROR (
"OTA message format error. Message number not found");
161 DEBUG_ERROR (
"OTA message format error, separator not found");
166 DEBUG_ERROR (
"OTA message format error, cannot find a number");
176 if (tempData[0] ==
',' && tempLen > 0) {
180 DEBUG_WARN (
"OTA message format warning. separator not found");
182 number = atoi (strNum);
185 DEBUG_DBG (
"Extracted number %d", number);
186 DEBUG_DBG (
"Resulting data %s",
data);
194 (c >=
'0' && c <=
'9')
195 || (c >=
'a' && c <=
'f')
200 bool buildOtaMsg (uint8_t*
data,
size_t& dataLen,
const uint8_t* inputData,
size_t inputLen) {
204 uint8_t* tempData =
data;
206 DEBUG_VERBOSE (
"Build 'OTA' message from: %s", inputData);
208 payload = (
char*)inputData;
209 payloadLen = inputLen;
216 uint16_t msgIdx = number;
220 memcpy (tempData, &msgIdx,
sizeof (uint16_t));
221 size_t decodedLen =
sizeof (uint8_t) +
sizeof (uint16_t);
222 tempData +=
sizeof (uint16_t);
224 DEBUG_WARN (
"OTA message number %u", msgIdx);
229 decodedLen += base64_decode_chars (payload, payloadLen, (
char*)(
data + 1 +
sizeof (uint16_t)));
236 DEBUG_ERROR (
"OTA message format error. Message #0 too short to be a MD5 string");
245 uint32_t fileSize = number;
247 memcpy (tempData, &fileSize,
sizeof (uint32_t));
248 tempData +=
sizeof (uint32_t);
249 decodedLen +=
sizeof (uint32_t);
257 uint16_t msgNum = number;
259 memcpy (tempData, &msgNum,
sizeof (uint16_t));
260 tempData +=
sizeof (uint16_t);
261 decodedLen +=
sizeof (uint16_t);
263 DEBUG_WARN (
"Number of OTA chunks %u", msgNum);
264 DEBUG_WARN (
"OTA length = %u bytes", fileSize);
267 if (payloadLen < 32) {
268 DEBUG_ERROR (
"OTA message format error. MD5 is too short: %d", payloadLen);
272 for (
size_t i = 0; i < 32; i++) {
274 DEBUG_ERROR (
"OTA message format error. MD5 string has no valid format");
277 *tempData = (uint8_t)payload[i];
286 DEBUG_ERROR (
"OTA message too long. %u bytes.", decodedLen);
289 dataLen = decodedLen;
290 DEBUG_VERBOSE (
"Payload has %u bytes of data: %s", dataLen,
printHexBuffer (
data, dataLen));
294 bool buildSetSleep (uint8_t*
data,
size_t& dataLen,
const uint8_t* inputData,
size_t inputLen) {
295 DEBUG_VERBOSE (
"Build 'Set Sleep' message from: %s",
printHexBuffer (inputData, inputLen));
297 DEBUG_ERROR (
"Not enough space to build message");
302 DEBUG_ERROR (
"Set sleep time value is empty");
306 for (
unsigned int i = 0; i < (inputLen - 1); i++) {
307 if (inputData[i] < 30 || inputData[i] >
'9') {
308 DEBUG_ERROR (
"Set sleep time value is not a number on position %d: %d", i, inputData[i]);
312 if (inputData[inputLen - 1] != 0) {
313 DEBUG_ERROR (
"Set sleep time value does not end with \\0");
317 uint32_t sleepTime = atoi ((
char*)inputData);
320 memcpy (
data + 1, &sleepTime,
sizeof (uint32_t));
330 uint8_t* addr =
node->getMacAddress ();
331 DEBUG_DBG (
"Message to node %s with address " MACSTR, nodeName, MAC2STR (addr));
344 DEBUG_DBG (
"Downstream message type 0x%02X", controlData);
348 switch (controlData) {
351 DEBUG_ERROR (
"Error building get Version message");
354 DEBUG_VERBOSE (
"Get Version. Len: %d Data %s", dataLen,
printHexBuffer (downstreamData, dataLen));
358 DEBUG_ERROR (
"Error building get Sleep message");
361 DEBUG_VERBOSE (
"Get Sleep. Len: %d Data %s", dataLen,
printHexBuffer (downstreamData, dataLen));
365 DEBUG_ERROR (
"Error building set Sleep message");
368 DEBUG_VERBOSE (
"Set Sleep. Len: %d Data %s", dataLen,
printHexBuffer (downstreamData, dataLen));
372 DEBUG_ERROR (
"Error building OTA message");
375 DEBUG_VERBOSE (
"OTA message. Len: %d Data %s", dataLen,
printHexBuffer (downstreamData, dataLen));
379 DEBUG_ERROR (
"Error building Identify message");
382 DEBUG_VERBOSE (
"Identify message. Len: %d Data %s", dataLen,
printHexBuffer (downstreamData, dataLen));
386 DEBUG_ERROR (
"Error building Reset message");
389 DEBUG_VERBOSE (
"Reset Config message. Len: %d Data %s", dataLen,
printHexBuffer (downstreamData, dataLen));
393 DEBUG_ERROR (
"Error building get RSSI message");
396 DEBUG_VERBOSE (
"Get RSSI message. Len: %d Data %s", dataLen,
printHexBuffer (downstreamData, dataLen));
400 DEBUG_ERROR (
"Error building get name message");
403 DEBUG_VERBOSE (
"Get name message. Len: %d Data %s", dataLen,
printHexBuffer (downstreamData, dataLen));
407 DEBUG_ERROR (
"Error building set name message");
410 DEBUG_VERBOSE (
"Set name message. Len: %d Data %s", dataLen,
printHexBuffer (downstreamData, dataLen));
413 DEBUG_INFO (
"Data message GET");
416 DEBUG_INFO (
"Data message SET");
423 DEBUG_INFO (
"Send downstream");
429 if (
node->getSleepy ()) {
430 DEBUG_ERROR (
"Node must be in non sleepy mode to receive OTA messages");
438 DEBUG_ERROR (
"Downlink destination %s not found", nodeName ? nodeName :
mac2str (mac, addr));
444 server =
new AsyncWebServer (80);
445 dns =
new DNSServer ();
448 char networkKey[33] =
"";
456 AsyncWiFiManagerParameter netKeyParam (
"netkey",
"NetworkKey", networkKey, 33,
"required type=\"password\" minlength=\"8\" maxlength=\"32\"");
457 AsyncWiFiManagerParameter channelParam (
"channel",
"WiFi Channel", channel, 4,
"required type=\"number\" min=\"0\" max=\"13\" step=\"1\"");
459 wifiManager->setCustomHeadElement (
"<style>input:invalid {border: 2px dashed red;input:valid{border: 2px solid black;}</style>");
463 wifiManager->addParameter (
new AsyncWiFiManagerParameter (
"<br>"));
470 #if CONNECT_TO_WIFI_AP != 1
472 #endif // CONNECT_TO_WIFI_AP
473 wifiManager->setTryConnectDuringConfigPortal (
false);
477 #if CONNECT_TO_WIFI_AP == 1
478 boolean result =
wifiManager->autoConnect (
"EnigmaIoTGateway", NULL, 3, 2000);
480 boolean result =
wifiManager->startConfigPortal (
"EnigmaIoTGateway", NULL);
482 #endif // CONNECT_TO_WIFI_AP
484 DEBUG_INFO (
"==== Config Portal result ====");
485 DEBUG_INFO (
"Network Name: %s", netNameParam.getValue ());
486 DEBUG_INFO (
"Network Key: %s", netKeyParam.getValue ());
487 DEBUG_INFO (
"Channel: %s", channelParam.getValue ());
488 DEBUG_INFO (
"Status: %s", result ?
"true" :
"false");
489 DEBUG_INFO (
"Save config: %s",
shouldSave ?
"yes" :
"no");
494 std::regex networkNameRegex (
"^[^/\\\\]+$");
495 regexResult = std::regex_match (netNameParam.getValue (), networkNameRegex);
500 DEBUG_WARN (
"Network name parameter error");
504 std::regex netKeyRegex (
"^.{8,32}$");
505 regexResult = std::regex_match (netKeyParam.getValue (), netKeyRegex);
507 uint8_t keySize = netKeyParam.getValueLength ();
510 const char* netKey = netKeyParam.getValue ();
511 if (netKey && (netKey[0] !=
'\0')) {
518 DEBUG_INFO (
"Network key password field empty. Keeping the old one");
521 DEBUG_WARN (
"Network key parameter error");
525 std::regex channelRegex (
"^([0-9]|[0-1][0-3])$");
526 regexResult = std::regex_match (channelParam.getValue (), channelRegex);
531 DEBUG_WARN (
"Network name parameter error");
535 DEBUG_DBG (
"Configuration does not need to be saved");
538 DEBUG_ERROR (
"WiFi connection unsuccessful. Restarting");
555 bool json_correct =
false;
562 size_t size = configFile.size ();
563 DEBUG_DBG (
"%s opened. %u bytes",
CONFIG_FILE, size);
565 const size_t capacity = JSON_OBJECT_SIZE (3) + 150;
566 DynamicJsonDocument doc (capacity);
568 DeserializationError error = deserializeJson (doc, configFile);
570 DEBUG_ERROR (
"Failed to parse file");
572 DEBUG_DBG (
"JSON file parsed");
575 if (doc.containsKey (
"channel") && doc.containsKey (
"networkKey")
576 && doc.containsKey (
"networkName")) {
586 DEBUG_VERBOSE (
"Gateway configuration successfuly read");
588 DEBUG_DBG (
"==== EnigmaIOT Gateway Configuration ====");
596 #if DEBUG_LEVEL >= DBG
598 size_t json_len = measureJsonPretty (doc)+1;
599 output = (
char*)malloc (json_len);
600 serializeJsonPretty (doc, output, json_len);
602 DEBUG_DBG (
"JSON file %s", output);
618 WiFi.begin (
"0",
"0");
619 DEBUG_WARN (
"Dummy STA config loaded");
627 DEBUG_WARN (
"failed to open config file %s for writing",
CONFIG_FILE);
631 const size_t capacity = JSON_OBJECT_SIZE (3) + 150;
632 DynamicJsonDocument doc (capacity);
638 if (serializeJson (doc, configFile) == 0) {
639 DEBUG_ERROR (
"Failed to write to file");
645 #if DEBUG_LEVEL >= DBG
647 size_t json_len = measureJsonPretty (doc) + 1;
648 output = (
char*)malloc (json_len);
649 serializeJsonPretty (doc, output, json_len);
651 DEBUG_DBG (
"\n%s", output);
657 size_t size = configFile.size ();
663 DEBUG_DBG (
"Gateway configuration saved to flash. %u bytes", size);
677 if (!SPIFFS.begin ()) {
678 DEBUG_ERROR (
"Error mounting flash");
680 DEBUG_ERROR (
"Formatted");
687 DEBUG_DBG (
"Got configuration. Storing");
689 DEBUG_DBG (
"Network Key stored on flash");
691 DEBUG_ERROR (
"Error saving data on flash");
695 DEBUG_INFO (
"Configuration has not to be saved");
698 DEBUG_ERROR (
"Configuration error. Restarting");
702 DEBUG_INFO (
"Configuration loaded from flash");
716 memcpy (message.
data, msg, len);
720 portENTER_CRITICAL (&myMutex);
728 portEXIT_CRITICAL (&myMutex);
739 portENTER_CRITICAL (&myMutex);
745 DEBUG_DBG (
"EnigmaIOT message got from queue. Size: %d",
input_queue->
size ());
746 memcpy (buffer->
data, message->
data, message->
len);
748 buffer->
len = message->
len;
752 portEXIT_CRITICAL (&myMutex);
781 DEBUG_VERBOSE (
"SENDStatus %s. Peer %s",
status == 0 ?
"OK" :
"ERROR",
mac2str (mac_addr, buffer));
783 DEBUG_VERBOSE (
"SENDStatus %d. Peer %s",
status,
mac2str (mac_addr, buffer));
789 static unsigned long rxOntime;
790 static unsigned long txOntime;
793 DEBUG_DBG (
"EnigmaIOTGatewayClass::flashrx");
798 rxOntime = millis ();
811 txOntime = millis ();
831 time_t currentTime = millis ();
834 DEBUG_WARN (
"OTA ongoing = false");
835 DEBUG_WARN (
"millis() = %u, lastOTAmsg = %u, diff = %d", currentTime,
lastOTAmsg, currentTime -
lastOTAmsg);
847 DEBUG_DBG (
"EnigmaIOT input message from queue. MsgType: 0x%02X", message->
data[0]);
856 DEBUG_INFO (
"Reveived message. Origin MAC: %02X:%02X:%02X:%02X:%02X:%02X", mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]);
860 DEBUG_WARN (
"Empty message");
874 DEBUG_INFO (
" <------- CLIENT HELLO");
876 if (espNowError == 0) {
879 DEBUG_INFO (
"Server Hello sent");
881 node->setKeyValidFrom (millis ());
882 node->setLastMessageCounter (0);
883 node->setLastMessageTime ();
887 #if DEBUG_LEVEL >= INFO
892 DEBUG_INFO (
"Error sending Server Hello");
899 DEBUG_ERROR (
"Error processing client hello");
902 DEBUG_ERROR (
"Error adding peer %d", espNowError);
909 DEBUG_INFO (
" <------- CONTROL MESSAGE");
912 DEBUG_INFO (
"Control message OK");
920 DEBUG_WARN (
"Control message not OK");
930 DEBUG_INFO (
" <------- ENCRYPTED DATA");
933 DEBUG_INFO (
" <------- UNENCRYPTED DATA");
938 float packetsHour = (float)1 / ((millis () -
node->getLastMessageTime ()) / (float)3600000);
939 node->updatePacketsRate (packetsHour);
941 node->setLastMessageTime ();
942 DEBUG_INFO (
"Data OK");
943 DEBUG_VERBOSE (
"Key valid from %lu ms", millis () -
node->getKeyValidFrom ());
951 DEBUG_WARN (
"Data not OK");
962 DEBUG_INFO (
" <------- CLOCK REQUEST");
965 DEBUG_INFO (
"Clock request OK");
971 DEBUG_WARN (
"Clock request not OK");
979 DEBUG_INFO (
" <------- NODE NAME REQUEST");
982 DEBUG_INFO (
"Node name for node %d set to %s",
node->getNodeId (),
node->getNodeName ());
987 DEBUG_WARN (
"Error setting node name for node %d",
node->getNodeId ());
992 DEBUG_WARN (
"Received unknown EnigmaIOT message 0x%02X");
1002 struct __attribute__ ((packed, aligned (1))) {
1007 } nodeNameSetResponse_msg;
1009 const unsigned int NNSRMSG_LEN =
sizeof (nodeNameSetResponse_msg);
1013 DEBUG_DBG (
"Set node name Response. Error code: %d", error);
1019 nodeNameSetResponse_msg.errorCode = error;
1021 const uint8_t addDataLen = 1 +
IV_LENGTH;
1024 memcpy (aad, (uint8_t*)&nodeNameSetResponse_msg, addDataLen);
1032 aad, sizeof (aad), nodeNameSetResponse_msg.tag,
TAG_LENGTH)) {
1033 DEBUG_ERROR (
"Error during encryption");
1037 DEBUG_VERBOSE (
"Encrypted set node name response message: %s",
printHexBuffer ((uint8_t*)&nodeNameSetResponse_msg, NNSRMSG_LEN));
1039 DEBUG_INFO (
" -------> SEND SET NODE NAME RESPONSE");
1040 uint8_t* addr =
node->getMacAddress ();
1042 if (
comm->
send (addr, (uint8_t*)&nodeNameSetResponse_msg, NNSRMSG_LEN) == 0) {
1043 DEBUG_INFO (
"Set Node Name Response message sent to %s",
mac2str(addr,addrStr));
1047 DEBUG_ERROR (
"Error sending Set Node Name Response message to %s",
mac2str (addr, addrStr));
1064 uint8_t nodeId_idx = iv_idx +
IV_LENGTH;
1065 uint8_t nodeName_idx = nodeId_idx +
sizeof (int16_t);
1068 const uint8_t addDataLen = 1 +
IV_LENGTH;
1071 memcpy (aad, buf, addDataLen);
1080 aad, sizeof (aad), buf + tag_idx,
TAG_LENGTH)) {
1081 DEBUG_ERROR (
"Error during decryption");
1088 size_t nodeNameLen = tag_idx - nodeName_idx;
1090 DEBUG_DBG (
"Node name length: %d bytes\n", nodeNameLen);
1096 memcpy ((
void*)nodeName, (
void*)(buf + nodeName_idx), nodeNameLen);
1106 node->setNodeName (nodeName);
1107 DEBUG_INFO (
"Node name set to %s",
node->getNodeName ());
1120 uint8_t length_idx = iv_idx +
IV_LENGTH;
1121 uint8_t nodeId_idx = length_idx +
sizeof (int16_t);
1122 uint8_t counter_idx = nodeId_idx +
sizeof (int16_t);
1123 uint8_t data_idx = counter_idx +
sizeof (int16_t);
1126 const uint8_t addDataLen = 1 +
IV_LENGTH;
1129 memcpy (aad, buf, addDataLen);
1139 aad, sizeof (aad), buf + tag_idx,
TAG_LENGTH)) {
1140 DEBUG_ERROR (
"Error during decryption");
1147 const uint8_t* payload = buf + data_idx;
1150 DEBUG_DBG (
"Check if sleepy mode has changed for node");
1151 memcpy (&sleepTime, payload + 1,
sizeof (uint32_t));
1152 if (sleepTime > 0) {
1153 DEBUG_DBG (
"Set node to sleepy mode");
1154 node->setSleepy (
true);
1156 DEBUG_DBG (
"Set node to non sleepy mode");
1157 node->setSleepy (
false);
1161 DEBUG_DBG (
"Payload length: %d bytes\n", tag_idx - data_idx);
1163 char* nodeName =
node->getNodeName ();
1166 notifyData (
const_cast<uint8_t*
>(mac), buf + data_idx, tag_idx - data_idx, 0,
true,
ENIGMAIOT, nodeName ? nodeName : NULL);
1179 uint8_t nodeId_idx = 1;
1180 uint8_t counter_idx = nodeId_idx +
sizeof (int16_t);
1181 uint8_t payloadType_idx = counter_idx +
sizeof (int16_t);
1182 uint8_t data_idx = payloadType_idx +
sizeof (int8_t);
1185 size_t lostMessages = 0;
1187 uint8_t packetLen = count;
1189 DEBUG_VERBOSE (
"Unencrypted data message: %s",
printHexBuffer (buf, count));
1191 node->packetNumber++;
1193 memcpy (&counter, &buf[counter_idx],
sizeof (uint16_t));
1195 if (counter >
node->getLastMessageCounter ()) {
1196 lostMessages = counter -
node->getLastMessageCounter () - 1;
1197 node->packetErrors += lostMessages;
1198 node->setLastMessageCounter (counter);
1200 DEBUG_WARN (
"Data counter error %d : %d", counter,
node->getLastMessageCounter ());
1205 char* nodeName =
node->getNodeName ();
1208 notifyData (
const_cast<uint8_t*
>(mac), &(buf[data_idx]), count - data_idx, lostMessages,
false,
RAW, nodeName ? nodeName : NULL);
1211 if (
node->getSleepy ()) {
1212 if (
node->qMessagePending) {
1213 DEBUG_INFO (
" -------> DOWNLINK QUEUED DATA");
1215 node->qMessagePending =
false;
1237 uint8_t length_idx = iv_idx +
IV_LENGTH;
1238 uint8_t nodeId_idx = length_idx +
sizeof (int16_t);
1239 uint8_t counter_idx = nodeId_idx +
sizeof (int16_t);
1240 uint8_t encoding_idx = counter_idx +
sizeof (int16_t);
1241 uint8_t data_idx = encoding_idx +
sizeof (int8_t);
1245 size_t lostMessages = 0;
1247 const uint8_t addDataLen = 1 +
IV_LENGTH;
1250 memcpy (aad, buf, addDataLen);
1260 aad, sizeof (aad), buf + tag_idx,
TAG_LENGTH)) {
1261 DEBUG_ERROR (
"Error during decryption");
1265 DEBUG_DBG (
"Data payload encoding: 0x%02X", buf[encoding_idx]);
1266 node->packetNumber++;
1268 memcpy (&counter, &(buf[counter_idx]),
sizeof (uint16_t));
1270 if (counter >
node->getLastMessageCounter ()) {
1271 lostMessages = counter -
node->getLastMessageCounter () - 1;
1272 node->packetErrors += lostMessages;
1273 node->setLastMessageCounter (counter);
1279 char* nodeName =
node->getNodeName ();
1283 notifyData (
const_cast<uint8_t*
>(mac), &(buf[data_idx]), tag_idx - data_idx, lostMessages,
false, (
gatewayPayloadEncoding_t)(buf[encoding_idx]), nodeName ? nodeName : NULL);
1286 if (
node->getSleepy ()) {
1287 if (
node->qMessagePending) {
1288 DEBUG_INFO (
" -------> DOWNLINK QUEUED DATA");
1290 node->qMessagePending =
false;
1302 if (
node->packetNumber > 0) {
1303 node->per = (double)
node->packetErrors / (
double)
node->packetNumber;
1318 return node->packetErrors;
1324 return node->packetsHour;
1336 uint16_t packet_length;
1338 if (!
node->isRegistered ()) {
1339 DEBUG_VERBOSE (
"Error sending downstream. Node is not registered");
1343 uint16_t nodeId =
node->getNodeId ();
1346 uint8_t length_idx = iv_idx +
IV_LENGTH;
1347 uint8_t nodeId_idx = length_idx +
sizeof (int16_t);
1349 uint8_t encoding_idx;
1351 encoding_idx = nodeId_idx +
sizeof (int16_t);
1352 data_idx = encoding_idx +
sizeof (int8_t);
1353 buffer[encoding_idx] = encoding;
1354 packet_length = 1 +
IV_LENGTH +
sizeof (int16_t) +
sizeof (int16_t) + 1 + len;
1356 data_idx = nodeId_idx +
sizeof (int16_t);
1357 packet_length = 1 +
IV_LENGTH +
sizeof (int16_t) +
sizeof (int16_t) + len;
1359 uint8_t tag_idx = data_idx + len;
1362 DEBUG_ERROR (
"Downlink message buffer empty");
1366 DEBUG_ERROR (
"Downlink message too long: %d bytes", len);
1382 memcpy (buffer + nodeId_idx, &nodeId,
sizeof (uint16_t));
1395 memcpy (buffer + data_idx,
data, len);
1396 DEBUG_VERBOSE (
"Data: %s",
printHexBuffer (buffer + data_idx, len));
1398 memcpy (buffer + length_idx, &packet_length,
sizeof (uint16_t));
1400 DEBUG_VERBOSE (
"Downlink message: %s",
printHexBuffer (buffer, packet_length));
1401 DEBUG_VERBOSE (
"Message length: %d bytes", packet_length);
1407 const uint8_t addDataLen = 1 +
IV_LENGTH;
1410 memcpy (aad, buffer, addDataLen);
1418 aad, sizeof (aad), buffer + tag_idx,
TAG_LENGTH)) {
1419 DEBUG_ERROR (
"Error during encryption");
1425 if (
node->getSleepy ()) {
1427 DEBUG_VERBOSE (
"Node is sleepy. Queing message");
1428 memcpy (
node->queuedMessage, buffer, packet_length +
TAG_LENGTH);
1431 node->qMessagePending =
true;
1434 DEBUG_ERROR (
"OTA is only possible with non sleepy nodes. Configure it accordingly first");
1438 DEBUG_INFO (
" -------> DOWNLINK DATA");
1451 struct __attribute__ ((packed, aligned (1))) {
1454 } invalidateKey_msg;
1456 #define IKMSG_LEN sizeof(invalidateKey_msg)
1460 invalidateKey_msg.reason = reason;
1463 DEBUG_INFO (
" -------> INVALIDATE_KEY");
1465 uint8_t* mac =
node->getMacAddress ();
1480 struct __attribute__ ((packed, aligned (1))) {
1488 #define CHMSG_LEN sizeof(clientHello_msg)
1491 DEBUG_WARN (
"Message too short");
1495 memcpy (&clientHello_msg, buf, count);
1500 memcpy (aad, (uint8_t*)&clientHello_msg, addDataLen);
1508 aad, sizeof (aad), clientHello_msg.tag,
TAG_LENGTH)) {
1509 DEBUG_ERROR (
"Error during decryption");
1515 node->setEncryptionKey (clientHello_msg.publicKey);
1523 node->setKeyValid (
true);
1529 mac2str ((uint8_t*)mac, macstr);
1530 DEBUG_ERROR (
"DH2 error with %s", macstr);
1534 sleepyNode = (clientHello_msg.random & 0x00000001U) == 1;
1538 DEBUG_VERBOSE (
"This is a %s node",
sleepyNode ?
"sleepy" :
"always awaken");
1547 struct __attribute__ ((packed, aligned (1))) {
1554 #define CRMSG_LEN sizeof(clockRequest_msg)
1557 DEBUG_WARN (
"Message too short");
1565 memcpy (&clockRequest_msg, buf, count);
1567 const uint8_t addDataLen = 1 +
IV_LENGTH;
1570 memcpy (aad, buf, addDataLen);
1580 aad, sizeof (aad), clockRequest_msg.tag,
TAG_LENGTH)) {
1581 DEBUG_ERROR (
"Error during decryption");
1585 DEBUG_VERBOSE (
"Decripted Clock Request message: %s",
printHexBuffer ((uint8_t*)&clockRequest_msg, packetLen));
1587 node->t1 = clockRequest_msg.t1;
1590 gettimeofday (&tv, &tz);
1591 int64_t time_ms = tv.tv_sec;
1593 time_ms += tv.tv_usec / 1000;
1596 DEBUG_DBG (
"T1: %llu",
node->t1);
1597 DEBUG_DBG (
"T2: %llu",
node->t2);
1607 struct __attribute__ ((packed, aligned (1))) {
1613 } clockResponse_msg;
1615 const unsigned int CRSMSG_LEN =
sizeof (clockResponse_msg);
1619 memcpy (&(clockResponse_msg.t2), &(
node->t2), sizeof (int64_t));
1622 gettimeofday (&tv, &tz);
1623 int64_t time_ms = tv.tv_sec;
1625 time_ms += tv.tv_usec / 1000;
1628 memcpy (&(clockResponse_msg.t3), &(
node->t3), sizeof (int64_t));
1632 #ifdef DEBUG_ESP_PORT
1636 DEBUG_DBG (
"T1: %llu",
node->t1);
1637 DEBUG_DBG (
"T2: %llu",
node->t2);
1638 DEBUG_DBG (
"T3: %llu",
node->t3);
1640 const uint8_t addDataLen = 1 +
IV_LENGTH;
1643 memcpy (aad, (uint8_t*)&clockResponse_msg, addDataLen);
1651 aad, sizeof (aad), clockResponse_msg.tag,
TAG_LENGTH)) {
1652 DEBUG_ERROR (
"Error during encryption");
1658 DEBUG_INFO (
" -------> CLOCK RESPONSE");
1660 DEBUG_INFO (
"Clock Response message sent to %s", mac);
1664 DEBUG_ERROR (
"Error sending Clock Response message to %s", mac);
1676 struct __attribute__ ((packed, aligned (1))) {
1685 #define SHMSG_LEN sizeof(serverHello_msg)
1690 DEBUG_ERROR (
"NULL key");
1701 serverHello_msg.publicKey[i] = key[i];
1704 uint16_t nodeId =
node->getNodeId ();
1705 memcpy (&(serverHello_msg.nodeId), &nodeId, sizeof (uint16_t));
1715 memcpy (aad, (uint8_t*)&serverHello_msg, addDataLen);
1723 aad, sizeof (aad), serverHello_msg.tag,
TAG_LENGTH)) {
1724 DEBUG_ERROR (
"Error during encryption");
1732 #ifdef DEBUG_ESP_PORT
1736 DEBUG_INFO (
" -------> SERVER_HELLO");
1738 DEBUG_INFO (
"Server Hello message sent to %s", mac);
1742 DEBUG_ERROR (
"Error sending Server Hello message to %s", mac);