forked from rstrouse/ESPSomfy-RTS
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSomfy.cpp
2505 lines (2468 loc) · 104 KB
/
Somfy.cpp
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
#include <Preferences.h>
#include <ELECHOUSE_CC1101_SRC_DRV.h>
#include <SPI.h>
#include "Utils.h"
#include "ConfigSettings.h"
#include "Somfy.h"
#include "Sockets.h"
#include "MQTT.h"
#include "ConfigFile.h"
extern Preferences pref;
extern SomfyShadeController somfy;
extern SocketEmitter sockEmit;
extern MQTTClass mqtt;
uint8_t rxmode = 0; // Indicates whether the radio is in receive mode. Just to ensure there isn't more than one interrupt hooked.
#define SYMBOL 640
#if defined(ESP8266)
#define RECEIVE_ATTR ICACHE_RAM_ATTR
#elif defined(ESP32)
#define RECEIVE_ATTR IRAM_ATTR
#else
#define RECEIVE_ATTR
#endif
#define SETMY_REPEATS 35
#define TILT_REPEATS 15
int sort_asc(const void *cmp1, const void *cmp2) {
int a = *((uint8_t *)cmp1);
int b = *((uint8_t *)cmp2);
if(a == b) return 0;
else if(a < b) return -1;
return 1;
}
static int interruptPin = 0;
static uint8_t bit_length = 56;
somfy_commands translateSomfyCommand(const String& string) {
if (string.equalsIgnoreCase("My")) return somfy_commands::My;
else if (string.equalsIgnoreCase("Up")) return somfy_commands::Up;
else if (string.equalsIgnoreCase("MyUp")) return somfy_commands::MyUp;
else if (string.equalsIgnoreCase("Down")) return somfy_commands::Down;
else if (string.equalsIgnoreCase("MyDown")) return somfy_commands::MyDown;
else if (string.equalsIgnoreCase("UpDown")) return somfy_commands::UpDown;
else if (string.equalsIgnoreCase("MyUpDown")) return somfy_commands::MyUpDown;
else if (string.equalsIgnoreCase("Prog")) return somfy_commands::Prog;
else if (string.equalsIgnoreCase("SunFlag")) return somfy_commands::SunFlag;
else if (string.equalsIgnoreCase("StepUp")) return somfy_commands::StepUp;
else if (string.equalsIgnoreCase("StepDown")) return somfy_commands::StepDown;
else if (string.equalsIgnoreCase("Flag")) return somfy_commands::Flag;
else if (string.startsWith("mud") || string.startsWith("MUD")) return somfy_commands::MyUpDown;
else if (string.startsWith("md") || string.startsWith("MD")) return somfy_commands::MyDown;
else if (string.startsWith("ud") || string.startsWith("UD")) return somfy_commands::UpDown;
else if (string.startsWith("mu") || string.startsWith("MU")) return somfy_commands::MyUp;
else if (string.startsWith("su") || string.startsWith("SU")) return somfy_commands::StepUp;
else if (string.startsWith("sd") || string.startsWith("SD")) return somfy_commands::StepDown;
else if (string.startsWith("p") || string.startsWith("P")) return somfy_commands::Prog;
else if (string.startsWith("u") || string.startsWith("U")) return somfy_commands::Up;
else if (string.startsWith("d") || string.startsWith("D")) return somfy_commands::Down;
else if (string.startsWith("m") || string.startsWith("M")) return somfy_commands::My;
else if (string.startsWith("f") || string.startsWith("F")) return somfy_commands::Flag;
else if (string.startsWith("s") || string.startsWith("S")) return somfy_commands::SunFlag;
else if (string.length() == 1) return static_cast<somfy_commands>(strtol(string.c_str(), nullptr, 16));
else return somfy_commands::My;
}
String translateSomfyCommand(const somfy_commands cmd) {
switch (cmd) {
case somfy_commands::Up:
return "Up";
case somfy_commands::Down:
return "Down";
case somfy_commands::My:
return "My";
case somfy_commands::MyUp:
return "My+Up";
case somfy_commands::UpDown:
return "Up+Down";
case somfy_commands::MyDown:
return "My+Down";
case somfy_commands::MyUpDown:
return "My+Up+Down";
case somfy_commands::Prog:
return "Prog";
case somfy_commands::SunFlag:
return "Sun Flag";
case somfy_commands::Flag:
return "Flag";
case somfy_commands::StepUp:
return "Step Up";
case somfy_commands::StepDown:
return "Step Down";
default:
return "Unknown(" + String((uint8_t)cmd) + ")";
}
}
void somfy_frame_t::decodeFrame(byte* frame) {
byte decoded[10];
decoded[0] = frame[0];
// The last 3 bytes are not encoded even on 80-bits. Go figure.
decoded[7] = frame[7];
decoded[8] = frame[8];
decoded[9] = frame[9];
for (byte i = 1; i < 7; i++) {
decoded[i] = frame[i] ^ frame[i - 1];
}
byte checksum = 0;
// We only want the upper nibble for the command byte.
for (byte i = 0; i < 7; i++) {
if (i == 1) checksum = checksum ^ (decoded[i] >> 4);
else checksum = checksum ^ decoded[i] ^ (decoded[i] >> 4);
}
checksum &= 0b1111; // We keep the last 4 bits only
this->checksum = decoded[1] & 0b1111;
this->encKey = decoded[0];
// Pull in the 80-bit commands. The upper nibble will be 0 even on 80 bit packets.
this->cmd = (somfy_commands)((decoded[1] >> 4));
// Pull in the data for an 80-bit step command.
if(this->cmd == somfy_commands::StepDown)
this->cmd = (somfy_commands)((decoded[1] >> 4) | ((decoded[8] & 0x08) << 4));
if(this->cmd == somfy_commands::RTWProto) {
this->proto = radio_proto::RTW;
switch(this->encKey) {
case 133:
this->cmd = somfy_commands::My;
break;
case 134:
this->cmd = somfy_commands::Up;
break;
case 135:
this->cmd = somfy_commands::MyUp;
break;
case 136:
this->cmd = somfy_commands::Down;
break;
case 137:
this->cmd = somfy_commands::MyDown;
break;
case 138:
this->cmd = somfy_commands::UpDown;
break;
case 139:
this->cmd = somfy_commands::MyUpDown;
break;
case 140:
this->cmd = somfy_commands::Prog;
break;
case 141:
this->cmd = somfy_commands::SunFlag;
break;
case 142:
this->cmd = somfy_commands::Flag;
break;
}
}
this->rollingCode = decoded[3] + (decoded[2] << 8);
this->remoteAddress = (decoded[6] + (decoded[5] << 8) + (decoded[4] << 16));
this->valid = this->checksum == checksum && this->remoteAddress > 0 && this->remoteAddress < 16777215 && this->rollingCode > 0;
if (this->valid) {
// Check for valid command.
switch (this->cmd) {
//case somfy_commands::Unknown0:
case somfy_commands::My:
case somfy_commands::Up:
case somfy_commands::MyUp:
case somfy_commands::Down:
case somfy_commands::MyDown:
case somfy_commands::UpDown:
case somfy_commands::MyUpDown:
case somfy_commands::Prog:
case somfy_commands::Flag:
case somfy_commands::SunFlag:
break;
case somfy_commands::UnknownC:
case somfy_commands::UnknownD:
case somfy_commands::RTWProto:
this->valid = false;
break;
case somfy_commands::StepUp:
case somfy_commands::StepDown:
// These must be 80 bit commands
break;
default:
this->valid = false;
break;
}
}
if(this->valid && this->encKey == 0) this->valid = false;
if (this->valid) {
/*
Serial.print("KEY:");
Serial.print(this->encKey);
Serial.print(" ADDR:");
Serial.print(this->remoteAddress);
Serial.print(" CMD:");
Serial.print(translateSomfyCommand(this->cmd));
Serial.print(" RCODE:");
Serial.print(this->rollingCode);
Serial.print(" BITS:");
Serial.print(this->bitLength);
Serial.print(" HWSYNC:");
Serial.println(this->hwsync);
*/
}
else {
Serial.print("INVALID FRAME ");
Serial.print("KEY:");
Serial.print(this->encKey);
Serial.print(" ADDR:");
Serial.print(this->remoteAddress);
Serial.print(" CMD:");
Serial.print(translateSomfyCommand(this->cmd));
Serial.print(" RCODE:");
Serial.println(this->rollingCode);
Serial.println(" KEY 1 2 3 4 5 6 ");
Serial.println("--------------------------------");
Serial.print("ENC ");
for (byte i = 0; i < 10; i++) {
if (frame[i] < 10)
Serial.print(" ");
else if (frame[i] < 100)
Serial.print(" ");
Serial.print(frame[i]);
Serial.print(" ");
}
Serial.println();
Serial.print("DEC ");
for (byte i = 0; i < 10; i++) {
if (decoded[i] < 10)
Serial.print(" ");
else if (decoded[i] < 100)
Serial.print(" ");
Serial.print(decoded[i]);
Serial.print(" ");
}
Serial.println();
}
}
void somfy_frame_t::decodeFrame(somfy_rx_t *rx) {
this->hwsync = rx->cpt_synchro_hw;
this->pulseCount = rx->pulseCount;
this->bitLength = rx->bit_length;
this->rssi = ELECHOUSE_cc1101.getRssi();
this->decodeFrame(rx->payload);
}
void somfy_frame_t::encodeFrame(byte *frame) {
const byte btn = static_cast<byte>(cmd);
frame[0] = this->encKey; // Encryption key. Doesn't matter much
frame[1] = (btn & 0x0F) << 4; // Which button did you press? The 4 LSB will be the checksum
frame[2] = this->rollingCode >> 8; // Rolling code (big endian)
frame[3] = this->rollingCode; // Rolling code
frame[4] = this->remoteAddress >> 16; // Remote address
frame[5] = this->remoteAddress >> 8; // Remote address
frame[6] = this->remoteAddress; // Remote address
frame[7] = 132;
frame[8] = 0;
frame[9] = 29;
// Ok so if this is an RTW things are a bit different.
if(this->proto == radio_proto::RTW) {
frame[1] = 0xF0;
switch(this->cmd) {
case somfy_commands::My:
frame[0] = 133;
break;
case somfy_commands::Up:
frame[0] = 134;
break;
case somfy_commands::MyUp:
frame[0] = 135;
break;
case somfy_commands::Down:
frame[0] = 136;
break;
case somfy_commands::MyDown:
frame[0] = 137;
break;
case somfy_commands::UpDown:
frame[0] = 138;
break;
case somfy_commands::MyUpDown:
frame[0] = 139;
break;
case somfy_commands::Prog:
frame[0] = 140;
break;
case somfy_commands::SunFlag:
frame[0] = 141;
break;
case somfy_commands::Flag:
frame[0] = 142;
break;
}
}
else {
switch(this->cmd) {
case somfy_commands::StepUp:
frame[7] = 132;
frame[8] = 56;
frame[9] = 22;
break;
case somfy_commands::StepDown:
frame[7] = 132;
frame[8] = 48;
frame[9] = 30;
break;
case somfy_commands::Prog:
frame[7] = 196;
frame[8] = 0;
frame[9] = 25;
break;
}
}
byte checksum = 0;
for (byte i = 0; i < 7; i++) {
checksum = checksum ^ frame[i] ^ (frame[i] >> 4);
}
checksum &= 0b1111; // We keep the last 4 bits only
// Checksum integration
frame[1] |= checksum;
// Obfuscation: a XOR of all the bytes
for (byte i = 1; i < 7; i++) {
frame[i] ^= frame[i - 1];
}
}
void somfy_frame_t::print() {
Serial.println("----------- Receiving -------------");
Serial.print("RSSI:");
Serial.print(this->rssi);
Serial.print(" LQI:");
Serial.println(this->lqi);
Serial.print("CMD:");
Serial.print(translateSomfyCommand(this->cmd));
Serial.print(" ADDR:");
Serial.print(this->remoteAddress);
Serial.print(" RCODE:");
Serial.println(this->rollingCode);
Serial.print("KEY:");
Serial.print(this->encKey, HEX);
Serial.print(" CS:");
Serial.println(this->checksum);
}
bool somfy_frame_t::isRepeat(somfy_frame_t &frame) { return this->remoteAddress == frame.remoteAddress && this->cmd == frame.cmd && this->rollingCode == frame.rollingCode; }
void somfy_frame_t::copy(somfy_frame_t &frame) {
if(this->isRepeat(frame)) {
this->repeats++;
this->rssi = frame.rssi;
this->lqi = frame.lqi;
}
else {
this->valid = frame.valid;
this->processed = frame.processed;
this->rssi = frame.rssi;
this->lqi = frame.lqi;
this->cmd = frame.cmd;
this->remoteAddress = frame.remoteAddress;
this->rollingCode = frame.rollingCode;
this->encKey = frame.encKey;
this->checksum = frame.checksum;
this->hwsync = frame.hwsync;
this->repeats = frame.repeats;
}
}
void SomfyShadeController::end() { this->transceiver.disableReceive(); }
SomfyShadeController::SomfyShadeController() {
memset(this->m_shadeIds, 255, sizeof(this->m_shadeIds));
uint64_t mac = ESP.getEfuseMac();
this->startingAddress = mac & 0x0FFFFF;
}
SomfyShade *SomfyShadeController::findShadeByRemoteAddress(uint32_t address) {
for(uint8_t i = 0; i < SOMFY_MAX_SHADES; i++) {
SomfyShade &shade = this->shades[i];
if(shade.getRemoteAddress() == address) return &shade;
else {
for(uint8_t j = 0; j < SOMFY_MAX_LINKED_REMOTES; j++) {
if(shade.linkedRemotes[j].getRemoteAddress() == address) return &shade;
}
}
}
return nullptr;
}
bool SomfyShadeController::loadLegacy() {
Serial.println("Loading Legacy shades using NVS");
pref.begin("Shades", true);
pref.getBytes("shadeIds", this->m_shadeIds, sizeof(this->m_shadeIds));
pref.end();
for(uint8_t i = 0; i < sizeof(this->m_shadeIds); i++) {
if(i != 0) DEBUG_SOMFY.print(",");
DEBUG_SOMFY.print(this->m_shadeIds[i]);
}
DEBUG_SOMFY.println();
sortArray<uint8_t>(this->m_shadeIds, sizeof(this->m_shadeIds));
#ifdef DEBUG_SOMFY
for(uint8_t i = 0; i < sizeof(this->m_shadeIds); i++) {
if(i != 0) DEBUG_SOMFY.print(",");
DEBUG_SOMFY.print(this->m_shadeIds[i]);
}
DEBUG_SOMFY.println();
#endif
uint8_t id = 0;
for(uint8_t i = 0; i < sizeof(this->m_shadeIds); i++) {
if(this->m_shadeIds[i] == id) this->m_shadeIds[i] = 255;
id = this->m_shadeIds[i];
SomfyShade *shade = &this->shades[i];
shade->setShadeId(id);
if(id == 255) {
continue;
}
shade->load();
}
#ifdef DEBUG_SOMFY
for(uint8_t i = 0; i < SOMFY_MAX_SHADES; i++) {
DEBUG_SOMFY.print(this->shades[i].getShadeId());
DEBUG_SOMFY.print(":");
DEBUG_SOMFY.print(this->m_shadeIds[i]);
if(i < SOMFY_MAX_SHADES - 1) DEBUG_SOMFY.print(",");
}
Serial.println();
#endif
if(!this->useNVS()) {
pref.begin("Shades");
pref.putBytes("shadeIds", this->m_shadeIds, sizeof(this->m_shadeIds));
pref.end();
}
this->commit();
return true;
}
bool SomfyShadeController::begin() {
// Load up all the configuration data.
ShadeConfigFile::getAppVersion(this->appVersion);
Serial.printf("App Version:%u.%u.%u\n", this->appVersion.major, this->appVersion.minor, this->appVersion.build);
if(!this->useNVS()) { // At 1.4 we started using the configuration file. If the file doesn't exist then booh.
// We need to remove all the extraeneous data from NVS for the shades. From here on out we
// will rely on the shade configuration.
Serial.println("No longer using NVS");
if(ShadeConfigFile::exists()) {
ShadeConfigFile::load(this);
}
else {
this->loadLegacy();
}
pref.begin("Shades");
if(pref.isKey("shadeIds")) {
pref.getBytes("shadeIds", this->m_shadeIds, sizeof(this->m_shadeIds));
pref.clear(); // Delete all the keys.
}
pref.end();
for(uint8_t i = 0; i < sizeof(this->m_shadeIds); i++) {
// Start deleting the keys for the shades.
if(this->m_shadeIds[i] == 255) continue;
char shadeKey[15];
sprintf(shadeKey, "SomfyShade%u", this->m_shadeIds[i]);
pref.begin(shadeKey);
pref.clear();
pref.end();
}
}
else if(ShadeConfigFile::exists()) {
Serial.println("shades.cfg exists so we are using that");
ShadeConfigFile::load(this);
}
else {
Serial.println("Starting clean");
this->loadLegacy();
}
this->transceiver.begin();
// Set the radio type for shades that have yet to be specified.
bool saveFlag = false;
for(uint8_t i = 0; i < SOMFY_MAX_SHADES; i++) {
SomfyShade *shade = &this->shades[i];
if(shade->getShadeId() != 255 && shade->bitLength == 0) {
Serial.printf("Setting bit length to %d\n", this->transceiver.config.type);
shade->bitLength = this->transceiver.config.type;
saveFlag = true;
}
}
if(saveFlag) somfy.commit();
return true;
}
void SomfyShadeController::commit() {
ShadeConfigFile file;
file.begin();
file.save(this);
file.end();
this->isDirty = false;
this->lastCommit = millis();
}
SomfyShade * SomfyShadeController::getShadeById(uint8_t shadeId) {
for(uint8_t i = 0; i < SOMFY_MAX_SHADES; i++) {
if(this->shades[i].getShadeId() == shadeId) return &this->shades[i];
}
return nullptr;
}
bool SomfyShade::linkRemote(uint32_t address, uint16_t rollingCode) {
// Check to see if the remote is already linked. If it is
// just return true after setting the rolling code
for(uint8_t i = 0; i < SOMFY_MAX_LINKED_REMOTES; i++) {
if(this->linkedRemotes[i].getRemoteAddress() == address) {
this->linkedRemotes[i].setRollingCode(rollingCode);
return true;
}
}
for(uint8_t i = 0; i < SOMFY_MAX_LINKED_REMOTES; i++) {
if(this->linkedRemotes[i].getRemoteAddress() == 0) {
this->linkedRemotes[i].setRemoteAddress(address);
this->linkedRemotes[i].setRollingCode(rollingCode);
if(somfy.useNVS()) {
uint32_t linkedAddresses[SOMFY_MAX_LINKED_REMOTES];
memset(linkedAddresses, 0x00, sizeof(linkedAddresses));
uint8_t j = 0;
for(uint8_t i = 0; i < SOMFY_MAX_LINKED_REMOTES; i++) {
SomfyLinkedRemote lremote = this->linkedRemotes[i];
if(lremote.getRemoteAddress() != 0) linkedAddresses[j++] = lremote.getRemoteAddress();
}
char shadeKey[15];
snprintf(shadeKey, sizeof(shadeKey), "SomfyShade%u", this->getShadeId());
pref.begin(shadeKey);
pref.putBytes("linkedAddr", linkedAddresses, sizeof(uint32_t) * SOMFY_MAX_LINKED_REMOTES);
pref.end();
}
this->commit();
return true;
}
}
return false;
}
void SomfyShade::commit() { somfy.commit(); }
void SomfyShade::commitShadePosition() {
somfy.isDirty = true;
char shadeKey[15];
if(somfy.useNVS()) {
snprintf(shadeKey, sizeof(shadeKey), "SomfyShade%u", this->shadeId);
Serial.print("Writing current shade position: ");
Serial.println(this->currentPos, 4);
pref.begin(shadeKey);
pref.putFloat("currentPos", this->currentPos);
pref.end();
}
}
void SomfyShade::commitMyPosition() {
somfy.isDirty = true;
if(somfy.useNVS()) {
char shadeKey[15];
snprintf(shadeKey, sizeof(shadeKey), "SomfyShade%u", this->shadeId);
Serial.print("Writing my shade position:");
Serial.print(this->myPos);
Serial.println("%");
pref.begin(shadeKey);
pref.putUShort("myPos", this->myPos);
pref.end();
}
}
void SomfyShade::commitTiltPosition() {
somfy.isDirty = true;
if(somfy.useNVS()) {
char shadeKey[15];
snprintf(shadeKey, sizeof(shadeKey), "SomfyShade%u", this->shadeId);
Serial.print("Writing current shade tilt position: ");
Serial.println(this->currentTiltPos, 4);
pref.begin(shadeKey);
pref.putFloat("currentTiltPos", this->currentTiltPos);
pref.end();
}
}
bool SomfyShade::unlinkRemote(uint32_t address) {
for(uint8_t i = 0; i < SOMFY_MAX_LINKED_REMOTES; i++) {
if(this->linkedRemotes[i].getRemoteAddress() == address) {
this->linkedRemotes[i].setRemoteAddress(0);
if(somfy.useNVS()) {
char shadeKey[15];
snprintf(shadeKey, sizeof(shadeKey), "SomfyShade%u", this->getShadeId());
uint32_t linkedAddresses[SOMFY_MAX_LINKED_REMOTES];
memset(linkedAddresses, 0x00, sizeof(linkedAddresses));
uint8_t j = 0;
for(uint8_t i = 0; i < SOMFY_MAX_LINKED_REMOTES; i++) {
SomfyLinkedRemote lremote = this->linkedRemotes[i];
if(lremote.getRemoteAddress() != 0) linkedAddresses[j++] = lremote.getRemoteAddress();
}
pref.begin(shadeKey);
pref.putBytes("linkedAddr", linkedAddresses, sizeof(uint32_t) * SOMFY_MAX_LINKED_REMOTES);
pref.end();
}
this->commit();
return true;
}
}
return false;
}
bool SomfyShade::isAtTarget() { return this->currentPos == this->target && this->currentTiltPos == this->tiltTarget; }
void SomfyShade::checkMovement() {
// We are checking movement for essentially 3 types of motors.
// If this is an integrated tilt we need to first tilt in the direction we are moving then move. We know
// what needs to be done by the tilt type. Set a tilt first flag to indicate whether we should be tilting or
// moving. If this is only a tilt action then the regular tilt action should operate fine.
int8_t currDir = this->direction;
int8_t currTiltDir = this->tiltDirection;
this->direction = this->currentPos == this->target ? 0 : this->currentPos > this->target ? -1 : 1;
bool tilt_first = this->tiltType == tilt_types::integrated && ((this->direction == -1 && this->currentTiltPos != 0.0f) || (this->direction == 1 && this->currentTiltPos != 100.0f));
this->tiltDirection = this->currentTiltPos == this->tiltTarget ? 0 : this->currentTiltPos > this->tiltTarget ? -1 : 1;
if(tilt_first) {
this->tiltDirection = this->direction;
this->direction = 0;
}
else if(this->direction != 0) this->tiltDirection = 0;
uint8_t currPos = floor(this->currentPos);
uint8_t currTiltPos = floor(this->currentTiltPos);
if(!tilt_first && this->direction > 0) {
if(this->downTime == 0) {
this->direction = 0;
this->currentPos = 100.0;
}
else {
// The shade is moving down so we need to calculate its position through the down position.
// 10000ms from 0 to 100
// The starting posion is a float value from 0-1 that indicates how much the shade is open. So
// if we take the starting position * the total down time then this will tell us how many ms it
// has moved in the down position.
int32_t msFrom0 = (int32_t)floor((this->startPos/100) * this->downTime);
// So if the start position is .1 it is 10% closed so we have a 1000ms (1sec) of time to account for
// before we add any more time.
msFrom0 += (millis() - this->moveStart);
// Now we should have the total number of ms that the shade moved from the top. But just so we
// don't have any rounding errors make sure that it is not greater than the max down time.
msFrom0 = min((int32_t)this->downTime, msFrom0);
if(msFrom0 >= this->downTime) {
this->currentPos = 100.0f;
this->direction = 0;
}
else {
// So now we know how much time has elapsed from the 0 position to down. The current position should be
// a ratio of how much time has travelled over the total time to go 100%.
// We should now have the number of ms it will take to reach the shade fully close.
this->currentPos = (min(max((float)0.0, (float)msFrom0 / (float)this->downTime), (float)1.0)) * 100;
// If the current position is >= 1 then we are at the bottom of the shade.
if(this->currentPos >= 100) {
this->direction = 0;
this->currentPos = 100.0;
}
}
}
if(this->currentPos >= this->target) {
this->currentPos = this->target;
// If we need to stop the shade do this before we indicate that we are
// not moving otherwise the my function will kick in.
if(this->settingPos) {
if(!isAtTarget()) {
if(this->target != 100.0) SomfyRemote::sendCommand(somfy_commands::My);
delay(100);
// We now need to move the tilt to the position we requested.
this->moveToTiltTarget(this->tiltTarget);
}
else
if(this->target != 100.0) SomfyRemote::sendCommand(somfy_commands::My);
}
this->direction = 0;
this->tiltStart = millis();
this->startTiltPos = this->currentTiltPos;
if(this->isAtTarget()) this->commitShadePosition();
}
}
else if(!tilt_first && this->direction < 0) {
if(this->upTime == 0) {
this->direction = 0;
this->currentPos = 0;
}
else {
// The shade is moving up so we need to calculate its position through the up position. Shades
// often move slower in the up position so since we are using a relative position the up time
// can be calculated.
// 10000ms from 100 to 0;
int32_t msFrom100 = (int32_t)this->upTime - (int32_t)floor((this->startPos/100) * this->upTime);
msFrom100 += (millis() - this->moveStart);
msFrom100 = min((int32_t)this->upTime, msFrom100);
if(msFrom100 >= this->upTime) {
this->currentPos = 0.0;
this->direction = 0;
}
// We should now have the number of ms it will take to reach the shade fully open.
this->currentPos = ((float)1.0 - min(max((float)0.0, (float)msFrom100 / (float)this->upTime), (float)1.0)) * 100;
// If we are at the top of the shade then set the movement to 0.
if(this->currentPos <= 0.0) {
this->direction = 0;
this->currentPos = 0;
}
}
if(this->currentPos <= this->target) {
this->currentPos = this->target;
// If we need to stop the shade do this before we indicate that we are
// not moving otherwise the my function will kick in.
if(this->settingPos) {
if(!isAtTarget()) {
if(this->target != 0.0) SomfyRemote::sendCommand(somfy_commands::My);
delay(100);
// We now need to move the tilt to the position we requested.
this->moveToTiltTarget(this->tiltTarget);
}
else
if(this->target != 0.0) SomfyRemote::sendCommand(somfy_commands::My);
}
this->direction = 0;
this->tiltStart = millis();
this->startTiltPos = this->currentTiltPos;
if(this->isAtTarget()) this->commitShadePosition();
}
}
if(this->tiltDirection > 0) {
if(tilt_first) this->moveStart = millis();
int32_t msFrom0 = (int32_t)floor((this->startTiltPos/100) * this->tiltTime);
msFrom0 += (millis() - this->tiltStart);
msFrom0 = min((int32_t)this->tiltTime, msFrom0);
if(msFrom0 >= this->tiltTime) {
this->currentTiltPos = 100.0f;
this->tiltDirection = 0;
}
else {
this->currentTiltPos = (min(max((float)0.0, (float)msFrom0 / (float)this->tiltTime), (float)1.0)) * 100;
if(this->currentTiltPos >= 100) {
this->tiltDirection = 0;
this->currentTiltPos = 100.0f;
}
}
if(tilt_first) {
if(this->currentTiltPos >= 100.0f) {
this->currentTiltPos = 100.0f;
this->moveStart = millis();
this->startPos = this->currentPos;
this->tiltDirection = 0;
}
}
else if(this->currentTiltPos >= this->tiltTarget) {
this->currentTiltPos = this->tiltTarget;
// If we need to stop the shade do this before we indicate that we are
// not moving otherwise the my function will kick in.
if(this->settingTiltPos) {
if(this->tiltType == tilt_types::integrated) {
// If this is an integrated tilt mechanism the we will simply let it finish. If it is not then we will stop it.
if(this->tiltTarget != 100.0 || this->currentPos != 100.0) SomfyRemote::sendCommand(somfy_commands::My);
}
else {
// This is a tilt motor so let it complete if it is going to 0.
if(this->tiltTarget != 100.0) SomfyRemote::sendCommand(somfy_commands::My);
}
}
this->tiltDirection = 0;
this->settingTiltPos = false;
if(this->isAtTarget()) this->commitShadePosition();
}
}
else if(this->tiltDirection < 0) {
if(tilt_first) this->moveStart = millis();
if(this->tiltTime == 0) {
this->tiltDirection = 0;
this->currentTiltPos = 0;
}
else {
int32_t msFrom100 = (int32_t)this->tiltTime - (int32_t)floor((this->startTiltPos/100) * this->tiltTime);
msFrom100 += (millis() - this->tiltStart);
msFrom100 = min((int32_t)this->tiltTime, msFrom100);
if(msFrom100 >= this->tiltTime) {
this->currentTiltPos = 0.0f;
this->tiltDirection = 0;
}
this->currentTiltPos = ((float)1.0 - min(max((float)0.0, (float)msFrom100 / (float)this->tiltTime), (float)1.0)) * 100;
// If we are at the top of the shade then set the movement to 0.
if(this->currentTiltPos <= 0.0f) {
this->tiltDirection = 0;
this->currentTiltPos = 0.0f;
}
}
if(tilt_first) {
if(this->currentTiltPos <= 0.0f) {
this->currentTiltPos = 0.0f;
this->moveStart = millis();
this->startPos = this->currentPos;
this->tiltDirection = 0;
}
}
else if(this->currentTiltPos <= this->tiltTarget) {
this->currentTiltPos = this->tiltTarget;
// If we need to stop the shade do this before we indicate that we are
// not moving otherwise the my function will kick in.
if(this->settingTiltPos) {
if(this->tiltType == tilt_types::integrated) {
// If this is an integrated tilt mechanism the we will simply let it finish. If it is not then we will stop it.
if(this->tiltTarget != 0.0 || this->currentPos != 0.0) SomfyRemote::sendCommand(somfy_commands::My);
}
else {
// This is a tilt motor so let it complete if it is going to 0.
if(this->tiltTarget != 0.0) SomfyRemote::sendCommand(somfy_commands::My);
}
}
this->tiltDirection = 0;
this->settingTiltPos = false;
Serial.println("Stopping at tilt position");
if(this->isAtTarget()) this->commitShadePosition();
}
}
if(this->settingMyPos && this->isAtTarget()) {
delay(200);
// Set this position before sending the command. If you don't the processFrame function
// will send the shade back to its original My position.
if(this->tiltType != tilt_types::none) {
if(this->myTiltPos == this->currentTiltPos && this->myPos == this->currentPos) this->myPos = this->myTiltPos = -1;
else {
this->myPos = this->currentPos;
this->myTiltPos = this->currentTiltPos;
}
}
else {
this->myTiltPos = -1;
if(this->myPos == this->currentPos) this->myPos = -1;
else this->myPos = this->currentPos;
}
SomfyRemote::sendCommand(somfy_commands::My, SETMY_REPEATS);
this->settingMyPos = false;
this->commitMyPosition();
this->emitState();
}
else if(currDir != this->direction || currPos != floor(this->currentPos) || currTiltDir != this->tiltDirection || currTiltPos != floor(this->currentTiltPos)) {
// We need to emit on the socket that our state has changed.
this->emitState();
}
}
void SomfyShade::load() {
char shadeKey[15];
uint32_t linkedAddresses[SOMFY_MAX_LINKED_REMOTES];
memset(linkedAddresses, 0x00, sizeof(uint32_t) * SOMFY_MAX_LINKED_REMOTES);
snprintf(shadeKey, sizeof(shadeKey), "SomfyShade%u", this->shadeId);
// Now load up each of the shades into memory.
//Serial.print("key:");
//Serial.println(shadeKey);
pref.begin(shadeKey, !somfy.useNVS());
pref.getString("name", this->name, sizeof(this->name));
this->paired = pref.getBool("paired", false);
if(pref.isKey("upTime") && pref.getType("upTime") != PreferenceType::PT_U32) {
// We need to convert these to 32 bits because earlier versions did not support this.
this->upTime = static_cast<uint32_t>(pref.getUShort("upTime", 1000));
this->downTime = static_cast<uint32_t>(pref.getUShort("downTime", 1000));
this->tiltTime = static_cast<uint32_t>(pref.getUShort("tiltTime", 7000));
if(somfy.useNVS()) {
pref.remove("upTime");
pref.putUInt("upTime", this->upTime);
pref.remove("downTime");
pref.putUInt("downTime", this->downTime);
pref.remove("tiltTime");
pref.putUInt("tiltTime", this->tiltTime);
}
}
else {
this->upTime = pref.getUInt("upTime", this->upTime);
this->downTime = pref.getUInt("downTime", this->downTime);
this->tiltTime = pref.getUInt("tiltTime", this->tiltTime);
}
this->setRemoteAddress(pref.getUInt("remoteAddress", 0));
this->currentPos = pref.getFloat("currentPos", 0);
this->target = floor(this->currentPos);
this->myPos = static_cast<float>(pref.getUShort("myPos", this->myPos));
this->tiltType = pref.getBool("hasTilt", false) ? tilt_types::none : tilt_types::tiltmotor;
this->shadeType = static_cast<shade_types>(pref.getChar("shadeType", static_cast<uint8_t>(this->shadeType)));
this->currentTiltPos = pref.getFloat("currentTiltPos", 0);
this->tiltTarget = floor(this->currentTiltPos);
pref.getBytes("linkedAddr", linkedAddresses, sizeof(linkedAddresses));
pref.end();
Serial.print("shadeId:");
Serial.print(this->getShadeId());
Serial.print(" name:");
Serial.print(this->name);
Serial.print(" address:");
Serial.print(this->getRemoteAddress());
Serial.print(" position:");
Serial.print(this->currentPos);
Serial.print(" myPos:");
Serial.println(this->myPos);
pref.begin("ShadeCodes");
this->lastRollingCode = pref.getUShort(this->m_remotePrefId, 0);
for(uint8_t j = 0; j < SOMFY_MAX_LINKED_REMOTES; j++) {
SomfyLinkedRemote &lremote = this->linkedRemotes[j];
lremote.setRemoteAddress(linkedAddresses[j]);
lremote.lastRollingCode = pref.getUShort(lremote.getRemotePrefId(), 0);
}
pref.end();
}
void SomfyShade::publish() {
if(mqtt.connected()) {
char topic[32];
snprintf(topic, sizeof(topic), "shades/%u/shadeId", this->shadeId);
mqtt.publish(topic, this->shadeId);
snprintf(topic, sizeof(topic), "shades/%u/name", this->shadeId);
mqtt.publish(topic, this->name);
snprintf(topic, sizeof(topic), "shades/%u/remoteAddress", this->shadeId);
mqtt.publish(topic, this->getRemoteAddress());
snprintf(topic, sizeof(topic), "shades/%u/position", this->shadeId);
mqtt.publish(topic, static_cast<uint8_t>(floor(this->currentPos)));
snprintf(topic, sizeof(topic), "shades/%u/direction", this->shadeId);
mqtt.publish(topic, this->direction);
snprintf(topic, sizeof(topic), "shades/%u/target", this->shadeId);
mqtt.publish(topic, static_cast<uint8_t>(floor(this->target)));
snprintf(topic, sizeof(topic), "shades/%u/lastRollingCode", this->shadeId);
mqtt.publish(topic, this->lastRollingCode);
snprintf(topic, sizeof(topic), "shades/%u/mypos", this->shadeId);
mqtt.publish(topic, static_cast<uint8_t>(floor(this->myPos)));
snprintf(topic, sizeof(topic), "shades/%u/shadeType", this->shadeId);
mqtt.publish(topic, static_cast<uint8_t>(this->shadeType));
snprintf(topic, sizeof(topic), "shades/%u/tiltType", this->shadeId);
mqtt.publish(topic, static_cast<uint8_t>(this->tiltType));
if(this->tiltType != tilt_types::none) {
snprintf(topic, sizeof(topic), "shades/%u/tiltDirection", this->shadeId);
mqtt.publish(topic, this->tiltDirection);
snprintf(topic, sizeof(topic), "shades/%u/tiltPosition", this->shadeId);
mqtt.publish(topic, static_cast<uint8_t>(floor(this->currentTiltPos)));
snprintf(topic, sizeof(topic), "shades/%u/tiltTarget", this->shadeId);
mqtt.publish(topic, static_cast<uint8_t>(floor(this->tiltTarget)));
}
}
}
void SomfyShade::emitState(const char *evt) { this->emitState(255, evt); }
void SomfyShade::emitState(uint8_t num, const char *evt) {
char buf[320];
if(this->tiltType != tilt_types::none)
snprintf(buf, sizeof(buf), "{\"shadeId\":%d,\"type\":%u,\"remoteAddress\":%d,\"name\":\"%s\",\"direction\":%d,\"position\":%d,\"target\":%d,\"mypos\":%d,\"myTiltPos\":%d,\"tiltType\":%u,\"tiltDirection\":%d,\"tiltTarget\":%d,\"tiltPosition\":%d,\"flags\":%d}",
this->shadeId, static_cast<uint8_t>(this->shadeType), this->getRemoteAddress(), this->name, this->direction, static_cast<uint8_t>(floor(this->currentPos)), static_cast<uint8_t>(floor(this->target)), static_cast<int8_t>(floor(this->myPos)), static_cast<int8_t>(this->myTiltPos), static_cast<uint8_t>(this->tiltType), this->tiltDirection, static_cast<uint8_t>(floor(this->tiltTarget)), static_cast<uint8_t>(floor(this->currentTiltPos)),this->flags);
else
snprintf(buf, sizeof(buf), "{\"shadeId\":%d,\"type\":%u,\"remoteAddress\":%d,\"name\":\"%s\",\"direction\":%d,\"position\":%d,\"target\":%d,\"mypos\":%d,\"tiltType\":%u,\"flags\":%d}",
this->shadeId, static_cast<uint8_t>(this->shadeType), this->getRemoteAddress(), this->name, this->direction, static_cast<uint8_t>(floor(this->currentPos)), static_cast<uint8_t>(floor(this->target)), static_cast<int8_t>(floor(this->myPos)), static_cast<uint8_t>(this->tiltType), this->flags);
if(num >= 255) sockEmit.sendToClients(evt, buf);
else sockEmit.sendToClient(num, evt, buf);
if(mqtt.connected()) {
char topic[32];
snprintf(topic, sizeof(topic), "shades/%u/position", this->shadeId);
mqtt.publish(topic, static_cast<uint8_t>(floor(this->currentPos)));
snprintf(topic, sizeof(topic), "shades/%u/direction", this->shadeId);
mqtt.publish(topic, this->direction);
snprintf(topic, sizeof(topic), "shades/%u/target", this->shadeId);
mqtt.publish(topic, static_cast<uint8_t>(floor(this->target)));
snprintf(topic, sizeof(topic), "shades/%u/lastRollingCode", this->shadeId);
mqtt.publish(topic, this->lastRollingCode);
snprintf(topic, sizeof(topic), "shades/%u/mypos", this->shadeId);
mqtt.publish(topic, static_cast<int8_t>(floor(this->myPos)));
snprintf(topic, sizeof(topic), "shades/%u/tiltType", this->shadeId);
mqtt.publish(topic, static_cast<uint8_t>(this->tiltType));
snprintf(topic, sizeof(topic), "shades/%u/flags", this->flags);
if(this->tiltType != tilt_types::none) {
snprintf(topic, sizeof(topic), "shades/%u/myTiltPos", this->shadeId);
mqtt.publish(topic, static_cast<int8_t>(floor(this->myTiltPos)));
snprintf(topic, sizeof(topic), "shades/%u/tiltPosition", this->shadeId);
mqtt.publish(topic, static_cast<uint8_t>(floor(this->currentTiltPos)));
snprintf(topic, sizeof(topic), "shades/%u/tiltTarget", this->shadeId);
mqtt.publish(topic, static_cast<uint8_t>(floor(this->tiltTarget)));
}
}
}
bool SomfyShade::isIdle() { return this->direction == 0 && this->tiltDirection == 0; }
void SomfyShade::processWaitingFrame() {
if(this->shadeId == 255) {
this->lastFrame.await = 0;
return;
}
if(this->lastFrame.processed) return;
if(this->lastFrame.await > 0 && (millis() > this->lastFrame.await)) {
switch(this->lastFrame.cmd) {
case somfy_commands::StepUp:
this->lastFrame.processed = true;
// Simply move the shade up by 1%.
if(this->currentPos > 0) {
this->target = floor(this->currentPos) - 1;
this->setMovement(-1);
}
break;
case somfy_commands::StepDown:
this->lastFrame.processed = true;
// Simply move the shade down by 1%.
if(this->currentPos < 100) {
this->target = floor(this->currentPos) + 1;
this->setMovement(1);
}
break;
case somfy_commands::Down:
case somfy_commands::Up:
if(this->tiltType == tilt_types::tiltmotor) { // Theoretically this should get here unless it does have a tilt motor.
if(this->lastFrame.repeats >= TILT_REPEATS) {
int8_t dir = this->lastFrame.cmd == somfy_commands::Up ? -1 : 1;
this->tiltTarget = dir > 0 ? 100.0f : 0.0f;
this->setTiltMovement(dir);
this->lastFrame.processed = true;
Serial.print(this->name);
Serial.print(" Processing tilt ");
Serial.print(translateSomfyCommand(this->lastFrame.cmd));
Serial.print(" after ");
Serial.print(this->lastFrame.repeats);
Serial.println(" repeats");
}
else {