-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathad2mqtt.cpp
1408 lines (1270 loc) · 55.8 KB
/
ad2mqtt.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
/**
* @file ad2mqtt.cpp
* @author Sean Mathews <[email protected]>
* @date 07/31/2021
* @version 1.0.0
*
* @brief Connect to an MQTT broker and publish state updates as
* well as subscribe to a command topic to listen for verbs.
*
* @copyright Copyright (C) 2021 Nu Tech Software Solutions, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
// FreeRTOS includes
#include "freertos/FreeRTOS.h"
#include "freertos/event_groups.h"
// Disable via sdkconfig
#if CONFIG_AD2IOT_MQTT_CLIENT
static const char *TAG = "MQTT";
// AlarmDecoder std includes
#include "alarmdecoder_main.h"
// esp component includes
#include "mqtt_client.h"
/* Constants that aren't configurable in menuconfig */
#define MQTT_COMMAND "mqtt"
#define MQTT_PREFIX "mq"
#define MQTT_ENABLE_CFGKEY "enable"
#define MQTT_URL_CFGKEY "url"
#define MQTT_CMDEN_CFGKEY "commands"
#define MQTT_TPREFIX_CFGKEY "tprefix"
#define MQTT_DPREFIX_CFGKEY "dprefix"
#define MQTT_SAS_CFGKEY "switch"
#define MAX_SEARCH_KEYS 9
// NV storage sub key values for virtual search switch
#define SK_NOTIFY_TOPIC "N"
#define SK_DEFAULT_STATE "D"
#define SK_AUTO_RESET "R"
#define SK_TYPE_LIST "T"
#define SK_PREFILTER_REGEX "P"
#define SK_OPEN_REGEX_LIST "O"
#define SK_CLOSED_REGEX_LIST "C"
#define SK_TROUBLE_REGEX_LIST "F"
#define SK_OPEN_OUTPUT_FMT "o"
#define SK_CLOSED_OUTPUT_FMT "c"
#define SK_TROUBLE_OUTPUT_FMT "f"
#define MQTT_TOPIC_PREFIX "ad2iot"
#define MQTT_LWT_TOPIC_SUFFIX "will"
#define MQTT_LWT_MESSAGE "offline"
#define MQTT_COMMANDS_TOPIC "commands"
#define MQTT_COMMAND_MAX_DATA_LEN 256
#define EXAMPLE_BROKER_URI "mqtt://mqtt.eclipseprojects.io"
static esp_mqtt_client_handle_t mqtt_client = nullptr;
static std::string mqttclient_UUID;
static std::string mqttclient_TPREFIX = "";
static std::string mqttclient_DPREFIX = "";
static std::vector<AD2EventSearch *> mqtt_AD2EventSearches;
static int commands_enabled = 0;
// prefix name lines to identy the source. User can change.
#define NAME_PREFIX "AD2IoT"
// Default MQTT message settings excluding LWT.
#define MQTT_DEF_QOS 1 // AT Least Once
#define MQTT_DEF_RETAIN 1 // Retain
#define MQTT_DEF_STORE 0 // No local storage
// LOG settings
//#define MQTT_EVENT_LOGGING
#if 0
/**
* @brief custom outbox handler
* see: MQTT_CUSTOM_OUTBOX
*
*/
esp_err_t outbox_set_pending(outbox_handle_t outbox, int msg_id, pending_state_t pending)
{
outbox_item_handle_t item = outbox_get(outbox, msg_id);
if (item) {
item->pending = pending;
return ESP_OK;
}
return ESP_FAIL;
}
#endif
/**
* @brief helper to send config json for auto discovery.
*
* @param [in]device_type - const char * - ex. 'binary_sensor'
* @param [in]device_class - const char * - ex. 'smoke'
* @param [in]type - const char * - ex. 'zone'
* @param [in]id - uint8_t - unique ID 000 to 255 for type
* @param [in]id_append_id - bool - append id to [unique|object]_id fields
* @param [in]name - const char * - name
* @param [in]name_append_id - bool - append id to name field
* @param [in]pairs - std::map<std::string,std::string> - attributes to add to config.
*/
void mqtt_publish_device_config(const char *device_type, const char *device_class,
const char *ad2type, uint8_t id, bool id_append_id,
const char* name, bool name_append_id,
std::map<std::string, std::string> pairs)
{
cJSON *root = cJSON_CreateObject();
// if id > 0 append id else no ID
std::string szid;
if (id_append_id) {
szid = ad2_to_string(id);
}
// Name
std::string value = name;
if (name_append_id) {
value += ad2_to_string(id);
}
cJSON_AddStringToObject(root, "name", value.c_str());
// unique_id ad2iot_{ad2type}[_{id}]
// object_id ad2iot_{ad2type}[_{id}]
// ex. ad2iot_zone_1
value = "ad2iot_";
value += ad2type;
if (id) {
value += szid;
}
cJSON_AddStringToObject(root, "unique_id", value.c_str());
cJSON_AddStringToObject(root, "object_id", value.c_str());
// set the device class
cJSON_AddStringToObject(root, "device_class", device_class);
// add the name value pairs
for (const auto& kv : pairs) {
cJSON_AddStringToObject(root, kv.first.c_str(), kv.second.c_str());
}
// compress json and convert to char *
char *szjson = cJSON_Print(root);
cJSON_Minify(szjson);
// set the correct topic for the config document
std::string topic = "";
if (mqttclient_DPREFIX.length()) {
topic = mqttclient_DPREFIX;
}
topic += device_type;
topic += "/";
topic += mqttclient_UUID;
topic += "/";
topic += ad2type;
if (id) {
topic += szid;
}
topic += "/config";
// non blocking publish
esp_mqtt_client_enqueue(mqtt_client,
topic.c_str(),
szjson,
0,
MQTT_DEF_QOS,
MQTT_DEF_RETAIN,
MQTT_DEF_STORE);
// cleanup free memory
cJSON_free(szjson);
cJSON_Delete(root);
}
/**
* @brief helper to send config json for a given partition.
*
*/
void mqtt_send_partition_config(AD2VirtualPartitionState *s)
{
// Partiting number string.
std::string szpid = ad2_to_string(s->partition);
// Base topic for device
std::string topic = mqttclient_TPREFIX + MQTT_TOPIC_PREFIX "/";
topic += mqttclient_UUID;
// alarm_control_panel
mqtt_publish_device_config("alarm_control_panel", "alarm_control_panel", "p",
s->partition, true,
NAME_PREFIX " Partition #", true, {{
{ "state_topic", topic+"/partitions/"+szpid },
{ "value_template", "{% if value_json.alarm_sounding == true or value_json.alarm_event_occurred == true %}triggered{% elif value_json.armed_stay == true %}{% if value_json.entry_delay_off == true %}armed_night{% else %}armed_home{% endif %}{% elif value_json.armed_away == true %}{% if value_json.entry_delay_off == true %}armed_vacation{% elif value_json.entry_delay_off == false %}armed_away{% endif %}{% else %}disarmed{% endif %}" },
{ "command_topic", topic+"/commands"},
{ "command_template", "{ \"vpart\": 0, \"action\": \"{{ action }}\", \"code\": \"{{ code }}\"}"},
{ "availability_topic", topic+"/status"},
{ "code", "REMOTE_CODE"},
{ "payload_arm_home", "ARM_STAY"},
{ "payload_trigger", "PANIC_ALARM"},
{ "icon", "mdi:shield-home"},
{ "sw_version", FIRMWARE_VERSION}
}
});
// ac_power
mqtt_publish_device_config("binary_sensor", "power", "ac_power",
0, false,
NAME_PREFIX " AC Power", false, {{
{ "state_topic", topic+"/partitions/"+szpid },
{ "value_template", "{% if value_json.ac_power == true %}ON{% else %}OFF{% endif %}" },
{ "availability_topic", topic+"/status"}
}
});
// partition fire
mqtt_publish_device_config("binary_sensor", "smoke", "fire_p",
s->partition, true,
NAME_PREFIX " Fire Partition #", true, {{
{ "state_topic", topic+"/partitions/"+szpid },
{ "value_template", "{% if value_json.fire_alarm == true %}ON{% else %}OFF{% endif %}" },
{ "availability_topic", topic+"/status"}
}
});
// partition chime
mqtt_publish_device_config("binary_sensor", "running", "chime_p",
s->partition, true,
NAME_PREFIX " Chime Mode Partition #", true, {{
{ "state_topic", topic+"/partitions/"+szpid },
{ "value_template", "{% if value_json.chime_on == true %}ON{% else %}OFF{% endif %}" },
{ "availability_topic", topic+"/status"}
}
});
}
/**
* @brief helper to send config json for every partition zones.
*
*/
void mqtt_send_fw_version(const char *available_version)
{
int msg_id;
if (mqtt_client != nullptr) {
std::string sTopic = mqttclient_TPREFIX + MQTT_TOPIC_PREFIX "/";
sTopic+=mqttclient_UUID;
sTopic+="/fw_version";
cJSON *root = cJSON_CreateObject();
cJSON_AddStringToObject(root, "installed", FIRMWARE_VERSION);
cJSON_AddStringToObject(root, "available", available_version);
char *state = cJSON_Print(root);
cJSON_Minify(state);
// Non blocking. We must not block AlarmDecoderParser
msg_id = esp_mqtt_client_enqueue(mqtt_client,
sTopic.c_str(),
state,
0,
MQTT_DEF_QOS,
MQTT_DEF_RETAIN,
MQTT_DEF_STORE);
cJSON_free(state);
cJSON_Delete(root);
}
}
/**
* @brief helper to send config json for every partition zones.
*
* TODO: This and other mqtt_client_enqueue calls will stack up
* a lot of memory for larger systems. This should instead be
* put into an efficient task list to be processed over time
* as resources are available. In this design it saves all of the
* JSON data and more for each enqueue.
*/
void mqtt_send_partition_zone_configs(AD2VirtualPartitionState *s)
{
// Send panel_power_0 config
std::string topic = mqttclient_TPREFIX + MQTT_TOPIC_PREFIX "/";
topic += mqttclient_UUID;
for (uint8_t zn : s->zone_list) {
std::string _type;
AD2Parse.getZoneType(zn, _type);
std::string _alpha;
AD2Parse.getZoneString(zn, _alpha);
mqtt_publish_device_config("binary_sensor", _type.c_str(), "zone_",
zn, true,
_alpha.c_str(), false, {{
{ "state_topic", topic+"/zones/"+ad2_to_string(zn) },
{ "value_template", "{% if value_json.state == 'CLOSE' %}OFF{% else %}ON{% endif %}" },
{ "availability_topic", topic+"/status"}
}
});
}
}
/**
* @brief Callback for MQTT_EVENT_CONNECTED event.
* Preform subscribe to commands and initial publish to status and info.
*
* @param [in]client esp_mqtt_client_handle_t
*/
void mqtt_on_connect(esp_mqtt_client_handle_t client)
{
std::string topic;
// Subscribe to command inputs for remote control if enabled.
if (commands_enabled) {
ESP_LOGI(TAG, "Warning! MQTT commands subscription enabled. Not sure on public servers.");
topic = mqttclient_TPREFIX + MQTT_TOPIC_PREFIX "/";
topic += mqttclient_UUID;
topic += "/" MQTT_COMMANDS_TOPIC;
esp_mqtt_client_subscribe(client,
topic.c_str(),
MQTT_DEF_QOS);
}
// Publish we are Online
topic = mqttclient_TPREFIX + MQTT_TOPIC_PREFIX "/";
topic += mqttclient_UUID;
topic += "/status";
// non blocking.
esp_mqtt_client_enqueue(mqtt_client,
topic.c_str(),
"online",
0,
MQTT_DEF_QOS,
MQTT_DEF_RETAIN,
MQTT_DEF_STORE);
// Publish our device HW/FW info.
cJSON *root = ad2_get_ad2iot_device_info_json();
topic = mqttclient_TPREFIX + MQTT_TOPIC_PREFIX "/";
topic += mqttclient_UUID;
topic += "/info";
char *state = cJSON_Print(root);
cJSON_Minify(state);
// non blocking.
esp_mqtt_client_enqueue(client,
topic.c_str(),
state,
0,
MQTT_DEF_QOS,
MQTT_DEF_RETAIN,
MQTT_DEF_STORE);
cJSON_free(state);
cJSON_Delete(root);
// set available version to current for now. Will be updated if new version available.
mqtt_send_fw_version(FIRMWARE_VERSION);
// Send firmware_update config
topic = mqttclient_TPREFIX + MQTT_TOPIC_PREFIX "/";
topic += mqttclient_UUID;
mqtt_publish_device_config("binary_sensor", "update", "fw_version",
0, false,
NAME_PREFIX " Firmware", false, {{
{ "state_topic", topic+"/fw_version" },
{ "value_template", "{% if value_json.installed != value_json.available %}ON{% else %}OFF{% endif %}" },
{ "availability_topic", topic+"/status"}
}
});
mqtt_publish_device_config("button", "update", "fw_update",
0, false,
NAME_PREFIX " Start firmware update", false, {{
{ "availability_topic", topic+"/fw_version" },
{ "availability_template", "{% if value_json.installed != value_json.available %}online{% else %}offline{% endif %}" },
{ "command_topic", topic+"/commands" },
{ "payload_press", "{\"action\": \"FW_UPDATE\"}" }
}
});
// Publish panel config info for home assistant or others for discovery
// for each partition that is configured with 'vpart' command.
for (int n = 0; n <= AD2_MAX_VPARTITION; n++) {
AD2VirtualPartitionState *s = ad2_get_partition_state(n);
if (s) {
mqtt_send_partition_config(s);
mqtt_send_partition_zone_configs(s);
}
}
// Send virtual switches in mqtt_AD2EventSearches
topic = mqttclient_TPREFIX + MQTT_TOPIC_PREFIX "/";
topic += mqttclient_UUID;
for (auto &sw : mqtt_AD2EventSearches) {
// Grab the topic using the virtusal switch ID pre saved into INT_ARG
std::string name = "NA";
std::string key = std::string(MQTT_PREFIX) + std::string(MQTT_SAS_CFGKEY);
ad2_get_nv_slot_key_string(key.c_str(), sw->INT_ARG, SK_NOTIFY_TOPIC, name);
ad2_trim(name);
std::string _type = "door";
mqtt_publish_device_config(
"binary_sensor", _type.c_str(), "switch_",
sw->INT_ARG, true,
name.c_str(), false, {{
{ "state_topic", topic+"/switches/"+ad2_to_string(sw->INT_ARG) },
{ "value_template", "{{value_json.state}}" },
{ "availability_topic", topic+"/status" }
}
});
}
}
/**
* @brief mqtt event callback handler.
*
* @param [in]handler_args void *
* @param [in]base esp_event_base_t
* @param [in]event_id int32_t
* @param [in]event_data void *
*
*/
static esp_err_t ad2_mqtt_event_handler(esp_mqtt_event_handle_t event_data)
{
esp_mqtt_client_handle_t client = event_data->client;
// your_context_t *context = event->context;
switch (event_data->event_id) {
case MQTT_EVENT_CONNECTED:
#if defined(MQTT_EVENT_LOGGING)
ESP_LOGI(TAG, "MQTT_EVENT_CONNECTED");
#endif
mqtt_on_connect(client);
break;
case MQTT_EVENT_DISCONNECTED:
#if defined(MQTT_EVENT_LOGGING)
ESP_LOGI(TAG, "MQTT_EVENT_DISCONNECTED");
#endif
break;
case MQTT_EVENT_SUBSCRIBED:
#if defined(MQTT_EVENT_LOGGING)
ESP_LOGI(TAG, "MQTT_EVENT_SUBSCRIBED, msg_id=%d", event_data->msg_id);
#endif
break;
case MQTT_EVENT_UNSUBSCRIBED:
#if defined(MQTT_EVENT_LOGGING)
ESP_LOGI(TAG, "MQTT_EVENT_UNSUBSCRIBED, msg_id=%d", event_data->msg_id);
#endif
break;
case MQTT_EVENT_PUBLISHED:
#if defined(MQTT_EVENT_LOGGING)
ESP_LOGI(TAG, "MQTT_EVENT_PUBLISHED, msg_id=%d", event_data->msg_id);
#endif
break;
case MQTT_EVENT_DATA:
#if defined(MQTT_EVENT_LOGGING)
ESP_LOGI(TAG, "MQTT_EVENT_DATA");
printf("TOPIC=%.*s\r\n", event_data->topic_len, event_data->topic);
printf("DATA=%.*s\r\n", event_data->data_len, event_data->data);
#endif
// test if commands subscription is enabled
if ( commands_enabled ) {
// Sanity test topic is the size of ```commands``` topic name.
// Topic pattern to confirm command
std::string topic_path;
topic_path = mqttclient_TPREFIX + MQTT_TOPIC_PREFIX "/";
topic_path += mqttclient_UUID;
topic_path += "/" MQTT_COMMANDS_TOPIC;
if ( event_data->topic_len == topic_path.length() ) {
std::string topic( event_data->topic, event_data->topic_len );
if ( topic.compare(topic_path) == 0 ) {
// We only want fresh messages no recordings.
// Check for retain flag skip if true.
if ( event_data->retain ) {
break;
}
// sanity check the event_data->data_len
if ( event_data->data_len < MQTT_COMMAND_MAX_DATA_LEN ) {
std::string command( event_data->data, event_data->data_len );
// grab the json buffer
// {
// vpart: {{ number virtual partition ID see ```vpart``` command. }},
// code: '{{ string code }}',
// action: '{{ string action }}',
// arg: '{{ string argument }}'
// }
cJSON * root = cJSON_Parse( command.c_str() );
if (root) {
cJSON *ovpart = NULL;
cJSON *ocode = NULL;
cJSON *oaction = NULL;
cJSON *oarg = NULL;
ovpart = cJSON_GetObjectItemCaseSensitive(root, "vpart");
ocode = cJSON_GetObjectItemCaseSensitive(root, "code");
oaction = cJSON_GetObjectItemCaseSensitive(root, "action");
oarg = cJSON_GetObjectItemCaseSensitive(root, "arg");
int vpart = 0; // default partition
std::string code = "";
std::string action = "";
std::string arg = "";
if ( cJSON_IsNumber(ovpart) ) {
vpart = ovpart->valuedouble;
}
if ( cJSON_IsString(ocode) ) {
code = ocode->valuestring;
}
if ( cJSON_IsString(oaction) && (oaction->valuestring != NULL) ) {
action = oaction->valuestring;
}
if ( cJSON_IsString(oarg) && (oarg->valuestring != NULL) ) {
arg = oarg->valuestring;
}
ESP_LOGI(TAG, "vpart: %i, code: '%s', action: %s, arg: %s", vpart, code.c_str(), action.c_str(), arg.c_str());
if ( action.compare("DISARM") == 0 ) {
ad2_disarm(code, vpart);
} else if ( action.compare("ARM_STAY") == 0 ) {
ad2_arm_stay(code, vpart);
} else if ( action.compare("ARM_AWAY") == 0 ) {
ad2_arm_away(code, vpart);
} else if ( action.compare("EXIT") == 0 ) {
ad2_exit_now(vpart);
} else if ( action.compare("CHIME_TOGGLE") == 0 ) {
ad2_chime_toggle(code, vpart);
} else if ( action.compare("AUX_ALARM") == 0 ) {
ad2_aux_alarm(vpart);
} else if ( action.compare("PANIC_ALARM") == 0 ) {
ad2_panic_alarm(vpart);
} else if ( action.compare("FIRE_ALARM") == 0 ) {
ad2_fire_alarm(vpart);
} else if ( action.compare("BYPASS") == 0 ) {
ad2_bypass_zone(code, vpart, std::atoi(arg.c_str()));
} else if ( action.compare("SEND_RAW") == 0 ) {
ad2_send(arg);
} else if ( action.compare("FW_UPDATE") == 0 ) {
hal_ota_do_update("");
} else {
// unknown command
}
cJSON_Delete(root);
} else {
// JSON parse error
ESP_LOGI(TAG, "json parse error '%s'", command.c_str());
}
} else {
ESP_LOGI(TAG, "invalid data len");
}
} else {
ESP_LOGI(TAG, "invalid topic path");
}
} else {
ESP_LOGI(TAG, "invalid topic len");
}
}
break;
case MQTT_EVENT_ERROR:
#if defined(MQTT_EVENT_LOGGING)
ESP_LOGI(TAG, "MQTT_EVENT_ERROR");
#endif
break;
default:
#if defined(MQTT_EVENT_LOGGING)
ESP_LOGI(TAG, "Other event id:%d", event_data->event_id);
#endif
break;
}
return ESP_OK;
}
/**
* @brief ON_LRR callback for all AlarmDecoder API event subscriptions.
*
* @param [in]msg std::string panel message.
* @param [in]s AD2VirtualPartitionState *.
* @param [in]arg cast as int for event type (ON_ARM,,,).
*
*/
void mqtt_on_lrr(std::string *msg, AD2VirtualPartitionState *s, void *arg)
{
int msg_id;
if (mqtt_client != nullptr) {
std::string sTopic = mqttclient_TPREFIX + MQTT_TOPIC_PREFIX "/";
sTopic+=mqttclient_UUID;
sTopic+="/cid";
cJSON *root = cJSON_CreateObject();
cJSON_AddStringToObject(root, "event_message", msg->c_str());
char *state = cJSON_Print(root);
cJSON_Minify(state);
// Non blocking. We must not block AlarmDecoderParser
msg_id = esp_mqtt_client_enqueue(mqtt_client,
sTopic.c_str(),
state,
0,
MQTT_DEF_QOS,
MQTT_DEF_RETAIN,
MQTT_DEF_STORE);
cJSON_free(state);
cJSON_Delete(root);
}
}
/**
* @brief ON_FIRMWARE_VERSION
* Called when a new firmware version is available.
*
* @param [in]msg std::string new version string.
* @param [in]s nullptr
* @param [in]arg nullptr.
*
*/
void on_new_firmware_cb(std::string *msg, AD2VirtualPartitionState *s, void *arg)
{
mqtt_send_fw_version(msg->c_str());
}
/**
* @brief ON_ZONE_CHANGE callback for all AlarmDecoder API event subscriptions.
*
* @param [in]msg std::string panel message.
* @param [in]s AD2VirtualPartitionState *.
* @param [in]arg cast as int for event type (ON_ARM,,,).
*
*/
void mqtt_on_zone_change(std::string *msg, AD2VirtualPartitionState *s, void *arg)
{
int msg_id;
if (mqtt_client != nullptr && s) {
std::string sTopic = mqttclient_TPREFIX + MQTT_TOPIC_PREFIX "/";
sTopic+=mqttclient_UUID;
sTopic+="/zones/";
// Append the zone to the topic string
sTopic+=ad2_to_string((int)s->zone);
cJSON *root = cJSON_CreateObject();
std::string buf;
// grab the verb(FOO) 'ZONE FOO 001'
ad2_copy_nth_arg(buf, (char *)s->last_event_message.c_str(), 1);
cJSON_AddStringToObject(root, "state", buf.c_str());
cJSON_AddNumberToObject(root, "partition", s->partition);
cJSON_AddNumberToObject(root, "mask", s->address_mask_filter);
std::string zalpha;
AD2Parse.getZoneString((int)s->zone, zalpha);
cJSON_AddStringToObject(root, "name", zalpha.c_str());
char *state = cJSON_Print(root);
cJSON_Minify(state);
// Non blocking. We must not block AlarmDecoderParser
msg_id = esp_mqtt_client_enqueue(mqtt_client,
sTopic.c_str(),
state,
0,
MQTT_DEF_QOS,
MQTT_DEF_RETAIN,
MQTT_DEF_STORE);
cJSON_free(state);
cJSON_Delete(root);
}
}
/**
* @brief Generic callback for all AlarmDecoder API event subscriptions.
*
* @param [in]msg std::string panel message.
* @param [in]s AD2VirtualPartitionState *.
* @param [in]arg cast as int for event type (ON_ARM,,,).
*
*/
void mqtt_on_state_change(std::string *msg, AD2VirtualPartitionState *s, void *arg)
{
int msg_id;
if (mqtt_client != nullptr && s) {
std::string sTopic = mqttclient_TPREFIX + MQTT_TOPIC_PREFIX "/";
sTopic+=mqttclient_UUID;
sTopic+="/partitions/";
sTopic+=ad2_to_string(s->partition);
cJSON *root = ad2_get_partition_state_json(s);
cJSON_AddStringToObject(root, "event", AD2Parse.event_str[(int)arg].c_str());
char *state = cJSON_Print(root);
cJSON_Minify(state);
// Non blocking. We must not block AlarmDecoderParser
msg_id = esp_mqtt_client_enqueue(mqtt_client,
sTopic.c_str(),
state,
0,
MQTT_DEF_QOS,
MQTT_DEF_RETAIN,
MQTT_DEF_STORE);
if (msg_id == -1) {
ESP_LOGE(TAG, "esp_mqtt_client_enqueue failed.");
}
cJSON_free(state);
cJSON_Delete(root);
}
}
/**
* cleanup memory
*/
void mqtt_free()
{
__attribute__((__unused__)) esp_err_t err;
if (mqtt_client) {
err = esp_mqtt_client_destroy(mqtt_client);
mqtt_client = nullptr;
}
}
/**
* @brief Search match callback.
* Called when the current message matches a AD2EventSearch test.
*
* @param [in]msg std::string new version string.
* @param [in]s nullptr
* @param [in]arg nullptr.
*
*/
void on_search_match_cb_mqtt(std::string *msg, AD2VirtualPartitionState *s, void *arg)
{
AD2EventSearch *es = (AD2EventSearch *)arg;
std::string message = es->out_message;
// Grab the topic using the virtual switch ID pre saved into INT_ARG
// publishing event
int msg_id;
if (mqtt_client != nullptr) {
std::string sTopic = mqttclient_TPREFIX + MQTT_TOPIC_PREFIX "/";
sTopic+=mqttclient_UUID;
sTopic+="/switches/";
sTopic+=ad2_to_string(es->INT_ARG);
cJSON *root = cJSON_CreateObject();
cJSON_AddStringToObject(root, "state", es->out_message.c_str());
char *state = cJSON_Print(root);
cJSON_Minify(state);
// Non blocking. We must not block AlarmDecoderParser
msg_id = esp_mqtt_client_enqueue(mqtt_client,
sTopic.c_str(),
state,
0,
MQTT_DEF_QOS,
MQTT_DEF_RETAIN,
MQTT_DEF_STORE);
cJSON_free(state);
cJSON_Delete(root);
}
}
/**
* Command support values.
*/
enum {
MQTT_ENABLE_CFGKEY_ID = 0,
MQTT_URL_CFGKEY_ID,
MQTT_CMDEN_CFGKEY_ID,
MQTT_TPREFIX_CFGKEY_ID,
MQTT_DPREFIX_CFGKEY_ID,
MQTT_SAS_CFGKEY_ID
};
char * MQTT_SUBCMD [] = {
(char*)MQTT_ENABLE_CFGKEY,
(char*)MQTT_URL_CFGKEY,
(char*)MQTT_CMDEN_CFGKEY,
(char*)MQTT_TPREFIX_CFGKEY,
(char*)MQTT_DPREFIX_CFGKEY,
(char*)MQTT_SAS_CFGKEY,
0 // EOF
};
/**
* MQTT smart alert switch command event processing
* command: [COMMAND] [SUB] <id> <setting> <arg1> <arg2>
* ex. Switch #0 [N]otification slot 0
* [COMMAND] [SUB] 0 N 0
*/
static void _cli_cmd_mqtt_smart_alert_switch(std::string &subcmd, char *instring)
{
int i;
int slot = -1;
std::string buf;
std::string arg1;
std::string arg2;
std::string tmpsz;
// get the sub command value validation
std::string key = std::string(MQTT_PREFIX) + subcmd.c_str();
if (ad2_copy_nth_arg(buf, instring, 2) >= 0) {
slot = std::atoi (buf.c_str());
}
// add the slot# to the key max 99 slots.
if (slot > 0 && slot < 100) {
if (ad2_copy_nth_arg(buf, instring, 3) >= 0) {
// sub key suffix.
std::string sk = ad2_string_printf("%c", buf[0]);
/* setting */
switch(buf[0]) {
case '-': // Remove entry
ad2_set_nv_slot_key_string(key.c_str(), slot, SK_NOTIFY_TOPIC, NULL);
ad2_set_nv_slot_key_int(key.c_str(), slot, SK_DEFAULT_STATE, -1);
ad2_set_nv_slot_key_int(key.c_str(), slot, SK_AUTO_RESET, -1);
ad2_set_nv_slot_key_string(key.c_str(), slot, SK_TYPE_LIST, NULL);
ad2_set_nv_slot_key_string(key.c_str(), slot, SK_PREFILTER_REGEX, NULL);
ad2_set_nv_slot_key_string(key.c_str(), slot, SK_OPEN_REGEX_LIST, NULL);
ad2_set_nv_slot_key_string(key.c_str(), slot, SK_CLOSED_REGEX_LIST, NULL);
ad2_set_nv_slot_key_string(key.c_str(), slot, SK_TROUBLE_REGEX_LIST, NULL);
ad2_set_nv_slot_key_string(key.c_str(), slot, SK_OPEN_OUTPUT_FMT, NULL);
ad2_set_nv_slot_key_string(key.c_str(), slot, SK_CLOSED_OUTPUT_FMT, NULL);
ad2_set_nv_slot_key_string(key.c_str(), slot, SK_TROUBLE_OUTPUT_FMT, NULL);
ad2_printf_host(false, "Deleteing smartswitch #%i.\r\n", slot);
break;
case SK_NOTIFY_TOPIC[0]: // MQTT Topic
// consume the arge and to EOL
ad2_copy_nth_arg(arg1, instring, 4, true);
ad2_set_nv_slot_key_string(key.c_str(), slot, sk.c_str(), arg1.c_str());
ad2_printf_host(false, "Setting smartswitch #%i MQTT topic to '%s'.\r\n", slot, arg1.c_str());
break;
case SK_DEFAULT_STATE[0]: // Default state
ad2_copy_nth_arg(arg1, instring, 4);
i = std::atoi (arg1.c_str());
ad2_set_nv_slot_key_int(key.c_str(), slot, sk.c_str(), i);
ad2_printf_host(false, "Setting smartswitch #%i to use default state '%s' %i.\r\n", slot, AD2Parse.state_str[i].c_str(), i);
break;
case SK_AUTO_RESET[0]: // Auto Reset
ad2_copy_nth_arg(arg1, instring, 4);
i = std::atoi (arg1.c_str());
ad2_set_nv_slot_key_int(key.c_str(), slot, sk.c_str(), i);
ad2_printf_host(false, "Setting smartswitch #%i auto reset value %i.\r\n", slot, i);
break;
case SK_TYPE_LIST[0]: // Message type filter list
// consume the arge and to EOL
ad2_copy_nth_arg(arg1, instring, 4, true);
ad2_set_nv_slot_key_string(key.c_str(), slot, sk.c_str(), arg1.c_str());
ad2_printf_host(false, "Setting smartswitch #%i message type filter list to '%s'.\r\n", slot, arg1.c_str());
break;
case SK_PREFILTER_REGEX[0]: // Pre filter REGEX
// consume the arge and to EOL
ad2_copy_nth_arg(arg1, instring, 4, true);
ad2_set_nv_slot_key_string(key.c_str(), slot, sk.c_str(), arg1.c_str());
ad2_printf_host(false, "Setting smartswitch #%i pre filter regex to '%s'.\r\n", slot, arg1.c_str());
break;
case SK_OPEN_REGEX_LIST[0]: // Open state REGEX list editor
case SK_CLOSED_REGEX_LIST[0]: // Closed state REGEX list editor
case SK_TROUBLE_REGEX_LIST[0]: // Trouble state REGEX list editor
// Add index to file name to track N number of elements.
ad2_copy_nth_arg(arg1, instring, 4);
i = std::atoi (arg1.c_str());
if ( i > 0 && i < MAX_SEARCH_KEYS) {
// consume the arge and to EOL
ad2_copy_nth_arg(arg2, instring, 5, true);
std::string op = arg2.length() > 0 ? "Setting" : "Clearing";
sk+=ad2_string_printf("%02i", i);
if (buf[0] == SK_OPEN_REGEX_LIST[0]) {
tmpsz = "OPEN";
}
if (buf[0] == SK_CLOSED_REGEX_LIST[0]) {
tmpsz = "CLOSED";
}
if (buf[0] == SK_TROUBLE_REGEX_LIST[0]) {
tmpsz = "TROUBLE";
}
ad2_set_nv_slot_key_string(key.c_str(), slot, sk.c_str(), arg2.c_str());
ad2_printf_host(false, "%s smartswitch #%i REGEX filter #%02i for state '%s' to '%s'.\r\n", op.c_str(), slot, i, tmpsz.c_str(), arg2.c_str());
} else {
ad2_printf_host(false, "Error invalid index %i. Valid values are 1-8.\r\n", slot, i);
}
break;
case SK_OPEN_OUTPUT_FMT[0]: // Open state output format string
case SK_CLOSED_OUTPUT_FMT[0]: // Closed state output format string
case SK_TROUBLE_OUTPUT_FMT[0]: // Trouble state output format string
// consume the arge and to EOL
ad2_copy_nth_arg(arg1, instring, 4, true);
if (buf[0] == SK_OPEN_OUTPUT_FMT[0]) {
tmpsz = "OPEN";
}
if (buf[0] == SK_CLOSED_OUTPUT_FMT[0]) {
tmpsz = "CLOSED";
}
if (buf[0] == SK_TROUBLE_OUTPUT_FMT[0]) {
tmpsz = "TROUBLE";
}
ad2_set_nv_slot_key_string(key.c_str(), slot, sk.c_str(), arg1.c_str());
ad2_printf_host(false, "Setting smartswitch #%i output format string for '%s' state to '%s'.\r\n", slot, tmpsz.c_str(), arg1.c_str());
break;
default:
ESP_LOGW(TAG, "Unknown setting '%c' ignored.", buf[0]);
return;
}
} else {
// query show contents.
int i;
std::string out;
std::string args = SK_NOTIFY_TOPIC
SK_DEFAULT_STATE
SK_AUTO_RESET
SK_TYPE_LIST
SK_PREFILTER_REGEX
SK_OPEN_REGEX_LIST
SK_CLOSED_REGEX_LIST
SK_TROUBLE_REGEX_LIST
SK_OPEN_OUTPUT_FMT
SK_CLOSED_OUTPUT_FMT
SK_TROUBLE_OUTPUT_FMT;
ad2_printf_host(false, "MQTT SmartSwitch #%i report\r\n", slot);
// sub key suffix.
std::string sk;
for(char& c : args) {
std::string sk = ad2_string_printf("%c", c);
switch(c) {
case SK_NOTIFY_TOPIC[0]:
out = ""; // Default 0
ad2_get_nv_slot_key_string(key.c_str(), slot, sk.c_str(), out);
ad2_printf_host(false, "# Set MQTT topic [%c] to '%s'.\r\n", c, out.c_str());
ad2_printf_host(false, "%s %s %i %c %s\r\n", MQTT_COMMAND, MQTT_SAS_CFGKEY, slot, c, out.c_str());
break;
case SK_DEFAULT_STATE[0]:
i = 0; // Default CLOSED
ad2_get_nv_slot_key_int(key.c_str(), slot, sk.c_str(), &i);
ad2_printf_host(false, "# Set default virtual switch state [%c] to '%s'(%i)\r\n", c, AD2Parse.state_str[i].c_str(), i);
ad2_printf_host(false, "%s %s %i %c %i\r\n", MQTT_COMMAND, MQTT_SAS_CFGKEY, slot, c, i);
break;
case SK_AUTO_RESET[0]:
i = 0; // Defaut 0 or disabled
ad2_get_nv_slot_key_int(key.c_str(), slot, sk.c_str(), &i);
ad2_printf_host(false, "# Set auto reset time in ms [%c] to '%s'\r\n", c, (i > 0) ? ad2_to_string(i).c_str() : "DISABLED");
ad2_printf_host(false, "%s %s %i %c %i\r\n", MQTT_COMMAND, MQTT_SAS_CFGKEY, slot, c, i);
break;
case SK_TYPE_LIST[0]:
out = "";
ad2_get_nv_slot_key_string(key.c_str(), slot, sk.c_str(), out);
ad2_printf_host(false, "# Set message type list [%c]\r\n", c);
if (out.length()) {
ad2_printf_host(false, "%s %s %i %c %s\r\n", MQTT_COMMAND, MQTT_SAS_CFGKEY, slot, c, out.c_str());
} else {
ad2_printf_host(false, "# disabled\r\n");
}
break;
case SK_PREFILTER_REGEX[0]:
out = "";
ad2_get_nv_slot_key_string(key.c_str(), slot, sk.c_str(), out);
if (out.length()) {
ad2_printf_host(false, "# Set pre filter REGEX [%c]\r\n", c);
ad2_printf_host(false, "%s %s %i %c %s\r\n", MQTT_COMMAND, MQTT_SAS_CFGKEY, slot, c, out.c_str());
}
break;
case SK_OPEN_REGEX_LIST[0]:
case SK_CLOSED_REGEX_LIST[0]:
case SK_TROUBLE_REGEX_LIST[0]:
// * Find all sub keys and show info.
if (c == SK_OPEN_REGEX_LIST[0]) {
tmpsz = "OPEN";
}
if (c == SK_CLOSED_REGEX_LIST[0]) {
tmpsz = "CLOSED";
}