-
Notifications
You must be signed in to change notification settings - Fork 4.9k
/
Copy pathxsns_62_esp32_mi.ino
3000 lines (2807 loc) · 108 KB
/
xsns_62_esp32_mi.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
/*
xsns_62_esp32_mi.ino - MI-BLE-sensors via ESP32 support for Tasmota
enabled by ESP32 && !USE_BLE_ESP32
if (ESP32 && USE_BLE_ESP32) then xsns_62_esp32_mi_ble.ino is used
Copyright (C) 2021 Christian Baars and 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/>.
--------------------------------------------------------------------------------------------
Version yyyymmdd Action Description
--------------------------------------------------------------------------------------------
0.9.5.6 20221006 changed - remove old HASS code, allow adding unknown sensors, prepare YLAI003
-------
0.9.5.5 20220326 changed - refactored connection task for asynchronous op, add response option,
fixed MI32Key command
-------
0.9.5.4 20220325 changed - add Berry adv_watch and adv_block to BLE class
-------
0.9.5.3 20220315 changed - reworked Berry part, active scanning and holding active connections possible, new format of advertisement buffer
-------
0.9.5.1 20220209 changed - rename YEERC to YLYK01, add dimmer YLKG08 (incl. YLKG07), change button report scheme
-------
0.9.5.0 20211016 changed - major rewrite, added mi32cfg (file and command), Homekit-Bridge,
extended GUI,
removed BLOCK, PERIOD, TIME, UNIT, BATTERY and PAGE -> replaced via Berry-Support
-------
0.9.1.7 20201116 changed - small bugfixes, add BLOCK and OPTION command, send BLE scan via MQTT
-------
0.9.1.0 20200712 changed - add lights and YLYK01, add pure passive mode with decryption,
lots of refactoring
-------
0.9.0.1 20200706 changed - adapt to new NimBLE-API, tweak scan process
-------
0.9.0.0 20200413 started - initial development by Christian Baars
forked - from arendst/tasmota - https://github.com/arendst/Tasmota
*/
#ifndef USE_BLE_ESP32
#ifdef ESP32 // ESP32 only. Use define USE_HM10 for ESP8266 support
#if defined CONFIG_IDF_TARGET_ESP32 || defined CONFIG_IDF_TARGET_ESP32C3 || defined CONFIG_IDF_TARGET_ESP32C2 || defined CONFIG_IDF_TARGET_ESP32C6 || defined CONFIG_IDF_TARGET_ESP32S3
#ifdef USE_MI_ESP32
#ifdef USE_ENERGY_SENSOR
// #define USE_MI_ESP32_ENERGY //prepare for some GUI extensions
#endif
#define XSNS_62 62
#include <vector>
#include "freertos/ringbuf.h"
#include <t_bearssl.h>
#include "include/xsns_62_esp32_mi.h"
#include "services/gap/ble_svc_gap.h"
void MI32notifyCB(NimBLERemoteCharacteristic* pRemoteCharacteristic, uint8_t* pData, size_t length, bool isNotify);
void MI32AddKey(mi_bindKey_t keyMAC);
void MI32HandleEveryDevice(NimBLEAdvertisedDevice* advertisedDevice, uint8_t addr[6], int RSSI);
std::vector<mi_sensor_t> MIBLEsensors;
RingbufHandle_t BLERingBufferQueue = nullptr;
static BLEScan* MI32Scan;
static NimBLEClient* MI32Client;
/*********************************************************************************************\
* BLE Callback Classes
\*********************************************************************************************/
class MI32SensorCallback : public NimBLEClientCallbacks {
void onConnect(NimBLEClient* pclient) {
// AddLog(LOG_LEVEL_DEBUG,PSTR("connected %s"), MI32getDeviceName(MI32.conCtx->slot));
MI32.infoMsg = MI32_DID_CONNECT;
MI32.mode.willConnect = 0;
MI32.mode.connected = 1;
pclient->updateConnParams(8,16,0,1000);
}
void onDisconnect(NimBLEClient* pclient, int reason) {
MI32.mode.connected = 0;
MI32.infoMsg = MI32_DID_DISCONNECT;
MI32.conCtx->error = reason;
MI32.conCtx->operation = 5; //set for all disconnects that come from the remote device or connection loss
MI32.mode.triggerBerryConnCB = 1;
//AddLog(LOG_LEVEL_DEBUG,PSTR("disconnected"));
}
};
class MI32AdvCallbacks: public NimBLEScanCallbacks {
void onScanEnd(NimBLEScanResults results) {
MI32.infoMsg = MI32_SCAN_ENDED;
MI32.mode.runningScan = 0;
MI32.mode.deleteScanTask = 1; // if scan ended dew to a BLE controller error, make sure we stop the task
}
void IRAM_ATTR onResult(NimBLEAdvertisedDevice* advertisedDevice) {
static bool _mutex = false;
if(_mutex) return;
_mutex = true;
int RSSI = advertisedDevice->getRSSI();
uint8_t addr[6];
memcpy(addr,advertisedDevice->getAddress().getNative(),6);
MI32_ReverseMAC(addr);
size_t ServiceDataLength = 0;
if(MI32.beAdvCB != nullptr && MI32.mode.triggerBerryAdvCB == 0){
berryAdvPacket_t *_packet = (berryAdvPacket_t *)MI32.beAdvBuf;
memcpy(_packet->MAC,addr,6);
_packet->addressType = advertisedDevice->getAddressType();
_packet->RSSI = (uint8_t)RSSI;
uint8_t *_payload = advertisedDevice->getPayload();
_packet->length = advertisedDevice->getPayloadLength();
memcpy(_packet->payload,_payload, _packet->length);
MI32.mode.triggerBerryAdvCB = 1;
}
if (advertisedDevice->getServiceDataCount() == 0) {
if(MI32.option.handleEveryDevice == 1) {
MI32HandleEveryDevice(advertisedDevice, addr, RSSI);
}
_mutex = false;
return;
}
uint16_t UUID = advertisedDevice->getServiceDataUUID(0).getNative()->u16.value;
ServiceDataLength = advertisedDevice->getServiceData(0).length();
if(UUID==0xfe95) {
MI32ParseResponse((char*)advertisedDevice->getServiceData(0).data(),ServiceDataLength, addr, RSSI);
}
else if(UUID==0xfcd2) {
std::string optionalName = advertisedDevice->getName();
MI32parseBTHomePacket((char*)advertisedDevice->getServiceData(0).data(),ServiceDataLength, addr, RSSI, optionalName.c_str());
}
else if(UUID==0xfdcd) { // deprecated
MI32parseCGD1Packet((char*)advertisedDevice->getServiceData(0).data(),ServiceDataLength, addr, RSSI);
}
else if(UUID==0x181a) { //ATC and PVVX - deprecated, change FW setting of these devices to BTHome V2
MI32ParseATCPacket((char*)advertisedDevice->getServiceData(0).data(),ServiceDataLength, addr, RSSI);
}
else if(MI32.option.handleEveryDevice == 1) {
MI32HandleEveryDevice(advertisedDevice, addr, RSSI);
}
_mutex = false;
};
};
class MI32ServerCallbacks: public NimBLEServerCallbacks {
void onConnect(NimBLEServer* pServer, NimBLEConnInfo& connInfo) {
struct{
BLERingBufferItem_t header;
uint8_t buffer[6];
} item;
item.header.length = 6;
item.header.type = BLE_OP_ON_CONNECT;
memcpy(item.buffer,connInfo.getAddress().getNative(),6);
xRingbufferSend(BLERingBufferQueue, (const void*)&item, sizeof(BLERingBufferItem_t) + 6 , pdMS_TO_TICKS(1));
MI32.infoMsg = MI32_SERV_CLIENT_CONNECTED;
};
void onDisconnect(NimBLEServer* pServer, NimBLEConnInfo& connInfo, int reason) {
struct{
BLERingBufferItem_t header;
} item;
item.header.length = 0;
item.header.type = BLE_OP_ON_DISCONNECT;
memset(MI32.conCtx->MAC,0,6);
xRingbufferSend(BLERingBufferQueue, (const void*)&item, sizeof(BLERingBufferItem_t), pdMS_TO_TICKS(1));
MI32.infoMsg = MI32_SERV_CLIENT_DISCONNECTED;
#ifdef CONFIG_BT_NIMBLE_EXT_ADV
NimBLEDevice::startAdvertising(0);
#else
NimBLEDevice::startAdvertising();
#endif
};
void onAuthenticationComplete(const NimBLEConnInfo& connInfo) {
struct{
BLERingBufferItem_t header;
uint8_t buffer[sizeof(ble_store_value_sec)];
} item;
item.header.length = sizeof(ble_store_value_sec);
item.header.type = BLE_OP_ON_AUTHENTICATED;
ble_store_value_sec value_sec;
ble_sm_read_bond(connInfo.getConnHandle(), &value_sec);
memcpy(item.buffer,(uint8_t*)&value_sec,sizeof(ble_store_value_sec));
xRingbufferSend(BLERingBufferQueue, (const void*)&item, sizeof(BLERingBufferItem_t), pdMS_TO_TICKS(1));
MI32.infoMsg = MI32_SERV_CLIENT_AUTHENTICATED;
}
};
class MI32CharacteristicCallbacks: public NimBLECharacteristicCallbacks {
void onRead(NimBLECharacteristic* pCharacteristic, NimBLEConnInfo& connInfo){
struct{
BLERingBufferItem_t header;
} item;
item.header.length = 0;
item.header.type = BLE_OP_ON_READ;
item.header.returnCharUUID = pCharacteristic->getUUID().getNative()->u16.value;
item.header.handle = pCharacteristic->getHandle();
xRingbufferSend(BLERingBufferQueue, (const void*)&item, sizeof(BLERingBufferItem_t), pdMS_TO_TICKS(1));
};
void onWrite(NimBLECharacteristic* pCharacteristic, NimBLEConnInfo& connInfo) {
struct{
BLERingBufferItem_t header;
uint8_t buffer[255];
} item;
item.header.length = pCharacteristic->getDataLength();;
item.header.type = BLE_OP_ON_WRITE;
item.header.returnCharUUID = pCharacteristic->getUUID().getNative()->u16.value;
item.header.handle = pCharacteristic->getHandle();
memcpy(item.buffer,pCharacteristic->getValue(),pCharacteristic->getDataLength());
xRingbufferSend(BLERingBufferQueue, (const void*)&item, sizeof(BLERingBufferItem_t) + item.header.length , pdMS_TO_TICKS(1));
};
/** The status returned in status is defined in NimBLECharacteristic.h.
* The value returned in code is the NimBLE host return code.
*/
void onStatus(NimBLECharacteristic* pCharacteristic, int code) {
struct{
BLERingBufferItem_t header;
uint8_t buffer[4];
} item;
item.header.length = 4;
item.header.type = BLE_OP_ON_STATUS;
item.header.returnCharUUID = pCharacteristic->getUUID().getNative()->u16.value;
item.header.handle = pCharacteristic->getHandle();
xRingbufferSend(BLERingBufferQueue, (const void*)&item, sizeof(BLERingBufferItem_t) + 4, pdMS_TO_TICKS(1));
};
void onSubscribe(NimBLECharacteristic* pCharacteristic, NimBLEConnInfo& connInfo, uint16_t subValue) {
struct{
BLERingBufferItem_t header;
} item;
item.header.length = 0;
item.header.type = BLE_OP_ON_UNSUBSCRIBE + subValue;;
item.header.returnCharUUID = pCharacteristic->getUUID().getNative()->u16.value;
item.header.handle = pCharacteristic->getHandle();
xRingbufferSend(BLERingBufferQueue, (const void*)&item, sizeof(BLERingBufferItem_t), pdMS_TO_TICKS(1));
};
};
void MI32notifyCB(NimBLERemoteCharacteristic* pRemoteCharacteristic, uint8_t* pData, size_t length, bool isNotify){
if(isNotify){
struct{
BLERingBufferItem_t header;
uint8_t buffer[255];
} item;
item.header.length = length;
// item.header.type = 103; does not matter for now
memcpy(item.buffer,pData,length);
item.header.returnCharUUID = pRemoteCharacteristic->getUUID().getNative()->u16.value;
item.header.handle = pRemoteCharacteristic->getHandle();
xRingbufferSend(BLERingBufferQueue, (const void*)&item, sizeof(BLERingBufferItem_t) + length , pdMS_TO_TICKS(5));
MI32.mode.readingDone = 1;
MI32.infoMsg = MI32_GOT_NOTIFICATION;
return;
}
}
static MI32AdvCallbacks MI32ScanCallbacks;
static MI32SensorCallback MI32SensorCB;
static MI32CharacteristicCallbacks MI32ChrCallback;
/*********************************************************************************************\
* Helper functions
\*********************************************************************************************/
/**
* @brief Remove all colons from null terminated char array
*
* @param _string Typically representing a MAC-address like AA:BB:CC:DD:EE:FF
*/
void MI32stripColon(char* _string){
uint32_t _length = strlen(_string);
uint32_t _index = 0;
while (_index < _length) {
char c = _string[_index];
if(c==':'){
memmove(_string+_index,_string+_index+1,_length-_index);
}
_index++;
}
_string[_index] = 0;
}
/**
* @brief Convert string that represents a hexadecimal number to a byte array
*
* @param _string input string in format: AABBCCDDEEFF or AA:BB:CC:DD:EE:FF, case insensitive
* @param _mac target byte array must match the correct size (i.e. AA:BB -> uint8_t bytes[2])
*/
void MI32HexStringToBytes(char* _string, uint8_t* _byteArray) {
MI32stripColon(_string);
UpperCase(_string,_string);
uint32_t index = 0;
uint32_t _end = strlen(_string);
memset(_byteArray,0,_end/2);
while (index < _end) {
char c = _string[index];
uint8_t value = 0;
if(c >= '0' && c <= '9')
value = (c - '0');
else if (c >= 'A' && c <= 'F')
value = (10 + (c - 'A'));
_byteArray[(index/2)] += value << (((index + 1) % 2) * 4);
index++;
}
}
/**
* @brief Reverse an array of 6 bytes
*
* @param _mac a byte array of size 6 (typically representing a MAC address)
*/
void MI32_ReverseMAC(uint8_t _mac[]){
uint8_t _reversedMAC[6];
for (uint8_t i=0; i<6; i++){
_reversedMAC[5-i] = _mac[i];
}
memcpy(_mac,_reversedMAC, sizeof(_reversedMAC));
}
void MI32AddKey(mi_bindKey_t keyMAC){
bool unknownMAC = true;
uint32_t _slot = 0;
for(auto &_sensor : MIBLEsensors){
if(memcmp(keyMAC.MAC,_sensor.MAC,sizeof(keyMAC.MAC))==0){
_sensor.key = new uint8_t[16];
memcpy(_sensor.key,keyMAC.key,16);
unknownMAC=false;
_sensor.status.hasWrongKey = 0;
AddLog(LOG_LEVEL_INFO,PSTR("add key to %s"),MI32getDeviceName(_slot));
}
_slot++;
}
if(unknownMAC){
AddLog(LOG_LEVEL_ERROR,PSTR("M32: unknown MAC"));
}
}
/**
* @brief Decrypts payload in place
*
* @param _buf - pointer to the buffer at position of PID
* @param _bufSize - buffersize (last position is two bytes behind last byte of TAG)
* @param _payload - target buffer
* @param _slot - sensor slot in the global vector
* @return int - error code, 0 for success
*/
int MI32_decryptPacket(char * _buf, uint16_t _bufSize, uint8_t * _payload, uint32 _slot){
// int32_t start = _getCycleCount();
mi_beacon_t *_beacon = (mi_beacon_t *)_buf;
uint8_t nonce[13]; //v3:13, v5:12
uint32_t nonceLen = 12; // most devices are v5
uint8_t tag[4] = {0};
const unsigned char authData[1] = {0x11};
size_t dataLen = _bufSize - 11 ; // _bufsize - frame - type - frame.counter - MAC
if(MIBLEsensors[_slot].key == nullptr){
// AddLog(LOG_LEVEL_DEBUG,PSTR("M32: No Key found !!"));
return -2;
}
uint32_t _version = (uint32_t)_beacon->frame.version;
// AddLog(LOG_LEVEL_DEBUG,PSTR("M32: encrypted msg from %s with version:%u"),MI32getDeviceName(_slot),_version);
if(_version == 5){
if(_beacon->frame.includesMAC){
for (uint32_t i = 0; i<6; i++){
nonce[i] = _beacon->MAC[i];
}
// AddLog(LOG_LEVEL_DEBUG,PSTR("M32: has MAC"));
memcpy(_payload,(uint8_t*)&_beacon->capability, dataLen); //special packet
dataLen -= 7;
}
else{
// AddLog(LOG_LEVEL_DEBUG,PSTR("M32: has no MAC"));
for (uint32_t i = 0; i<6; i++){
nonce[i] = MIBLEsensors[_slot].MAC[5-i];
}
dataLen = _bufSize -5 ;
memcpy(_payload,_beacon->MAC, dataLen); //special packet
dataLen -= 7;
// AddLogBuffer(LOG_LEVEL_DEBUG,(uint8_t*) _payload, dataLen);
}
// nonce: device MAC, device type, frame cnt, ext. cnt
memcpy((uint8_t*)&nonce+6,(uint8_t*)&_beacon->productID,2);
nonce[8] = _beacon->counter;
memcpy((uint8_t*)&nonce+9,(uint8_t*)&_payload[dataLen],3);
// memcpy((uint8_t*)&tag,(uint8_t*)&_payload[dataLen-4],4);
memcpy((uint8_t*)&tag,(uint8_t*)&_buf[_bufSize-4],4);
}
else if(_version == 3){
// nonce: frame_ctrl, device type, ext. cnt, frame cnt, device MAC(only first 5 bytes)
memcpy(_payload,(uint8_t*)&_beacon->capability, dataLen); //special packet
nonceLen = 13;
memcpy((uint8_t*)&nonce,(uint8_t*)&_beacon->frame,2);
memcpy((uint8_t*)&nonce+2,(uint8_t*)&_beacon->productID,2);
nonce[4] = _beacon->counter;
memcpy((uint8_t*)&nonce+5,(uint8_t*)&_buf[_bufSize-4],3);
for (uint32_t i = 0; i<5; i++){
nonce[i+8] = _beacon->MAC[i];
}
// tag[0] = _buf[_bufSize-1]; // it is unclear, if this value is a checksum
dataLen -= 4;
}
else{
AddLog(LOG_LEVEL_DEBUG,PSTR("M32: unexpected decryption version:%u"),_version); // should never happen
}
br_aes_small_ctrcbc_keys keyCtx;
br_aes_small_ctrcbc_init(&keyCtx, MIBLEsensors[_slot].key, 16);
br_ccm_context ctx;
br_ccm_init(&ctx, &keyCtx.vtable);
br_ccm_reset(&ctx, nonce, nonceLen, sizeof(authData), dataLen, sizeof(tag));
br_ccm_aad_inject(&ctx, authData, sizeof(authData));
br_ccm_flip(&ctx);
br_ccm_run(&ctx, 0, _payload, dataLen);
if(br_ccm_check_tag(&ctx, &tag)) return 0;
// AddLog(LOG_LEVEL_DEBUG,PSTR("M32: decrypted in %2_f mSec"), &enctime);
// AddLogBuffer(LOG_LEVEL_DEBUG,(uint8_t*) _payload, dataLen);
if(_version == 3 && _payload[1] == 0x10) return 0; // no known way to really verify decryption, but 0x10 is expected here for button events
return -1; // wrong key ... maybe corrupt data packet too
}
/*********************************************************************************************\
* common functions
\*********************************************************************************************/
/**
* @brief Return the slot number of a known sensor or return create new sensor slot
*
* @param _MAC BLE address of the sensor
* @param _type Type number of the sensor
* @return uint32_t Known or new slot in the sensors-vector
*/
uint32_t MIBLEgetSensorSlot(uint8_t * _MAC, uint16_t _type, uint8_t counter){
DEBUG_SENSOR_LOG(PSTR("%s: will test ID-type: %x"),D_CMND_MI32, _type);
uint16_t _pid = _type; // save for unknown types
bool _success = false;
for (uint32_t i=0;i<MI32_TYPES;i++){ // i < sizeof(kMI32DeviceID) gives compiler warning
if(_type == kMI32DeviceID[i]){
DEBUG_SENSOR_LOG(PSTR("M32: ID is type %u"), i);
_type = i+1;
_success = true;
}
}
if(!_success) _type = UNKNOWN_MI;
DEBUG_SENSOR_LOG(PSTR("%s: vector size %u"),D_CMND_MI32, MIBLEsensors.size());
for(uint32_t i=0; i<MIBLEsensors.size(); i++){
if(memcmp(_MAC,MIBLEsensors[i].MAC,6)==0){
DEBUG_SENSOR_LOG(PSTR("%s: known sensor at slot: %u"),D_CMND_MI32, i);
MIBLEsensors[i].lastTime = Rtc.local_time;
// AddLog(LOG_LEVEL_DEBUG,PSTR("Counters: %x %x"),MIBLEsensors[i].lastCnt, counter);
if(MIBLEsensors[i].lastCnt==counter && counter!=0) {
// AddLog(LOG_LEVEL_DEBUG,PSTR("Old packet"));
return 0xff; // packet received before, stop here
}
return i;
}
DEBUG_SENSOR_LOG(PSTR("%s: i: %x %x %x %x %x %x"),D_CMND_MI32, MIBLEsensors[i].MAC[5], MIBLEsensors[i].MAC[4],MIBLEsensors[i].MAC[3],MIBLEsensors[i].MAC[2],MIBLEsensors[i].MAC[1],MIBLEsensors[i].MAC[0]);
DEBUG_SENSOR_LOG(PSTR("%s: n: %x %x %x %x %x %x"),D_CMND_MI32, _MAC[5], _MAC[4], _MAC[3],_MAC[2],_MAC[1],_MAC[0]);
}
if(MI32.mode.didGetConfig || MIBLEsensors.size() > 31){ // web UI is currently limited to 32
DEBUG_SENSOR_LOG(PSTR("M32: ignore new sensor, because of loaded config"));
return 0xff; //discard the data
}
DEBUG_SENSOR_LOG(PSTR("%s: found new sensor"),D_CMND_MI32);
mi_sensor_t _newSensor{};
memcpy(_newSensor.MAC,_MAC, 6);
_newSensor.PID = _pid;
_newSensor.type = _type;
_newSensor.eventType.raw = 0;
_newSensor.feature.raw = 0;
_newSensor.status.raw = 0;
_newSensor.temp = NAN;
_newSensor.bat=0x00;
_newSensor.RSSI=0;
_newSensor.lux = 0x00ffffff;
_newSensor.key = nullptr;
_newSensor.lastTime = Rtc.local_time;
switch (_type)
{
case UNKNOWN_MI: case BTHOME:
_newSensor.feature.raw = 0;
break;
case FLORA:
_newSensor.moisture =0xff;
_newSensor.fertility =0xffff;
_newSensor.firmware[0]='\0';
_newSensor.feature.temp=1;
_newSensor.feature.moist=1;
_newSensor.feature.fert=1;
_newSensor.feature.lux=1;
_newSensor.feature.bat=1;
break;
case NLIGHT:
_newSensor.events=0x00;
_newSensor.feature.motion=1;
_newSensor.feature.NMT=1;
_newSensor.NMT=0;
break;
case MJYD2S:
_newSensor.NMT=0;
_newSensor.events=0x00;
_newSensor.feature.motion=1;
_newSensor.feature.NMT=1;
_newSensor.feature.lux=1;
_newSensor.feature.bat=1;
_newSensor.NMT=0;
break;
case YLYK01: case YLKG08: case YLAI003:
_newSensor.feature.Btn = 1;
_newSensor.Btn = 99;
if(_type == YLKG08){
_newSensor.feature.knob = 1;
_newSensor.dimmer = 0;
}
break;
case MCCGQ02:
_newSensor.events=0x00;
_newSensor.feature.bat=1;
_newSensor.feature.door=1;
_newSensor.door = 255;
break;
case SJWS01L:
_newSensor.feature.leak=1;
_newSensor.feature.bat=1;
_newSensor.feature.Btn=1;
_newSensor.Btn=99;
break;
default:
_newSensor.hum=NAN;
_newSensor.feature.temp=1;
_newSensor.feature.hum=1;
_newSensor.feature.tempHum=1;
_newSensor.feature.bat=1;
break;
}
MIBLEsensors.push_back(_newSensor);
AddLog(LOG_LEVEL_DEBUG,PSTR("M32: new %s at slot: %u"),MI32getDeviceName(MIBLEsensors.size()-1),MIBLEsensors.size()-1);
MI32.mode.shallShowStatusInfo = 1;
return MIBLEsensors.size()-1;
};
/**
* @brief trigger real-time message for motion or RC
*
*/
void MI32triggerTele(void){
MI32.mode.triggeredTele = 1;
MqttPublishSensor();
XdrvRulesProcess(0);
}
#ifdef USE_MI_EXT_GUI
/**
* @brief Saves a sensor value mapped to the graph range of 0-20 pixel, this function automatically reads the actual hour from system time
*
* @param history - pointer to uint8_t[23]
* @param value - value as float, this
* @param type - internal type. for BLE: 0 - temperature, 1 - humidity, 2 - illuminance, for internal sensors: 100 - wattage
*/
void MI32addHistory(uint8_t history[24], float value, const uint32_t type){
const uint32_t _hour = (LocalTime()%SECS_PER_DAY)/SECS_PER_HOUR;
// AddLog(LOG_LEVEL_DEBUG,PSTR("M32: history hour: %u"),_hour);
switch(type){
case 0: //temperature
history[_hour] = ((((value + 5.0f)/4) + 1) + 0b10000000); //temp
break;
case 1: //humidity
history[_hour] = (((value/5.0f) + 1) + 0b10000000) ; //hum
break;
case 2: //light
if(value>100.0f) value=100.0f; //clamp it for now
history[_hour] = (((value/5.0f) + 1) + 0b10000000); //lux
// AddLog(LOG_LEVEL_DEBUG,PSTR("M32: history lux: %u in hour:%u"),history[_hour], _hour);
break;
case 3: //BLE device sighting
uint16_t sightings = history[_hour] & 0b01111111;
if(sightings<20){
history[_hour] = (sightings | 0b10000000) + 1;
// AddLog(LOG_LEVEL_DEBUG,PSTR("M32: history sighting: %u in hour:%u"),history[_hour], _hour);
}
break;
#ifdef USE_MI_ESP32_ENERGY
case 100: // energy
if(value == 0.0f) value = 1.0f;
const uint8_t _watt = ((MI32ln(value)*2) + 0b10000000); //watt
history[_hour] = _watt;
// AddLog(LOG_LEVEL_DEBUG,PSTR("M32: history energy: %u for value:%u"),history[_hour], value); //still playing with the mapping
break;
#endif //USE_MI_ESP32_ENERGY
}
}
/**
* @brief Returns a value between 0-21 for use as a data point in the history graph of the extended web UI
*
* @param history - pointer to uint8_t[23]
* @param hour - hour of datapoint
* @return uint8_t - value for the y-axis, should be between 0-21
*/
uint8_t MI32fetchHistory(uint8_t history[24], uint32_t hour){
if((hour>23 || bitRead(history[hour],7)) == 0) {
return 0; //invalidated data
}
return (history[hour]) - 0b10000000;
}
/**
* @brief Invalidates the history data of the following hour by setting MSB to 0, should be called at FUNC_JSON_APPEND
*
*/
void Mi32invalidateOldHistory(){
uint32_t _hour = (LocalTime()%SECS_PER_DAY)/SECS_PER_HOUR;
static uint32_t _lastInvalidatedHour = 99;
if (_lastInvalidatedHour == _hour){
return;
}
uint32_t _nextHour = (_hour>22)?0:_hour+1;
for(auto &_sensor:MIBLEsensors){
if(_sensor.feature.temp == 1){
bitClear(_sensor.temp_history[_nextHour],7);
}
if(_sensor.feature.hum == 1){
bitClear(_sensor.hum_history[_nextHour],7);
}
if(_sensor.feature.lux == 1){
bitClear(_sensor.lux_history[_nextHour],7);
}
if(_sensor.feature.payload == 1){
bitClear(_sensor.temp_history[_nextHour],7);
}
}
_lastInvalidatedHour = _hour;
}
#endif //USE_MI_EXT_GUI
/*********************************************************************************************\
* init NimBLE
\*********************************************************************************************/
void MI32PreInit(void) {
MI32.mode.init = false;
//test section for options
MI32.option.allwaysAggregate = 1;
MI32.option.noSummary = 0;
MI32.option.directBridgeMode = 0;
MI32.option.ignoreBogusBattery = 1; // from advertisements
MI32.option.handleEveryDevice = 0; // scan for every BLE device with a public address
MI32loadCfg();
if(MIBLEsensors.size()>0){
MI32.mode.didGetConfig = 1;
}
MI32.beAdvCB = nullptr;
AddLog(LOG_LEVEL_INFO,PSTR("M32: pre-init"));
}
void MI32Init(void) {
if (MI32.mode.init) { return; }
if (TasmotaGlobal.global_state.wifi_down && TasmotaGlobal.global_state.eth_down) {
if (!(WIFI_MANAGER == Wifi.config_type || WIFI_MANAGER_RESET_ONLY == Wifi.config_type)) return;
}
if (!TasmotaGlobal.global_state.wifi_down) {
TasmotaGlobal.wifi_stay_asleep = true;
if (WiFi.getSleep() == false) {
AddLog(LOG_LEVEL_DEBUG,PSTR("M32: Put WiFi modem in sleep mode"));
WiFi.setSleep(true); // Sleep
}
}
if (!MI32.mode.init) {
#ifdef CONFIG_BTDM_BLE_SCAN_DUPL
// NimBLEDevice::setScanFilterMode(2); //CONFIG_BTDM_SCAN_DUPL_TYPE_DATA_DEVICE
// NimBLEDevice::setScanDuplicateCacheSize(10); // will not be perfect for every situation (few vs many BLE devices nearby)
#endif
const std::string name(TasmotaGlobal.hostname);
NimBLEDevice::init(name);
#ifdef CONFIG_BT_NIMBLE_NVS_PERSIST
NimBLEDevice::setSecurityAuth(true, true, true);
#else
NimBLEDevice::setSecurityAuth(false, true, true);
#endif
AddLog(LOG_LEVEL_INFO,PSTR("M32: Init BLE device: %s"),TasmotaGlobal.hostname);
MI32.mode.init = 1;
MI32.mode.readyForNextConnJob = 1;
MI32StartTask(MI32_TASK_SCAN); // Let's get started !!
}
return;
}
/*********************************************************************************************\
* Berry section - partly used by HomeKit too
\*********************************************************************************************/
extern "C" {
bool MI32checkBLEinitialization(){
return (MI32.mode.init && Settings->flag5.mi32_enable);
}
void MI32BerryLoop(){
MI32BLELoop();
}
bool MI32runBerryConfig(uint16_t operation){
bool success = false;
#ifdef CONFIG_BT_NIMBLE_EXT_ADV
NimBLEExtAdvertising *pAdvertising = NimBLEDevice::getAdvertising();
#else
NimBLEAdvertising *pAdvertising = NimBLEDevice::getAdvertising();
#endif
if(pAdvertising == nullptr){
return success;
}
switch(operation){
case 231: // set address
pAdvertising->stop();
if(MI32.conCtx->addrType > 0){
ble_hs_id_set_rnd(MI32.conCtx->MAC);
AddLog(LOG_LEVEL_DEBUG,PSTR("BLE: set MAC to random"));
}
NimBLEDevice::setOwnAddrType(MI32.conCtx->addrType);
success = true;
break;
case 232: // set adv params via bytes() descriptor of size 5,
#ifndef CONFIG_BT_NIMBLE_EXT_ADV
if(MI32.conCtx->buffer[0] == 5){
uint16_t itvl_min = MI32.conCtx->buffer[2] + (MI32.conCtx->buffer[3] << 8);
uint16_t itvl_max = MI32.conCtx->buffer[4] + (MI32.conCtx->buffer[5] << 8);
pAdvertising->setAdvertisementType(MI32.conCtx->buffer[1]);
pAdvertising->setMinInterval(itvl_min);
pAdvertising->setMaxInterval(itvl_max);
AddLog(LOG_LEVEL_DEBUG,PSTR("BLE: adv params: type: %u, min: %u, max: %u"),MI32.conCtx->buffer[1], (uint16_t)(itvl_min * 0.625), (uint16_t)(itvl_max * 0.625)) ;
success = true;
}
#endif //CONFIG_BT_NIMBLE_EXT_ADV
break;
case 233:
int ret = ble_svc_gap_device_name_set((const char*)MI32.conCtx->buffer + 1);
AddLog(LOG_LEVEL_DEBUG,PSTR("BLE: new gap device name - %s"),(const char*) MI32.conCtx->buffer + 1);
success = (ret == 0);
break;
}
return success;
}
bool MI32runBerryServer(uint16_t operation){
if(operation > 230){
return MI32runBerryConfig(operation);
}
MI32.conCtx->operation = operation;
AddLog(LOG_LEVEL_DEBUG,PSTR("BLE: Berry server op: %d, response: %u"),MI32.conCtx->operation, MI32.conCtx->response);
if(MI32.mode.readyForNextServerJob == 0){
MI32.mode.triggerNextServerJob = 0;
AddLog(LOG_LEVEL_DEBUG,PSTR("M32: old server job not finished yet!!"));
return false;
}
MI32.mode.triggerNextServerJob = 1;
return true;
}
bool MI32runBerryConnection(uint8_t operation, bool response, int32_t* arg1){
if(MI32.conCtx != nullptr){
if(arg1 != nullptr){
MI32.conCtx->arg1 = *arg1;
MI32.conCtx->hasArg1 = true;
AddLog(LOG_LEVEL_DEBUG,PSTR("BLE: arg1: %u"),MI32.conCtx->arg1);
}
else{
MI32.conCtx->hasArg1 = false;
}
MI32.conCtx->response = response;
if(operation > 200){
return MI32runBerryServer(operation);
}
MI32.conCtx->oneOp = (operation > 9);
MI32.conCtx->operation = operation%10;
AddLog(LOG_LEVEL_DEBUG,PSTR("BLE: Berry connection op: %d, addrType: %d, oneOp: %u, response: %u"),MI32.conCtx->operation, MI32.conCtx->addrType, MI32.conCtx->oneOp, MI32.conCtx->response);
if(MI32.conCtx->oneOp){
MI32StartConnectionTask();
}
else{
if(MI32.mode.connected){
AddLog(LOG_LEVEL_DEBUG,PSTR("BLE: continue connection job"));
MI32.mode.triggerNextConnJob = 1;
if(!MI32.mode.readyForNextConnJob){
AddLog(LOG_LEVEL_DEBUG,PSTR("BLE: old connection job not finished yet!!"));
}
}
else{
MI32StartConnectionTask(); //first job of many or unexpected disconnect
}
}
return true;
}
return false;
}
void MI32setBerryConnCB(void* function, uint8_t *buffer){
if(MI32.conCtx == nullptr){
MI32.conCtx = new MI32connectionContextBerry_t;
}
MI32.conCtx->buffer = buffer;
MI32.beConnCB = function;
AddLog(LOG_LEVEL_INFO,PSTR("BLE: Connection Ctx created"));
}
void MI32setBerryServerCB(void* function, uint8_t *buffer){
if(function == nullptr || buffer == nullptr)
{
MI32.mode.deleteServerTask = 1;
MI32.beServerCB = nullptr;
AddLog(LOG_LEVEL_INFO,PSTR("BLE: Server session stopping"));
return;
}
if(MI32.conCtx == nullptr){
MI32.conCtx = new MI32connectionContextBerry_t;
}
MI32.conCtx->buffer = buffer;
MI32.beServerCB = function;
MI32StartTask(MI32_TASK_SERV);
AddLog(LOG_LEVEL_INFO,PSTR("BLE: Server Ctx created"));
}
bool MI32setBerryCtxSvc(const char *Svc, bool discoverAttributes){
if(MI32.conCtx != nullptr){
MI32.conCtx->serviceUUID = NimBLEUUID(Svc);
AddLog(LOG_LEVEL_DEBUG,PSTR("M32: SVC: %s"),MI32.conCtx->serviceUUID.toString().c_str());
MI32.mode.discoverAttributes = discoverAttributes;
return true;
}
return false;
}
bool MI32setBerryCtxChr(const char *Chr){
if(MI32.conCtx != nullptr){
MI32.conCtx->charUUID = NimBLEUUID(Chr);
AddLog(LOG_LEVEL_DEBUG,PSTR("M32: CHR: %s"),MI32.conCtx->charUUID.toString().c_str());
uint16_t _uuid = MI32.conCtx->charUUID.getNative()->u16.value; //if not "notify op" -> present requested characteristic as return UUID
MI32.conCtx->returnCharUUID = _uuid;
AddLog(LOG_LEVEL_DEBUG,PSTR("M32: return 16-bit UUID: %04x"),MI32.conCtx->returnCharUUID);
return true;
}
return false;
}
bool MI32setBerryCtxMAC(uint8_t *MAC, uint8_t type){
if(MI32.conCtx != nullptr){
memcpy(MI32.conCtx->MAC,MAC,6);
if(type<4) MI32.conCtx->addrType = type;
else MI32.conCtx->addrType = 0;
return true;
}
return false;
}
void MI32setBerryAdvCB(void* function, uint8_t *buffer){
MI32.beAdvCB = function;
MI32.beAdvBuf = buffer;
}
bool MI32addMACtoBlockList(uint8_t *MAC, uint8_t type){
NimBLEDevice::addIgnored(NimBLEAddress(MAC,type));
return NimBLEDevice::isIgnored(NimBLEAddress(MAC,type));
}
bool MI32addMACtoWatchList(uint8_t *MAC, uint8_t type){
NimBLEAddress _newAddress = NimBLEAddress(MAC,type);
if(MI32Scan==nullptr){
if(!NimBLEDevice::whiteListAdd(_newAddress)){
return false;
}
}
else{
bool _runningScan = MI32Scan->stop();
if(NimBLEDevice::whiteListAdd(_newAddress)){
MI32Scan->setFilterPolicy(BLE_HCI_SCAN_FILT_USE_WL);
if(_runningScan) MI32Scan->start(0, false);
}
else {
if(_runningScan) MI32Scan->start(0, false);
return false;
}
}
AddLog(LOG_LEVEL_DEBUG,PSTR("M32: add %s to watchlist of size: %u"),_newAddress.toString().c_str(),NimBLEDevice::getWhiteListCount());
return true;
}
void MI32setBatteryForSlot(uint32_t slot, uint8_t value){
if(slot>MIBLEsensors.size()-1) return;
if(MIBLEsensors[slot].feature.bat){
MIBLEsensors[slot].bat = value;
}
}
void MI32setHumidityForSlot(uint32_t slot, float value){
if(slot>MIBLEsensors.size()-1) return;
if(MIBLEsensors[slot].feature.hum){
MIBLEsensors[slot].hum = value;
}
}
void MI32setTemperatureForSlot(uint32_t slot, float value){
if(slot>MIBLEsensors.size()-1) return;
if(MIBLEsensors[slot].feature.temp){
MIBLEsensors[slot].temp = value;
}
}
uint32_t MI32numberOfDevices(){
return MIBLEsensors.size();
}
uint8_t * MI32getDeviceMAC(uint32_t slot){
if(slot>MIBLEsensors.size()-1) return NULL;
return MIBLEsensors[slot].MAC;
}
char * MI32getDeviceName(uint32_t slot){
if(MIBLEsensors[slot].name != nullptr){
return MIBLEsensors[slot].name;
}
static char _name[12];
if( MIBLEsensors[slot].type == UNKNOWN_MI){
if(MIBLEsensors[slot].PID == 0){
snprintf_P(_name,8,PSTR("BLE_%02u"),slot);
} else {
snprintf_P(_name,8,PSTR("MI_%04X"),MIBLEsensors[slot].PID);
}
}
else{
GetTextIndexed(_name, sizeof(_name), MIBLEsensors[slot].type-1, kMI32DeviceType);
}
return _name;
}
void MI32sendBerryWidget() {
if(be_MI32Widget.size != 0) {
WSContentSend(be_MI32Widget.data, be_MI32Widget.size);
be_MI32Widget.data = nullptr;
be_MI32Widget.size = 0;
}
}
} //extern "C"
/*********************************************************************************************\
* Config section
\*********************************************************************************************/
void MI32loadCfg(){
if (TfsFileExists("/mi32cfg")){
MIBLEsensors.reserve(10);
const size_t _buf_size = 2048;
char * _filebuf = (char*)calloc(_buf_size,1);
AddLog(LOG_LEVEL_INFO,PSTR("M32: found config file"));
if(TfsLoadFile("/mi32cfg",(uint8_t*)_filebuf,_buf_size)){
AddLog(LOG_LEVEL_INFO,PSTR("M32: %s"),_filebuf);
JsonParser parser(_filebuf);
JsonParserToken root = parser.getRoot();
if (!root) {AddLog(LOG_LEVEL_INFO,PSTR("M32: invalid root "));}
JsonParserArray arr = root.getArray();
if (!arr) {AddLog(LOG_LEVEL_INFO,PSTR("M32: invalid array object"));; }
bool _error;
int32_t _numberOfDevices;
for (auto _dev : arr) {
AddLog(LOG_LEVEL_INFO,PSTR("M32: found device in config file"));
JsonParserObject _device = _dev.getObject();
uint8_t _mac[6];