-
Notifications
You must be signed in to change notification settings - Fork 319
/
_P126_HassDiscovery.ino
2312 lines (1987 loc) · 87.5 KB
/
_P126_HassDiscovery.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
//---------------------------------------------------------------------------//
// //
// HOMEASSISTANT DISCOVERY //
// //
//---------------------------------------------------------------------------//
/* by michael baeck
plugin searches for active mqtt-enabled taskvalues and pushes json payloads
for homeassistant to take for discovery.
https://www.letscontrolit.com/forum/viewtopic.php?f=18&t=6061
* REQUIRES P128 (Homeassistant Output Device) to be included!
* P126 + P128 are dependend on each other (at least to compile, may be changed later)
[!] MAJOR ISSUE: by espeasy default MQTT_MAX_PACKET_SIZE in pubsubclient.h is set to 384
[!] most payloads will be 500-600, please increase for testing this plugin.
[!] section in lib\pubsubclient\src\PubSubClient.h:
// MQTT_MAX_PACKET_SIZE : Maximum packet size
#ifndef MQTT_MAX_PACKET_SIZE
#define MQTT_MAX_PACKET_SIZE 384
#endif
1 value = 1 entity.
whole unit (ESP) = 1 device & 1 entity.
classification of sensor (motion, light, temp, etc.) can be done in webform.
devices can also be deleted but homeassistant refuses to remove them from its store.
(it's an issue with HA, that should be fixed soon)
this is my first arduino code and first commit ever to anything, but it's pretty useful already.
However, it's all done learning by doing and code might be ugly...
testing and feedback highly appreciated!
only tested on a couple of 4M ESP12 yet, ESP01 soon, ESP32 doesn't compile.
storage might be short on ESP32 as struct reserves space for all tasks
* stay tuned for more plugins like homeassistant-switch, etc
supported components
binary_sensor
[X] homeassistant native [1/0]
[X] battery [low/norm]
[X] cold [cold/norm]
[X] connectivity [conn/disco]
[X] door [open/close]
[X] garage_door [open/close]
[X] gas [gas/clear]
[X] heat [hot/norm]
[X] light [light/dark]
[X] lock [unlocked/locked]
[X] moisture [wet/dry]
[X] motion [motion/clear]
[X] moving [moving/stopped]
[X] occupancy [occ/clear]
[X] opening [open/close]
[X] plug [plug/unplug]
[X] power [power/none]
[X] presesnce [home/away]
[X] problem [problem/ok]
[X] safety [unsafe/safe]
[X] smoke [smoke/clear]
[X] sound [sound/clear]
[X] vibration [vibration/clear]
[X] window [open/close]
[x] custom
[x] water
sensor
[X] homeassistant native
[x] battery
[x] humimdity
[x] illuminance
[x] unit_of_measurement lx or lm
[x] temperature
[x] unit_of_measurement °C or °F
[x] pressure
[x] unit_of_measurement hPa or mbar
[x] custom
[x] plant
[x] radio
[x] scale
[ ] camera
[ ] cover
damper
garage
window
[ ] fan
[ ] climate
[ ] light
[ ] lock
output
[dev] switch
[test] simple gpio switch (included)
[dev] complex switch (via P128)
naming conventions
entity_id COMPONENT.SYSNAME_TASK_VALUE (adjustable)
COMPONENT.char[26]_char[41]_char[41]
last-will-topic -> controller settings
sensor-discovery-topic PREFIX / COMPONENT / MAC / MAC_TASKID_VALUEID /config
sensor-state-topic -> controller settings
system-discovery-topic PREFIX / COMPONENT / MAC / MAC_system /config
system-state-topic PREFIX / COMPONENT / MAC / MAC_system /state
observation-this-unit PREFIX / + / MAC / + /config
observation-all-units PREFIX / + / + / + /config
example payload:
{
"name":"esp22",
"ic":"mdi:chip",
"stat_t":"dev/sensor/807D3A6EA0C5/807D3A6EA0C5_system/state",
"val_tpl":"{{ value_json.state }}",
"uniq_id":"807D3A6EA0C5_system",
"avty_t":"esp22/state",
"pl_avail":"online",
"pl_not_avail":"offline",
"json_attr":["plugin","unit","version","uptime","cpu","hostname","ip","mac","ssid","bssid","rssi","last_disconnect","last_boot_cause" ],
"device":{
"sw_version":"EspEasy - Mega (Nov 12 2018)",
"manufacturer":"letscontrolit.com",
"model":"PLATFORMIO_ESP12E",
"connections":[["mac","80:7D:3A:6E:A0:C5"]],
"name":"esp22",
"identifiers":["7250117","807D3A6EA0C5"]
}
}
bugs/todo
[!] no command return (commands working though)
[todo] simple/advanced mode
[test] unit choice
[test] assign settings by Pxxx
build results [20181112]
[!] Environment esp-wrover-kit_test_1M8_partition [ERROR]
[!] Environment esp32dev [ERROR]
[!] Environment esp32test_1M8_partition [ERROR]
[x] Environment normal_ESP8266_1024 [SUCCESS]
[x] Environment normal_core_241_ESP8266_1024 [SUCCESS]
[x] Environment normal_ESP8285_1024 [SUCCESS]
[x] Environment normal_WROOM02_2048 [SUCCESS]
[x] Environment normal_ESP8266_4096 [SUCCESS]
[x] Environment normal_core_241_ESP8266_4096 [SUCCESS]
[x] Environment normal_IR_ESP8266_4096 [SUCCESS]
[x] Environment test_ESP8266_1024 [SUCCESS]
[x] Environment test_ESP8285_1024 [SUCCESS]
[x] Environment test_WROOM02_2048 [SUCCESS]
[x] Environment test_ESP8266_4096 [SUCCESS]
[x] Environment test_ESP8266_4096_VCC [SUCCESS]
[x] Environment dev_ESP8266_1024 [SUCCESS]
[x] Environment dev_ESP8285_1024 [SUCCESS]
[x] Environment dev_WROOM02_2048 [SUCCESS]
[x] Environment dev_ESP8266_4096 [SUCCESS]
[x] Environment dev_ESP8266PUYA_1024 [SUCCESS]
[x] Environment dev_ESP8266PUYA_1024_VCC [SUCCESS]
[x] Environment hard_SONOFF_POW [SUCCESS]
[x] Environment hard_SONOFF_POW_R2_4M [SUCCESS]
[x] Environment hard_Shelly_1 [SUCCESS]
[x] Environment hard_Ventus_W266 [SUCCESS]
*/
//#ifdef USES_P126
//#ifdef PLUGIN_BUILD_DEVELOPMENT
//#ifdef PLUGIN_BUILD_TESTING
//#define PLUGIN_119_DEBUG true
// force using discovery plugin when using this one
#ifndef USES_P128
#define USES_P128
#endif
#define PLUGIN_126
#define PLUGIN_ID_126 126
#define PLUGIN_NAME_126 "Generic - Homeassistant Discovery [DEVELOPMENT]"
//---------------------------------------------------------------------------//
// struct + global vars
#define _P126_VERSION 53
#define _P126_HASWITCH 128
#define _P128_F(taskid,mode) (_P128_make_config(discovery,taskid,mode))
#define _P128_WEB 1
#define _P128_COMPONENT 2
#define _P128_ENTITYID 3
#define _P128_PAYLOAD 4
#define _P128_TOPIC 5
#define _P128_COMPCOUNT 7 // 9
#define _P126_INTERVAL 5000
#define _P126_CLASSCOUNT 9
#define _P126_BINCLASSCOUNT 26
#define _P126_GENERIC 0 // % raw K
#define _P126_BATTERY 1
#define _P126_HUMIDITY 2
#define _P126_LIGHT 3
#define _P126_TEMP 4
#define _P126_PRESSURE 5
#define _P126_PLANT 6
#define _P126_RADIO 7
#define _P126_LOAD 8
#define _P126_UNITMAP 1
#define _P126_LIGHTUNITMAP 2
#define _P126_TEMPUNITMAP 3
#define _P126_LOADUNITMAP 4
#define _P126_PRESSUNITMAP 5
#define _P126_COLORUNITMAP 6
#define _P126_DISTANCEUNITMAP 7
#define _P126_PARTICLEUNITMAP 8
#define _P126_ENERGYUNITMAP 9
#define _P126_PERCENTUNITMAP 10
#define _P126_UNITCOUNT 9
#define _P126_LIGHTUNITCOUNT 4
#define _P126_TEMPUNITCOUNT 2
#define _P126_LOADUNITCOUNT 4
#define _P126_PRESSUNITCOUNT 2
#define _P126_COLORUNITCOUNT 8
#define _P126_DISTANCEUNITCOUNT 4
#define _P126_PARTICLEUNITCOUNT 3
#define _P126_ENERGYUNITCOUNT 4
#define _P126_MAXCLASS _P126_BINCLASSCOUNT
#define _P126_MAXUNIT _P126_UNITCOUNT
//#define _P126_DEVICE // saves another char to flash shown in HA frontend for device "D1mini bedroom", etc
//#define _P126_DEBUG
struct DiscoveryStruct {
// temporary
int taskid;
int ctrlid;
String cmdtopic;
String publish;
String lwttopic;
String lwtup;
String lwtdown;
int qsize;
int pubinterval;
// save to flash
struct savestruct {
byte init;
char prefix[21];
char custom[41];
#ifdef _P126_DEVICE
char device[21];
#endif
bool usename;
bool usecustom;
bool usetask;
bool usevalue;
bool moved;
struct taskstruct {
bool enable;
struct valuestruct {
bool enable;
bool binary;
byte type;
byte unit;
byte unitmap;
} value[4];
} task[TASKS_MAX];
} save;
};
bool _P126_cleaning = false;
unsigned long _P126_time;
byte _P126_increment;
String _P126_log;
String _P126_class[_P126_CLASSCOUNT];
String _P126_binclass[_P126_BINCLASSCOUNT];
String _P126_unit[_P126_UNITCOUNT];
String _P126_lightunit[_P126_LIGHTUNITCOUNT];
String _P126_tempunit[_P126_TEMPUNITCOUNT];
String _P126_loadunit[_P126_LOADUNITCOUNT];
String _P126_pressunit[_P126_PRESSUNITCOUNT];
String _P126_colorunit[_P126_COLORUNITCOUNT];
String _P126_distanceunit[_P126_DISTANCEUNITCOUNT];
String _P126_particleunit[_P126_PARTICLEUNITCOUNT];
String _P126_energyunit[_P126_ENERGYUNITCOUNT];
//---------------------------------------------------------------------------//
boolean Plugin_126(byte function, struct EventStruct *event, String& string) {
boolean success = false;
String tmpnote;
switch (function)
{
case PLUGIN_DEVICE_ADD:
{
Device[++deviceCount].Number = PLUGIN_ID_126;
Device[deviceCount].Type = DEVICE_TYPE_DUMMY;
Device[deviceCount].VType = SENSOR_TYPE_NONE;
Device[deviceCount].Ports = 0;
Device[deviceCount].PullUpOption = false;
Device[deviceCount].InverseLogicOption = false;
Device[deviceCount].FormulaOption = false;
Device[deviceCount].ValueCount = 0;
Device[deviceCount].SendDataOption = false;
Device[deviceCount].TimerOption = true;
Device[deviceCount].TimerOptional = true;
Device[deviceCount].GlobalSyncOption = false;
Device[deviceCount].DecimalsOnly = false;
break;
}
case PLUGIN_GET_DEVICENAME:
{
string = F(PLUGIN_NAME_126);
break;
}
case PLUGIN_WEBFORM_LOAD:
{
//---------------------------------------------------------------------------//
// load user setting
struct DiscoveryStruct discovery;
discovery.ctrlid = 0;
discovery.pubinterval = 0;
discovery.qsize = 0;
discovery.save.init = 0;
LoadCustomTaskSettings(event->TaskIndex, (byte*)&discovery.save, sizeof(discovery.save));
String errnote = F("<br>");
if (discovery.save.init != _P126_VERSION) {
//---------------------------------------------------------------------------//
// clean settings, if major changes in plugin to avoid corrupt config
if (discovery.save.init == 0) {
// set default strings, if new config (and keep if older config)
errnote = F("No settings found.");
strncpy(discovery.save.prefix, "homeassistant", sizeof(discovery.save.prefix));
strncpy(discovery.save.custom, "customstring", sizeof(discovery.save.custom));
} else {
errnote = F("<font color=\"red\">Loaded settings with ID ");
errnote += String(discovery.save.init);
errnote += F(" not matching v");
errnote += String(_P126_VERSION);
errnote += F(".</font>");
}
errnote += F(" Loading defaults.<br><br>");
discovery.save.usecustom = false;
discovery.save.usename = true;
discovery.save.usetask = true;
discovery.save.usevalue = true;
for (byte i = 0; i < TASKS_MAX; i++) {
discovery.save.task[i].enable = false;
for (byte j = 0; j < VARS_PER_TASK; j++) {
discovery.save.task[i].value[j].enable = false;
discovery.save.task[i].value[j].binary = false;
discovery.save.task[i].value[j].type = 0;
discovery.save.task[i].value[j].unit = 0;
discovery.save.task[i].value[j].unitmap = 0;
}
}
}
//---------------------------------------------------------------------------//
// introduction
html_BR();
tmpnote += errnote;
tmpnote += F("This plugin pushes configs that are compliant to home-assistant's discovery feature.");
tmpnote += F("<br>It creates one additional sensor for the ESP node itself which contains system info like wifi-signal, ip-address, etc.");
tmpnote += F(" Interval setting on bottom defines update frequency of that sensor. Set to 0 to disable.");
addFormNote(tmpnote);
//---------------------------------------------------------------------------//
// global settings
addFormSubHeader(F("GLOBAL SETTINGS"));
#ifdef _P126_DEVICE
addFormTextBox(String(F("hardware model")), String(F("Plugin_126_device")), discovery.save.device, 20);
#endif
addFormTextBox(String(F("discovery prefix")), String(F("Plugin_126_prefix")), discovery.save.prefix, 20);
addFormNote(F("Change discovery topic here, if done in home-assistant. Defaults to \"homeassistant\"."));
html_BR();
addFormCheckBox(String(F("include sysname")), String(F("Plugin_126_usename")), discovery.save.usename);
addFormCheckBox(String(F("include custom")), String(F("Plugin_126_usecustom")), discovery.save.usecustom);
addFormCheckBox(String(F("include taskname")), String(F("Plugin_126_usetask")), discovery.save.usetask);
//.addFormCheckBox(String(F("use value name")), String(F("Plugin_126_usevalue")), discovery.save.usevalue);
//.if (discovery.save.usecustom) {
addFormTextBox(String(F("custom string ")), String(F("Plugin_126_custom")), discovery.save.custom, 40);
addFormCheckBox(String(F("move custom to end")), String(F("Plugin_126_moved")), discovery.save.moved);
//.}
html_BR();
tmpnote = F("Adjust how the entity_ids in homeassistant are named.");
tmpnote += F(" Click submit to preview your settings before publishing.");
addFormNote(tmpnote);
//---------------------------------------------------------------------------//
// show example entity_id based on settings
bool b1 = discovery.save.usename;
String s1 = Settings.Name;
bool b2 = discovery.save.usecustom;
String s2 = discovery.save.custom;
bool b3 = discovery.save.usetask;
String s3 = F("%tskname%");
bool b4 = true; //.discovery.save.usevalue;
String s4 = F("%valname%");
if (discovery.save.moved) {
b4 = discovery.save.usecustom;
s4 = discovery.save.custom;
b2 = discovery.save.usetask;
s2 = F("%tskname%");
b3 = discovery.save.usevalue;
s3 = F("%valname%");
}
String entity_id = F("example: ");
entity_id += F("<b>sensor.");
if (b1) {
entity_id += String(s1);
if (b2 || b3 || b4) entity_id += F("_");
}
if (b2) {
entity_id += String(s2);
if (b3 || b4) entity_id += F("_");
}
if (b3) {
entity_id += String(s3);
if (b4) entity_id += F("_");
}
if (b4) {
entity_id += String(s4);
}
entity_id += F("</b>");
entity_id.toLowerCase();
addHtml(entity_id);
//---------------------------------------------------------------------------//
// device settings
int msgcount = _P126_find_sensors(&discovery);
SaveCustomTaskSettings(event->TaskIndex, (byte*)&discovery.save, sizeof(discovery.save)); // need to save unit-map here
if (Settings.TaskDeviceTimer[event->TaskIndex] > 0) msgcount++;
//---------------------------------------------------------------------------//
// command buttons
addFormSubHeader(F("CONTROL"));
tmpnote = F("<br>Configs will NOT be pushed automatically. ");
tmpnote += F("Once plugin is saved, you can use the buttons below.<br>");
tmpnote += F("You can trigger actions via these commands as well: ");
tmpnote += F("\"<b>discovery,update</b>\", \"<b>discovery,delete</b>\" and \"<b>discovery,cleanup</b>\" ");
addFormNote(tmpnote);
//.html_BR();
if (Settings.TaskDeviceEnabled[event->TaskIndex] && !_P126_cleaning) {
html_BR();
addButton(F("/tools?cmd=discovery%2Cupdate"), F("Update Configs"));
addButton(F("/tools?cmd=discovery%2Cdelete"), F("Delete Configs"));
addButton(F("/tools?cmd=discovery%2Ccleanup"), F("Full cleanup"));
html_BR();
int duration = TASKS_MAX * 2 * _P126_INTERVAL /1000/60;
int payloads = TASKS_MAX * 2 * 4;
tmpnote = F("<br><font color=\"red\">Warning!</font> Cleanup will send ");
tmpnote += String(payloads);
tmpnote += F(" empty payloads in about ");
tmpnote += String(duration);
tmpnote += F(" minutes.");
addFormNote(tmpnote);
}
if (_P126_cleaning) {
html_BR();
int duration = (TASKS_MAX * 2 - (_P126_increment + 1)) * _P126_INTERVAL / 1000;
String message = F("<font color=\"red\">CLEANUP IN PROGESS!</font> Remaining time: about ");
message += String(duration);
message += F(" seconds");
addHtml(message);
}
//---------------------------------------------------------------------------//
// notes
addFormSubHeader(F("NOTES"));
_P126_get_ctrl(&discovery);
tmpnote = F("<br>- On update, <font color=\"#07D\">");
tmpnote += String(msgcount);
tmpnote += F("</font> messages will be published.");
if (discovery.qsize < 2 * msgcount) {
tmpnote += F("Your message queue is set to: <font color=\"#07D\">");
tmpnote += String(discovery.qsize);
tmpnote += F("</font>");
tmpnote += F(". Consider increasing it, if not all configs reach homeassistant.");
}
if (discovery.lwtup.length() > 10) {
tmpnote += F("Your LWT Connect Message is <font color=\"#07D\">");
tmpnote += String(discovery.lwtup.length());
tmpnote += F("</font> charackters long");
tmpnote += F(". Consider to shorten it, to reduce payload size.");
}
if (discovery.lwtdown.length() > 10) {
tmpnote += F("Your LWT Disconnect Message is <font color=\"#07D\">");
tmpnote += String(discovery.lwtdown.length());
tmpnote += F("</font> charackters long");
tmpnote += F(". Consider to shorten it, to reduce payload size.");
}
if (!Settings.MQTTRetainFlag) {
tmpnote += F("<br>- Retain option is not set. It's highly advised to set it in advanced settings.");
}
// if (discovery.pubinterval < 500) {
// tmpnote += F("<br>- Message interval is set to <font color=\"#07D\">");
// tmpnote += String(discovery.pubinterval);
// tmpnote += F("</font>ms. Consider increasing it, if not all configs reach homeassistant.");
// }
tmpnote += F("<br>- ESPEasy limits mqtt message size to <font color=\"#07D\">");
tmpnote += String(MQTT_MAX_PACKET_SIZE);
tmpnote += F("</font>, check logs, to see if this affects you.");
tmpnote += F("<br>- Tasks must have a MQTT controller enabled to show up.");
tmpnote += F("<br>- Don't forget to submit this form, before using commands.");
tmpnote += F("<br>- New sensors will be added immediately to homeassistant.");
tmpnote += F(" Changes and deletions require homeassistant to be restarted.");
tmpnote += F("<br><br>v");
tmpnote += _P126_VERSION;
tmpnote += F("; struct size: ");
tmpnote += String(sizeof(discovery));
tmpnote += F("Byte memory / ");
tmpnote += String(sizeof(discovery.save));
tmpnote += F("Byte flash");
addFormNote(tmpnote);
//---------------------------------------------------------------------------//
success = true;
break;
}
case PLUGIN_WEBFORM_SAVE:
{
//---------------------------------------------------------------------------//
// init settings struct
struct DiscoveryStruct discovery;
#ifdef _P126_DEBUG
Serial.println(F("--------------- WEBSAVE INIT ---------------------------"));
Serial.println(F("Filling empty struct"));
#endif
discovery.save.init = _P126_VERSION;
strncpy(discovery.save.prefix, "homeassistant", sizeof(discovery.save.prefix));
discovery.save.usecustom = false;
discovery.save.usename = true;
discovery.save.usetask = true;
discovery.save.usevalue = true;
discovery.save.moved = false;
for (byte i = 0; i < TASKS_MAX; i++) {
discovery.save.task[i].enable = false;
for (byte j = 0; j < VARS_PER_TASK; j++) {
discovery.save.task[i].value[j].enable = false;
discovery.save.task[i].value[j].binary = false;
discovery.save.task[i].value[j].type = 0;
discovery.save.task[i].value[j].unit = 0;
discovery.save.task[i].value[j].unitmap = 0;
}
}
//---------------------------------------------------------------------------//
// copy settings from webserver to settings struct
#ifdef _P126_DEVICE
strncpy(discovery.save.device, WebServer.arg(F("Plugin_126_device")).c_str(), sizeof(discovery.save.device));
#endif
strncpy(discovery.save.prefix, WebServer.arg(F("Plugin_126_prefix")).c_str(), sizeof(discovery.save.prefix));
#ifdef _P126_DEBUG
Serial.print(F("prefix from form: "));
Serial.println(WebServer.arg(F("Plugin_126_prefix")).c_str());
Serial.print(F("prefix saved to struct: "));
Serial.println(String(discovery.save.prefix));
#endif
strncpy(discovery.save.custom, WebServer.arg(F("Plugin_126_custom")).c_str(), sizeof(discovery.save.custom));
#ifdef _P126_DEBUG
Serial.print(F("custom from form: "));
Serial.println(WebServer.arg(F("Plugin_126_custom")).c_str());
Serial.print(F("custom saved to struct: "));
Serial.println(String(discovery.save.custom));
#endif
if (WebServer.arg(F("Plugin_126_custom")).length() == 0) {
discovery.save.usecustom = false;
} else {
discovery.save.usecustom = isFormItemChecked(F("Plugin_126_usecustom"));
}
discovery.save.usename = isFormItemChecked(F("Plugin_126_usename"));
discovery.save.usetask = isFormItemChecked(F("Plugin_126_usetask"));
discovery.save.usevalue = true; //isFormItemChecked(F("Plugin_126_usevalue"));
discovery.save.moved = isFormItemChecked(F("Plugin_126_moved"));
#ifdef _P126_DEBUG
Serial.print(F("usename saved to struct: "));
Serial.println(toString(discovery.save.usename));
Serial.print(F("usecustom saved to struct: "));
Serial.println(toString(discovery.save.usecustom));
Serial.print(F("usetask saved to struct: "));
Serial.println(toString(discovery.save.usetask));
Serial.print(F("usevalue saved to struct: "));
Serial.println(toString(discovery.save.usevalue));
#endif
_P126_find_sensors(&discovery, true);
//---------------------------------------------------------------------------//
// save user settings to flash
SaveCustomTaskSettings(event->TaskIndex, (byte*)&discovery.save, sizeof(discovery.save));
#ifdef _P126_DEBUG
Serial.println(F("saved discovery to flash "));
Serial.println(F("-----------------------------------------------------"));
#endif
//---------------------------------------------------------------------------//
success = true;
break;
}
case PLUGIN_READ:
{
//---------------------------------------------------------------------------//
// load settings
struct DiscoveryStruct discovery;
LoadCustomTaskSettings(event->TaskIndex, (byte*)&discovery.save, sizeof(discovery.save));
//---------------------------------------------------------------------------//
// valid check
if (discovery.save.init != _P126_VERSION) {
addLog(LOG_LEVEL_ERROR, F("[P126] no valid settings found!"));
success = false;
} else {
//---------------------------------------------------------------------------//
// publish system state
_P126_get_ctrl(&discovery);
success = _P126_system_state(&discovery, false);
}
//---------------------------------------------------------------------------//
break;
}
case PLUGIN_WRITE:
{
String tmpString = string;
int argIndex = tmpString.indexOf(',');
if (argIndex)
tmpString = tmpString.substring(0, argIndex);
if (tmpString.equalsIgnoreCase(F("discovery"))) {
success = true;
_P126_log = F("P[126] command issued : ");
_P126_log += string;
addLog(LOG_LEVEL_INFO,_P126_log);
if (_P126_cleaning) {
addLog(LOG_LEVEL_ERROR, F("[P126] cleanup in progress, ignoring command"));
} else {
//---------------------------------------------------------------------------//
// load settings
struct DiscoveryStruct discovery;
_P126_get_id(&discovery); // search for taskid (not given with event)
LoadCustomTaskSettings(discovery.taskid, (byte*)&discovery.save, sizeof(discovery.save));
if (discovery.save.init != _P126_VERSION) {
addLog(LOG_LEVEL_ERROR, F("[P126] no valid settings found!"));
break;
}
_P126_get_ctrl(&discovery);
//---------------------------------------------------------------------------//
argIndex = string.lastIndexOf(',');
tmpString = string.substring(argIndex + 1);
if (tmpString.equalsIgnoreCase(F("update"))) {
_P126_system_config(&discovery, false);
_P126_sensor_config(&discovery, false);
_P126_system_state(&discovery, false);
}
else if (tmpString.equalsIgnoreCase(F("delete"))) {
_P126_delete_configs(&discovery);
}
else if (tmpString.equalsIgnoreCase(F("debug"))) {
_P126_debug(&discovery);
}
else if (tmpString.equalsIgnoreCase(F("cleanup"))) {
int duration = TASKS_MAX * 2 * _P126_INTERVAL / 1000 / 60;
_P126_log = F("[P126] starting cleanup; expected duration is: ");
_P126_log += String(duration);
_P126_log += F(" minutes");
addLog(LOG_LEVEL_INFO, _P126_log);
_P126_cleaning = true; // enable cleanup-mode
_P126_time = millis();
_P126_increment = 0;
_P126_delete_system(&discovery); // run once
_P126_cleanup(&discovery); // run first time
}
else {success = false;}
}
}
break;
}
case PLUGIN_EXIT:
{
//_P126_get_ctrl(ctrlid, ctrldat);
//success = _P126_delete_configs(event->TaskIndex, ctrlid, ctrldat);
//perform cleanup tasks here. For example, free memory
break;
}
case PLUGIN_ONCE_A_SECOND:
{
if (_P126_cleaning && timeOutReached(_P126_time + _P126_INTERVAL)) {
_P126_time = millis();
struct DiscoveryStruct discovery;
LoadCustomTaskSettings(event->TaskIndex, (byte*)&discovery.save, sizeof(discovery.save));
if (discovery.save.init != _P126_VERSION) {
addLog(LOG_LEVEL_ERROR, F("[P126] no valid settings found!"));
break;
}
_P126_get_ctrl(&discovery);
_P126_cleanup(&discovery); // run 2nd to nth time
if (_P126_increment >= TASKS_MAX * 2 - 1) {
_P126_cleaning = false;
_P126_increment = 0;
addLog(LOG_LEVEL_INFO, F("[P126] cleanup completed"));
} else {
tmpnote = F("[P126] cleanup ");
tmpnote += String(_P126_increment);
tmpnote += F(" of ");
tmpnote += String(TASKS_MAX * 2 - 1);
tmpnote += F(" completed");
addLog(LOG_LEVEL_DEBUG, tmpnote);
_P126_increment++;
}
}
success = true;
}
} //switch
return success;
}
//---------------------------------------------------------------------------//
// plugin functions
void _P126_make_classes() {
//---------------------------------------------------------------------------//
// declare classes and units
_P126_class[_P126_GENERIC] = F("generic sensor"); // % raw K
_P126_class[_P126_BATTERY] = F("battery"); // %
_P126_class[_P126_HUMIDITY] = F("humidity"); // %
_P126_class[_P126_LIGHT] = F("illuminance"); // lx lm
_P126_class[_P126_TEMP] = F("temperature"); // °C °F
_P126_class[_P126_PRESSURE] = F("pressure"); // hPa mbar
_P126_class[_P126_PLANT] = F("plant"); // %
_P126_class[_P126_RADIO] = F("radio/RF"); // none
_P126_class[_P126_LOAD] = F("scale/load/weight"); // kg
_P126_binclass[0] = F("generic binary sensor");
_P126_binclass[1] = F("OUTPUT switch");
_P126_binclass[2] = F("battery");
_P126_binclass[3] = F("cold");
_P126_binclass[4] = F("connectivity");
_P126_binclass[5] = F("door");
_P126_binclass[6] = F("garage_door");
_P126_binclass[7] = F("gas");
_P126_binclass[8] = F("heat");
_P126_binclass[9] = F("light");
_P126_binclass[10] = F("lock");
_P126_binclass[11] = F("moisture");
_P126_binclass[12] = F("motion");
_P126_binclass[13] = F("moving");
_P126_binclass[14] = F("occupancy");
_P126_binclass[15] = F("opening");
_P126_binclass[16] = F("plug");
_P126_binclass[17] = F("power");
_P126_binclass[18] = F("presence");
_P126_binclass[19] = F("problem");
_P126_binclass[20] = F("safety");
_P126_binclass[21] = F("smoke");
_P126_binclass[22] = F("sound");
_P126_binclass[23] = F("vibration");
_P126_binclass[24] = F("water");
_P126_binclass[25] = F("window");
_P126_unit[0] = F("NONE ");
_P126_unit[1] = F("%");
_P126_unit[2] = F("dB");
_P126_unit[3] = F("count");
_P126_unit[4] = F("total");
_P126_unit[5] = F("h"); // hours
_P126_unit[6] = F("m"); // minutes
_P126_unit[7] = F("s"); // seconds
_P126_unit[8] = F("raw");
_P126_lightunit[0] = F("lx");
_P126_lightunit[1] = F("lm");
_P126_lightunit[2] = F("infrared");
_P126_lightunit[3] = F("broadband");
_P126_tempunit[0] = F("°C");
_P126_tempunit[1] = F("°F");
_P126_energyunit[0] = F("V");
_P126_energyunit[1] = F("A");
_P126_energyunit[2] = F("W");
_P126_energyunit[3] = F("Pulses");
_P126_energyunit[4] = F("raw");
_P126_loadunit[0] = F("g");
_P126_loadunit[1] = F("kg");
_P126_loadunit[2] = F("lb");
_P126_loadunit[3] = F("raw");
_P126_distanceunit[0] = F("mm");
_P126_distanceunit[1] = F("cm");
_P126_distanceunit[2] = F("m");
_P126_distanceunit[3] = F("ft");
_P126_particleunit[0] = F("pm");
_P126_particleunit[1] = F("ppm");
_P126_particleunit[2] = F("dust");
// _P126_particleunit[1] = F("pm2.5");
// _P126_particleunit[2] = F("pm10");
_P126_pressunit[0] = F("hPa");
_P126_pressunit[1] = F("mbar");
_P126_colorunit[0] = F("r");
_P126_colorunit[1] = F("g");
_P126_colorunit[2] = F("b");
_P126_colorunit[3] = F("W");
_P126_colorunit[4] = F("Y");
_P126_colorunit[5] = F("K");
_P126_colorunit[6] = F("lx");
_P126_colorunit[7] = F("%");
//---------------------------------------------------------------------------//
}
int _P126_find_sensors(struct DiscoveryStruct *discovery) {
int msgcount = _P126_find_sensors(discovery, false);
return msgcount;
}
int _P126_find_sensors(struct DiscoveryStruct *discovery, bool save) {
_P126_log = F("P[126] search active tasks: state of save is : ");
_P126_log += String(save);
addLog(LOG_LEVEL_DEBUG,_P126_log);
_P126_debug2(F("find sensor, save mode : "), save);
int msgcount = 0;
byte firstTaskIndex = 0;
byte lastTaskIndex = TASKS_MAX - 1;
byte lastActiveTaskIndex = 0;
_P126_make_classes();
if (save) {
lastActiveTaskIndex = lastTaskIndex;
} else {
for (byte TaskIndex = firstTaskIndex; TaskIndex <= lastTaskIndex; TaskIndex++) { // find last task
if (Settings.TaskDeviceNumber[TaskIndex]) lastActiveTaskIndex = TaskIndex;
}
}
for (byte TaskIndex = firstTaskIndex; TaskIndex <= lastActiveTaskIndex; TaskIndex++) { // for each task
//discovery->save.task[TaskIndex].enable = false;
_P126_debug2(F("find sensor "));
_P126_debug2(F("taskindex "), TaskIndex);
if (Settings.TaskDeviceNumber[TaskIndex]) {
byte pluginid = Settings.TaskDeviceNumber[TaskIndex]; // if task exists
_P126_debug2(F("pluginid "),pluginid);
byte DeviceIndex = getDeviceIndex(pluginid);
LoadTaskSettings(TaskIndex);
if (Settings.TaskDeviceEnabled[TaskIndex]) { // if task enabled
bool ctrlenabled = false;
_P126_debug2(F("task is enabled "));
for (byte x = 0; x < CONTROLLER_MAX; x++) { // if any controller enabled //[TODO] only if specific controller matches
if (Settings.TaskDeviceSendData[x][TaskIndex]) ctrlenabled = true;
}
if (ctrlenabled) {
if (Device[DeviceIndex].ValueCount != 0) { // only tasks with values
_P126_log = F("P[126] found active task with id : ");
_P126_log += String(TaskIndex);
addLog(LOG_LEVEL_DEBUG,_P126_log);
// Serial.println(_P126_log);
_P126_debug2(F("ctrl enabled and values available "));
if (!save) {
String header = F("Task ");
header += String(TaskIndex + 1);
header += F(" - ");
header += getPluginNameFromDeviceIndex(DeviceIndex);
addFormSubHeader(header);
_P126_debug2(F("print header "),header);
}
byte unitmap; //[todo] where to declare? compiler complaining
for (byte x = 0; x < VARS_PER_TASK; x++) { // for each value
if (x < Device[DeviceIndex].ValueCount && !(x > 0 && pluginid == _P126_HASWITCH)) {
if (String(ExtraTaskSettings.TaskDeviceValueNames[x]).length() > 0) {
_P126_log = F("P[126] found value with name : ");
_P126_log += String(ExtraTaskSettings.TaskDeviceValueNames[x]);
addLog(LOG_LEVEL_DEBUG,_P126_log);
// Serial.println(_P126_log);
_P126_debug2(F("starting with value "),x);
msgcount++;
String enableid = F("P126_");
enableid += String(TaskIndex);
enableid += F("_");
enableid += String(x);
enableid += F("_enable");
_P126_debug2(F("enableid "),enableid);
String classid = F("P126_");
classid += String(TaskIndex);
classid += F("_");
classid += String(x);
classid += F("_type");
_P126_debug2(F("classid "),classid);
String unitid = F("P126_");
unitid += String(TaskIndex);
unitid += F("_");
unitid += String(x);
unitid += F("_unit");
_P126_debug2(F("unitid: "),unitid);
String outputid = F("P126_");
outputid += String(TaskIndex);
outputid += F("_");
outputid += String(x);
outputid += F("_output");
_P126_debug2(F("outputid: "),outputid);
if (!save) { // if loading webform
//---------------------------------------------------------------------------//
// print value header
String valuename = F("<font color=\"#07D\"><b>");
valuename += String(ExtraTaskSettings.TaskDeviceName);
if (pluginid != _P126_HASWITCH) {
valuename += F(" ");
valuename += String(ExtraTaskSettings.TaskDeviceValueNames[x]);
valuename += F("</b></font>");
}
html_TR_TD();