Repository navigation
Expand file tree
/
Copy pathxdrv_02_9_mqtt.ino
More file actions
2551 lines (2274 loc) · 105 KB
/
Copy pathxdrv_02_9_mqtt.ino
File metadata and controls
2551 lines (2274 loc) · 105 KB
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
/*
xdrv_02_9_mqtt.ino - mqtt support for Tasmota
Copyright (C) 2021 Theo Arends
This program 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.
This program 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/>.
*/
#define XDRV_02 2
#define USE_MQTT_NEW_PUBSUBCLIENT
// #define DEBUG_DUMP_TLS // allow dumping of TLS Flash keys
#ifdef USE_MQTT_TLS
#include "WiFiClientSecureLightBearSSL.h"
BearSSL::WiFiClientSecure_light *tlsClient;
#endif
WiFiClient EspClient; // Wifi Client - non-TLS
#ifdef USE_MQTT_AZURE_IOT
#undef MQTT_PORT
#define MQTT_PORT 8883
#if defined(USE_MQTT_AZURE_DPS_SCOPEID) && defined(USE_MQTT_AZURE_DPS_PRESHAREDKEY)
#include <ESP8266HTTPClient.h>
// dedicated tlsHttpsClient for DPS as the 'tlsClient' above causes error '-1' in httpsClient after it is associated with PubSub. It cost ~5K of heap
BearSSL::WiFiClientSecure_light *tlsHttpsClient = new BearSSL::WiFiClientSecure_light(1024,1024);
HTTPClient httpsClient;
int httpsClientReturn;
#endif // USE_MQTT_AZURE_DPS_SCOPEID
#include <base64.hpp>
#include <t_bearssl.h>
#include <JsonParser.h>
#endif // USE_MQTT_AZURE_IOT
const char kMqttCommands[] PROGMEM = "|" // No prefix
#ifndef FIRMWARE_MINIMAL
// SetOption synonyms
D_SO_MQTTJSONONLY "|"
#ifdef USE_MQTT_TLS
D_SO_MQTTTLS "|" D_SO_MQTTTLS_FINGERPRINT "|"
#endif
D_SO_MQTTNORETAIN "|" D_SO_MQTTDETACHRELAY "|"
// regular commands
#if defined(USE_MQTT_TLS)
D_CMND_MQTTFINGERPRINT "|"
#endif
D_CMND_MQTTUSER "|" D_CMND_MQTTPASSWORD "|" D_CMND_MQTTKEEPALIVE "|" D_CMND_MQTTTIMEOUT "|" D_CMND_MQTTWIFITIMEOUT "|"
#if defined(USE_MQTT_TLS) && defined(USE_MQTT_CLIENT_CERT)
D_CMND_TLSKEY "|"
#endif
#ifdef USE_MQTT_FILE
D_CMND_FILEUPLOAD "|" D_CMND_FILEDOWNLOAD "|"
#endif // USE_MQTT_FILE
D_CMND_MQTTHOST "|" D_CMND_MQTTPORT "|" D_CMND_MQTTRETRY "|" D_CMND_MQTTCLIENT "|"
D_CMND_FULLTOPIC "|" D_CMND_PREFIX "|" D_CMND_GROUPTOPIC "|" D_CMND_TOPIC "|" D_CMND_PUBLISH "|" D_CMND_MQTTLOG "|"
D_CMND_BUTTONTOPIC "|" D_CMND_SWITCHTOPIC "|" D_CMND_BUTTONRETAIN "|" D_CMND_SWITCHRETAIN "|" D_CMND_POWERRETAIN "|"
D_CMND_SENSORRETAIN "|" D_CMND_INFORETAIN "|" D_CMND_STATERETAIN "|" D_CMND_STATUSRETAIN
#endif // FIRMWARE_MINIMAL
;
SO_SYNONYMS(kMqttSynonyms,
90,
#ifdef USE_MQTT_TLS
103, 132,
#endif
104, 114
);
void (* const MqttCommand[])(void) PROGMEM = {
#ifndef FIRMWARE_MINIMAL
#if defined(USE_MQTT_TLS)
&CmndMqttFingerprint,
#endif
&CmndMqttUser, &CmndMqttPassword, &CmndMqttKeepAlive, &CmndMqttTimeout, &CmndMqttWifiTimeout,
#if defined(USE_MQTT_TLS) && defined(USE_MQTT_CLIENT_CERT)
&CmndTlsKey,
#endif
#ifdef USE_MQTT_FILE
&CmndFileUpload, &CmndFileDownload,
#endif // USE_MQTT_FILE
&CmndMqttHost, &CmndMqttPort, &CmndMqttRetry, &CmndMqttClient,
&CmndFullTopic, &CmndPrefix, &CmndGroupTopic, &CmndTopic, &CmndPublish, &CmndMqttlog,
&CmndButtonTopic, &CmndSwitchTopic, &CmndButtonRetain, &CmndSwitchRetain, &CmndPowerRetain,
&CmndSensorRetain, &CmndInfoRetain, &CmndStateRetain, &CmndStatusRetain
#endif // FIRMWARE_MINIMAL
};
struct MQTT {
uint16_t connect_count = 0; // MQTT re-connect count
uint16_t retry_counter = 1; // MQTT connection retry counter
uint16_t retry_counter_multiplier = 1; // MQTT retry counter multiplier
uint8_t initial_connection_state = 2; // MQTT connection messages state
bool connected = false; // MQTT virtual connection status
bool allowed = false; // MQTT enabled and parameters valid
bool mqtt_tls = false; // MQTT TLS is enabled
bool disable_logging = false; // Temporarly disable logging on some commands
} Mqtt;
#if MQTT_VERSION == MQTT_VERSION_5_0
struct MqttCommandContext {
String response_topic;
uint8_t correlation_data[PubSubClient::MQTT_CORRELATION_DATA_MAX] = {};
uint8_t correlation_data_len = 0;
bool has_response_topic = false;
bool has_correlation_data = false;
bool active() const {
return has_response_topic;
}
};
class MqttCommandContextScope {
public:
explicit MqttCommandContextScope(const MqttCommandContext* context)
: previous_(XdrvMailbox.mqtt_context) {
XdrvMailbox.mqtt_context = context;
}
~MqttCommandContextScope() {
XdrvMailbox.mqtt_context = previous_;
}
private:
const MqttCommandContext* previous_;
};
#endif // MQTT_VERSION == MQTT_VERSION_5_0
#ifdef USE_MQTT_TLS
// This part of code is necessary to store Private Key and Cert in Flash
#if defined(USE_MQTT_CLIENT_CERT)
#include <base64.hpp>
const br_ec_private_key *AWS_IoT_Private_Key = nullptr;
const br_x509_certificate *AWS_IoT_Client_Certificate = nullptr;
class tls_entry_t {
public:
uint32_t name; // simple 4 letters name. Currently 'skey', 'crt ', 'crt1', 'crt2'
uint16_t start; // start offset
uint16_t len; // len of object
}; // 8 bytes
const static uint32_t TLS_NAME_SKEY = 0x2079656B; // 'key ' little endian
const static uint32_t TLS_NAME_CRT = 0x20747263; // 'crt ' little endian
class tls_dir_t {
public:
tls_entry_t entry[4]; // 4 entries max, only 4 used today, for future use
}; // 4*8 = 64 bytes
tls_dir_t tls_dir; // memory copy of tls_dir from flash
#endif // USE_MQTT_CLIENT_CERT
// check whether the fingerprint is filled with a single value
// Filled with 0x00 = accept any fingerprint and learn it for next time
// Filled with 0xFF = accept any fingerpring forever
bool is_fingerprint_mono_value(uint8_t finger[20], uint8_t value) {
for (uint32_t i = 0; i<20; i++) {
if (finger[i] != value) {
return false;
}
}
return true;
}
#endif // USE_MQTT_TLS
void MakeValidMqtt(uint32_t option, char* str) {
// option 0 = replace by underscore
// option 1 = delete character
uint32_t i = 0;
while (str[i] > 0) {
// if ((str[i] == '/') || (str[i] == '+') || (str[i] == '#') || (str[i] == ' ')) {
if ((str[i] == '+') || (str[i] == '#') || (str[i] == ' ')) {
if (option) {
uint32_t j = i;
while (str[j] > 0) {
str[j] = str[j +1];
j++;
}
i--;
} else {
str[i] = '_';
}
}
i++;
}
}
void MqttDisableLogging(bool state) {
// Disable logging only on repeating MQTT messages
Mqtt.disable_logging = state;
TasmotaGlobal.masterlog_level = (Mqtt.disable_logging) ? LOG_LEVEL_DEBUG_MORE : LOG_LEVEL_NONE;
}
// The following emits a warning if the connection is non-TLS on a TLS port
// this makes troubleshooting easier
// This function is called only when a non-TLS connection is detected
void MqttNonTLSWarning(void) {
#ifndef FIRMWARE_MINIMAL // not needed in MINIMAL firmware
if ((443 == Settings->mqtt_port) ||
(8883 == Settings->mqtt_port ) ||
(8443 == Settings->mqtt_port)) {
AddLog(LOG_LEVEL_INFO, PSTR(D_LOG_MQTT "Warning non-TLS connection on TLS port %d"), Settings->mqtt_port);
}
#endif // FIRMWARE_MINIMAL
}
/*********************************************************************************************\
* MQTT driver specific code need to provide the following functions:
*
* bool MqttIsConnected()
* void MqttDisconnect()
* void MqttSubscribeLib(char *topic)
* bool MqttPublishLib(const char* topic, const uint8_t* payload, unsigned int plength, bool retained)
*
* Change/Verify PubSubClient.h defines:
* #define MQTT_MAX_PACKET_SIZE 1200 // Tasmota v8.1.0.8
\*********************************************************************************************/
PubSubClient MqttClient;
void MqttSetClientTimeout(void) {
#ifdef ESP8266
// setTimeout in msecs
EspClient.setTimeout(Settings->mqtt_wifi_timeout * 100);
#else
// setTimeout in secs
uint32_t timeout = (Settings->mqtt_wifi_timeout < 10) ? 1 : Settings->mqtt_wifi_timeout / 10;
EspClient.setTimeout(timeout);
#endif
}
#if MQTT_VERSION == MQTT_VERSION_5_0 && defined(USE_MQTT_DETAILED_LOGGING_BINARY)
// Raw wire dump of every MQTT packet the client reads from and writes to the transport.
// Registered with PubSubClient as its WireLogCallback; called with the complete received
// packet (tx == false) or the exact bytes about to be sent (tx == true). Emitted at
// DEBUG_MORE as a single hex line: `%*_H` expands the whole packet to two hex chars per
// byte into a heap buffer (freed here), so no large buffer is placed on the stack.
void MqttLogWirePacket(bool tx, const uint8_t* data, uint32_t len) {
const uint32_t highest_loglevel = HighestLogLevel();
if ((LOG_LEVEL_DEBUG_MORE > highest_loglevel) ||
(TasmotaGlobal.masterlog_level > highest_loglevel)) {
return;
}
char* hex = ext_snprintf_malloc_P(PSTR("%*_H"), len, data);
if (hex != nullptr) {
AddLog(LOG_LEVEL_DEBUG_MORE, PSTR(D_LOG_MQTT "%cx bin [%u]: %s"),
tx ? 'T' : 'R', (unsigned)len, hex);
free(hex);
}
}
#endif // MQTT_VERSION == MQTT_VERSION_5_0 && USE_MQTT_DETAILED_LOGGING_BINARY
void MqttInit(void) {
// Force buffer size since the #define may not be visible from Arduino lib
MqttClient.setBufferSize(MQTT_MAX_PACKET_SIZE);
MqttClient.setMaxIncomingPacketSize(MQTT_MAX_PACKET_SIZE);
#if MQTT_VERSION == MQTT_VERSION_5_0 && defined(USE_MQTT_DETAILED_LOGGING_BINARY)
MqttClient.setWireLogCallback(MqttLogWirePacket);
#endif
#ifdef USE_MQTT_AZURE_IOT
Settings->mqtt_port = 8883;
#endif //USE_MQTT_AZURE_IOT
#ifdef USE_MQTT_TLS
bool aws_iot_host = false;
Mqtt.mqtt_tls = Settings->flag4.mqtt_tls; // this flag should not change even if we change the SetOption (until reboot)
// Detect AWS IoT and set default parameters
String host = String(SettingsText(SET_MQTT_HOST));
if (host.indexOf(F(".iot.")) && host.endsWith(F(".amazonaws.com"))) { // look for ".iot." and ".amazonaws.com" in the domain name
Settings->flag4.mqtt_no_retain = true;
aws_iot_host = true;
}
if (Mqtt.mqtt_tls) {
#ifdef ESP32
#if MQTT_MAX_PACKET_SIZE > 2000
tlsClient = new BearSSL::WiFiClientSecure_light(4096,4096);
#else
tlsClient = new BearSSL::WiFiClientSecure_light(2048,2048);
#endif
#else // ESP32 - ESP8266
tlsClient = new BearSSL::WiFiClientSecure_light(1024,1024);
#endif
if (443 == Settings->mqtt_port && aws_iot_host) {
static const char * alpn_mqtt = "mqtt"; // needs to be static
tlsClient->setALPN(&alpn_mqtt, 1); // need to set alpn to 'mqtt' for AWS IoT
}
#if defined(USE_MQTT_CLIENT_CERT)
loadTlsDir(); // load key and certificate data from Flash
if ((nullptr != AWS_IoT_Private_Key) && (nullptr != AWS_IoT_Client_Certificate)) {
tlsClient->setClientECCert(AWS_IoT_Client_Certificate,
AWS_IoT_Private_Key,
0xFFFF /* all usages, don't care */, 0);
}
#endif
if (!Settings->flag5.tls_use_fingerprint) {
tlsClient->setTrustAnchor(Tasmota_TA, nitems(Tasmota_TA));
}
tlsClient->setECDSA(Settings->flag6.tls_use_ecdsa);
MqttClient.setClient(*tlsClient);
} else {
MqttClient.setClient(EspClient); // non-TLS
MqttNonTLSWarning();
}
#else // USE_MQTT_TLS
MqttClient.setClient(EspClient);
MqttNonTLSWarning();
#endif // USE_MQTT_TLS
MqttClient.setKeepAlive(Settings->mqtt_keepalive);
MqttClient.setSocketTimeout(Settings->mqtt_socket_timeout);
}
#ifdef USE_MQTT_AZURE_IOT
String Sha256Sign(String dataToSign, String preSharedKey){
AddLog(LOG_LEVEL_DEBUG, PSTR(D_LOG_MQTT "sha256 dataToSign is '%s'"), String(dataToSign).c_str());
char dataToSignChar[dataToSign.length() + 1];
dataToSign.toCharArray(dataToSignChar, dataToSign.length() + 1);
unsigned char decodedPSK[32];
unsigned char encryptedSignature[100];
unsigned char encodedSignature[100];
br_sha256_context sha256_context;
br_hmac_key_context hmac_key_context;
br_hmac_context hmac_context;
// need to base64 decode the Preshared key and the length
int base64_decoded_device_length = decode_base64((unsigned char*)preSharedKey.c_str(), decodedPSK);
// create the sha256 hmac and hash the data
br_sha256_init(&sha256_context);
br_hmac_key_init(&hmac_key_context, sha256_context.vtable, decodedPSK, base64_decoded_device_length);
br_hmac_init(&hmac_context, &hmac_key_context, 32);
br_hmac_update(&hmac_context, dataToSignChar, sizeof(dataToSignChar)-1);
br_hmac_out(&hmac_context, encryptedSignature);
// base64 decode the HMAC to a char
encode_base64(encryptedSignature, br_hmac_size(&hmac_context), encodedSignature);
// creating the real SAS Token
AddLog(LOG_LEVEL_DEBUG, PSTR(D_LOG_MQTT "sha256 signature is '%s'"), String((char*)encodedSignature).c_str());
return String((char*)encodedSignature);
}
String urlEncodeBase64(String stringToEncode){
// correctly URL encoding the 64 characters of Base64 and the '=' sign
stringToEncode.replace("+", "%2B");
stringToEncode.replace("=", "%3D");
stringToEncode.replace("/", "%2F");
return stringToEncode;
}
String AzurePSKtoToken(char *iotHubFQDN, const char *deviceId, const char *preSharedKey, int sasTTL = 86400){
int ttl = time(NULL) + sasTTL;
String dataToSignString = urlEncodeBase64(String(iotHubFQDN) + "/devices/" + String(deviceId)) + "\n" + String(ttl);
String signedData = Sha256Sign(dataToSignString, String(preSharedKey));
// creating the real SAS Token
String realSASToken = "SharedAccessSignature sr=" + urlEncodeBase64(String(iotHubFQDN) + "/devices/" + String(deviceId));
realSASToken += "&sig=" + urlEncodeBase64(signedData) + "&se=" + String(ttl);
AddLog(LOG_LEVEL_DEBUG, PSTR(D_LOG_MQTT "Azure IoT Hub SAS Token is '%s'"), realSASToken.c_str());
return realSASToken;
}
#if defined(USE_MQTT_AZURE_DPS_SCOPEID) && defined(USE_MQTT_AZURE_DPS_PRESHAREDKEY)
String AzureDSPPSKtoToken(String scopeId, String deviceId, const char *preSharedKey, int sasTTL = 3600){
int ttl = time(NULL) + sasTTL;
String dataToSignString = urlEncodeBase64(scopeId + "/registrations/" + deviceId) + "\n" + String(ttl);
String signedData = Sha256Sign(dataToSignString, String(preSharedKey));
// creating the real SAS Token
String realSASToken = "SharedAccessSignature sr=" + urlEncodeBase64(scopeId + "/registrations/" + deviceId);
realSASToken += "&sig=" + urlEncodeBase64(signedData) + "&skn=registration" + "&se=" + String(ttl);
AddLog(LOG_LEVEL_DEBUG, PSTR(D_LOG_MQTT "Azure DPS SAS Token is '%s'"), realSASToken.c_str());
return realSASToken;
}
void ProvisionAzureDPS(){
AddLog(LOG_LEVEL_INFO, PSTR(D_LOG_MQTT "Starting Azure DPS registration..."));
// Scope and Key are derived from user_config_override.h, USE_MQTT_AZURE_DPS_SCOPE_ENDPOINT is optional
String dPSScopeId = USE_MQTT_AZURE_DPS_SCOPEID;
String dPSPreSharedKey = USE_MQTT_AZURE_DPS_PRESHAREDKEY;
#if defined(USE_MQTT_AZURE_DPS_SCOPE_ENDPOINT)
String endpoint=USE_MQTT_AZURE_DPS_SCOPE_ENDPOINT;
#else
String endpoint="https://global.azure-devices-provisioning.net/";
#endif //USE_MQTT_AZURE_DPS_SCOPE_ENDPOINT
String MACAddress = WiFiHelper::macAddress();
MACAddress.replace(":", "");
AddLog(LOG_LEVEL_DEBUG, PSTR(D_LOG_MQTT "DPS register for %s, scope %s to %s."), MACAddress.c_str(), dPSScopeId.c_str(), endpoint.c_str());
// derive our PSK from the DPS and set the device ID
String devicePresharedKey = Sha256Sign(MACAddress, dPSPreSharedKey);
char devicePresharedKeyChar[devicePresharedKey.length() + 1];
devicePresharedKey.toCharArray(devicePresharedKeyChar, devicePresharedKey.length() + 1);
// generate a SAS Token with this new derived key
String dPSSASToken = AzureDSPPSKtoToken(dPSScopeId, MACAddress, devicePresharedKey.c_str());
// REST to DPS to start the assigning process
String dPSURL = endpoint + dPSScopeId + "/registrations/" + MACAddress + "/register?api-version=2019-03-31";
String dPSPutContent = "{\"registrationId\": \"" + MACAddress + "\"}";
httpsClient.setReuse(true);
httpsClient.begin(*tlsHttpsClient, dPSURL);
httpsClient.addHeader("User-Agent", "Tasmota");
httpsClient.addHeader("Content-Type", "application/json");
httpsClient.addHeader("Content-Encoding", "utf-8");
httpsClient.addHeader("Authorization", dPSSASToken);
httpsClientReturn = httpsClient.PUT(dPSPutContent);
String dPSAssigningResponseJSON;
if (httpsClientReturn == HTTP_CODE_ACCEPTED){
dPSAssigningResponseJSON = httpsClient.getString();
AddLog(LOG_LEVEL_DEBUG, PSTR(D_LOG_MQTT "DPS Assigning response '%s'"), dPSAssigningResponseJSON.c_str());
} else {
dPSAssigningResponseJSON = httpsClient.getString();
AddLog(LOG_LEVEL_DEBUG, PSTR(D_LOG_MQTT "DPS Assigning response '%s'"), dPSAssigningResponseJSON.c_str());
AddLog(LOG_LEVEL_ERROR, PSTR(D_LOG_MQTT "Azure DPS REST assignment connection failed with code '%d'. Restarting."), httpsClientReturn);
WebRestart(1);
}
if (dPSAssigningResponseJSON.indexOf("\"assigning\"") == -1){
AddLog(LOG_LEVEL_ERROR, PSTR(D_LOG_MQTT "Azure DPS assignment failed with response '%s'. Restarting."), dPSAssigningResponseJSON.c_str());
WebRestart(1);
} else {
AddLog(LOG_LEVEL_DEBUG, PSTR(D_LOG_MQTT "Azure DPS assignment response '%s'."), dPSAssigningResponseJSON.c_str());
}
httpsClient.end();
JsonParser dPSAssigningResponseParser((char*) dPSAssigningResponseJSON.c_str());
JsonParserObject dPSAssigningResponseRoot = dPSAssigningResponseParser.getRootObject();
String dPSAssigningOperationId = dPSAssigningResponseRoot.getStr("operationId");
AddLog(LOG_LEVEL_DEBUG, PSTR(D_LOG_MQTT "DPS operationId is '%s'."), dPSAssigningOperationId.c_str());
bool assigned = false;
int assignedCounter = 1;
String dPSAssignedResponseJSON;
dPSURL = endpoint + dPSScopeId + "/registrations/" + MACAddress + "/operations/" + dPSAssigningOperationId + "?api-version=2019-03-31";
while (!assigned && assignedCounter < 5){
httpsClient.begin(*tlsHttpsClient, dPSURL);
httpsClient.addHeader("User-Agent", "Tasmota");
httpsClient.addHeader("Content-Type", "application/json");
httpsClient.addHeader("Content-Encoding", "utf-8");
httpsClient.addHeader("Authorization", dPSSASToken);
httpsClientReturn = httpsClient.GET();
if (httpsClientReturn == HTTP_CODE_OK){
dPSAssignedResponseJSON = httpsClient.getString();
} else if (httpsClientReturn != HTTP_CODE_ACCEPTED){
AddLog(LOG_LEVEL_ERROR, PSTR(D_LOG_MQTT "Azure DPS REST check connection failed with code '%d'."), httpsClientReturn);
}
if (dPSAssignedResponseJSON.indexOf("\"status\":\"assigned\"") > 0){
assigned = true;
} else if (httpsClientReturn != HTTP_CODE_ACCEPTED) {
AddLog(LOG_LEVEL_DEBUG, PSTR(D_LOG_MQTT "DPS try %d, response '%s'."), assignedCounter, dPSAssignedResponseJSON.c_str());
}
delay(1000 * assignedCounter);
assignedCounter+=1;
}
httpsClient.end();
if (assigned){
AddLog(LOG_LEVEL_DEBUG, PSTR(D_LOG_MQTT "Azure DPS registration response '%s'."), dPSAssignedResponseJSON.c_str());
JsonParser parser((char*) dPSAssignedResponseJSON.c_str());
JsonParserObject stateObject = parser.getRootObject()[PSTR("registrationState")].getObject();
String deviceId = stateObject["deviceId"].getStr();
String iotHub = stateObject["assignedHub"].getStr();
bool newProvision = false;
if (String(SettingsText(SET_MQTT_PWD)) != devicePresharedKey ||
String(SettingsText(SET_MQTT_HOST)) != iotHub ||
String(SettingsText(SET_MQTT_CLIENT)) != deviceId ||
String(SettingsText(SET_MQTT_USER)) != deviceId) {
newProvision = true;
SettingsUpdateText(SET_MQTT_PWD, devicePresharedKey.c_str());
SettingsUpdateText(SET_MQTT_HOST, iotHub.c_str());
SettingsUpdateText(SET_MQTT_CLIENT, deviceId.c_str());
SettingsUpdateText(SET_MQTT_USER, deviceId.c_str());
}
if (newProvision){ // because this is the first time we have been provisioned must reboot
AddLog(LOG_LEVEL_INFO, PSTR(D_LOG_MQTT "Azure DPS registration success, changed in DPS registration, restarting."));
WebRestart(1);
} else {
AddLog(LOG_LEVEL_INFO, PSTR(D_LOG_MQTT "Azure DPS registration success, no changes."));
}
} else {
AddLog(LOG_LEVEL_ERROR, PSTR(D_LOG_MQTT "Azure DPS registration response failed with response '%s'."), dPSAssignedResponseJSON.c_str());
}
}
#endif // USE_MQTT_AZURE_DPS_SCOPEID
#endif // USE_MQTT_AZURE_IOT
bool MqttIsConnected(void) {
return MqttClient.connected();
}
void MqttDisconnect(void) {
if (MqttClient.connected()) {
MqttClient.disconnect();
}
}
void MqttSubscribeLib(const char *topic) {
#ifdef USE_MQTT_AZURE_IOT
// Azure IoT Hub currently does not support custom topics: https://docs.microsoft.com/en-us/azure/iot-hub/iot-hub-mqtt-support
String realTopicString = "devices/" + String(SettingsText(SET_MQTT_CLIENT));
realTopicString += "/messages/devicebound/#";
MqttClient.subscribe(realTopicString.c_str());
MqttClient.subscribe("$iothub/methods/POST/#");
SettingsUpdateText(SET_MQTT_FULLTOPIC, SettingsText(SET_MQTT_CLIENT));
SettingsUpdateText(SET_MQTT_TOPIC, SettingsText(SET_MQTT_CLIENT));
#else
MqttClient.subscribe(topic);
#endif // USE_MQTT_AZURE_IOT
MqttClient.loop(); // Solve LmacRxBlk:1 messages
}
void MqttUnsubscribeLib(const char *topic) {
MqttClient.unsubscribe(topic);
MqttClient.loop(); // Solve LmacRxBlk:1 messages
}
#if MQTT_VERSION == MQTT_VERSION_5_0 && defined(USE_MQTT_DETAILED_LOGGING)
// Emits the outbound "Tx" diagnostic for a PUBLISH the moment Tasmota hands it to the
// transport. Only PUBLISH is logged (no PINGREQ/SUBSCRIBE/ACK/DISCONNECT), and the QoS
// is taken straight from the publish request rather than decoded from a wire header, so
// no cross-layer hook into the MQTT library is needed.
void MqttLogTxPublish(const char* topic, const uint8_t* payload, unsigned int payload_len,
uint8_t qos, const MqttMessageProperties* mqtt_properties);
#endif // MQTT_VERSION == MQTT_VERSION_5_0 && USE_MQTT_DETAILED_LOGGING
#if MQTT_VERSION == MQTT_VERSION_5_0
// Arduino's sketch preprocessor can generate these prototypes outside the surrounding
// MQTT_VERSION guard. Declare them explicitly here so MQTT5-only types never leak into
// the generated MQTT 3.1.1 translation unit.
static bool MqttMessagePropertiesEmpty(const MqttMessageProperties& properties);
static bool MqttPublishLibSingle(const char* topic, const uint8_t* payload,
unsigned int plength, bool retained,
const MqttMessageProperties* properties);
static void MqttPublishCorrelatedResponse(const uint8_t* payload,
unsigned int plength);
bool MqttPublish5(const MqttPublishRequest& request, uint16_t* packet_id_out);
static bool MqttPublishLibSingle(const char* topic, const uint8_t* payload,
unsigned int plength, bool retained,
const MqttMessageProperties* properties) {
#else
bool MqttPublishLib(const char* topic, const uint8_t* payload, unsigned int plength, bool retained) {
#endif
// If Prefix1 equals Prefix2 disable next MQTT subscription to prevent loop
if (!strcmp(SettingsText(SET_MQTTPREFIX1), SettingsText(SET_MQTTPREFIX2))) {
char *str = strstr(topic, SettingsText(SET_MQTTPREFIX1));
if (str == topic) {
TasmotaGlobal.mqtt_cmnd_blocked_reset = 4; // Allow up to four seconds before resetting residual cmnd blocks
TasmotaGlobal.mqtt_cmnd_blocked++;
}
}
#ifdef USE_TASMESH
if (MESHrouteMQTTtoMESH(topic, (char*)payload, retained)) { // If we are a node, send this via ESP-Now
yield();
return true;
}
#endif // USE_TASMESH
#ifdef USE_MQTT_AZURE_IOT
String sourceTopicString = urlEncodeBase64(String(topic));
String topicString = "devices/" + String(SettingsText(SET_MQTT_CLIENT));
topicString += "/messages/events/topic=" + sourceTopicString;
JsonParser mqtt_message((char*) String((const char*)payload).c_str());
JsonParserObject message_object = mqtt_message.getRootObject();
if (!message_object.isValid()) { // only sending valid JSON, yet this is optional
AddLog(LOG_LEVEL_DEBUG, PSTR(D_LOG_MQTT "Invalid JSON for topic '%s', not sending to Azure IoT Hub"), topic);
return true;
}
topic = topicString.c_str();
#endif // USE_MQTT_AZURE_IOT
#if MQTT_VERSION == MQTT_VERSION_5_0
const bool publish_started = (properties != nullptr)
? MqttClient.beginPublishWithProperties(topic, plength, retained, *properties)
: MqttClient.beginPublish(topic, plength, retained);
#else
const bool publish_started = MqttClient.beginPublish(topic, plength, retained);
#endif
if (!publish_started) {
// AddLog(LOG_LEVEL_DEBUG, PSTR(D_LOG_MQTT "Connection lost or message too large"));
return false;
}
uint32_t written = MqttClient.write(payload, plength);
if (written != plength) {
// The fixed header (and possibly part of the payload) has already been sent
// by beginPublish()/write(). A short write leaves an incomplete MQTT control packet
// on the wire, so the connection is desynchronised and must not be reused. Drop it;
// Tasmota will reconnect on the next loop.
AddLog(LOG_LEVEL_DEBUG, PSTR(D_LOG_MQTT "Partial write (%u/%u), dropping connection"), written, plength);
MqttClient.disconnect();
return false;
}
/*
// Solves #6525??
const uint8_t* write_buf = payload;
uint32_t bytes_remaining = plength;
uint32_t bytes_to_write;
uint32_t written;
while (bytes_remaining > 0) {
bytes_to_write = (bytes_remaining > 256) ? 256 : bytes_remaining;
written = MqttClient.write(write_buf, bytes_to_write);
if (written != bytes_to_write) {
AddLog(LOG_LEVEL_DEBUG, PSTR(D_LOG_MQTT "Message too large"));
return false;
}
write_buf += written;
bytes_remaining -= written;
}
*/
MqttClient.endPublish();
#if MQTT_VERSION == MQTT_VERSION_5_0 && defined(USE_MQTT_DETAILED_LOGGING)
// The streamed path (beginPublish/write/endPublish) is QoS 0 only.
MqttLogTxPublish(topic, payload, plength, 0, properties);
#endif // MQTT_VERSION == MQTT_VERSION_5_0 && USE_MQTT_DETAILED_LOGGING
// yield(); // #3313
delay(0);
return true;
}
#if MQTT_VERSION == MQTT_VERSION_5_0
static bool MqttMessagePropertiesEmpty(const MqttMessageProperties& properties) {
return !properties.hasPayloadFormat &&
(properties.contentType == nullptr) &&
(properties.responseTopic == nullptr) &&
(properties.correlationData == nullptr) &&
(properties.correlationDataLen == 0) &&
(properties.userPropertyCount == 0);
}
static void MqttPublishCorrelatedResponse(const uint8_t* payload,
unsigned int plength) {
const MqttCommandContext* context =
(MqttClient.protocolVersion() == MQTT_VERSION_5_0) ? XdrvMailbox.mqtt_context : nullptr;
if (context == nullptr) {
return;
}
MqttMessageProperties response_properties;
if (context->has_correlation_data) {
response_properties.correlationData = context->correlation_data;
response_properties.correlationDataLen = context->correlation_data_len;
}
// A command response is always a distinct QoS 0, non-retained publication. It carries
// only the request Correlation Data, even when its topic equals the primary topic.
if (!MqttPublishLibSingle(context->response_topic.c_str(), payload, plength, false,
&response_properties)) {
AddLog(LOG_LEVEL_DEBUG, PSTR(D_LOG_MQTT "Unable to publish correlated response to %s"),
context->response_topic.c_str());
}
}
// Berry `mqtt.is_request()` support: true while an inbound MQTT 5.0 request (a message that
// carried a Response Topic) is being handled synchronously.
bool MqttIsRequest(void) {
return (MqttClient.protocolVersion() == MQTT_VERSION_5_0) &&
(XdrvMailbox.mqtt_context != nullptr);
}
// Berry `mqtt.respond(payload)` support: explicit reply to the request currently being
// handled. Publishes `payload` to the request's Response Topic with its Correlation Data
// echoed back, QoS 0 and non-retained. Uses the non-recursing single publish so it does not
// itself re-trigger MqttPublishCorrelatedResponse. Returns false when no request is active.
bool MqttRespond(const uint8_t* payload, unsigned int plength) {
const MqttCommandContext* context =
(MqttClient.protocolVersion() == MQTT_VERSION_5_0) ? XdrvMailbox.mqtt_context : nullptr;
if (context == nullptr) {
return false;
}
MqttMessageProperties response_properties;
if (context->has_correlation_data) {
response_properties.correlationData = context->correlation_data;
response_properties.correlationDataLen = context->correlation_data_len;
}
return MqttPublishLibSingle(context->response_topic.c_str(), payload, plength, false,
&response_properties);
}
bool MqttPublishLib(const char* topic, const uint8_t* payload, unsigned int plength, bool retained) {
const bool published = MqttPublishLibSingle(topic, payload, plength, retained, nullptr);
MqttPublishCorrelatedResponse(payload, plength);
return published;
}
bool MqttPublish5(const MqttPublishRequest& request, uint16_t* packet_id_out) {
if (packet_id_out != nullptr) {
*packet_id_out = 0;
}
if (!Settings->flag.mqtt_enabled) { // SetOption3 - Enable MQTT
return false;
}
MqttPublishRequest effective_request = request;
if (Settings->flag4.mqtt_no_retain) { // SetOption104 - Disable retained messages
effective_request.retained = false;
}
if (MqttClient.protocolVersion() != MQTT_VERSION_5_0) {
if ((effective_request.qos != 0) ||
!MqttMessagePropertiesEmpty(effective_request.properties)) {
return false;
}
return MqttPublishLib(effective_request.topic, effective_request.payload,
effective_request.plength, effective_request.retained);
}
const bool published = MqttClient.publish(effective_request, packet_id_out);
#ifdef USE_MQTT_DETAILED_LOGGING
if (published) {
MqttLogTxPublish(effective_request.topic, effective_request.payload,
effective_request.plength, effective_request.qos,
&effective_request.properties);
}
#endif // USE_MQTT_DETAILED_LOGGING
MqttPublishCorrelatedResponse(effective_request.payload, effective_request.plength);
return published;
}
#endif // MQTT_VERSION == MQTT_VERSION_5_0
#if MQTT_VERSION == MQTT_VERSION_5_0 && defined(USE_MQTT_DETAILED_LOGGING)
void MqttLogTxPublish(const char* topic, const uint8_t* payload, unsigned int payload_len,
uint8_t qos, const MqttMessageProperties* mqtt_properties) {
if (MqttClient.protocolVersion() != MQTT_VERSION_5_0) {
return; // Detailed Tx diagnostics are an MQTT 5.0 feature; skip after level-4 fallback.
}
const uint32_t highest_loglevel = HighestLogLevel();
if ((LOG_LEVEL_DEBUG_MORE > highest_loglevel) ||
(TasmotaGlobal.masterlog_level > highest_loglevel)) {
return;
}
JsonGeneratorObject properties;
if (mqtt_properties != nullptr) {
if (mqtt_properties->correlationData != nullptr) { // correlation data is always binary
properties.addHex("corr", mqtt_properties->correlationData, mqtt_properties->correlationDataLen);
}
if (mqtt_properties->responseTopic != nullptr) {
properties.addStr("respTopic", mqtt_properties->responseTopic);
}
if (mqtt_properties->hasPayloadFormat) {
properties.add("payloadFormat", (uint32_t)mqtt_properties->payloadFormat);
}
if (mqtt_properties->contentType != nullptr) {
properties.addStr("contentType", mqtt_properties->contentType);
}
if ((mqtt_properties->userPropertyKeys != nullptr) &&
(mqtt_properties->userPropertyValues != nullptr) &&
(mqtt_properties->userPropertyCount != 0)) {
JsonGeneratorArray user_props;
for (uint8_t i = 0; i < mqtt_properties->userPropertyCount; i++) {
const char* key = mqtt_properties->userPropertyKeys[i];
const char* value = mqtt_properties->userPropertyValues[i];
JsonGeneratorObject kv;
kv.addStr("key", (key != nullptr) ? key : "");
kv.addStr("value", (value != nullptr) ? value : "");
user_props.addStrRaw(kv.toString().c_str());
}
properties.addStrRaw("userProperties", user_props.toString().c_str());
}
}
String safe_topic = EscapeJSONString(topic);
String payload_str;
payload_str.concat((const char*)payload, payload_len);
String safe_payload = EscapeJSONString(payload_str.c_str());
// Single uniform format for every QoS so logs parse consistently: QoS is always shown,
// in parentheses right after "Tx".
AddLog(LOG_LEVEL_DEBUG_MORE,
PSTR(D_LOG_MQTT "Tx(%d) \"%s\" | \"%s\" | %s"),
qos, safe_topic.c_str(), safe_payload.c_str(), properties.toString().c_str());
}
void MqttLogReceivedMessage(const char* topic, const uint8_t* payload, unsigned int payload_len) {
const uint32_t highest_loglevel = HighestLogLevel();
if ((LOG_LEVEL_DEBUG_MORE > highest_loglevel) ||
(TasmotaGlobal.masterlog_level > highest_loglevel)) {
return;
}
struct MqttLogPropertyContext {
bool has_expiry = false;
uint32_t expiry = 0;
bool has_sub_ids = false;
JsonGeneratorArray sub_ids;
bool has_user_properties = false;
JsonGeneratorArray user_properties;
} context;
auto collect_property = [](const MqttPropertyView& property, void* raw_context) -> bool {
MqttLogPropertyContext* context = static_cast<MqttLogPropertyContext*>(raw_context);
if (property.id == 0x02) { // Message Expiry Interval
context->has_expiry = true;
context->expiry = property.value;
} else if (property.id == 0x0B) { // Subscription Identifier
context->sub_ids.add((uint32_t)property.value);
context->has_sub_ids = true;
} else if (property.id == MQTT_PROP_USER_PROPERTY) {
String key;
key.concat((const char*)property.data, property.len);
String value;
value.concat((const char*)property.data2, property.len2);
JsonGeneratorObject kv;
kv.addStr("key", key.c_str());
kv.addStr("value", value.c_str());
context->user_properties.addStrRaw(kv.toString().c_str());
context->has_user_properties = true;
}
return true;
};
const bool properties_ok = MqttClient.forEachInboundProperty(collect_property, &context);
const MqttInboundProperties& mqtt_properties = MqttClient.inboundProperties();
JsonGeneratorObject properties;
if (mqtt_properties.hasCorrelationData) { // correlation data is always binary
properties.addHex("corr", mqtt_properties.correlationData, mqtt_properties.correlationDataLen);
}
if (mqtt_properties.responseTopic.present()) {
String resp_topic;
resp_topic.concat((const char*)mqtt_properties.responseTopic.data, mqtt_properties.responseTopic.len);
properties.addStr("respTopic", resp_topic.c_str());
}
if (context.has_expiry) {
properties.add("expiry", context.expiry);
}
if (mqtt_properties.hasPayloadFormat) {
properties.add("payloadFormat", (uint32_t)mqtt_properties.payloadFormat);
}
if (mqtt_properties.contentType.present()) {
String content_type;
content_type.concat((const char*)mqtt_properties.contentType.data, mqtt_properties.contentType.len);
properties.addStr("contentType", content_type.c_str());
}
if (mqtt_properties.topicAlias != 0) {
properties.add("topicAlias", (uint32_t)mqtt_properties.topicAlias);
}
if (context.has_sub_ids) {
properties.addStrRaw("subIds", context.sub_ids.toString().c_str());
}
if (context.has_user_properties) {
properties.addStrRaw("userProperties", context.user_properties.toString().c_str());
}
if (!properties_ok) {
properties.addStrRaw("propertiesError", "true");
}
String safe_topic = EscapeJSONString(topic);
String payload_str;
payload_str.concat((const char*)payload, payload_len);
String safe_payload = EscapeJSONString(payload_str.c_str());
AddLog(LOG_LEVEL_DEBUG_MORE, PSTR(D_LOG_MQTT "Rx \"%s\" | \"%s\" | %s"),
safe_topic.c_str(), safe_payload.c_str(), properties.toString().c_str());
}
#endif // MQTT_VERSION == MQTT_VERSION_5_0 && USE_MQTT_DETAILED_LOGGING
void MqttDataHandler(char* mqtt_topic, uint8_t* mqtt_data, unsigned int data_len) {
SHOW_FREE_MEM(PSTR("MqttDataHandler"));
#if MQTT_VERSION == MQTT_VERSION_5_0 && defined(USE_MQTT_DETAILED_LOGGING)
if (MqttClient.protocolVersion() == MQTT_VERSION_5_0) {
MqttLogReceivedMessage(mqtt_topic, mqtt_data, data_len);
}
#endif // MQTT_VERSION == MQTT_VERSION_5_0 && USE_MQTT_DETAILED_LOGGING
// Do not allow more data than would be feasable within stack space
if (data_len >= MQTT_MAX_PACKET_SIZE) { return; }
// Do not execute multiple times if Prefix1 equals Prefix2
if (!strcmp(SettingsText(SET_MQTTPREFIX1), SettingsText(SET_MQTTPREFIX2))) {
char *str = strstr(mqtt_topic, SettingsText(SET_MQTTPREFIX1));
if ((str == mqtt_topic) && TasmotaGlobal.mqtt_cmnd_blocked) {
TasmotaGlobal.mqtt_cmnd_blocked--;
return;
}
}
#ifdef USE_MQTT_FILE
FMqtt.topic_size = strlen(mqtt_topic);
#endif // USE_MQTT_FILE
// AddLog(LOG_LEVEL_DEBUG, PSTR(D_LOG_MQTT "BufferSize %d, Topic |%s|, Length %d, data_len %d"), MqttClient.getBufferSize(), mqtt_topic, strlen(mqtt_topic), data_len);
char topic[TOPSZ];
#ifdef USE_MQTT_AZURE_IOT
#ifdef USE_AZURE_DIRECT_METHOD
String fullTopicString = String(mqtt_topic);
int startOfMethod = fullTopicString.indexOf("methods/POST");
int endofMethod = fullTopicString.indexOf("/?$rid");
String req_id = fullTopicString.substring(endofMethod + 7);
if (startOfMethod == -1){
AddLog(LOG_LEVEL_ERROR, PSTR(D_LOG_MQTT "Azure IoT Hub message without a method."));
return;
}
String newMethod = fullTopicString.substring(startOfMethod + 12,endofMethod);
strlcpy(topic, newMethod.c_str(), sizeof(topic));
mqtt_data[data_len] = 0;
JsonParser mqtt_json_data((char*) mqtt_data);
JsonParserObject message_object = mqtt_json_data.getRootObject();
String mqtt_data_str= message_object.getStr("payload","");
strncpy(reinterpret_cast<char*>(mqtt_data),mqtt_data_str.c_str(),data_len);
mqtt_data[data_len] = 0;
#else
// for Azure, we read the topic from the property of the message
String fullTopicString = String(mqtt_topic);
String toppicUpper = fullTopicString;
toppicUpper.toUpperCase();
int startOfTopic = toppicUpper.indexOf("TOPIC=");
if (startOfTopic == -1){
AddLog(LOG_LEVEL_ERROR, PSTR(D_LOG_MQTT "Azure IoT message without the property topic."));
return;
}
String newTopic = fullTopicString.substring(startOfTopic + 6);
newTopic.replace("%2F", "/");
if (newTopic.indexOf("/") == -1){
AddLog(LOG_LEVEL_ERROR, PSTR(D_LOG_MQTT "Invalid Topic %s"), newTopic.c_str());
return;
}
strlcpy(topic, newTopic.c_str(), sizeof(topic));
#endif
#else
strlcpy(topic, mqtt_topic, sizeof(topic));
#endif // USE_MQTT_AZURE_IOT
mqtt_data[data_len] = 0;
if (Mqtt.disable_logging) {
TasmotaGlobal.masterlog_level = LOG_LEVEL_DEBUG_MORE; // Hide logging
}
#ifdef USE_TASMESH
#ifdef ESP32
if (MESHinterceptMQTTonBroker(topic, (uint8_t*)mqtt_data, data_len +1)) {
return; // Check if this is a message for a node
}
#endif // ESP32
#endif // USE_TASMESH
#if MQTT_VERSION == MQTT_VERSION_5_0
// Snapshot request/response metadata before command dispatch. PubSubClient's inbound
// views are reused by the next received PUBLISH, while command handling may call
// MqttClient.loop() recursively. Keeping capture local avoids Arduino generating an
// MQTT5-only type in an unguarded sketch prototype.
MqttCommandContext mqtt_context;
if (MqttClient.protocolVersion() == MQTT_VERSION_5_0) {
const MqttInboundProperties& properties = MqttClient.inboundProperties();
if (properties.valid) {
bool response_topic_valid = properties.responseTopic.present() &&
(properties.responseTopic.len != 0) &&
(properties.responseTopic.len < TOPSZ);
for (uint16_t i = 0; response_topic_valid && (i < properties.responseTopic.len); i++) {
response_topic_valid = (properties.responseTopic.data[i] != '\0') &&
(properties.responseTopic.data[i] != '+') &&