-
-
Notifications
You must be signed in to change notification settings - Fork 29
Expand file tree
/
Copy pathnspanel.cpp
More file actions
1451 lines (1322 loc) · 71.3 KB
/
nspanel.cpp
File metadata and controls
1451 lines (1322 loc) · 71.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include "nspanel.hpp"
#include "database_manager/database_manager.hpp"
#include "entity_manager/entity_manager.hpp"
#include "mqtt_manager/mqtt_manager.hpp"
#include "mqtt_manager_config/mqtt_manager_config.hpp"
#include "protobuf_nspanel.pb.h"
#include "room/room_entities_page.hpp"
#include "web_helper/WebHelper.hpp"
#include <algorithm>
#include <boost/algorithm/string.hpp>
#include <boost/bind.hpp>
#include <boost/bind/placeholders.hpp>
#include <boost/exception/diagnostic_information.hpp>
#include <boost/filesystem.hpp>
#include <boost/iostreams/device/file.hpp>
#include <boost/iostreams/stream.hpp>
#include <boost/iostreams/write.hpp>
#include <chrono>
#include <command_manager/command_manager.hpp>
#include <cstddef>
#include <cstdint>
#include <ctime>
#include <curl/curl.h>
#include <curl/easy.h>
#include <entity/entity.hpp>
#include <exception>
#include <fmt/chrono.h>
#include <fmt/core.h>
#include <iomanip>
#include <ixwebsocket/IXWebSocketSendInfo.h>
#include <light/light.hpp>
#include <mutex>
#include <netinet/in.h>
#include <nlohmann/json.hpp>
#include <nlohmann/json_fwd.hpp>
#include <optional>
#include <room/room.hpp>
#include <spdlog/spdlog.h>
#include <sqlite3.h>
#include <sqlite_orm/sqlite_orm.h>
#include <sstream>
#include <string>
#include <sys/stat.h>
#include <system_error>
#include <vector>
#include <websocket_server/websocket_server.hpp>
NSPanel::NSPanel(uint32_t id) {
// Assume panel to be offline until proven otherwise
this->_state = MQTT_MANAGER_NSPANEL_STATE::OFFLINE;
// If this panel is just a panel in waiting (ie. not accepted the request yet) it won't have an id.
this->_has_registered_to_manager = false;
this->_id = id;
SPDLOG_INFO("Loading new NSPanel with ID {}.", id);
this->reload_config();
CommandManager::attach_callback(boost::bind(&NSPanel::command_callback, this, _1));
WebsocketServer::attach_stomp_callback(fmt::format("nspanel/{}/command", this->_mac), boost::bind(&NSPanel::handle_stomp_command_callback, this, _1));
// Create default JSON structure for historical logs
this->_log_messages_backlog["logs"] = nlohmann::json::array();
}
std::shared_ptr<NSPanel> NSPanel::create_from_discovery_request(nlohmann::json request_data) {
auto db_room = database_manager::database.get_all<database_manager::Room>();
if (db_room.size() > 0) {
SPDLOG_INFO("Will create new NSPanel in DB from discovery request. Will set default room to {}::{}.", db_room[0].id, db_room[0].friendly_name);
database_manager::NSPanel panel_data;
panel_data.mac_address = request_data.at("mac_origin").get<std::string>();
panel_data.friendly_name = request_data.at("friendly_name").get<std::string>();
panel_data.room_id = db_room[0].id;
panel_data.version = request_data.at("version").get<std::string>();
panel_data.button1_detached_mode_entity_id = std::nullopt;
panel_data.button1_mode = 0;
panel_data.button2_detached_mode_entity_id = std::nullopt;
panel_data.button2_mode = 0;
panel_data.button1_long_detached_mode_entity_id = std::nullopt;
panel_data.button1_long_mode = 0;
panel_data.button2_long_detached_mode_entity_id = std::nullopt;
panel_data.button2_long_mode = 0;
panel_data.md5_data_file = request_data.at("md5_data_file").get<std::string>();
panel_data.md5_firmware = request_data.at("md5_firmware").get<std::string>();
panel_data.md5_tft_file = request_data.at("md5_tft_file").get<std::string>();
panel_data.denied = false;
panel_data.accepted = false;
try {
int new_nspanel_id = database_manager::database.insert(panel_data);
if (MqttManagerConfig::get_setting_with_default<std::string>(MQTT_MANAGER_SETTING::DEFAULT_NSPANEL_TYPE).compare("eu") == 0) {
MqttManagerConfig::set_nspanel_setting_value(new_nspanel_id, "is_us_panel", "False");
} else {
MqttManagerConfig::set_nspanel_setting_value(new_nspanel_id, "is_us_panel", "True");
}
return std::shared_ptr<NSPanel>(new NSPanel(new_nspanel_id));
} catch (std::system_error &ex) {
SPDLOG_ERROR("Failed to create new NSPanel {} in database. What: {}.", request_data.at("mac_origin").get<std::string>(), ex.what());
return nullptr;
}
} else {
SPDLOG_ERROR("No rooms found when trying to create a new NSPanel from discovery request. Cannot set default room ID. Will cancel.");
return nullptr;
}
}
void NSPanel::reload_config() {
try {
auto panel_settings = database_manager::database.get<database_manager::NSPanel>(this->_id);
std::lock_guard<std::mutex> lock_guard(this->_settings_mutex);
bool rebuilt_mqtt = false; // Wether or not to rebuild mqtt topics and subscribe to the new topics.
bool name_changed = false;
bool reregister_to_ha_mqtt_discovery = false;
this->_settings = panel_settings;
this->_has_registered_to_manager = true; // We managed to get the object in above statement and did not throw, ie. has been registered in manager and has an ID in DB.
this->_mac = panel_settings.mac_address;
this->_is_us_panel = this->_get_nspanel_setting_with_default("is_us_panel", "False").compare("True") == 0;
std::string us_panel_orientation = this->_get_nspanel_setting_with_default("us_panel_orientation", "vertical");
if (us_panel_orientation.compare("vertical") == 0) {
this->_us_panel_orientation = US_PANEL_ORIENTATION::PORTRAIT;
} else if (us_panel_orientation.compare("horizontal") == 0) {
this->_us_panel_orientation = US_PANEL_ORIENTATION::LANDSCAPE_LEFT;
} else if (us_panel_orientation.compare("horizontal_mirrored") == 0) {
this->_us_panel_orientation = US_PANEL_ORIENTATION::LANDSCAPE_RIGHT;
} else {
this->_us_panel_orientation = US_PANEL_ORIENTATION::PORTRAIT;
SPDLOG_ERROR("Error while processing US panel orientation, unknown orientation '{}'. Defaulting to vertical/portrait.", us_panel_orientation);
}
if (this->_name.compare(panel_settings.friendly_name) != 0) {
this->_name = panel_settings.friendly_name;
rebuilt_mqtt = true;
name_changed = true;
}
bool register_relay1_as_light = this->_get_nspanel_setting_with_default("relay1_is_light", "False").compare("True") == 0;
SPDLOG_DEBUG("Will register NSPanel {}::{} relay 1 as {}", this->_id, this->_name, register_relay1_as_light ? "light" : "relay");
if (this->_register_relay1_as_light != register_relay1_as_light) {
rebuilt_mqtt = true;
this->_register_relay1_as_light = register_relay1_as_light;
reregister_to_ha_mqtt_discovery = true;
}
bool register_relay2_as_light = this->_get_nspanel_setting_with_default("relay2_is_light", "False").compare("True") == 0;
SPDLOG_DEBUG("Will register NSPanel {}::{} relay 2 as {}", this->_id, this->_name, register_relay1_as_light ? "light" : "relay");
if (this->_register_relay2_as_light != register_relay2_as_light) {
rebuilt_mqtt = true;
this->_register_relay2_as_light = register_relay2_as_light;
reregister_to_ha_mqtt_discovery = true;
}
if (this->_state == MQTT_MANAGER_NSPANEL_STATE::OFFLINE || this->_state == MQTT_MANAGER_NSPANEL_STATE::UNKNOWN) {
this->_rssi = 0;
this->_heap_used_pct = 0;
this->_nspanel_warnings.clear();
this->_temperature = 0;
this->_update_progress = 0;
}
// Last thing to do, check if the panel as actually accepted into our manager.
if (panel_settings.denied) {
SPDLOG_INFO("Loaded denied NSPanel {}::{}.", this->_id, this->_name);
this->_state = MQTT_MANAGER_NSPANEL_STATE::DENIED;
rebuilt_mqtt = false;
}
if (panel_settings.accepted) {
SPDLOG_INFO("Loaded accepted NSPanel {}::{}.", this->_id, this->_name);
this->_state = MQTT_MANAGER_NSPANEL_STATE::WAITING;
rebuilt_mqtt = true;
}
if (!panel_settings.denied && !panel_settings.accepted) {
// No decission has been made on wether ot accept or deny panel. It is therefore awaiting_accept
this->_state = MQTT_MANAGER_NSPANEL_STATE::AWAITING_ACCEPT;
rebuilt_mqtt = true;
}
if (rebuilt_mqtt) {
SPDLOG_DEBUG("Building MQTT topics for NSPanel {}::{}", this->_id, this->_name);
this->reset_mqtt_topics();
// Convert stored MAC to MAC used in MQTT, ex. AA:AA:AA:BB:BB:BB to aa_aa_aa_bb_bb_bb
std::string mqtt_register_mac = this->_mac;
std::replace(mqtt_register_mac.begin(), mqtt_register_mac.end(), ':', '_');
std::transform(mqtt_register_mac.begin(), mqtt_register_mac.end(), mqtt_register_mac.begin(), [](unsigned char c) {
return std::tolower(c);
});
this->_mqtt_register_mac = mqtt_register_mac;
this->_mqtt_config_topic = fmt::format("nspanel/{}/config", this->_mac);
this->_mqtt_log_topic = fmt::format("nspanel/{}/log", this->_name); // TODO: Remove as this is the old log topic. Use the new based on MAC-address instead.
this->_mqtt_command_topic = fmt::format("nspanel/{}/command", this->_mac);
this->_mqtt_sensor_temperature_topic = fmt::format("homeassistant/sensor/nspanelmanager/{}_temperature/config", mqtt_register_mac);
this->_mqtt_switch_relay1_topic = fmt::format("homeassistant/switch/nspanelmanager/{}_relay1/config", mqtt_register_mac);
this->_mqtt_light_relay1_topic = fmt::format("homeassistant/light/nspanelmanager/{}_relay1/config", mqtt_register_mac);
this->_mqtt_switch_relay2_topic = fmt::format("homeassistant/switch/nspanelmanager/{}_relay2/config", mqtt_register_mac);
this->_mqtt_light_relay2_topic = fmt::format("homeassistant/light/nspanelmanager/{}_relay2/config", mqtt_register_mac);
this->_mqtt_switch_screen_topic = fmt::format("homeassistant/switch/nspanelmanager/{}_screen/config", mqtt_register_mac);
this->_mqtt_number_screen_brightness_topic = fmt::format("homeassistant/number/nspanelmanager/{}_screen_brightness/config", mqtt_register_mac);
this->_mqtt_number_screensaver_brightness_topic = fmt::format("homeassistant/number/nspanelmanager/{}_screensaver_brightness/config", mqtt_register_mac);
this->_mqtt_select_screensaver_topic = fmt::format("homeassistant/select/nspanelmanager/{}_screensaver_select/config", mqtt_register_mac);
this->_mqtt_relay1_command_topic = fmt::format("nspanel/{}/relay1_cmd", this->_mac);
this->_mqtt_relay1_state_topic = fmt::format("nspanel/{}/relay1_state", this->_mac);
this->_mqtt_relay2_command_topic = fmt::format("nspanel/{}/relay2_cmd", this->_mac);
this->_mqtt_relay2_state_topic = fmt::format("nspanel/{}/relay2_state", this->_mac);
this->_mqtt_status_topic = fmt::format("nspanel/{}/status", this->_mac);
this->_mqtt_status_report_topic = fmt::format("nspanel/{}/status_report", this->_mac);
this->_mqtt_temperature_topic = fmt::format("nspanel/{}/temperature", this->_mac);
this->_mqtt_topic_home_page_status = fmt::format("nspanel/{}/home_page", this->_mac);
this->_mqtt_topic_home_page_all_rooms_status = fmt::format("nspanel/{}/home_page_all", this->_mac);
this->_mqtt_topic_room_entities_page_status = fmt::format("nspanel/{}/entities_page", this->_mac);
}
if (this->_has_registered_to_manager && !panel_settings.denied && panel_settings.accepted) {
WebsocketServer::set_stomp_topic_retained(this->_mqtt_status_topic, true);
WebsocketServer::set_stomp_topic_retained(fmt::format("nspanel/{}/log_backlog", this->_mac), true);
// If this NSPanel is registered to manager, listen to state topics.
SPDLOG_INFO("Subscribing to NSPanel MQTT topics.");
MQTT_Manager::subscribe(this->_mqtt_relay1_state_topic, boost::bind(&NSPanel::mqtt_callback, this, _1, _2));
MQTT_Manager::subscribe(this->_mqtt_relay2_state_topic, boost::bind(&NSPanel::mqtt_callback, this, _1, _2));
MQTT_Manager::subscribe(this->_mqtt_log_topic, boost::bind(&NSPanel::mqtt_callback, this, _1, _2)); // TODO: Remove me and use only topic based on MAC-address instead
MQTT_Manager::subscribe(fmt::format("nspanel/{}/status", this->_name), boost::bind(&NSPanel::mqtt_callback, this, _1, _2)); // TODO: Remove me and use only topic based on MAC-address instead
MQTT_Manager::subscribe(fmt::format("nspanel/{}/status_report", this->_name), boost::bind(&NSPanel::mqtt_callback, this, _1, _2)); // TODO: Remove me and use only topic based on MAC-address instead
MQTT_Manager::subscribe(fmt::format("nspanel/{}/log", this->_mac), boost::bind(&NSPanel::mqtt_log_callback, this, _1, _2));
MQTT_Manager::subscribe(this->_mqtt_status_topic, boost::bind(&NSPanel::mqtt_callback, this, _1, _2));
MQTT_Manager::subscribe(this->_mqtt_status_report_topic, boost::bind(&NSPanel::mqtt_callback, this, _1, _2));
}
if (name_changed || reregister_to_ha_mqtt_discovery) {
this->reset_ha_mqtt_topics();
this->register_to_home_assistant();
}
SPDLOG_DEBUG("Loaded NSPanel {}::{}, type: {}. Sending config.", this->_id, this->_name, this->_is_us_panel ? "US" : "EU");
this->send_config();
} catch (std::system_error &ex) {
SPDLOG_ERROR("Failed to get config for NSPanel {} from database.", this->_id);
}
SPDLOG_TRACE("NSPanel {}::{} received config update.", this->_id, this->_name);
// Config changed, send updated status to web interface
this->send_websocket_status_update();
}
void NSPanel::send_config() {
std::lock_guard<std::mutex> lock(this->_send_config_mutex);
SPDLOG_INFO("Sending config over MQTT for panel {}::{}", this->_id, this->_name);
NSPanelConfig config;
auto default_room = EntityManager::get_room(this->_settings.room_id);
if (!default_room) {
SPDLOG_ERROR("Failed to reterive default room for NSPanel.");
return;
}
config.set_nspanel_id(this->_id);
config.set_name(this->_name);
config.set_default_room(this->_settings.room_id);
config.set_default_page(static_cast<NSPanelConfig_NSPanelDefaultPage>(std::stoi(this->_get_nspanel_setting_with_default("default_page", "0"))));
config.set_min_button_push_time(MqttManagerConfig::get_setting_with_default<uint32_t>(MQTT_MANAGER_SETTING::MIN_BUTTON_PUSH_TIME));
config.set_button_long_press_time(MqttManagerConfig::get_setting_with_default<uint32_t>(MQTT_MANAGER_SETTING::BUTTON_LONG_PRESS_TIME));
config.set_special_mode_trigger_time(MqttManagerConfig::get_setting_with_default<uint32_t>(MQTT_MANAGER_SETTING::SPECIAL_MODE_TRIGGER_TIME));
config.set_special_mode_release_time(MqttManagerConfig::get_setting_with_default<uint32_t>(MQTT_MANAGER_SETTING::SPECIAL_MODE_RELEASE_TIME));
config.set_screen_dim_level(std::stoi(this->_get_nspanel_setting_with_default("screen_dim_level", MqttManagerConfig::get_setting_with_default<std::string>(MQTT_MANAGER_SETTING::SCREEN_DIM_LEVEL))));
config.set_screensaver_dim_level(std::stoi(this->_get_nspanel_setting_with_default("screensaver_dim_level", MqttManagerConfig::get_setting_with_default<std::string>(MQTT_MANAGER_SETTING::SCREENSAVER_DIM_LEVEL))));
config.set_screensaver_activation_timeout(std::stoi(this->_get_nspanel_setting_with_default("screensaver_activation_timeout", MqttManagerConfig::get_setting_with_default<std::string>(MQTT_MANAGER_SETTING::SCREENSAVER_ACTIVATION_TIMEOUT))));
config.set_clock_us_style(MqttManagerConfig::get_setting_with_default<bool>(MQTT_MANAGER_SETTING::CLOCK_US_STYLE));
config.set_use_fahrenheit(MqttManagerConfig::get_setting_with_default<bool>(MQTT_MANAGER_SETTING::USE_FAHRENHEIT));
config.set_is_us_panel(this->_get_nspanel_setting_with_default("is_us_panel", "False").compare("True") == 0);
config.set_reverse_relays(this->_get_nspanel_setting_with_default("reverse_relays", "False").compare("True") == 0);
config.set_relay1_default_mode(this->_get_nspanel_setting_with_default("relay1_default_mode", "False").compare("True") == 0);
config.set_relay2_default_mode(this->_get_nspanel_setting_with_default("relay2_default_mode", "False").compare("True") == 0);
config.set_temperature_calibration((std::stof(this->_get_nspanel_setting_with_default("temperature_calibration", "0.0")) * 10));
config.set_default_light_brightess(MqttManagerConfig::get_setting_with_default<uint32_t>(MQTT_MANAGER_SETTING::LIGHT_TURN_ON_BRIGHTNESS));
config.set_locked_to_default_room(this->is_locked_to_default_room());
config.set_button1_lower_temperature(std::stoi(this->_get_nspanel_setting_with_default("button1_relay_upper_temperature", "0")));
config.set_button1_upper_temperature(std::stoi(this->_get_nspanel_setting_with_default("button1_relay_upper_temperature", "0")));
config.set_button2_lower_temperature(std::stoi(this->_get_nspanel_setting_with_default("button2_relay_lower_temperature", "0")));
config.set_button2_upper_temperature(std::stoi(this->_get_nspanel_setting_with_default("button2_relay_upper_temperature", "0")));
if ((*default_room)->has_temperature_sensor()) {
config.set_inside_temperature_sensor_mqtt_topic((*default_room)->get_temperature_sensor_mqtt_topic());
}
ButtonMode b1_mode = static_cast<ButtonMode>(this->_settings.button1_mode);
if (b1_mode == ButtonMode::DIRECT) {
config.set_button1_mode(NSPanelConfig_NSPanelButtonMode_DIRECT);
} else if (b1_mode == ButtonMode::FOLLOW) {
config.set_button1_mode(NSPanelConfig_NSPanelButtonMode_FOLLOW);
} else if (b1_mode == ButtonMode::THERMOSTAT_HEATING) {
config.set_button1_mode(NSPanelConfig_NSPanelButtonMode_THERMOSTAT_HEAT);
} else if (b1_mode == ButtonMode::THERMOSTAT_COOLING) {
config.set_button1_mode(NSPanelConfig_NSPanelButtonMode_THERMOSTAT_COOL);
} else {
config.set_button1_mode(NSPanelConfig_NSPanelButtonMode_NOTIFY_MANAGER);
}
ButtonMode b2_mode = static_cast<ButtonMode>(this->_settings.button2_mode);
if (b2_mode == ButtonMode::DIRECT) {
config.set_button2_mode(NSPanelConfig_NSPanelButtonMode_DIRECT);
} else if (b2_mode == ButtonMode::FOLLOW) {
config.set_button2_mode(NSPanelConfig_NSPanelButtonMode_FOLLOW);
} else if (b2_mode == ButtonMode::THERMOSTAT_HEATING) {
config.set_button2_mode(NSPanelConfig_NSPanelButtonMode_THERMOSTAT_HEAT);
} else if (b2_mode == ButtonMode::THERMOSTAT_COOLING) {
config.set_button2_mode(NSPanelConfig_NSPanelButtonMode_THERMOSTAT_COOL);
} else {
config.set_button2_mode(NSPanelConfig_NSPanelButtonMode_NOTIFY_MANAGER);
}
ButtonMode b1_long_mode = static_cast<ButtonMode>(this->_settings.button1_long_mode);
if (b1_long_mode == ButtonMode::DIRECT) {
config.set_button1_long_mode(NSPanelConfig_NSPanelButtonMode_DIRECT);
} else if (b1_long_mode == ButtonMode::FOLLOW) {
config.set_button1_long_mode(NSPanelConfig_NSPanelButtonMode_FOLLOW);
} else if (b1_long_mode == ButtonMode::THERMOSTAT_HEATING) {
config.set_button1_long_mode(NSPanelConfig_NSPanelButtonMode_THERMOSTAT_HEAT);
} else if (b1_long_mode == ButtonMode::THERMOSTAT_COOLING) {
config.set_button1_long_mode(NSPanelConfig_NSPanelButtonMode_THERMOSTAT_COOL);
} else {
config.set_button1_long_mode(NSPanelConfig_NSPanelButtonMode_NOTIFY_MANAGER);
}
ButtonMode b2_long_mode = static_cast<ButtonMode>(this->_settings.button2_long_mode);
if (b2_long_mode == ButtonMode::DIRECT) {
config.set_button2_long_mode(NSPanelConfig_NSPanelButtonMode_DIRECT);
} else if (b2_long_mode == ButtonMode::FOLLOW) {
config.set_button2_long_mode(NSPanelConfig_NSPanelButtonMode_FOLLOW);
} else if (b2_long_mode == ButtonMode::THERMOSTAT_HEATING) {
config.set_button2_long_mode(NSPanelConfig_NSPanelButtonMode_THERMOSTAT_HEAT);
} else if (b2_long_mode == ButtonMode::THERMOSTAT_COOLING) {
config.set_button2_long_mode(NSPanelConfig_NSPanelButtonMode_THERMOSTAT_COOL);
} else {
config.set_button2_long_mode(NSPanelConfig_NSPanelButtonMode_NOTIFY_MANAGER);
}
config.set_optimistic_mode(MqttManagerConfig::get_setting_with_default<bool>(MQTT_MANAGER_SETTING::OPTIMISTIC_MODE));
config.set_raise_light_level_to_100_above(MqttManagerConfig::get_setting_with_default<uint32_t>(MQTT_MANAGER_SETTING::RAISE_TO_100_LIGHT_LEVEL));
std::string screensaver_mode = this->_get_nspanel_setting_with_default("screensaver_mode", MqttManagerConfig::get_setting_with_default<std::string>(MQTT_MANAGER_SETTING::SCREENSAVER_MODE));
if (screensaver_mode.compare("with_background") == 0) {
config.set_screensaver_mode(NSPanelConfig_NSPanelScreensaverMode::NSPanelConfig_NSPanelScreensaverMode_WEATHER_WITH_BACKGROUND);
if (config.screensaver_dim_level() == 0) {
SPDLOG_WARN("Setting screensaver dim level to 10 as a screensaver has been chosen to be displayed but screensaver brightness is set to 0.");
config.set_screensaver_dim_level(10);
}
} else if (screensaver_mode.compare("without_background") == 0) {
config.set_screensaver_mode(NSPanelConfig_NSPanelScreensaverMode::NSPanelConfig_NSPanelScreensaverMode_WEATHER_WITHOUT_BACKGROUND);
if (config.screensaver_dim_level() == 0) {
SPDLOG_WARN("Setting screensaver dim level to 10 as a screensaver has been chosen to be displayed but screensaver brightness is set to 0.");
config.set_screensaver_dim_level(10);
}
} else if (screensaver_mode.compare("datetime_with_background") == 0) {
config.set_screensaver_mode(NSPanelConfig_NSPanelScreensaverMode::NSPanelConfig_NSPanelScreensaverMode_DATETIME_WITH_BACKGROUND);
if (config.screensaver_dim_level() == 0) {
SPDLOG_WARN("Setting screensaver dim level to 10 as a screensaver has been chosen to be displayed but screensaver brightness is set to 0.");
config.set_screensaver_dim_level(10);
}
} else if (screensaver_mode.compare("datetime_without_background") == 0) {
config.set_screensaver_mode(NSPanelConfig_NSPanelScreensaverMode::NSPanelConfig_NSPanelScreensaverMode_DATETIME_WITHOUT_BACKGROUND);
if (config.screensaver_dim_level() == 0) {
SPDLOG_WARN("Setting screensaver dim level to 10 as a screensaver has been chosen to be displayed but screensaver brightness is set to 0.");
config.set_screensaver_dim_level(10);
}
} else if (screensaver_mode.compare("no_screensaver") == 0) {
config.set_screensaver_mode(NSPanelConfig_NSPanelScreensaverMode::NSPanelConfig_NSPanelScreensaverMode_NO_SCREENSAVER);
if (config.screensaver_dim_level() == 0) {
SPDLOG_WARN("Setting screensaver dim level to 10 as a screensaver has been chosen to be displayed but screensaver brightness is set to 0.");
config.set_screensaver_dim_level(10);
}
} else {
SPDLOG_ERROR("Unknown screensaver mode '{}' for NSPanel {}::{}, assuming weather with background.", screensaver_mode, this->_id, this->_name);
config.set_screensaver_mode(NSPanelConfig_NSPanelScreensaverMode::NSPanelConfig_NSPanelScreensaverMode_WEATHER_WITH_BACKGROUND);
}
std::string show_screensaver_inside_temperature = this->_get_nspanel_setting_with_default("show_screensaver_inside_temperature", MqttManagerConfig::get_setting_with_default<std::string>(MQTT_MANAGER_SETTING::SHOW_SCREENSAVER_INSIDE_TEMPERATURE));
if (show_screensaver_inside_temperature.compare("True") == 0) {
config.set_show_screensaver_inside_temperature(true);
} else {
config.set_show_screensaver_inside_temperature(false);
}
std::string show_screensaver_outside_temperature = this->_get_nspanel_setting_with_default("show_screensaver_outside_temperature", MqttManagerConfig::get_setting_with_default<std::string>(MQTT_MANAGER_SETTING::SHOW_SCREENSAVER_OUTSIDE_TEMPERATURE));
if (show_screensaver_outside_temperature.compare("True") == 0) {
config.set_show_screensaver_outside_temperature(true);
} else {
config.set_show_screensaver_outside_temperature(false);
}
try {
auto relay_group_binding = database_manager::database.get_all<database_manager::NSPanelRelayGroupBinding>(
sqlite_orm::where(sqlite_orm::c(&database_manager::NSPanelRelayGroupBinding::relay_num) == 1) and sqlite_orm::c(&database_manager::NSPanelRelayGroupBinding::nspanel_id) == this->_id);
if (relay_group_binding.size() > 0) {
for (auto &binding : relay_group_binding) {
config.add_relay1_relay_group(binding.relay_group_id);
}
}
} catch (std::system_error) {
// Did not find matching relay group binind, relay is not bound.
}
try {
auto relay_group_binding = database_manager::database.get_all<database_manager::NSPanelRelayGroupBinding>(
sqlite_orm::where(sqlite_orm::c(&database_manager::NSPanelRelayGroupBinding::relay_num) == 2) and sqlite_orm::c(&database_manager::NSPanelRelayGroupBinding::nspanel_id) == this->_id);
if (relay_group_binding.size() > 0) {
for (auto &binding : relay_group_binding) {
config.add_relay2_relay_group(binding.relay_group_id);
}
}
} catch (std::system_error) {
// Did not find matching relay group binind, relay is not bound.
}
// Load rooms
// TODO: Only add rooms on the "allowed" list for this room.
SPDLOG_DEBUG("NSPanel {}::{} loading available rooms.", this->_id, this->_name);
if (this->is_locked_to_default_room()) {
SPDLOG_DEBUG("NSPanel {}::{} locked to default room.", this->_id, this->_name);
auto room = EntityManager::get_room(this->get_default_room_id());
if (room) {
NSPanelConfig_RoomInfo *room_info = config.add_room_infos();
room_info->set_room_id((*room)->get_id());
// Get all entity pages attached to room and add those IDs to list of availabe entity pages for that room
for (std::shared_ptr<RoomEntitiesPage> &page : (*room)->get_all_entities_pages()) {
room_info->add_entity_page_ids(page->get_id());
}
for (std::shared_ptr<RoomEntitiesPage> &page : (*room)->get_all_scenes_pages()) {
room_info->add_scene_page_ids(page->get_id());
}
}
} else {
auto rooms = EntityManager::get_all_rooms();
if (rooms) {
for (auto &room : *rooms) {
if (room != nullptr) {
NSPanelConfig_RoomInfo *room_info = config.add_room_infos();
room_info->set_room_id(room->get_id());
// Get all entity pages attached to room and add those IDs to list of availabe entity pages for that room
for (std::shared_ptr<RoomEntitiesPage> &page : room->get_all_entities_pages()) {
room_info->add_entity_page_ids(page->get_id());
}
for (std::shared_ptr<RoomEntitiesPage> &page : room->get_all_scenes_pages()) {
room_info->add_scene_page_ids(page->get_id());
}
}
}
} else {
SPDLOG_ERROR("No rooms loaded while trying to send config to NSPanel {}::{}.", this->_id, this->_name);
}
}
SPDLOG_DEBUG("NSPanel {}::{} loaded {} rooms.", this->_id, this->_name, config.room_infos_size());
// Load global scenes
std::vector<uint32_t> global_scene_entity_pages_ids;
auto global_entities_pages = EntityManager::get_all_global_room_entities_pages();
if (global_entities_pages) {
for (auto &page : *global_entities_pages) {
config.add_global_scene_entity_page_ids(page->get_id());
}
} else {
SPDLOG_WARN("No global entities pages were loaded while building config for NSPanel {}::{}", this->_id, this->_name);
}
SPDLOG_DEBUG("Sending updated NSPanelConfig to panel {}::{} over MQTT.", this->_id, this->_name);
MQTT_Manager::publish_protobuf(this->_mqtt_config_topic, config, true);
}
NSPanel::~NSPanel() {
SPDLOG_INFO("Destroying NSPanel {}::{}", this->_id, this->_name);
WebsocketServer::detach_stomp_callback(fmt::format("nspanel/{}/command", this->_mac), boost::bind(&NSPanel::handle_stomp_command_callback, this, _1));
this->reset_mqtt_topics();
this->reset_ha_mqtt_topics();
}
void NSPanel::reset_mqtt_topics() {
MQTT_Manager::detach_callback(this->_mqtt_relay1_state_topic, boost::bind(&NSPanel::mqtt_callback, this, _1, _2));
MQTT_Manager::detach_callback(this->_mqtt_relay2_state_topic, boost::bind(&NSPanel::mqtt_callback, this, _1, _2));
MQTT_Manager::detach_callback(this->_mqtt_log_topic, boost::bind(&NSPanel::mqtt_callback, this, _1, _2));
MQTT_Manager::detach_callback(this->_mqtt_status_topic, boost::bind(&NSPanel::mqtt_callback, this, _1, _2));
MQTT_Manager::detach_callback(this->_mqtt_status_report_topic, boost::bind(&NSPanel::mqtt_callback, this, _1, _2));
// This nspanel was removed. Clear any retain on any MQTT topic.
MQTT_Manager::clear_retain(this->_mqtt_command_topic);
}
void NSPanel::reset_ha_mqtt_topics() {
MQTT_Manager::clear_retain(this->_mqtt_light_relay1_topic);
MQTT_Manager::clear_retain(this->_mqtt_light_relay2_topic);
MQTT_Manager::clear_retain(this->_mqtt_switch_relay1_topic);
MQTT_Manager::clear_retain(this->_mqtt_switch_relay2_topic);
MQTT_Manager::clear_retain(this->_mqtt_switch_screen_topic);
MQTT_Manager::clear_retain(this->_mqtt_sensor_temperature_topic);
MQTT_Manager::clear_retain(this->_mqtt_number_screen_brightness_topic);
MQTT_Manager::clear_retain(this->_mqtt_number_screensaver_brightness_topic);
MQTT_Manager::clear_retain(this->_mqtt_select_screensaver_topic);
}
void NSPanel::erase() {
this->reboot();
this->reset_mqtt_topics();
this->reset_ha_mqtt_topics();
}
uint NSPanel::get_id() {
return this->_id;
}
std::string NSPanel::get_mac() {
return this->_mac;
}
MQTT_MANAGER_NSPANEL_STATE NSPanel::get_state() {
return this->_state;
}
void NSPanel::mqtt_callback(std::string topic, std::string payload) {
if (payload.empty()) {
return;
}
try {
if (topic.compare(this->_mqtt_log_topic) == 0) {
// Split log message by semicolon to extract MAC, log level and message.
std::string message = payload;
std::vector<std::string> message_parts;
size_t pos = 0;
uint8_t count = 0;
std::string token;
while ((pos = message.find(";")) != std::string::npos && count < 2) {
token = message.substr(0, pos);
message_parts.push_back(token);
message.erase(0, pos + 1); // Remove current part from beginning of topic string (including delimiter)
count++;
}
message_parts.push_back(message);
if (message_parts.size() == 3) {
std::time_t now = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now());
std::tm tm = *std::localtime(&now);
std::stringstream buffer;
if (!MqttManagerConfig::get_setting_with_default<bool>(MQTT_MANAGER_SETTING::CLOCK_US_STYLE)) {
buffer << std::put_time(&tm, "%H:%M:%S");
} else {
buffer << std::put_time(&tm, "%I:%M:%S %p");
}
std::string send_mac = message_parts[0];
send_mac.erase(std::remove(send_mac.begin(), send_mac.end(), ':'), send_mac.end());
nlohmann::json log_data;
log_data["type"] = "log";
log_data["time"] = buffer.str();
log_data["panel"] = this->_name;
log_data["mac_address"] = message_parts[0];
log_data["level"] = message_parts[1];
log_data["message"] = message_parts[2];
WebsocketServer::update_stomp_topic_value(fmt::format("nspanel/{}/log", this->_mac), log_data);
// Save log message in backtrace for when (if) the log interface requests it.
this->_log_messages_backlog["logs"].insert(this->_log_messages_backlog["logs"].begin(), log_data);
// Remove older messages from backtrace.
if (this->_log_messages_backlog["logs"].size() > MqttManagerConfig::get_setting_with_default<uint32_t>(MQTT_MANAGER_SETTING::MAX_LOG_BUFFER_SIZE)) {
this->_log_messages_backlog["logs"].erase(this->_log_messages_backlog["logs"].begin() + MqttManagerConfig::get_setting_with_default<uint32_t>(MQTT_MANAGER_SETTING::MAX_LOG_BUFFER_SIZE), this->_log_messages_backlog["logs"].end());
}
WebsocketServer::update_stomp_topic_value(fmt::format("nspanel/{}/log_backlog", this->_mac), this->_log_messages_backlog);
} else {
SPDLOG_ERROR("Received message on log topic {} with wrong format. Message: {}", topic, payload);
}
} else if (topic.compare(this->_mqtt_status_topic) == 0 || topic.compare(fmt::format("nspanel/{}/status", this->_name)) == 0) { // TODO: Remove and only use MAC-based topic after 2.0 is stable.
nlohmann::json data = nlohmann::json::parse(payload);
// Update internal state.
std::string state = data["state"];
if (state.compare("online") == 0) {
this->_state = MQTT_MANAGER_NSPANEL_STATE::ONLINE;
SPDLOG_DEBUG("NSPanel {}::{} became ONLINE.", this->_id, this->_name);
} else if (state.compare("offline") == 0) {
this->_state = MQTT_MANAGER_NSPANEL_STATE::OFFLINE;
SPDLOG_DEBUG("NSPanel {}::{} became OFFLINE.", this->_id, this->_name);
} else {
SPDLOG_ERROR("Received unknown state for nspanel {}::{}. State: {}", this->_id, this->_name, state);
}
this->send_websocket_status_update();
} else if (topic.compare(this->_mqtt_status_report_topic) == 0 || topic.compare(fmt::format("nspanel/{}/status_report", this->_name)) == 0) { // TODO: Remove and only use MAC-based topic after 2.0 is stable.
NSPanelStatusReport report;
if (report.ParseFromString(payload)) {
// Successfully received a new type of status report in protobuf format. This means that we have successfully updated to 2.0 firmware. Remove old MQTT topic retains:
// TODO: Remove once 2.0 is stable release
MQTT_Manager::clear_retain(fmt::format("nspanel/{}/status", this->_name));
MQTT_Manager::clear_retain(fmt::format("nspanel/{}/status_report", this->_name));
MQTT_Manager::clear_retain(fmt::format("nspanel/{}/log", this->_name));
MQTT_Manager::clear_retain(fmt::format("nspanel/{}/r1_state", this->_name));
MQTT_Manager::clear_retain(fmt::format("nspanel/{}/r2_state", this->_name));
MQTT_Manager::clear_retain(fmt::format("nspanel/{}/screen_state", this->_name));
MQTT_Manager::clear_retain(fmt::format("nspanel/{}/temperature_state", this->_name));
MQTT_Manager::clear_retain(fmt::format("nspanel/{}/command", this->_name));
MQTT_Manager::clear_retain(fmt::format("nspanel/{}", this->_name));
SPDLOG_DEBUG("Got new status report from NSPanel {}::{}", this->_id, this->_name);
this->_ip_address = report.ip_address();
this->_rssi = report.rssi();
this->_heap_used_pct = report.heap_used_pct();
this->_temperature = report.temperature();
this->_version = report.version();
this->_current_firmware_md5_checksum = report.md5_firmware();
this->_current_littlefs_md5_checksum = report.md5_littlefs();
this->_current_tft_md5_checksum = report.md5_tft_gui();
switch (report.nspanel_state()) {
case NSPanelStatusReport_state::NSPanelStatusReport_state_ONLINE:
this->_update_progress = 0;
this->_state = MQTT_MANAGER_NSPANEL_STATE::ONLINE;
break;
case NSPanelStatusReport_state_OFFLINE:
this->_state = MQTT_MANAGER_NSPANEL_STATE::OFFLINE; // This should never happen, offline state is handled in "/state" and not "/status_report"
break;
case NSPanelStatusReport_state_UPDATING_TFT:
this->_state = MQTT_MANAGER_NSPANEL_STATE::UPDATING_TFT;
break;
case NSPanelStatusReport_state_UPDATING_FIRMWARE:
this->_state = MQTT_MANAGER_NSPANEL_STATE::UPDATING_FIRMWARE;
break;
case NSPanelStatusReport_state_UPDATING_LITTLEFS:
this->_state = MQTT_MANAGER_NSPANEL_STATE::UPDATING_DATA;
break;
case NSPanelStatusReport_state_NSPanelStatusReport_state_INT_MIN_SENTINEL_DO_NOT_USE_:
case NSPanelStatusReport_state_NSPanelStatusReport_state_INT_MAX_SENTINEL_DO_NOT_USE_:
break;
}
this->_update_progress = report.update_progress();
this->_nspanel_warnings.clear();
for (const NSPanelWarning &warning : report.warnings()) {
NSPanelWarningWebsocketRepresentation ws_warn;
ws_warn.text = warning.text();
switch (warning.level()) {
case CRITICAL:
ws_warn.level = "CRITICAL";
break;
case ERROR:
ws_warn.level = "ERROR";
break;
case WARNING:
ws_warn.level = "WARNING";
break;
case INFO:
ws_warn.level = "INFO";
break;
case DEBUG:
ws_warn.level = "DEBUG";
break;
case TRACE:
ws_warn.level = "TRACE";
break;
case NSPanelWarningLevel_INT_MIN_SENTINEL_DO_NOT_USE_:
case NSPanelWarningLevel_INT_MAX_SENTINEL_DO_NOT_USE_:
break;
}
this->_nspanel_warnings.push_back(ws_warn);
}
// Received new temperature from status report, send out on temperature topic:
MQTT_Manager::publish(this->_mqtt_temperature_topic, fmt::format("{:.1f}", this->_temperature));
this->send_websocket_status_update();
} else {
SPDLOG_ERROR("Failed to parse NSPanelStatusReport from string as protobuf. Will try JSON.");
nlohmann::json data = nlohmann::json::parse(payload);
if (std::string(data["mac"]).compare(this->_mac) == 0) {
// Update internal status
this->_rssi = data["rssi"];
this->_heap_used_pct = data["heap_used_pct"];
if (data["temperature"].is_number_float()) {
this->_temperature = data["temperature"];
} else if (data["temperature"].is_string()) {
this->_temperature = atof(std::string(data["temperature"]).c_str());
} else {
SPDLOG_ERROR("Incorrect format of temperature data. Expected float.");
}
this->_ip_address = data["ip"];
this->_nspanel_warnings.clear();
if (data.at("warnings").is_string()) {
// Loaded from old firmware, split string and assume level warning
std::vector<std::string> message_lines;
boost::split(message_lines, std::string(data.at("warnings")), boost::is_any_of("\n"));
for (std::string line : message_lines) {
if (line.empty()) {
continue;
}
NSPanelWarningWebsocketRepresentation warning_obj = {
.level = "warning",
.text = line};
this->_nspanel_warnings.push_back(warning_obj);
}
} else if (data.at("warnings").is_array()) {
for (nlohmann::json warning : data.at("warnings")) {
if (warning.contains("level") && warning.contains("text")) {
NSPanelWarningWebsocketRepresentation warning_obj = {
.level = warning.at("level"),
.text = warning.at("text")};
this->_nspanel_warnings.push_back(warning_obj);
} else {
SPDLOG_WARN("Failed to load warning from NSPanel {}::{}. Missing level or text attribute.", this->_id, this->_name);
}
}
}
if (data.contains("state")) {
std::string state = data["state"];
if (this->_state == MQTT_MANAGER_NSPANEL_STATE::AWAITING_ACCEPT) {
// Do nothing, simply block state change to something else.
} else if (state.compare("updating_tft") == 0) {
this->_state = MQTT_MANAGER_NSPANEL_STATE::UPDATING_TFT;
} else if (state.compare("updating_fw") == 0) {
this->_state = MQTT_MANAGER_NSPANEL_STATE::UPDATING_FIRMWARE;
} else if (state.compare("updating_fs") == 0) {
this->_state = MQTT_MANAGER_NSPANEL_STATE::UPDATING_DATA;
} else {
SPDLOG_ERROR("Received unknown state from nspanel {}::{}. State: {}", this->_id, this->_name, state);
}
} else {
if (this->_state == MQTT_MANAGER_NSPANEL_STATE::WAITING) {
// We were waiting for a new status report. Set panel to online.
this->_state = MQTT_MANAGER_NSPANEL_STATE::ONLINE;
}
}
if (data.contains("progress")) {
this->_update_progress = data["progress"];
} else {
this->_update_progress = 0;
}
this->send_websocket_status_update();
}
}
}
} catch (std::exception &e) {
SPDLOG_ERROR("Caught exception: {}", e.what());
SPDLOG_ERROR("Stacktrace: {}", boost::diagnostic_information(e, true));
}
}
void NSPanel::mqtt_log_callback(std::string topic, std::string payload) {
size_t trim_start_pos = payload.find_first_not_of(" \n\r\t");
if (trim_start_pos == std::string::npos) {
return; // Message contains no valid chars, only spaces
}
size_t trim_end_pos = payload.find_last_not_of(" \n\r\t");
if (trim_start_pos == std::string::npos) {
return; // Message contains no valid chars, only spaces
}
if (payload.length() <= 0) [[unlikely]] {
return; // Message is empty.
}
payload = payload.substr(trim_start_pos, trim_end_pos + 1 - 4); // Trim spaces and such but also the first 7 chars that is the color coding for the message
if (payload[0] == 0x1B) { // Message formated with color. Remove color
payload = payload.substr(7);
}
std::time_t now = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now());
std::tm tm = *std::localtime(&now);
std::stringstream buffer;
if (!MqttManagerConfig::get_setting_with_default<bool>(MQTT_MANAGER_SETTING::CLOCK_US_STYLE)) {
buffer << std::put_time(&tm, "%H:%M:%S");
} else {
buffer << std::put_time(&tm, "%I:%M:%S %p");
}
nlohmann::json log_data;
log_data["type"] = "log";
log_data["time"] = buffer.str();
log_data["panel"] = this->_name;
log_data["mac_address"] = this->_mac;
if (payload[0] == 'E') {
log_data["level"] = "ERROR";
} else if (payload[0] == 'W') {
log_data["level"] = "WARNING";
} else if (payload[0] == 'I') {
log_data["level"] = "INFO";
} else if (payload[0] == 'D') {
log_data["level"] = "DEBUG";
} else {
SPDLOG_ERROR("Received log message from NSPanel but could not determin level, will not store/forward log message to web interface! Level: {}, Message: {}", payload[0], payload);
return;
}
// Convert payload strings non-printable characters to their hex representation
std::string converted_payload;
for (char c : payload) {
if (!std::isprint(c)) {
converted_payload += fmt::format("{{0x{:02X}}}", static_cast<unsigned char>(c));
} else {
converted_payload += c;
}
}
// Remove first char that indicates log level. This is stored separately
payload = payload.substr(1);
log_data["message"] = converted_payload; // TODO: Clean up message before sending it out
WebsocketServer::update_stomp_topic_value(fmt::format("nspanel/{}/log", this->_mac), log_data.dump());
// Save log message in backtrace for when (if) the log interface requests it.
this->_log_messages_backlog["logs"].insert(this->_log_messages_backlog["logs"].begin(), log_data);
// Remove older messages from backtrace.
if (this->_log_messages_backlog["logs"].size() > MqttManagerConfig::get_setting_with_default<uint32_t>(MQTT_MANAGER_SETTING::MAX_LOG_BUFFER_SIZE)) {
this->_log_messages_backlog["logs"].erase(this->_log_messages_backlog["logs"].begin() + MqttManagerConfig::get_setting_with_default<uint32_t>(MQTT_MANAGER_SETTING::MAX_LOG_BUFFER_SIZE), this->_log_messages_backlog["logs"].end());
}
WebsocketServer::update_stomp_topic_value(fmt::format("nspanel/{}/log_backlog", this->_mac), this->_log_messages_backlog);
}
void NSPanel::send_websocket_status_update() {
// Send out status report on status topic through STOMP
SPDLOG_TRACE("Sending websocket status update for {}::{}", this->_id, this->_name);
nlohmann::json status_data = {
{"id", this->_id},
{"name", this->_name},
{"version", this->_version},
{"firmware_md5", this->_current_firmware_md5_checksum},
{"ip_address", this->_ip_address},
{"rssi", this->_rssi},
{"temperature", this->_temperature},
{"ram_usage", this->_heap_used_pct},
{"update_progress", this->_update_progress},
};
status_data["warnings"] = nlohmann::json::array({});
for (NSPanelWarningWebsocketRepresentation warning : this->_nspanel_warnings) {
status_data["warnings"].push_back(nlohmann::json{
{"level", warning.level},
{"text", warning.text},
});
}
// Check if NSPanel has firmware, littlefs or tft file updates available and set appropriate warning.
if (this->_current_firmware_md5_checksum.empty() || this->_current_littlefs_md5_checksum.empty()) {
status_data["warnings"].push_back(nlohmann::json{
{"level", "warning"},
{"text", "Manager has no checksum for installed firmware on panel. If this doesn't go away within 5 minutes, try performing a firmware update from the manager."}});
} else if (this->has_firmware_update() || this->has_littlefs_update()) {
status_data["warnings"].push_back(nlohmann::json{
{"level", "warning"},
{"text", "Firmware update available"}});
}
if (this->_current_tft_md5_checksum.empty()) {
status_data["warnings"].push_back(nlohmann::json{
{"level", "warning"},
{"text", "Manager has no checksum for installed GUI on panel. If this doesn't go away within 5 minutes, try performing a GUI update from the manager."}});
} else if (this->has_tft_update()) {
status_data["warnings"].push_back(nlohmann::json{
{"level", "warning"},
{"text", "GUI update available"}});
}
switch (this->_state) {
case MQTT_MANAGER_NSPANEL_STATE::ONLINE:
status_data["state"] = "online";
break;
case MQTT_MANAGER_NSPANEL_STATE::OFFLINE:
status_data["state"] = "offline";
break;
case MQTT_MANAGER_NSPANEL_STATE::UPDATING_FIRMWARE:
status_data["state"] = "updating_fw";
status_data["progress"] = this->_update_progress;
break;
case MQTT_MANAGER_NSPANEL_STATE::UPDATING_DATA:
status_data["state"] = "updating_fs";
status_data["progress"] = this->_update_progress;
break;
case MQTT_MANAGER_NSPANEL_STATE::UPDATING_TFT:
status_data["state"] = "updating_tft";
status_data["progress"] = this->_update_progress;
break;
case MQTT_MANAGER_NSPANEL_STATE::WAITING:
status_data["state"] = "waiting";
break;
case MQTT_MANAGER_NSPANEL_STATE::AWAITING_ACCEPT:
status_data["state"] = "awaiting_accept";
break;
default:
status_data["state"] = "unknown";
break;
}
WebsocketServer::update_stomp_topic_value(this->_mqtt_status_topic, status_data);
}
bool NSPanel::has_firmware_update() {
auto file_checksum = MqttManagerConfig::get_firmware_checksum();
if (file_checksum) {
return this->_current_firmware_md5_checksum.compare(*file_checksum) != 0;
} else {
SPDLOG_ERROR("Failed to get checksum for firmware file!");
return false;
}
}
bool NSPanel::has_littlefs_update() {
auto file_checksum = MqttManagerConfig::get_littlefs_checksum();
if (file_checksum) {
return this->_current_littlefs_md5_checksum.compare(*file_checksum) != 0;
} else {
SPDLOG_ERROR("Failed to get checksum for littlefs file!");
return false;
}
}
bool NSPanel::has_tft_update() {
// Check if using EU file (we use EU file for US panel in landscape left orientation as it's the same screen and orientation as the EU panel).
if (!this->_is_us_panel || (this->_is_us_panel && this->_us_panel_orientation == US_PANEL_ORIENTATION::LANDSCAPE_LEFT)) {
if (this->_get_nspanel_setting_with_default("selected_tft", "tft1").compare("tft1") == 0) {
auto file_checksum = MqttManagerConfig::get_eu_tft1_checksum();
if (file_checksum) {
return this->_current_tft_md5_checksum.compare(*file_checksum) != 0;
} else {
SPDLOG_ERROR("Checksum for selected TFT file does not exist!");
return false;
}
} else if (this->_get_nspanel_setting_with_default("selected_tft", "tft1").compare("tft2") == 0) {
auto file_checksum = MqttManagerConfig::get_eu_tft2_checksum();
if (file_checksum) {
return this->_current_tft_md5_checksum.compare(*file_checksum) != 0;
} else {
SPDLOG_ERROR("Checksum for selected TFT file does not exist!");
return false;
}
} else if (this->_get_nspanel_setting_with_default("selected_tft", "tft1").compare("tft3") == 0) {
auto file_checksum = MqttManagerConfig::get_eu_tft3_checksum();
if (file_checksum) {
return this->_current_tft_md5_checksum.compare(*file_checksum) != 0;
} else {
SPDLOG_ERROR("Checksum for selected TFT file does not exist!");
return false;
}
} else if (this->_get_nspanel_setting_with_default("selected_tft", "tft1").compare("tft4") == 0) {
auto file_checksum = MqttManagerConfig::get_eu_tft4_checksum();
if (file_checksum) {
return this->_current_tft_md5_checksum.compare(*file_checksum) != 0;
} else {
SPDLOG_ERROR("Checksum for selected TFT file does not exist!");
return false;
}
} else {
SPDLOG_ERROR("Could not determin selected TFT file when comparing checksums! Selected TFT for nspanel {}::{} is {}", this->_id, this->_name, this->_get_nspanel_setting_with_default("selected_tft", "tft1"));
return false;
}
} else if (this->_is_us_panel && this->_us_panel_orientation == US_PANEL_ORIENTATION::PORTRAIT) {
if (this->_get_nspanel_setting_with_default("selected_tft", "tft1").compare("tft1") == 0) {
auto file_checksum = MqttManagerConfig::get_us_tft1_checksum();
if (file_checksum) {
return this->_current_tft_md5_checksum.compare(*file_checksum) != 0;
} else {
SPDLOG_ERROR("Checksum for selected TFT file does not exist!");
return false;
}
} else if (this->_get_nspanel_setting_with_default("selected_tft", "tft1").compare("2222") == 0) {
auto file_checksum = MqttManagerConfig::get_us_tft2_checksum();
if (file_checksum) {
return this->_current_tft_md5_checksum.compare(*file_checksum) != 0;
} else {
SPDLOG_ERROR("Checksum for selected TFT file does not exist!");
return false;
}
}
if (this->_get_nspanel_setting_with_default("selected_tft", "tft1").compare("tft3") == 0) {
auto file_checksum = MqttManagerConfig::get_us_tft3_checksum();
if (file_checksum) {
return this->_current_tft_md5_checksum.compare(*file_checksum) != 0;
} else {
SPDLOG_ERROR("Checksum for selected TFT file does not exist!");
return false;
}
} else if (this->_get_nspanel_setting_with_default("selected_tft", "tft1").compare("tft4") == 0) {
auto file_checksum = MqttManagerConfig::get_us_tft4_checksum();
if (file_checksum) {
return this->_current_tft_md5_checksum.compare(*file_checksum) != 0;
} else {
SPDLOG_ERROR("Checksum for selected TFT file does not exist!");
return false;
}
} else {
SPDLOG_ERROR("Could not determin selected TFT file when comparing checksums! Selected TFT for nspanel {}::{} is {}", this->_id, this->_name, this->_get_nspanel_setting_with_default("selected_tft", "tft1"));
}
} else if (this->_is_us_panel && this->_us_panel_orientation == US_PANEL_ORIENTATION::LANDSCAPE_RIGHT) {
if (this->_get_nspanel_setting_with_default("selected_tft", "tft1").compare("tft1") == 0) {
auto file_checksum = MqttManagerConfig::get_us_horizontal_mirrored_tft1_checksum();
if (file_checksum) {
return this->_current_tft_md5_checksum.compare(*file_checksum) != 0;
} else {
SPDLOG_ERROR("Checksum for selected TFT file does not exist!");