-
-
Notifications
You must be signed in to change notification settings - Fork 66
Expand file tree
/
Copy pathlg-controller.h
More file actions
1464 lines (1304 loc) · 56.1 KB
/
Copy pathlg-controller.h
File metadata and controls
1464 lines (1304 loc) · 56.1 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
#pragma once
#include "esphome.h"
#include "esphome/components/uart/uart.h"
static const char* const TAG = "lg-controller";
namespace esphome::lg_controller {
static constexpr size_t MIN_TEMP_SETPOINT = 16;
static constexpr size_t MAX_TEMP_SETPOINT = 30;
class LgSwitch final : public switch_::Switch {
void write_state(bool value) override {
publish_state(value);
}
public:
void restore_and_set_mode(switch_::SwitchRestoreMode mode) {
set_restore_mode(mode);
if (auto state = get_initial_state_with_restore_mode()) {
write_state(*state);
}
}
};
class LgSelect final : public select::Select {
void control(const std::string& value) override {
if (this->current_option() != value) {
this->publish_state(value);
}
}
};
class LgNumber final : public number::Number {
void control(float value) override {
if (this->state != value) {
this->publish_state(value);
}
}
};
// The LG protocol always uses Celsius. The HA/ESPHome climate component internally
// converts between Fahrenheit and Celsius. Values from the Home Assistant room temperature sensor
// are not converted automatically so can be Celsius or Fahrenheit.
//
// Unfortunately LG uses their own Fahrenheit/Celsius mapping that's different from what you'd
// expect. For example, 78F is ~25.5C, but LG controllers will send 26C for 78F. A value of 25.5C
// would be interpreted by the AC as 77F.
//
// This class has some functions to convert between Fahrenheit, Celsius and "LG-Celsius" (values
// we send to or receive from the unit). This ensures Home Assistant and the LG unit always agree
// on the setpoint in Fahrenheit.
//
// These conversions are only used in Fahrenheit mode.
class TempConversion {
private:
static constexpr int8_t FahToLGCel[] = {
0 /* 32 */, 1 /* 33 */, 2 /* 34 */, 3 /* 35 */, 4 /* 36 */,
5 /* 37 */, 6 /* 38 */, 7 /* 39 */, 8 /* 40 */, 10 /* 41 */,
12 /* 42 */, 13 /* 43 */, 14 /* 44 */, 15 /* 45 */, 16 /* 46 */,
17 /* 47 */, 18 /* 48 */, 19 /* 49 */, 20 /* 50 */, 21 /* 51 */,
22 /* 52 */, 23 /* 53 */, 24 /* 54 */, 25 /* 55 */, 26 /* 56 */,
27 /* 57 */, 28 /* 58 */, 30 /* 59 */, 32 /* 60 */, 33 /* 61 */,
34 /* 62 */, 35 /* 63 */, 36 /* 64 */, 37 /* 65 */, 38 /* 66 */,
39 /* 67 */, 40 /* 68 */, 41 /* 69 */, 42 /* 70 */, 43 /* 71 */,
44 /* 72 */, 45 /* 73 */, 46 /* 74 */, 47 /* 75 */, 48 /* 76 */,
50 /* 77 */, 52 /* 78 */, 53 /* 79 */, 54 /* 80 */, 55 /* 81 */,
56 /* 82 */, 57 /* 83 */, 58 /* 84 */, 59 /* 85 */, 60 /* 86 */,
61 /* 87 */, 62 /* 88 */, 63 /* 89 */, 64 /* 90 */, 65 /* 91 */,
66 /* 92 */, 67 /* 93 */, 68 /* 94 */, 70 /* 95 */, 72 /* 96 */,
73 /* 97 */, 74 /* 98 */, 75 /* 99 */, 76 /* 100 */, 77 /* 101 */,
78 /* 102 */, 79 /* 103 */, 80 /* 104 */
};
static constexpr int8_t LGCelToCelAdjustment[] = {
0 /* 0 */, 0 /* 0.5 */, 0 /* 1.0 */, 0 /* 1.5 */, 0 /* 2.0 */,
1 /* 2.5 */, 1 /* 3.0 */, 1 /* 3.5 */, 1 /* 4.0 */, 0 /* 4.5 */,
0 /* 5.0 */, -1 /* 5.5 */, -1 /* 6.0 */, -1 /* 6.5 */, -1 /* 7.0 */,
-1 /* 7.5 */, 0 /* 8.0 */, 0 /* 8.5 */, 0 /* 9.0 */, 0 /* 9.5 */,
0 /* 10.0 */, 0 /* 10.5 */, 0 /* 11.0 */, 0 /* 11.5 */, 0 /* 12.0 */,
1 /* 12.5 */, 1 /* 13.0 */, 1 /* 13.5 */, 1 /* 14.0 */, 0 /* 14.5 */,
0 /* 15.0 */, -1 /* 15.5 */, -1 /* 16.0 */, -1 /* 16.5 */, -1 /* 17.0 */,
-1 /* 17.5 */, 0 /* 18.0 */, 0 /* 18.5 */, 0 /* 19.0 */, 0 /* 19.5 */,
0 /* 20.0 */, 0 /* 20.5 */, 0 /* 21.0 */, 0 /* 21.5 */, 0 /* 22.0 */,
1 /* 22.5 */, 1 /* 23.0 */, 1 /* 23.5 */, 1 /* 24.0 */, 0 /* 24.5 */,
0 /* 25.0 */, -1 /* 25.5 */, -1 /* 26.0 */, -1 /* 26.5 */, -1 /* 27.0 */,
-1 /* 27.5 */, 0 /* 28.0 */, 0 /* 28.5 */, 0 /* 29.0 */, 0 /* 29.5 */,
0 /* 30.0 */, 0 /* 30.5 */, 0 /* 31.0 */, 0 /* 31.5 */, 0 /* 32.0 */,
1 /* 32.5 */, 1 /* 33.0 */, 1 /* 33.5 */, 1 /* 34.0 */, 0 /* 34.5 */,
0 /* 35.0 */, -1 /* 35.5 */, -1 /* 36.0 */, -1 /* 36.5 */, -1 /* 37.0 */,
-1 /* 37.5 */, 0 /* 38.0 */, 0 /* 38.5 */, 0 /* 39.0 */, 0 /* 39.5 */,
0 /* 40.0 */
};
public:
// Convert from Fahrenheit to LG-Celsius (using the LG-compatible conversion).
static float fahrenheit_to_lgcelsius(float temp) {
int temp_int = int(round(temp));
if (temp_int < 32 || temp_int > 104) {
return esphome::fahrenheit_to_celsius(temp);
}
int8_t val = FahToLGCel[temp_int - 32];
return float(val / 2) + ((val & 1) ? 0.5f : 0.0f);
}
// Convert an LG-Celsius value to Celsius. This is done to ensure the LG unit and HA agree
// on the value in Fahrenheit. For example, the unit sends 78F as 26C (LG Celsius), but HA
// would convert this to 78.8F => 79F. To work around this, we adjust 26C to 25.5C because
// this maps to 78F in HA.
static float lgcelsius_to_celsius(float temp) {
int index = int(temp * 2);
if (index < 0 || index >= sizeof(LGCelToCelAdjustment)) {
return temp;
}
int8_t adjustment = LGCelToCelAdjustment[index];
if (adjustment == -1) {
return temp - 0.5;
}
if (adjustment == 1) {
return temp + 0.5;
}
return temp;
}
static float celsius_to_lgcelsius(float temp) {
float fahrenheit = esphome::celsius_to_fahrenheit(temp);
return fahrenheit_to_lgcelsius(fahrenheit);
}
};
constexpr int8_t TempConversion::FahToLGCel[];
constexpr int8_t TempConversion::LGCelToCelAdjustment[];
class LgController final : public climate::Climate, public uart::UARTDevice, public Component {
static constexpr size_t MsgLen = 13;
climate::ClimateTraits supported_traits_{};
InternalGPIOPin& rx_pin_;
esphome::sensor::Sensor* temperature_sensor_;
LgSelect& vane_select_1_;
LgSelect& vane_select_2_;
LgSelect& vane_select_3_;
LgSelect& vane_select_4_;
LgSelect& overheating_select_;
LgNumber& fan_speed_slow_;
LgNumber& fan_speed_low_;
LgNumber& fan_speed_medium_;
LgNumber& fan_speed_high_;
LgNumber& sleep_timer_;
esphome::sensor::Sensor& error_code_;
esphome::sensor::Sensor& pipe_temp_in_;
esphome::sensor::Sensor& pipe_temp_mid_;
esphome::sensor::Sensor& pipe_temp_out_;
esphome::sensor::Sensor* power_consumption_;
esphome::sensor::Sensor* current_power_;
esphome::binary_sensor::BinarySensor& defrost_;
esphome::binary_sensor::BinarySensor& preheat_;
esphome::binary_sensor::BinarySensor& outdoor_;
esphome::binary_sensor::BinarySensor& auto_dry_active_;
uint32_t last_outdoor_change_millis_ = 0;
LgSwitch& purifier_;
LgSwitch& internal_thermistor_;
LgSwitch& auto_dry_;
uint8_t recv_buf_[MsgLen] = {};
uint32_t recv_buf_len_ = 0;
uint32_t last_recv_millis_ = 0;
// Last received 0xC8 message.
uint8_t last_recv_status_[MsgLen] = {};
// Last received 0xCA message.
uint8_t last_recv_type_a_settings_[MsgLen] = {};
// Last received 0xCB message.
uint8_t last_recv_type_b_settings_[MsgLen] = {};
uint8_t send_buf_[MsgLen] = {};
uint32_t last_sent_status_millis_ = 0;
uint32_t last_sent_recv_type_b_millis_ = 0;
enum class PendingSendKind : uint8_t { None, Status, TypeA, TypeB };
PendingSendKind pending_send_ = PendingSendKind::None;
bool pending_status_change_ = false;
bool pending_type_a_settings_change_ = false;
bool pending_type_b_settings_change_ = false;
bool is_initializing_ = true;
uint8_t vane_position_[4] = {0,0,0,0};
uint8_t fan_speed_[4] = {0,0,0,0};
uint8_t overheating_ = 0;
optional<uint32_t> sleep_timer_target_millis_{};
bool active_reservation_ = false;
bool ignore_sleep_timer_callback_ = false;
uint32_t NVS_STORAGE_VERSION = 2843654U; // Change version if the NVSStorage struct changes
struct NVSStorage {
uint8_t capabilities_message[13] = {};
};
NVSStorage nvs_storage_;
const bool fahrenheit_;
// Whether a message came from the HVAC unit, a master controller, or a slave controller.
enum class MessageSender : uint8_t { Unit, Master, Slave };
// Set if this controller is configured as slave controller.
const bool slave_;
enum class LgCapability {
FAN_AUTO,
FAN_SLOW,
FAN_LOW,
FAN_LOW_MEDIUM,
FAN_MEDIUM,
FAN_MEDIUM_HIGH,
FAN_HIGH,
MODE_HEATING,
MODE_FAN,
MODE_AUTO,
MODE_DEHUMIDIFY,
VERTICAL_SWING,
HORIZONTAL_SWING,
};
bool parse_capability(LgCapability capability) {
switch (capability) {
case LgCapability::FAN_AUTO:
return (nvs_storage_.capabilities_message[3] & 0x01) != 0;
case LgCapability::FAN_SLOW:
return (nvs_storage_.capabilities_message[3] & 0x20) != 0;
case LgCapability::FAN_LOW:
return (nvs_storage_.capabilities_message[3] & 0x10) != 0;
case LgCapability::FAN_LOW_MEDIUM:
return (nvs_storage_.capabilities_message[6] & 0x08) != 0;
case LgCapability::FAN_MEDIUM:
return (nvs_storage_.capabilities_message[3] & 0x08) != 0;
case LgCapability::FAN_MEDIUM_HIGH:
return (nvs_storage_.capabilities_message[6] & 0x10) != 0;
case LgCapability::FAN_HIGH:
return true;
case LgCapability::MODE_HEATING:
return (nvs_storage_.capabilities_message[2] & 0x40) != 0;
case LgCapability::MODE_FAN:
return (nvs_storage_.capabilities_message[2] & 0x80) != 0;
case LgCapability::MODE_AUTO:
return (nvs_storage_.capabilities_message[2] & 0x08) != 0;
case LgCapability::MODE_DEHUMIDIFY:
return (nvs_storage_.capabilities_message[2] & 0x80) != 0;
case LgCapability::VERTICAL_SWING:
return (nvs_storage_.capabilities_message[1] & 0x80) != 0;
case LgCapability::HORIZONTAL_SWING:
return (nvs_storage_.capabilities_message[1] & 0x40) != 0;
}
return false;
}
void configure_capabilities() {
// Default traits
climate::ClimateModeMask device_modes;
device_modes.insert(climate::CLIMATE_MODE_OFF);
device_modes.insert(climate::CLIMATE_MODE_COOL);
device_modes.insert(climate::CLIMATE_MODE_HEAT);
device_modes.insert(climate::CLIMATE_MODE_DRY);
device_modes.insert(climate::CLIMATE_MODE_FAN_ONLY);
device_modes.insert(climate::CLIMATE_MODE_HEAT_COOL);
climate::ClimateFanModeMask fan_modes;
fan_modes.insert(climate::CLIMATE_FAN_LOW);
fan_modes.insert(climate::CLIMATE_FAN_MEDIUM);
fan_modes.insert(climate::CLIMATE_FAN_HIGH);
fan_modes.insert(climate::CLIMATE_FAN_AUTO);
climate::ClimateSwingModeMask swing_modes;
swing_modes.insert(climate::CLIMATE_SWING_OFF);
swing_modes.insert(climate::CLIMATE_SWING_BOTH);
swing_modes.insert(climate::CLIMATE_SWING_VERTICAL);
swing_modes.insert(climate::CLIMATE_SWING_HORIZONTAL);
supported_traits_.set_supported_modes(device_modes);
supported_traits_.set_supported_fan_modes(fan_modes);
supported_traits_.set_supported_swing_modes(swing_modes);
supported_traits_.add_feature_flags(climate::CLIMATE_SUPPORTS_CURRENT_TEMPERATURE);
supported_traits_.set_visual_min_temperature(MIN_TEMP_SETPOINT);
supported_traits_.set_visual_max_temperature(MAX_TEMP_SETPOINT);
supported_traits_.set_visual_current_temperature_step(fahrenheit_ ? 1 : 0.5);
supported_traits_.set_visual_target_temperature_step(fahrenheit_ ? 1 : 0.5);
// Only override defaults if the capabilities are known
if (nvs_storage_.capabilities_message[0] != 0) {
// Configure the climate traits
climate::ClimateModeMask override_device_modes;
override_device_modes.insert(climate::CLIMATE_MODE_OFF);
override_device_modes.insert(climate::CLIMATE_MODE_COOL);
if (parse_capability(LgCapability::MODE_HEATING))
override_device_modes.insert(climate::CLIMATE_MODE_HEAT);
if (parse_capability(LgCapability::MODE_FAN))
override_device_modes.insert(climate::CLIMATE_MODE_FAN_ONLY);
if (parse_capability(LgCapability::MODE_AUTO))
override_device_modes.insert(climate::CLIMATE_MODE_HEAT_COOL);
if (parse_capability(LgCapability::MODE_DEHUMIDIFY))
override_device_modes.insert(climate::CLIMATE_MODE_DRY);
supported_traits_.set_supported_modes(override_device_modes);
climate::ClimateFanModeMask override_fan_modes;
if (parse_capability(LgCapability::FAN_AUTO))
override_fan_modes.insert(climate::CLIMATE_FAN_AUTO);
if (parse_capability(LgCapability::FAN_SLOW))
override_fan_modes.insert(climate::CLIMATE_FAN_QUIET);
if (parse_capability(LgCapability::FAN_LOW))
override_fan_modes.insert(climate::CLIMATE_FAN_LOW);
if (parse_capability(LgCapability::FAN_MEDIUM))
override_fan_modes.insert(climate::CLIMATE_FAN_MEDIUM);
if (parse_capability(LgCapability::FAN_HIGH))
override_fan_modes.insert(climate::CLIMATE_FAN_HIGH);
supported_traits_.set_supported_fan_modes(override_fan_modes);
climate::ClimateSwingModeMask override_swing_modes;
override_swing_modes.insert(climate::CLIMATE_SWING_OFF);
if (parse_capability(LgCapability::VERTICAL_SWING) && parse_capability(LgCapability::HORIZONTAL_SWING))
override_swing_modes.insert(climate::CLIMATE_SWING_BOTH);
if (parse_capability(LgCapability::VERTICAL_SWING))
override_swing_modes.insert(climate::CLIMATE_SWING_VERTICAL);
if (parse_capability(LgCapability::HORIZONTAL_SWING))
override_swing_modes.insert(climate::CLIMATE_SWING_HORIZONTAL);
supported_traits_.set_supported_swing_modes(override_swing_modes);
}
}
public:
LgController(InternalGPIOPin* rx_pin,
sensor::Sensor* temperature_sensor,
LgSelect* vane_select_1,
LgSelect* vane_select_2,
LgSelect* vane_select_3,
LgSelect* vane_select_4,
LgSelect* overheating_select,
LgNumber* fan_speed_slow,
LgNumber* fan_speed_low,
LgNumber* fan_speed_medium,
LgNumber* fan_speed_high,
LgNumber* sleep_timer,
sensor::Sensor* error_code,
sensor::Sensor* pipe_temp_in,
sensor::Sensor* pipe_temp_mid,
sensor::Sensor* pipe_temp_out,
sensor::Sensor* power_consumption,
sensor::Sensor* current_power,
binary_sensor::BinarySensor* defrost,
binary_sensor::BinarySensor* preheat,
binary_sensor::BinarySensor* outdoor,
binary_sensor::BinarySensor* auto_dry_active,
LgSwitch* purifier,
LgSwitch* internal_thermistor,
LgSwitch* auto_dry,
bool fahrenheit, bool is_slave_controller)
: rx_pin_(*rx_pin),
temperature_sensor_(temperature_sensor),
vane_select_1_(*vane_select_1),
vane_select_2_(*vane_select_2),
vane_select_3_(*vane_select_3),
vane_select_4_(*vane_select_4),
overheating_select_(*overheating_select),
fan_speed_slow_(*fan_speed_slow),
fan_speed_low_(*fan_speed_low),
fan_speed_medium_(*fan_speed_medium),
fan_speed_high_(*fan_speed_high),
sleep_timer_(*sleep_timer),
error_code_(*error_code),
pipe_temp_in_(*pipe_temp_in),
pipe_temp_mid_(*pipe_temp_mid),
pipe_temp_out_(*pipe_temp_out),
power_consumption_(power_consumption),
current_power_(current_power),
defrost_(*defrost),
preheat_(*preheat),
outdoor_(*outdoor),
auto_dry_active_(*auto_dry_active),
purifier_(*purifier),
internal_thermistor_(*internal_thermistor),
auto_dry_(*auto_dry),
fahrenheit_(fahrenheit),
slave_(is_slave_controller)
{
vane_select_1_.add_on_state_callback([this](size_t index) {
set_vane_position(1, index);
});
vane_select_2_.add_on_state_callback([this](size_t index) {
set_vane_position(2, index);
});
vane_select_3_.add_on_state_callback([this](size_t index) {
set_vane_position(3, index);
});
vane_select_4_.add_on_state_callback([this](size_t index) {
set_vane_position(4, index);
});
overheating_select_.add_on_state_callback([this](size_t index) {
set_overheating(index);
});
fan_speed_slow_.add_on_state_callback([this](float v) {
set_fan_speed(0, v);
});
fan_speed_low_.add_on_state_callback([this](float v) {
set_fan_speed(1, v);
});
fan_speed_medium_.add_on_state_callback([this](float v) {
set_fan_speed(2, v);
});
fan_speed_high_.add_on_state_callback([this](float v) {
set_fan_speed(3, v);
});
sleep_timer_.add_on_state_callback([this](float v) {
set_sleep_timer(v);
});
purifier_.add_on_state_callback([this](bool) {
pending_status_change_ = true;
});
internal_thermistor_.add_on_state_callback([this](bool) {
pending_status_change_ = true;
});
auto_dry_.add_on_state_callback([this](bool) {
pending_type_a_settings_change_ = true;
});
}
float get_setup_priority() const override {
return esphome::setup_priority::BUS;
}
void setup() override {
// Load our custom NVS storage to get the capabilities message
ESPPreferenceObject pref = global_preferences->make_preference<NVSStorage>(this->get_object_id_hash() ^ NVS_STORAGE_VERSION);
pref.load(&nvs_storage_);
auto restore = this->restore_state_();
if (restore.has_value()) {
restore->apply(this);
} else {
this->mode = climate::CLIMATE_MODE_OFF;
this->target_temperature = 20;
this->fan_mode = climate::CLIMATE_FAN_MEDIUM;
this->swing_mode = climate::CLIMATE_SWING_OFF;
this->publish_state();
}
internal_thermistor_.restore_and_set_mode(esphome::switch_::SWITCH_RESTORE_DEFAULT_OFF);
sleep_timer_.publish_state(0);
// Configure climate traits and entities based on the capabilities message (if available)
configure_capabilities();
while (UARTDevice::available() > 0) {
uint8_t b;
UARTDevice::read_byte(&b);
}
pending_status_change_ = true;
// Call `update` every 6 seconds, but first wait 10 seconds.
set_timeout("initial_send", 10000, [this]() {
set_interval("update", 6000, [this]() { update(); });
});
}
// Process changes from HA.
void control(const climate::ClimateCall &call) override {
if (call.get_mode().has_value()) {
this->mode = *call.get_mode();
}
if (call.get_target_temperature().has_value()) {
this->target_temperature = *call.get_target_temperature();
}
if (call.get_fan_mode().has_value()) {
this->fan_mode = *call.get_fan_mode();
}
if (call.get_swing_mode().has_value()) {
set_swing_mode(*call.get_swing_mode());
}
this->pending_status_change_ = true;
this->publish_state();
}
climate::ClimateTraits traits() override {
return supported_traits_;
}
private:
// Sets position of vane index (1-4) to position (0-6).
void set_vane_position(int index, int position) {
if (index < 1 || index > 4) {
ESP_LOGE(TAG, "Unexpected vane index: %d", index);
return;
}
if (position < 0 || position > 6) {
ESP_LOGE(TAG, "Unexpected vane position: %d", position);
return;
}
if (vane_position_[index-1] == position) {
return;
}
ESP_LOGD(TAG, "Setting vane %d position: %d", index, position);
vane_position_[index-1] = position;
if (!is_initializing_) {
pending_type_a_settings_change_ = true;
}
}
// Sets installer setting fan speed index (0-3 for slow-high) to value (0-255), with "0" being the factory default
void set_fan_speed(int index, int value) {
if (index < 0 || index > 3) {
ESP_LOGE(TAG, "Unexpected fan speed index: %d", index);
return;
}
if (value<0 || value>255) {
ESP_LOGE(TAG, "Unexpected fan speed: %d", value);
return;
}
if (fan_speed_[index] == value) {
return;
}
fan_speed_[index] = value;
if (!is_initializing_) {
pending_type_a_settings_change_ = true;
}
}
// Set overheating installer setting 15 to 0-4.
void set_overheating(int value) {
if (value < 0 || value > 4) {
ESP_LOGE(TAG, "Unexpected overheating value: %d", value);
return;
}
if (overheating_ == value) {
return;
}
ESP_LOGD(TAG, "Setting overheating installer setting: %d", value);
overheating_ = value;
if (!is_initializing_) {
pending_type_b_settings_change_ = true;
}
}
void set_sleep_timer(int minutes) {
if (ignore_sleep_timer_callback_) {
return;
}
// 0 clears the timer. Accept max 7 hours.
if (minutes < 0 || minutes > 7 * 60) {
ESP_LOGE(TAG, "Ignoring invalid sleep timer value: %d minutes", minutes);
return;
}
ESP_LOGD(TAG, "Setting sleep timer: %d minutes", minutes);
if (minutes > 0) {
sleep_timer_target_millis_ = millis() + unsigned(minutes) * 60 * 1000;
active_reservation_ = true;
} else {
sleep_timer_target_millis_.reset();
active_reservation_ = false;
}
pending_status_change_ = true;
}
optional<float> get_room_temp() const {
if (temperature_sensor_ == nullptr) {
return {};
}
float temp = temperature_sensor_->get_state();
if (std::isnan(temp) || temp == 0) {
return {};
}
if (fahrenheit_) {
temp = TempConversion::fahrenheit_to_lgcelsius(temp);
}
if (temp < 11) {
return 11;
}
if (temp > 35) {
return 35;
}
// Round to nearest 0.5 degrees.
return round(temp * 2) / 2;
}
optional<uint32_t> get_sleep_timer_minutes() const {
if (!sleep_timer_target_millis_.has_value()) {
return {};
}
int32_t diff = int32_t(sleep_timer_target_millis_.value() - millis());
if (diff <= 0) {
return {};
}
uint32_t minutes = uint32_t(diff) / 1000 / 60 + 1;
return minutes;
}
static uint8_t calc_checksum(const uint8_t* buffer) {
size_t result = 0;
for (size_t i = 0; i < 12; i++) {
result += buffer[i];
}
return (result & 0xff) ^ 0x55;
}
void set_swing_mode(climate::ClimateSwingMode mode) {
if (this->swing_mode != mode) {
// If vertical swing is off, send a 0xAA message to restore the vane position.
if (mode == climate::CLIMATE_SWING_OFF || mode == climate::CLIMATE_SWING_HORIZONTAL) {
pending_type_a_settings_change_ = true;
}
}
this->swing_mode = mode;
}
void send_status_message() {
// Byte 0: message type.
send_buf_[0] = slave_ ? 0x28 : 0xA8;
// Byte 1: changed flag (0x1), power on (0x2), mode (0x1C), fan speed (0x70).
uint8_t b = 0;
if (pending_status_change_) {
b |= 0x1;
}
switch (this->mode) {
case climate::CLIMATE_MODE_COOL:
b |= (0 << 2) | 0x2;
break;
case climate::CLIMATE_MODE_DRY:
b |= (1 << 2) | 0x2;
break;
case climate::CLIMATE_MODE_FAN_ONLY:
b |= (2 << 2) | 0x2;
break;
case climate::CLIMATE_MODE_HEAT_COOL:
b |= (3 << 2) | 0x2;
break;
case climate::CLIMATE_MODE_HEAT:
b |= (4 << 2) | 0x2;
break;
case climate::CLIMATE_MODE_OFF:
// Don't set power-on flag, but preserve previous operation mode.
b |= (last_recv_status_[1] & 0x1C);
break;
default:
ESP_LOGE(TAG, "unknown operation mode, turning off");
b |= (2 << 2);
break;
}
// Fix: Check if fan_mode has a value before dereferencing
if (this->fan_mode.has_value()) {
switch (this->fan_mode.value()) {
case climate::CLIMATE_FAN_LOW:
b |= 0 << 5;
break;
case climate::CLIMATE_FAN_MEDIUM:
b |= 1 << 5;
break;
case climate::CLIMATE_FAN_HIGH:
b |= 2 << 5;
break;
case climate::CLIMATE_FAN_AUTO:
b |= 3 << 5;
break;
case climate::CLIMATE_FAN_QUIET:
b |= 4 << 5;
break;
default:
ESP_LOGE(TAG, "unknown fan mode, using Medium");
b |= 1 << 5;
break;
}
} else {
// Default to Medium if no fan mode is set
ESP_LOGD(TAG, "no fan mode set, using Medium as default");
b |= 1 << 5;
}
send_buf_[1] = b;
// Byte 2: swing mode and purifier/plasma setting. Preserve the other bits.
b = last_recv_status_[2] & ~(0x4|0x40|0x80);
if (purifier_.state) {
b |= 0x4;
}
switch (this->swing_mode) {
case climate::CLIMATE_SWING_OFF:
break;
case climate::CLIMATE_SWING_HORIZONTAL:
b |= 0x40;
break;
case climate::CLIMATE_SWING_VERTICAL:
b |= 0x80;
break;
case climate::CLIMATE_SWING_BOTH:
b |= 0x40 | 0x80;
break;
default:
ESP_LOGE(TAG, "unknown swing mode");
break;
}
send_buf_[2] = b;
// Byte 3.
send_buf_[3] = last_recv_status_[3];
if (active_reservation_) {
send_buf_[3] |= 0x10;
} else {
send_buf_[3] &= ~0x10;
}
// Byte 4.
send_buf_[4] = last_recv_status_[4];
float target = this->target_temperature;
if (fahrenheit_) {
target = TempConversion::celsius_to_lgcelsius(target);
}
if (target < MIN_TEMP_SETPOINT) {
target = MIN_TEMP_SETPOINT;
} else if (target > MAX_TEMP_SETPOINT) {
target = MAX_TEMP_SETPOINT;
}
// Byte 5. Unchanged except for the low bit which indicates the target temperature has a
// 0.5 fractional part.
send_buf_[5] = last_recv_status_[5] & ~0x1;
if (target - uint8_t(target) == 0.5) {
send_buf_[5] |= 0x1;
}
// Byte 6: thermistor setting and target temperature (fractional part in byte 5).
// Byte 7: room temperature. Preserve the (unknown) upper two bits.
enum ThermistorSetting { Unit = 0, Controller = 1, TwoTH = 2 };
ThermistorSetting thermistor =
internal_thermistor_.state ? ThermistorSetting::Unit : ThermistorSetting::Controller;
float temp;
if (auto maybe_temp = get_room_temp()) {
temp = *maybe_temp;
} else {
// Room temperature isn't available. Use the unit's thermistor and send something
// reasonable.
thermistor = ThermistorSetting::Unit;
temp = 20;
}
send_buf_[6] = (thermistor << 4) | ((uint8_t(target) - 15) & 0xf);
send_buf_[7] = (last_recv_status_[7] & 0xC0) | uint8_t((temp - 10) * 2);
// Bytes 8-10. Initialize bytes 8-9 to 0 to not echo back timer settings set by the AC.
send_buf_[8] = 0;
send_buf_[9] = 0;
send_buf_[10] = last_recv_status_[10];
if (is_initializing_) {
// Request settings when controller turns on.
send_buf_[8] |= 0x40;
// Set bit 0x80 of byte 10 to use byte 9 for the Fahrenheit setting flag (0x40).
if (fahrenheit_) {
send_buf_[9] |= 0x40;
}
send_buf_[10] = 0x80;
} else if (optional<uint32_t> minutes = get_sleep_timer_minutes()) {
// Set sleep timer.
// Byte 8 stores the kind (0x38) and high bits of number of minutes (0x7).
// Byte 9 stores the low bits of the number of minutes.
constexpr uint8_t timer_kind_sleep = 3;
send_buf_[8] = timer_kind_sleep << 3;
send_buf_[8] |= (*minutes >> 8) & 0b111;
send_buf_[9] = *minutes & 0xff;
}
// Byte 11.
send_buf_[11] = last_recv_status_[11];
// Byte 12.
send_buf_[12] = calc_checksum(send_buf_);
ESP_LOGD(TAG, "sending %s", format_hex_pretty(send_buf_, MsgLen).c_str());
UARTDevice::write_array(send_buf_, MsgLen);
pending_status_change_ = false;
pending_send_ = PendingSendKind::Status;
last_sent_status_millis_ = millis();
// If we sent an updated temperature to the AC, update temperature in HA too.
// Slave controller temperature sensor is ignored.
if (!slave_ && thermistor == ThermistorSetting::Controller) {
float ha_temp = temp;
if (fahrenheit_) {
ha_temp = TempConversion::lgcelsius_to_celsius(ha_temp);
}
if (this->current_temperature != ha_temp) {
this->current_temperature = ha_temp;
publish_state();
}
}
}
void send_type_a_settings_message() {
if (last_recv_type_a_settings_[0] != 0xCA && last_recv_type_a_settings_[0] != 0xAA) {
ESP_LOGE(TAG, "Unexpected missing previous CA/AA message");
pending_type_a_settings_change_ = false;
return;
}
// Copy settings from the CA/AA message we received.
memcpy(send_buf_, last_recv_type_a_settings_, MsgLen);
send_buf_[0] = slave_ ? 0x2A : 0xAA;
// Bytes 2-6 store the installer fan speeds
send_buf_[2] = fan_speed_[0];
send_buf_[3] = fan_speed_[1];
send_buf_[4] = fan_speed_[2];
send_buf_[5] = fan_speed_[3];
// Bytes 7-8 store vane positions.
send_buf_[7] = (send_buf_[7] & 0xf0) | (vane_position_[0] & 0x0f); // Set vane 1
send_buf_[7] = (send_buf_[7] & 0x0f) | ((vane_position_[1] & 0x0f) << 4); // Set vane 2
send_buf_[8] = (send_buf_[8] & 0xf0) | (vane_position_[2] & 0x0f); // Set vane 3
send_buf_[8] = (send_buf_[8] & 0x0f) | ((vane_position_[3] & 0x0f) << 4); // Set vane 4
// Set auto dry setting.
uint8_t b = send_buf_[11] & ~0x8;
if (auto_dry_.state) {
b |= 0x8;
}
send_buf_[11] = b;
send_buf_[12] = calc_checksum(send_buf_);
ESP_LOGD(TAG, "sending %s", format_hex_pretty(send_buf_, MsgLen).c_str());
UARTDevice::write_array(send_buf_, MsgLen);
pending_type_a_settings_change_ = false;
pending_send_ = PendingSendKind::TypeA;
}
void send_type_b_settings_message(bool timed) {
if (timed) {
ESP_LOGD(TAG, "sending timed AB message");
}
if (last_recv_type_b_settings_[0] != 0xCB && last_recv_type_b_settings_[0] != 0xAB) {
ESP_LOGE(TAG, "Unexpected missing previous CB/AB message");
pending_type_b_settings_change_ = false;
// Don't try to send another message immediately after.
last_sent_recv_type_b_millis_ = millis();
return;
}
// Copy settings from the CB/AB message we received.
memcpy(send_buf_, last_recv_type_b_settings_, MsgLen);
send_buf_[0] = slave_ ? 0x2B : 0xAB;
// Set the high bit of the second byte to request a CB message from the unit.
if (timed) {
send_buf_[1] |= 0x80;
} else {
send_buf_[1] &= ~0x80;
}
// Byte 2 stores installer setting 15.
send_buf_[2] = (send_buf_[2] & 0xC7) | (overheating_ << 3);
send_buf_[12] = calc_checksum(send_buf_);
ESP_LOGD(TAG, "sending %s", format_hex_pretty(send_buf_, MsgLen).c_str());
UARTDevice::write_array(send_buf_, MsgLen);
pending_type_b_settings_change_ = false;
pending_send_ = PendingSendKind::TypeB;
last_sent_recv_type_b_millis_ = millis();
}
void process_message(const uint8_t* buffer, bool* had_error) {
ESP_LOGD(TAG, "received %s", format_hex_pretty(buffer, MsgLen).c_str());
if (calc_checksum(buffer) != buffer[12]) {
// When initializing, the unit sends an all-zeroes message as padding between
// messages. Ignore those false checksum failures.
auto is_zero = [](uint8_t b) { return b == 0; };
if (std::all_of(buffer, buffer + MsgLen, is_zero)) {
ESP_LOGD(TAG, "Ignoring padding message sent by unit");
return;
}
ESP_LOGE(TAG, "invalid checksum %s", format_hex_pretty(buffer, MsgLen).c_str());
*had_error = true;
return;
}
if (pending_send_ != PendingSendKind::None && memcmp(send_buf_, buffer, MsgLen) == 0) {
ESP_LOGD(TAG, "verified send");
pending_send_ = PendingSendKind::None;
return;
}
// Determine message type.
optional<MessageSender> sender;
switch (buffer[0] & 0xf8) {
case 0xC8:
sender = MessageSender::Unit;
break;
case 0xA8:
if (!slave_) {
// Ignore (our own?) master controller messages.
return;
}
sender = MessageSender::Master;
break;
case 0x28:
if (slave_) {
// Ignore (our own?) slave controller messages.
return;
}
sender = MessageSender::Slave;
break;
default:
return; // Unknown message sender. Ignore.
}
switch (buffer[0] & 0b111) {
case 0: // 0xC8/A8/28
process_status_message(*sender, buffer, had_error);
break;
case 1: // 0xC9
process_capabilities_message(*sender, buffer);
break;
case 2: // 0xCA/AA/2A
process_type_a_settings_message(*sender, buffer);
break;
case 3: // 0xCB/AB/2B
process_type_b_settings_message(*sender, buffer);
break;
case 4: // 0xCC/AC/2C
process_type_c_status_message(*sender, buffer);
break;
case 7: // 0xCF/AF/2F
process_type_f_status_message(*sender, buffer);
break;
default:
return;
}
}
void process_status_message(MessageSender sender, const uint8_t* buffer, bool* had_error) {
// If we just had a failure, ignore this messsage because it might be invalid too.
if (*had_error) {
ESP_LOGE(TAG, "ignoring due to previous error %s",
format_hex_pretty(buffer, MsgLen).c_str());
return;
}
// Consider slave controller initialized if we received a status message from the other
// controller or the unit.
if (slave_) {
is_initializing_ = false;
}
// Handle simple input sensors first. These are safe to update even if we have a pending
// change.
defrost_.publish_state(buffer[3] & 0x4);
preheat_.publish_state(buffer[3] & 0x8);
if (sender == MessageSender::Unit) {
error_code_.publish_state(buffer[11]);
}
// When turning on the outdoor unit, the AC sometimes reports ON => OFF => ON within a
// few seconds. No big deal but it causes noisy state changes in HA. Only report OFF if
// the last state change was at least 8 seconds ago.
bool outdoor_on = buffer[5] & 0x4;
bool outdoor_changed = outdoor_.state != outdoor_on;
if (outdoor_on) {
outdoor_.publish_state(true);
} else if (millis() - last_outdoor_change_millis_ > 8000) {
outdoor_.publish_state(false);
}
if (outdoor_changed) {
last_outdoor_change_millis_ = millis();
}
if (sender == MessageSender::Unit && !auto_dry_.is_internal()) {
bool unit_off = (buffer[1] & 0x2) == 0;
bool drying = (buffer[10] & 0x10) && unit_off;
auto_dry_active_.publish_state(drying);
}
bool read_temp = false;
if (slave_) {