-
Notifications
You must be signed in to change notification settings - Fork 819
/
Copy pathmain.ino
3597 lines (3321 loc) · 115 KB
/
main.ino
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
OpenMQTTGateway - ESP8266 or Arduino program for home automation
Act as a gateway between your 433mhz, infrared IR, BLE, LoRa signal and one interface like an MQTT broker
Send and receiving command by MQTT
This program enables to:
- receive MQTT data from a topic and send signal (RF, IR, BLE, GSM) corresponding to the received MQTT data
- publish MQTT data to a different topic related to received signals (RF, IR, BLE, GSM)
Copyright: (c)Florian ROBERT
This file is part of OpenMQTTGateway.
OpenMQTTGateway is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
OpenMQTTGateway is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "User_config.h"
enum GatewayState {
WAITING_ONBOARDING,
ONBOARDING,
OFFLINE,
NTWK_CONNECTED,
BROKER_CONNECTED,
PROCESSING,
NTWK_DISCONNECTED,
BROKER_DISCONNECTED,
LOCAL_OTA_IN_PROGRESS,
REMOTE_OTA_IN_PROGRESS,
SLEEPING,
ERROR
};
GatewayState gatewayState = GatewayState::WAITING_ONBOARDING;
// Macros and structure to enable the duplicates removing on the following gateways
#if defined(ZgatewayRF) || defined(ZgatewayIR) || defined(ZgatewaySRFB) || defined(ZgatewayWeatherStation) || defined(ZgatewayRTL_433)
// array to store previous received RFs, IRs codes and their timestamps
struct ReceivedSignal {
uint64_t value;
uint32_t time;
};
ReceivedSignal receivedSignal[] = {{0, 0}, {0, 0}, {0, 0}, {0, 0}, {0, 0}, {0, 0}, {0, 0}, {0, 0}, {0, 0}, {0, 0}, {0, 0}, {0, 0}};
# define struct_size (sizeof(receivedSignal) / sizeof(ReceivedSignal))
#endif
//Time used to wait for an interval before measures
unsigned long timer_sys_measures = 0;
// Time used to wait before system checkings
unsigned long timer_sys_checks = 0;
// First Start of offline mode modules
bool firstStart = true;
#define ARDUINOJSON_USE_LONG_LONG 1
#define ARDUINOJSON_ENABLE_STD_STRING 1
#include <queue>
int queueLength = -1; // We want to give one cycle of the loop before starting modules that are big msgs producers (example BT), to avoid queue overloading
unsigned long queueLengthSum = 0;
unsigned long blockedMessages = 0;
unsigned long receivedMessages = 0;
int maxQueueLength = 0;
#ifndef QueueSize
# define QueueSize 18
#endif
/**
* Deep-sleep for the ESP8266 & ESP32 we need some form of indicator that we have posted the measurements and am ready to deep sleep.
* Set this to true in the sensor code after publishing the measurement.
*/
bool ready_to_sleep = false;
#include <ArduinoJson.h>
#include <ArduinoLog.h>
#include <PicoMQTT.h>
#include <memory>
#include "LEDManager.h"
#include "TheengsUtils.h"
LEDManager ledManager;
struct JsonBundle {
StaticJsonDocument<JSON_MSG_BUFFER> doc;
};
std::queue<std::string> jsonQueue;
#ifdef ESP32
# include <driver/adc.h>
// Mutex to protect the queue
SemaphoreHandle_t xQueueMutex;
// Mutex to protect mqtt publish
SemaphoreHandle_t xMqttMutex;
#endif
StaticJsonDocument<JSON_MSG_BUFFER> modulesBuffer;
JsonArray modules = modulesBuffer.to<JsonArray>();
bool ethConnected = false;
#ifndef ZgatewayGFSunInverter
// Arduino IDE compiles, it automatically creates all the header declarations for all the functions you have in your *.ino file.
// Unfortunately it ignores #if directives.
// This is a simple workaround for this problem.
struct GfSun2000Data {};
#endif
// Modules config inclusion
#if defined(ZwebUI) && defined(ESP32)
# include "config_WebUI.h"
#endif
#if defined(ZgatewayRF) || defined(ZgatewayRF2) || defined(ZgatewayPilight) || defined(ZactuatorSomfy) || defined(ZgatewayRTL_433)
# include "config_RF.h"
#endif
#ifdef ZgatewayWeatherStation
# include "config_WeatherStation.h"
#endif
#ifdef ZgatewayGFSunInverter
# include "config_GFSunInverter.h"
#endif
#ifdef ZgatewayLORA
# include "config_LORA.h"
#endif
#ifdef ZgatewaySRFB
# include "config_SRFB.h"
#endif
#ifdef ZgatewayBT
# include "config_BT.h"
#endif
#ifdef ZgatewayIR
# include "config_IR.h"
#endif
#ifdef Zgateway2G
# include "config_2G.h"
#endif
#ifdef ZactuatorONOFF
# include "config_ONOFF.h"
#endif
#ifdef ZsensorINA226
# include "config_INA226.h"
#endif
#ifdef ZsensorHCSR501
# include "config_HCSR501.h"
#endif
#ifdef ZsensorADC
# include "config_ADC.h"
#endif
#ifdef ZsensorBH1750
# include "config_BH1750.h"
#endif
#ifdef ZsensorMQ2
# include "config_MQ2.h"
#endif
#ifdef ZsensorTEMT6000
# include "config_TEMT6000.h"
#endif
#ifdef ZsensorTSL2561
# include "config_TSL2561.h"
#endif
#ifdef ZsensorBME280
# include "config_BME280.h"
#endif
#ifdef ZsensorHTU21
# include "config_HTU21.h"
#endif
#ifdef ZsensorLM75
# include "config_LM75.h"
#endif
#ifdef ZsensorAHTx0
# include "config_AHTx0.h"
#endif
#ifdef ZsensorRN8209
# include "config_RN8209.h"
#endif
#ifdef ZsensorHCSR04
# include "config_HCSR04.h"
#endif
#ifdef ZsensorC37_YL83_HMRD
# include "config_C37_YL83_HMRD.h"
#endif
#ifdef ZsensorDHT
# include "config_DHT.h"
#endif
#ifdef ZsensorSHTC3
# include "config_SHTC3.h"
#endif
#ifdef ZsensorDS1820
# include "config_DS1820.h"
#endif
#ifdef ZgatewayRFM69
# include "config_RFM69.h"
#endif
#ifdef ZsensorGPIOInput
# include "config_GPIOInput.h"
#endif
#ifdef ZsensorGPIOKeyCode
# include "config_GPIOKeyCode.h"
#endif
#ifdef ZsensorTouch
# include "config_Touch.h"
#endif
#ifdef ZmqttDiscovery
# include "config_mqttDiscovery.h"
#endif
#ifdef ZactuatorFASTLED
# include "config_FASTLED.h"
#endif
#ifdef ZactuatorPWM
# include "config_PWM.h"
#endif
#ifdef ZactuatorSomfy
# include "config_Somfy.h"
#endif
#if defined(ZboardM5STICKC) || defined(ZboardM5STICKCP) || defined(ZboardM5STACK) || defined(ZboardM5TOUGH)
# include "config_M5.h"
#endif
#if defined(ZdisplaySSD1306)
# include "config_SSD1306.h"
#endif
#if defined(ZgatewaySERIAL)
# include "config_SERIAL.h"
#endif
/*------------------------------------------------------------------------*/
void setupTLS(int index = CNT_DEFAULT_INDEX);
char ota_pass[parameters_size] = gw_password;
#ifdef USE_MAC_AS_GATEWAY_NAME
# undef WifiManager_ssid
# undef ota_hostname
# define MAC_NAME_MAX_LEN 30
char WifiManager_ssid[MAC_NAME_MAX_LEN];
char ota_hostname[MAC_NAME_MAX_LEN];
#endif
int failure_number_ntwk = 0; // number of failure connecting to network
int failure_number_mqtt = 0; // number of failure connecting to MQTT
static unsigned long last_ota_activity_millis = 0;
// Global struct to store live SYS configuration data
SYSConfig_s SYSConfig;
bool failSafeMode = false;
bool ProcessLock = true; // Process lock when we want to use a critical function like OTA for example
static bool mqttSetupPending = true;
static int cnt_index = CNT_DEFAULT_INDEX;
#ifdef ESP32
# include <ArduinoOTA.h>
# include <FS.h>
# include <SPIFFS.h>
# include <esp_task_wdt.h>
# include <nvs.h>
# include <nvs_flash.h>
bool BTProcessLock = true; // Process lock when we want to use a critical function like OTA for example, at start to true so as to wait for critical functions to be performed before BLE start
# if !defined(NO_INT_TEMP_READING)
// ESP32 internal temperature reading
# include <stdio.h>
# include "rom/ets_sys.h"
# include "soc/rtc_cntl_reg.h"
# include "soc/sens_reg.h"
# endif
# ifdef ESP32_ETHERNET
# include <ETH.h>
void WiFiEvent(WiFiEvent_t event);
# endif
# include <WiFiClientSecure.h>
# include <WiFiMulti.h>
WiFiMulti wifiMulti;
# include <WiFiManager.h>
# ifdef MDNS_SD
# include <ESPmDNS.h>
# endif
#elif defined(ESP8266)
# include <ArduinoOTA.h>
# include <DNSServer.h>
# include <ESP8266WebServer.h>
# include <ESP8266WiFi.h>
# include <ESP8266WiFiMulti.h>
# include <FS.h>
# include <WiFiManager.h>
X509List caCert;
# if MQTT_SECURE_SIGNED_CLIENT
X509List* pClCert = nullptr;
PrivateKey* pClKey = nullptr;
# endif
ESP8266WiFiMulti wifiMulti;
# ifdef MDNS_SD
# include <ESP8266mDNS.h>
# endif
#else
# include <Ethernet.h>
#endif
void handle_autodiscovery() {
#ifdef ZmqttDiscovery
static bool connectedOnce = false;
const unsigned long now = millis();
// at first connection we publish the discovery payloads
// or, when we have just re-connected (only when discovery_republish_on_reconnect is enabled)
const bool publishDiscovery = SYSConfig.discovery && (!connectedOnce || discovery_republish_on_reconnect);
if (publishDiscovery) {
pubMqttDiscovery();
# ifdef ZgatewayLORA
launchLORADiscovery(true);
# endif
# ifdef ZgatewayBT
launchBTDiscovery(true);
# endif
# ifdef ZgatewayRTL_433
launchRTL_433Discovery(true);
# endif
}
connectedOnce = true;
#endif
}
#if MQTT_BROKER_MODE
class MQTTServer : public PicoMQTT::Server {
public:
size_t get_client_count() const {
return clients.size();
}
bool connected() const {
return !clients.empty();
}
protected:
virtual void on_subscribe(const char* client_id, const char* topic) override {
// Whenever a client subscribes successfully to some topic, see if this is likely a subscription to a
// autodiscovery topic. If it is, fire handle_autodiscovery().
const String pattern(topic);
const bool is_autodiscovery_subscription = (pattern == "#") || (pattern.startsWith(String(discovery_prefix) + "/"));
if (is_autodiscovery_subscription)
handle_autodiscovery();
}
};
std::unique_ptr<MQTTServer> mqtt;
#else
std::unique_ptr< ::Client> eClient;
std::unique_ptr<PicoMQTT::Client> mqtt;
#endif
template <typename T> // Declared here to avoid pre-compilation issue (missing "template" in auto declaration by pio)
void Config_update(JsonObject& data, const char* key, T& var);
template <typename T>
void Config_update(JsonObject& data, const char* key, T& var) {
if (data.containsKey(key)) {
if (var != data[key].as<T>()) {
var = data[key].as<T>();
Log.notice(F("Config %s changed to: %T" CR), key, data[key].as<T>());
} else {
Log.notice(F("Config %s unchanged, currently: %T" CR), key, data[key].as<T>());
}
}
}
/*
* Dispatch json messages towards the communication layer
*
*/
bool jsonDispatch(JsonObject& data) {
bool res = false;
if (data.containsKey("origin") || data.containsKey("topic")) {
GatewayState previousGatewayState = gatewayState;
gatewayState = GatewayState::PROCESSING;
#if message_UTCtimestamp == true
data["UTCtime"] = TheengsUtils::UTCtimestamp();
#endif
#if message_unixtimestamp == true
data["unixtime"] = TheengsUtils::unixtimestamp();
#endif
if (data.containsKey("origin")) {
pubWebUI((char*)data["origin"].as<const char*>(), data);
}
if (SYSConfig.mqtt && !SYSConfig.offline) {
res = pub(data);
}
#ifdef ZgatewaySERIAL
if (SYSConfig.serial) {
char jsonStr[JSON_MSG_BUFFER_MAX];
serializeJson(data, jsonStr);
receivingDATA("", jsonStr);
res = true; // Return the state from receivingDATA
}
#endif
gatewayState = previousGatewayState; // restore the previous state
} else {
Log.error(F("No origin or topic in JSON filtered" CR));
gatewayState = GatewayState::ERROR;
}
return res;
}
// Add a document to the queue
boolean enqueueJsonObject(const StaticJsonDocument<JSON_MSG_BUFFER>& jsonDoc, int timeout) {
receivedMessages++;
if (jsonDoc.size() == 0) {
Log.error(F("Empty JSON, skipping" CR));
gatewayState = GatewayState::ERROR;
return true;
}
if (queueLength >= QueueSize) {
Log.warning(F("%d Doc(s) in queue, doc blocked" CR), queueLength);
blockedMessages++;
return false;
}
Log.trace(F("Enqueue JSON" CR));
std::string jsonString;
serializeJson(jsonDoc, jsonString);
#ifdef ESP32
// Semaphore check before enqueueing a document
if (xSemaphoreTake(xQueueMutex, pdMS_TO_TICKS(timeout)) == pdFALSE) {
Log.error(F("xQueueMutex not taken" CR));
gatewayState = GatewayState::ERROR;
blockedMessages++;
return false;
}
#endif
jsonQueue.push(jsonString);
#ifdef ESP32
xSemaphoreGive(xQueueMutex);
#endif
Log.trace(F("Queue length: %d" CR), jsonQueue.size());
return true;
}
// Semaphore check before enqueueing a document with default timeout QueueSemaphoreTimeOutLoop
bool enqueueJsonObject(const StaticJsonDocument<JSON_MSG_BUFFER>& jsonDoc) {
return enqueueJsonObject(jsonDoc, QueueSemaphoreTimeOutLoop);
}
#ifdef ESP32
# include "mbedtls/sha256.h"
std::string generateHash(const std::string& input) {
unsigned char hash[32];
mbedtls_sha256((unsigned char*)input.c_str(), input.length(), hash, 0);
char hashString[65]; // Room for null terminator
for (int i = 0; i < 32; ++i) {
sprintf(&hashString[i * 2], "%02x", hash[i]);
}
return std::string(hashString);
}
#else
std::string generateHash(const std::string& input) {
return "Not implemented for ESP8266";
}
#endif
/*
* Add the jsonObject id as a topic to the jsonObject origin
*
*/
void buildTopicFromId(JsonObject& Jsondata, const char* origin) {
if (!Jsondata.containsKey("id")) {
Log.error(F("No id in Jsondata" CR));
gatewayState = GatewayState::ERROR;
return;
}
std::string topic = Jsondata["id"].as<std::string>();
// Replace ":" in topic
size_t pos = topic.find(":");
while (pos != std::string::npos) {
topic.erase(pos, 1);
pos = topic.find(":", pos);
}
#ifdef ZgatewayBT
if (BTConfig.pubBeaconUuidForTopic && !BTConfig.extDecoderEnable && Jsondata.containsKey("model_id") && Jsondata["model_id"].as<std::string>() == "IBEACON") {
if (Jsondata.containsKey("uuid")) {
topic = Jsondata["uuid"].as<std::string>();
} else {
Log.error(F("No uuid in Jsondata" CR));
gatewayState = GatewayState::ERROR;
}
}
if (BTConfig.extDecoderEnable && !Jsondata.containsKey("model"))
topic = BTConfig.extDecoderTopic.c_str();
#endif
std::string subjectStr(origin);
topic = subjectStr + "/" + topic;
Jsondata["origin"] = topic;
Log.trace(F("Origin: %s" CR), Jsondata["origin"].as<const char*>());
}
// Empty the documents queue
void emptyQueue() {
queueLength = jsonQueue.size();
if (queueLength > maxQueueLength) {
maxQueueLength = queueLength;
}
if (queueLength <= 0) {
return;
}
Log.trace(F("Dequeue JSON" CR));
DynamicJsonDocument jsonBuffer(JSON_MSG_BUFFER_MAX);
JsonObject obj = jsonBuffer.to<JsonObject>();
#ifdef ESP32
if (xSemaphoreTake(xQueueMutex, pdMS_TO_TICKS(QueueSemaphoreTimeOutTask)) == pdFALSE) {
Log.error(F("xQueueMutex not taken" CR));
gatewayState = GatewayState::ERROR;
return;
}
#endif
auto error = deserializeJson(jsonBuffer, jsonQueue.front());
jsonQueue.pop();
#ifdef ESP32
xSemaphoreGive(xQueueMutex);
#endif
if (error) {
Log.error(F("deserialize jsonQueue.front() failed: %s, buffer capacity: %u" CR), error.c_str(), jsonBuffer.capacity());
gatewayState = GatewayState::ERROR;
} else {
if (jsonDispatch(obj))
queueLengthSum++;
}
}
/**
* @brief Publish the payload on default MQTT topic.
*
* @param topicori suffix to add on default MQTT Topic
* @param payload the message to sends
* @param retainFlag true if you what a retain
*/
bool pub(const char* topicori, const char* payload, bool retainFlag) {
String topic = String(mqtt_topic) + String(gateway_name) + String(topicori);
return pubMQTT(topic.c_str(), payload, retainFlag);
}
/**
* @brief Publish the payload on default MQTT topic
*
* @param topicori suffix to add on default MQTT Topic
* @param data The Json Object that represents the message
*/
bool pub(JsonObject& data) {
bool res = false;
bool ret = sensor_Retain;
if (data.containsKey("retain") && data["retain"].is<bool>()) {
ret = data["retain"];
data.remove("retain");
}
if (data.size() == 0) {
Log.error(F("Empty JSON, not published" CR));
gatewayState = GatewayState::ERROR;
return res;
}
String topic;
if (data.containsKey("origin") && data["origin"].is<const char*>()) {
topic = String(mqtt_topic) + String(gateway_name) + String(data["origin"].as<const char*>());
data.remove("origin");
} else if (data.containsKey("topic") && data["topic"].is<const char*>()) {
topic = data["topic"].as<const char*>();
if (data.containsKey("info_topic") && data["info_topic"].is<const char*>()) {
// Sometimes it is necessary to provide information about the publishing topic, not just use it.
// This is the case, for example, for the RF2MQTT device trigger announcement message where the
// temporary variable info_topic provides information about the topic that will be used to publish the message,
// and it can be different of current message topic (This is a clever pun, I hope it's clear).
data["topic"].set(data["info_topic"]);
data.remove("info_topic");
} else {
data.remove("topic");
}
} else {
Log.error(F("No topic or origin in JSON, not published" CR));
gatewayState = GatewayState::ERROR;
return res;
}
#if valueAsATopic
# ifdef ZgatewayPilight
String value = data["value"];
String protocol = data["protocol"];
if (value != "null" && value != 0) {
topic = topic + "/" + protocol + "/" + value;
}
# else
uint64_t value = data["value"];
if (value != 0) {
topic = topic + "/" + TheengsUtils::toString(value);
}
# endif
#endif
#if jsonPublishing
String dataAsString = "";
serializeJson(data, dataAsString);
res = pubMQTT(topic.c_str(), dataAsString.c_str(), ret);
#endif
#if simplePublishing
Log.trace(F("simplePub - ON" CR));
// Loop through all the key-value pairs in obj
for (JsonPair p : data) {
# if defined(ESP8266)
yield();
# endif
if (p.value().is<uint64_t>() && strcmp(p.key().c_str(), "rssi") != 0) { //test rssi , bypass solution due to the fact that a int is considered as an uint64_t
if (strcmp(p.key().c_str(), "value") == 0) { // if data is a value we don't integrate the name into the topic
res = pubMQTT(topic, p.value().as<uint64_t>());
} else { // if data is not a value we integrate the name into the topic
res = pubMQTT(topic + "/" + String(p.key().c_str()), p.value().as<uint64_t>());
}
} else if (p.value().is<int>()) {
res = pubMQTT(topic + "/" + String(p.key().c_str()), p.value().as<int>());
} else if (p.value().is<float>()) {
res = pubMQTT(topic + "/" + String(p.key().c_str()), p.value().as<float>());
} else if (p.value().is<char*>()) {
res = pubMQTT(topic + "/" + String(p.key().c_str()), p.value().as<const char*>());
}
}
#endif
return res;
}
/**
* @brief Publish the payload on default MQTT topic
*
* @param topicori suffix to add on default MQTT Topic
* @param payload the message to sends
*/
bool pub(const char* topicori, const char* payload) {
String topic = String(mqtt_topic) + String(gateway_name) + String(topicori);
return pubMQTT(topic, payload);
}
/**
* @brief Low level MQTT functions without retain
*
* @param topic the topic
* @param payload the payload
*/
bool pubMQTT(const char* topic, const char* payload) {
return pubMQTT(topic, payload, sensor_Retain);
}
/**
* @brief Very Low level MQTT functions with retain Flag
*
* @param topic the topic
* @param payload the payload
* @param retainFlag true if retain the retain Flag
*/
bool pubMQTT(const char* topic, const char* payload, bool retainFlag) {
bool res = false;
if (SYSConfig.mqtt && !SYSConfig.offline) {
#ifdef ESP32
if (xSemaphoreTake(xMqttMutex, pdMS_TO_TICKS(QueueSemaphoreTimeOutTask)) == pdFALSE) {
Log.error(F("xMqttMutex not taken" CR));
gatewayState = GatewayState::ERROR;
return res;
}
#endif
if (mqtt && mqtt->connected()) {
Log.notice(F("[ OMG->MQTT ] topic: %s msg: %s " CR), topic, payload);
res = mqtt->publish(topic, payload, 0, retainFlag);
} else {
Log.warning(F("MQTT not connected, aborting the publication" CR));
}
#ifdef ESP32
xSemaphoreGive(xMqttMutex);
#endif
} else {
Log.notice(F("[ OMG->MQTT deactivated or offline] topic: %s msg: %s " CR), topic, payload);
}
return res;
}
bool pubMQTT(String topic, const char* payload) {
return pubMQTT(topic.c_str(), payload);
}
bool pubMQTT(const char* topic, unsigned long payload) {
char val[11];
sprintf(val, "%lu", payload);
return pubMQTT(topic, val);
}
bool pubMQTT(const char* topic, unsigned long long payload) {
char val[21];
sprintf(val, "%llu", payload);
return pubMQTT(topic, val);
}
bool pubMQTT(const char* topic, String payload) {
return pubMQTT(topic, payload.c_str());
}
bool pubMQTT(String topic, String payload) {
return pubMQTT(topic.c_str(), payload.c_str());
}
bool pubMQTT(String topic, int payload) {
char val[12];
sprintf(val, "%d", payload);
return pubMQTT(topic.c_str(), val);
}
bool pubMQTT(String topic, unsigned long long payload) {
char val[21];
sprintf(val, "%llu", payload);
return pubMQTT(topic.c_str(), val);
}
bool pubMQTT(String topic, float payload) {
char val[12];
dtostrf(payload, 3, 1, val);
return pubMQTT(topic.c_str(), val);
}
bool pubMQTT(const char* topic, float payload) {
char val[12];
dtostrf(payload, 3, 1, val);
return pubMQTT(topic, val);
}
bool pubMQTT(const char* topic, int payload) {
char val[12];
sprintf(val, "%d", payload);
return pubMQTT(topic, val);
}
bool pubMQTT(const char* topic, unsigned int payload) {
char val[12];
sprintf(val, "%u", payload);
return pubMQTT(topic, val);
}
bool pubMQTT(const char* topic, long payload) {
char val[11];
sprintf(val, "%ld", payload);
return pubMQTT(topic, val);
}
bool pubMQTT(const char* topic, double payload) {
char val[16];
sprintf(val, "%f", payload);
return pubMQTT(topic, val);
}
bool pubMQTT(String topic, unsigned long payload) {
char val[11];
sprintf(val, "%lu", payload);
return pubMQTT(topic.c_str(), val);
}
void delayWithOTA(long waitMillis) {
long waitStep = 100;
for (long waitedMillis = 0; waitedMillis < waitMillis; waitedMillis += waitStep) {
#ifndef ESPWifiManualSetup
checkButton(); // check if a reset of wifi/mqtt settings is asked
#endif
ArduinoOTA.handle();
#if defined(ZwebUI) && defined(ESP32)
WebUILoop();
#endif
#ifdef ESP32
//esp_task_wdt_reset();
#endif
delay(waitStep);
}
}
void SYSConfig_init() {
SYSConfig.mqtt = DEFAULT_MQTT;
SYSConfig.serial = DEFAULT_SERIAL;
SYSConfig.offline = DEFAULT_OFFLINE;
#if USE_BLUFI
SYSConfig.blufi = DEFAULT_BLUFI;
#endif
#ifdef ZmqttDiscovery
SYSConfig.discovery = DEFAULT_DISCOVERY;
#endif
#ifdef LED_ADDRESSABLE
SYSConfig.rgbbrightness = DEFAULT_ADJ_BRIGHTNESS;
#endif
SYSConfig.powerMode = DEFAULT_LOW_POWER_MODE;
}
void SYSConfig_fromJson(JsonObject& SYSdata) {
Config_update(SYSdata, "mqtt", SYSConfig.mqtt);
Config_update(SYSdata, "serial", SYSConfig.serial);
Config_update(SYSdata, "offline", SYSConfig.offline);
#if USE_BLUFI
Config_update(SYSdata, "blufi", SYSConfig.blufi);
#endif
#ifdef ZmqttDiscovery
Config_update(SYSdata, "disc", SYSConfig.discovery);
#endif
#ifdef LED_ADDRESSABLE
Config_update(SYSdata, "rgbb", SYSConfig.rgbbrightness);
#endif
Config_update(SYSdata, "powermode", SYSConfig.powerMode);
}
#ifdef ESP32
void SYSConfig_save() {
StaticJsonDocument<JSON_MSG_BUFFER> jsonBuffer;
JsonObject SYSdata = jsonBuffer.to<JsonObject>();
SYSdata["mqtt"] = SYSConfig.mqtt;
SYSdata["serial"] = SYSConfig.serial;
SYSdata["offline"] = SYSConfig.offline;
SYSdata["powermode"] = SYSConfig.powerMode;
# if USE_BLUFI
SYSdata["blufi"] = SYSConfig.blufi;
# endif
# ifdef ZmqttDiscovery
SYSdata["disc"] = SYSConfig.discovery;
# endif
# ifdef LED_ADDRESSABLE
SYSdata["rgbb"] = SYSConfig.rgbbrightness;
# endif
String conf = "";
serializeJson(jsonBuffer, conf);
preferences.begin(Gateway_Short_Name, false);
int result = preferences.putString("SYSConfig", conf);
preferences.end();
Log.notice(F("SYS Config_save: %s, result: %d" CR), conf.c_str(), result);
}
#else // Function not available for ESP8266
void SYSConfig_save() {}
#endif
bool cmpToMainTopic(const char* topicOri, const char* toAdd) {
if (strcmp(topicOri, toAdd) == 0)
return true;
// Is string "<mqtt_topic><gateway_name><toAdd>" equal to "<topicOri>"?
// Compare first part with first chunk
if (strncmp(topicOri, mqtt_topic, strlen(mqtt_topic)) != 0)
return false;
// Move pointer of sizeof chunk
topicOri += strlen(mqtt_topic);
// And so on...
if (strncmp(topicOri, gateway_name, strlen(gateway_name)) != 0)
return false;
topicOri += strlen(gateway_name);
if (strncmp(topicOri, toAdd, strlen(toAdd)) != 0)
return false;
return true;
}
#if defined(ESP32)
void SYSConfig_load() {
StaticJsonDocument<JSON_MSG_BUFFER> jsonBuffer;
preferences.begin(Gateway_Short_Name, true);
if (preferences.isKey("SYSConfig")) {
auto error = deserializeJson(jsonBuffer, preferences.getString("SYSConfig", "{}"));
preferences.end();
if (error) {
Log.error(F("SYS config deserialization failed: %s, buffer capacity: %u" CR), error.c_str(), jsonBuffer.capacity());
gatewayState = GatewayState::ERROR;
return;
}
if (jsonBuffer.isNull()) {
Log.warning(F("SYS config is null" CR));
return;
}
JsonObject jo = jsonBuffer.as<JsonObject>();
SYSConfig_fromJson(jo);
Log.notice(F("SYS config loaded" CR));
} else {
preferences.end();
Log.notice(F("SYS config not found" CR));
}
}
#else // Function not available for ESP8266
void SYSConfig_load() {}
#endif
#if defined(MDNS_SD)
std::pair<String, uint16_t> discoverMQTTbroker() {
Log.trace(F("Browsing for MQTT service" CR));
int n = MDNS.queryService("mqtt", "tcp");
if (n == 0) {
Log.warning(F("no services found" CR));
} else {
Log.trace(F("%d service(s) found" CR), n);
for (int i = 0; i < n; ++i) {
Log.trace(F("Service %d %s found" CR), i, MDNS.hostname(i).c_str());
Log.trace(F("IP %s Port %d" CR), MDNS.IP(i).toString().c_str(), MDNS.port(i));
}
if (n == 1) {
Log.trace(F("One MQTT server found setting parameters" CR));
return {MDNS.IP(0).toString(), uint16_t(MDNS.port(0))};
} else {
Log.warning(F("Several MQTT servers found, please deactivate mDNS and set your default server" CR));
}
}
return {"", 0};
}
#endif
#if MQTT_BROKER_MODE
void setupMQTT() {
Log.notice(F("Reconfiguring MQTT broker..." CR));
mqtt.reset(new MQTTServer());
mqtt->begin();
# ifdef ZgatewayBT
BTProcessLock = !BTConfig.enabled; // Release BLE processes at start if enabled
# endif
}
#else
struct ss_cnt_parameters_backup {
ss_cnt_parameters parameters;
int cnt_index;
bool saveOnSuccess;
};
static std::unique_ptr<ss_cnt_parameters_backup> cnt_parameters_backup;
void setupMQTT() {
Log.notice(F("Reconfiguring MQTT client..." CR));
const auto& parameters = cnt_parameters_array[cnt_index];
// free the old MQTT client and underlying connection
mqtt.reset();
eClient.reset();
failure_number_mqtt = 0;
// configure socket
if (parameters.isConnectionSecure) {
eClient.reset(new WiFiClientSecure);
if (parameters.isCertValidate) {
setupTLS(cnt_index);
} else {
static_cast<WiFiClientSecure*>(eClient.get())->setInsecure();
}
} else {
eClient.reset(new WiFiClient);
}
# if defined(MDNS_SD)
Log.trace(F("Connecting to MQTT by mDNS without MQTT hostname" CR));
const auto discovered_broker = discoverMQTTbroker();
const auto broker_host = discovered_broker.first.c_str();
const auto broker_port = discovered_broker.second;
# else
const auto broker_host = parameters.mqtt_server;
const auto broker_port = String(parameters.mqtt_port).toInt();
# endif
Log.trace(F("Mqtt server: %s" CR), broker_host);
Log.trace(F("Port: %u" CR), broker_port);
mqtt.reset(new PicoMQTT::Client(*eClient, broker_host, broker_port, gateway_name,
parameters.mqtt_user, parameters.mqtt_pass,
0, // minimum reconnect attempt interval [ms]
60 * 1000, // keep alive interval [ms]
(GeneralTimeOut - 1) * 1000 // socket timeout [ms]
));
# if AWS_IOT
// AWS doesn't support will topic for the moment
mqtt->will.topic = "";
mqtt->will.payload = "";
mqtt->will.qos = 0;
mqtt->will.retain = false;
# else
mqtt->will.topic = String(mqtt_topic) + gateway_name + will_Topic;
mqtt->will.payload = will_Message;
mqtt->will.qos = will_QoS;
mqtt->will.retain = will_Retain;