-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlvgl_esphome.cpp
More file actions
891 lines (797 loc) · 30.6 KB
/
lvgl_esphome.cpp
File metadata and controls
891 lines (797 loc) · 30.6 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
#include "esphome/core/defines.h"
#include "esphome/core/hal.h"
#include "esphome/core/helpers.h"
#include "esphome/core/log.h"
#include "lvgl_esphome.h"
#include "core/lv_obj_class_private.h"
#ifdef USE_LVGL_PPA
extern "C" {
void lv_draw_ppa_init(void);
}
#endif
#include <cstring>
#include <numeric>
namespace esphome::lvgl {
static const char *const TAG = "lvgl";
static const size_t MIN_BUFFER_FRAC = 8;
static const char *const EVENT_NAMES[] = {
"NONE",
"PRESSED",
"PRESSING",
"PRESS_LOST",
"SHORT_CLICKED",
"LONG_PRESSED",
"LONG_PRESSED_REPEAT",
"CLICKED",
"RELEASED",
"SCROLL_BEGIN",
"SCROLL_END",
"SCROLL",
"GESTURE",
"KEY",
"FOCUSED",
"DEFOCUSED",
"LEAVE",
"HIT_TEST",
"COVER_CHECK",
"REFR_EXT_DRAW_SIZE",
"DRAW_MAIN_BEGIN",
"DRAW_MAIN",
"DRAW_MAIN_END",
"DRAW_POST_BEGIN",
"DRAW_POST",
"DRAW_POST_END",
"DRAW_PART_BEGIN",
"DRAW_PART_END",
"VALUE_CHANGED",
"INSERT",
"REFRESH",
"READY",
"CANCEL",
"DELETE",
"CHILD_CHANGED",
"CHILD_CREATED",
"CHILD_DELETED",
"SCREEN_UNLOAD_START",
"SCREEN_LOAD_START",
"SCREEN_LOADED",
"SCREEN_UNLOADED",
"SIZE_CHANGED",
"STYLE_CHANGED",
"LAYOUT_CHANGED",
"GET_SELF_SIZE",
};
static const unsigned LOG_LEVEL_MAP[] = {
ESPHOME_LOG_LEVEL_DEBUG, ESPHOME_LOG_LEVEL_INFO, ESPHOME_LOG_LEVEL_WARN,
ESPHOME_LOG_LEVEL_ERROR, ESPHOME_LOG_LEVEL_ERROR, ESPHOME_LOG_LEVEL_NONE,
};
std::string lv_event_code_name_for(lv_event_t *event) {
auto event_code = lv_event_get_code(event);
if (event_code < sizeof(EVENT_NAMES) / sizeof(EVENT_NAMES[0])) {
return EVENT_NAMES[event_code];
}
return str_sprintf("%2d", event_code);
}
static void rounder_cb(lv_event_t *event) {
auto *comp = static_cast<LvglComponent *>(lv_event_get_user_data(event));
auto *area = static_cast<lv_area_t *>(lv_event_get_param(event));
// cater for display driver chips with special requirements for bounds of partial
// draw areas. Extend the draw area to satisfy:
// * Coordinates must be a multiple of draw_rounding
auto draw_rounding = comp->draw_rounding;
// round down the start coordinates
area->x1 = area->x1 / draw_rounding * draw_rounding;
area->y1 = area->y1 / draw_rounding * draw_rounding;
// round up the end coordinates
area->x2 = (area->x2 + draw_rounding) / draw_rounding * draw_rounding - 1;
area->y2 = (area->y2 + draw_rounding) / draw_rounding * draw_rounding - 1;
}
void LvglComponent::render_end_cb(lv_event_t *event) {
auto *comp = static_cast<LvglComponent *>(lv_event_get_user_data(event));
comp->draw_end_();
}
void LvglComponent::render_start_cb(lv_event_t *event) {
ESP_LOGVV(TAG, "Draw start");
auto *comp = static_cast<LvglComponent *>(lv_event_get_user_data(event));
comp->draw_start_();
}
lv_event_code_t lv_api_event; // NOLINT
lv_event_code_t lv_update_event; // NOLINT
void LvglComponent::dump_config() {
ESP_LOGCONFIG(TAG,
"LVGL:\n"
" Display width/height: %d x %d\n"
" Buffer size: %zu%%\n"
" Rotation: %d\n"
" Draw rounding: %d",
this->width_, this->height_, 100 / this->buffer_frac_, this->rotation, (int) this->draw_rounding);
}
void LvglComponent::set_paused(bool paused, bool show_snow) {
this->paused_ = paused;
this->show_snow_ = show_snow;
if (!paused && lv_screen_active() != nullptr) {
lv_display_trigger_activity(this->disp_); // resets the inactivity time
lv_obj_invalidate(lv_screen_active());
}
if (paused && this->pause_callback_ != nullptr)
this->pause_callback_->trigger();
if (!paused && this->resume_callback_ != nullptr)
this->resume_callback_->trigger();
}
void LvglComponent::esphome_lvgl_init() {
lv_init();
#ifdef USE_LVGL_PPA
// Initialize PPA draw unit after lv_init()
// Uses custom PPA code (based on https://github.com/lvgl/lvgl/pull/9162)
// LVGL 9.5 includes this fix natively; kept as fallback
lv_draw_ppa_init();
#endif
lv_tick_set_cb([] { return millis(); });
lv_update_event = static_cast<lv_event_code_t>(lv_event_register_id());
lv_api_event = static_cast<lv_event_code_t>(lv_event_register_id());
}
void LvglComponent::add_event_cb(lv_obj_t *obj, event_callback_t callback, lv_event_code_t event) {
lv_obj_add_event_cb(obj, callback, event, nullptr);
}
void LvglComponent::add_event_cb(lv_obj_t *obj, event_callback_t callback, lv_event_code_t event1,
lv_event_code_t event2) {
add_event_cb(obj, callback, event1);
add_event_cb(obj, callback, event2);
}
void LvglComponent::add_event_cb(lv_obj_t *obj, event_callback_t callback, lv_event_code_t event1,
lv_event_code_t event2, lv_event_code_t event3) {
add_event_cb(obj, callback, event1);
add_event_cb(obj, callback, event2);
add_event_cb(obj, callback, event3);
}
void LvglComponent::add_page(LvPageType *page) {
this->pages_.push_back(page);
page->set_parent(this);
lv_display_set_default(this->disp_);
page->setup(this->pages_.size() - 1);
}
void LvglComponent::show_page(size_t index, lv_scr_load_anim_t anim, uint32_t time) {
if (index >= this->pages_.size())
return;
this->current_page_ = index;
lv_scr_load_anim(this->pages_[this->current_page_]->obj, anim, time, 0, false);
}
void LvglComponent::show_next_page(lv_scr_load_anim_t anim, uint32_t time) {
if (this->pages_.empty() || (this->current_page_ == this->pages_.size() - 1 && !this->page_wrap_))
return;
auto start = this->current_page_;
do {
this->current_page_ = (this->current_page_ + 1) % this->pages_.size();
if (this->current_page_ == start)
return; // all pages are skipped, avoid infinite loop
} while (this->pages_[this->current_page_]->skip);
this->show_page(this->current_page_, anim, time);
}
void LvglComponent::show_prev_page(lv_scr_load_anim_t anim, uint32_t time) {
if (this->pages_.empty() || (this->current_page_ == 0 && !this->page_wrap_))
return;
auto start = this->current_page_;
do {
this->current_page_ = (this->current_page_ + this->pages_.size() - 1) % this->pages_.size();
if (this->current_page_ == start)
return; // all pages are skipped, avoid infinite loop
} while (this->pages_[this->current_page_]->skip);
this->show_page(this->current_page_, anim, time);
}
size_t LvglComponent::get_current_page() const { return this->current_page_; }
bool LvPageType::is_showing() const { return this->parent_->get_current_page() == this->index; }
void LvglComponent::draw_buffer_(const lv_area_t *area, lv_color_data *ptr) {
auto width = lv_area_get_width(area);
auto height = lv_area_get_height(area);
auto height_rounded = (height + this->draw_rounding - 1) / this->draw_rounding * this->draw_rounding;
auto x1 = area->x1;
auto y1 = area->y1;
auto *dst = reinterpret_cast<lv_color_data *>(this->rotate_buf_);
switch (this->rotation) {
case display::DISPLAY_ROTATION_90_DEGREES:
for (lv_coord_t x = height; x-- != 0;) {
for (lv_coord_t y = 0; y != width; y++) {
dst[y * height_rounded + x] = *ptr++;
}
}
y1 = x1;
x1 = this->height_ - area->y1 - height;
height = width;
width = height_rounded;
break;
case display::DISPLAY_ROTATION_180_DEGREES:
for (lv_coord_t y = height; y-- != 0;) {
for (lv_coord_t x = width; x-- != 0;) {
dst[y * width + x] = *ptr++;
}
}
x1 = this->width_ - x1 - width;
y1 = this->height_ - y1 - height;
break;
case display::DISPLAY_ROTATION_270_DEGREES:
for (lv_coord_t x = 0; x != height; x++) {
for (lv_coord_t y = width; y-- != 0;) {
dst[y * height_rounded + x] = *ptr++;
}
}
x1 = y1;
y1 = this->width_ - area->x1 - width;
height = width;
width = height_rounded;
break;
default:
dst = ptr;
break;
}
for (auto *display : this->displays_) {
display->draw_pixels_at(x1, y1, width, height, (const uint8_t *) dst, display::COLOR_ORDER_RGB, LV_BITNESS,
this->big_endian_);
}
}
void LvglComponent::flush_cb_(lv_display_t *disp_drv, const lv_area_t *area, uint8_t *color_p) {
if (!this->is_paused()) {
auto now = millis();
this->draw_buffer_(area, reinterpret_cast<lv_color_data *>(color_p));
ESP_LOGV(TAG, "flush_cb, area=%d/%d, %d/%d took %dms", area->x1, area->y1, lv_area_get_width(area),
lv_area_get_height(area), (int) (millis() - now));
}
lv_display_flush_ready(disp_drv);
}
IdleTrigger::IdleTrigger(LvglComponent *parent, TemplatableValue<uint32_t> timeout) : timeout_(std::move(timeout)) {
parent->add_on_idle_callback([this](uint32_t idle_time) {
if (!this->is_idle_ && idle_time > this->timeout_.value()) {
this->is_idle_ = true;
this->trigger();
} else if (this->is_idle_ && idle_time < this->timeout_.value()) {
this->is_idle_ = false;
}
});
}
#ifdef USE_LVGL_TOUCHSCREEN
LVTouchListener::LVTouchListener(uint16_t long_press_time, uint16_t long_press_repeat_time, LvglComponent *parent) {
this->set_parent(parent);
this->drv_ = lv_indev_create();
lv_indev_set_type(this->drv_, LV_INDEV_TYPE_POINTER);
lv_indev_set_disp(this->drv_, parent->get_disp());
lv_indev_set_long_press_time(this->drv_, long_press_time);
// long press repeat time TBD
lv_indev_set_user_data(this->drv_, this);
lv_indev_set_read_cb(this->drv_, [](lv_indev_t *d, lv_indev_data_t *data) {
auto *l = static_cast<LVTouchListener *>(lv_indev_get_user_data(d));
if (l->touch_pressed_) {
data->point.x = l->touch_point_.x;
data->point.y = l->touch_point_.y;
data->state = LV_INDEV_STATE_PRESSED;
} else {
data->state = LV_INDEV_STATE_RELEASED;
}
});
}
void LVTouchListener::update(const touchscreen::TouchPoints_t &tpoints) {
this->touch_pressed_ = !this->parent_->is_paused() && !tpoints.empty();
if (this->touch_pressed_)
this->touch_point_ = tpoints[0];
}
#endif // USE_LVGL_TOUCHSCREEN
#ifdef USE_LVGL_METER
int16_t lv_get_needle_angle_for_value(lv_obj_t *obj, int value) {
auto *scale = lv_obj_get_parent(obj);
auto min_value = lv_scale_get_range_min_value(scale);
return ((value - min_value) * lv_scale_get_angle_range(scale) / (lv_scale_get_range_max_value(scale) - min_value) +
lv_scale_get_rotation((scale))) %
360;
}
void IndicatorLine::set_obj(lv_obj_t *lv_obj) {
LvCompound::set_obj(lv_obj);
lv_line_set_points(lv_obj, this->points_, 2);
lv_obj_add_event_cb(
lv_obj_get_parent(obj),
[](lv_event_t *e) {
auto *indicator = static_cast<IndicatorLine *>(lv_event_get_user_data(e));
indicator->update_length_();
ESP_LOGD(TAG, "Updated length, value = %d", indicator->angle_);
},
LV_EVENT_SIZE_CHANGED, this);
}
void IndicatorLine::set_value(int value) {
auto angle = lv_get_needle_angle_for_value(this->obj, value);
if (angle != this->angle_) {
this->angle_ = angle;
this->update_length_();
}
}
void IndicatorLine::update_length_() {
uint32_t actual_needle_length;
auto radius = lv_obj_get_width(lv_obj_get_parent(this->obj)) / 2;
auto length = lv_obj_get_style_length(this->obj, LV_PART_MAIN);
auto radial_offset = lv_obj_get_style_radial_offset(this->obj, LV_PART_MAIN);
if (LV_COORD_IS_PCT(radial_offset)) {
radial_offset = radius * LV_COORD_GET_PCT(radial_offset) / 100;
}
if (LV_COORD_IS_PCT(length)) {
actual_needle_length = radius * LV_COORD_GET_PCT(length) / 100;
} else if (length < 0) {
actual_needle_length = radius + length;
} else {
actual_needle_length = length;
}
auto x = lv_trigo_cos(this->angle_) / 32768.0f;
auto y = lv_trigo_sin(this->angle_) / 32768.0f;
this->points_[0].x = radius + radial_offset * x;
this->points_[0].y = radius + radial_offset * y;
this->points_[1].x = x * actual_needle_length + radius;
this->points_[1].y = y * actual_needle_length + radius;
lv_obj_refresh_self_size(this->obj);
lv_obj_invalidate(this->obj);
}
#endif
#ifdef USE_LVGL_KEY_LISTENER
LVEncoderListener::LVEncoderListener(lv_indev_type_t type, uint16_t long_press_time, uint16_t long_press_repeat_time) {
this->drv_ = lv_indev_create();
lv_indev_set_type(this->drv_, type);
lv_indev_set_long_press_time(this->drv_, long_press_time);
lv_indev_set_long_press_repeat_time(this->drv_, long_press_repeat_time);
lv_indev_set_user_data(this->drv_, this);
lv_indev_set_read_cb(this->drv_, [](lv_indev_t *d, lv_indev_data_t *data) {
auto *l = static_cast<LVEncoderListener *>(lv_indev_get_user_data(d));
data->state = l->pressed_ ? LV_INDEV_STATE_PRESSED : LV_INDEV_STATE_RELEASED;
data->key = l->key_;
data->enc_diff = (int16_t) (l->count_ - l->last_count_);
l->last_count_ = l->count_;
data->continue_reading = false;
});
}
#endif // USE_LVGL_KEY_LISTENER
#if defined(USE_LVGL_DROPDOWN) || defined(LV_USE_ROLLER)
std::string LvSelectable::get_selected_text() {
auto selected = this->get_selected_index();
if (selected >= this->options_.size())
return "";
return this->options_[selected];
}
static std::string join_string(std::vector<std::string> options) {
return std::accumulate(
options.begin(), options.end(), std::string(),
[](const std::string &a, const std::string &b) -> std::string { return a + (!a.empty() ? "\n" : "") + b; });
}
void LvSelectable::set_selected_text(const std::string &text, lv_anim_enable_t anim) {
auto index = std::find(this->options_.begin(), this->options_.end(), text);
if (index != this->options_.end()) {
this->set_selected_index(index - this->options_.begin(), anim);
lv_obj_send_event(this->obj, lv_api_event, nullptr);
}
}
void LvSelectable::set_options(std::vector<std::string> options) {
auto index = this->get_selected_index();
if (index >= options.size())
index = options.size() - 1;
this->options_ = std::move(options);
this->set_option_string(join_string(this->options_).c_str());
lv_obj_send_event(this->obj, LV_EVENT_REFRESH, nullptr);
this->set_selected_index(index, LV_ANIM_OFF);
}
#endif // USE_LVGL_DROPDOWN || LV_USE_ROLLER
#ifdef USE_LVGL_BUTTONMATRIX
void LvButtonMatrixType::set_obj(lv_obj_t *lv_obj) {
LvCompound::set_obj(lv_obj);
lv_obj_add_event_cb(
lv_obj,
[](lv_event_t *event) {
auto *self = static_cast<LvButtonMatrixType *>(lv_event_get_user_data(event));
if (self->key_callback_.size() == 0)
return;
auto key_idx = lv_buttonmatrix_get_selected_button(self->obj);
if (key_idx == LV_BUTTONMATRIX_BUTTON_NONE)
return;
if (self->key_map_.count(key_idx) != 0) {
self->send_key_(self->key_map_[key_idx]);
return;
}
const auto *str = lv_buttonmatrix_get_button_text(self->obj, key_idx);
auto len = strlen(str);
while (len--)
self->send_key_(*str++);
},
LV_EVENT_PRESSED, this);
}
#endif // USE_LVGL_BUTTONMATRIX
#ifdef USE_LVGL_KEYBOARD
static const char *const KB_SPECIAL_KEYS[] = {
"abc", "ABC", "1#",
// maybe add other special keys here
};
void LvKeyboardType::set_obj(lv_obj_t *lv_obj) {
LvCompound::set_obj(lv_obj);
lv_obj_add_event_cb(
lv_obj,
[](lv_event_t *event) {
auto *self = static_cast<LvKeyboardType *>(lv_event_get_user_data(event));
if (self->key_callback_.size() == 0)
return;
auto key_idx = lv_buttonmatrix_get_selected_button(self->obj);
if (key_idx == LV_BUTTONMATRIX_BUTTON_NONE)
return;
const char *txt = lv_buttonmatrix_get_button_text(self->obj, key_idx);
if (txt == nullptr)
return;
for (const auto *kb_special_key : KB_SPECIAL_KEYS) {
if (strcmp(txt, kb_special_key) == 0)
return;
}
while (*txt != 0)
self->send_key_(*txt++);
},
LV_EVENT_PRESSED, this);
}
#endif // USE_LVGL_KEYBOARD
void LvglComponent::draw_end_() {
if (this->draw_end_callback_ != nullptr)
this->draw_end_callback_->trigger();
if (this->update_when_display_idle_) {
for (auto *disp : this->displays_)
disp->update();
}
}
bool LvglComponent::is_paused() const {
if (this->paused_)
return true;
if (this->update_when_display_idle_) {
for (auto *disp : this->displays_) {
if (!disp->is_idle())
return true;
}
}
return false;
}
void LvglComponent::write_random_() {
int iterations = 6 - lv_display_get_inactive_time(this->disp_) / 60000;
if (iterations <= 0)
iterations = 1;
while (iterations-- != 0) {
auto col = random_uint32() % this->width_;
col = col / this->draw_rounding * this->draw_rounding;
auto row = random_uint32() % this->height_;
row = row / this->draw_rounding * this->draw_rounding;
auto raw_size = (random_uint32() % 32) / this->draw_rounding * this->draw_rounding;
if (raw_size == 0)
continue;
auto size = raw_size - 1;
lv_area_t area;
area.x1 = col;
area.y1 = row;
area.x2 = col + size;
area.y2 = row + size;
if (area.x2 >= this->width_)
area.x2 = this->width_ - 1;
if (area.y2 >= this->height_)
area.y2 = this->height_ - 1;
size_t line_len = lv_area_get_width(&area) * lv_area_get_height(&area) / 2;
for (size_t i = 0; i != line_len; i++) {
((uint32_t *) (this->draw_buf_))[i] = random_uint32();
}
this->draw_buffer_(&area, (lv_color_data *) this->draw_buf_);
}
}
/**
* @class LvglComponent
* @brief Component for rendering LVGL.
*
* This component renders LVGL widgets on a display. Some initialisation must be done in the constructor
* since LVGL needs to be initialised before any widgets can be created.
*
* @param displays a list of displays to render onto. All displays must have the same
* resolution.
* @param buffer_frac the fraction of the display resolution to use for the LVGL
* draw buffer. A higher value will make animations smoother but
* also increase memory usage.
* @param full_refresh if true, the display will be fully refreshed on every frame.
* If false, only changed areas will be updated.
* @param draw_rounding the rounding to use when drawing. A value of 1 will draw
* without any rounding, a value of 2 will round to the nearest
* multiple of 2, and so on.
* @param resume_on_input if true, this component will resume rendering when the user
* presses a key or clicks on the screen.
*/
LvglComponent::LvglComponent(std::vector<display::Display *> displays, float buffer_frac, bool full_refresh,
int draw_rounding, bool resume_on_input, bool update_when_display_idle)
: draw_rounding(draw_rounding),
displays_(std::move(displays)),
buffer_frac_(buffer_frac),
full_refresh_(full_refresh),
resume_on_input_(resume_on_input),
update_when_display_idle_(update_when_display_idle) {
this->disp_ = lv_display_create(240, 240);
}
void LvglComponent::setup() {
auto *display = this->displays_[0];
auto rounding = this->draw_rounding;
// cater for displays with dimensions that don't divide by the required rounding
this->width_ = display->get_width();
this->height_ = display->get_height();
auto width = (display->get_width() + rounding - 1) / rounding * rounding;
auto height = (display->get_height() + rounding - 1) / rounding * rounding;
auto frac = this->buffer_frac_;
if (frac == 0)
frac = 1;
auto buf_bytes = width * height / frac * LV_COLOR_DEPTH / 8;
void *buffer = nullptr;
// CRITICAL: Always use lv_malloc_core() which guarantees 64-byte alignment
// Don't use malloc() as it may not be aligned correctly for LVGL 9.5
buffer = lv_malloc_core(buf_bytes); // NOLINT
// if specific buffer size not set and can't get 100%, try for a smaller one
if (buffer == nullptr && this->buffer_frac_ == 0) {
frac = MIN_BUFFER_FRAC;
buf_bytes /= MIN_BUFFER_FRAC;
buffer = lv_malloc_core(buf_bytes); // NOLINT
}
this->buffer_frac_ = frac;
if (buffer == nullptr) {
this->status_set_error(LOG_STR("Memory allocation failure"));
this->mark_failed();
return;
}
this->draw_buf_ = static_cast<uint8_t *>(buffer);
lv_display_set_resolution(this->disp_, this->width_, this->height_);
lv_display_set_color_format(this->disp_, LV_COLOR_FORMAT_RGB565);
// CRITICAL: Set user_data BEFORE flush_cb, as flush_cb uses user_data
lv_display_set_user_data(this->disp_, this);
lv_display_set_flush_cb(this->disp_, static_flush_cb);
lv_display_add_event_cb(this->disp_, rounder_cb, LV_EVENT_INVALIDATE_AREA, this);
// Store buf_bytes - lv_display_set_buffers() is called at the END of setup()
// to avoid triggering rendering before all callbacks and pages are configured.
this->buf_bytes_ = buf_bytes;
this->rotation = display->get_rotation();
if (this->rotation != display::DISPLAY_ROTATION_0_DEGREES) {
this->rotate_buf_ = static_cast<lv_color_t *>(lv_malloc_core(buf_bytes));
if (this->rotate_buf_ == nullptr) {
this->status_set_error(LOG_STR("Memory allocation failure"));
this->mark_failed();
return;
}
}
if (this->draw_start_callback_ != nullptr) {
lv_display_add_event_cb(this->disp_, render_start_cb, LV_EVENT_RENDER_START, this);
}
if (this->draw_end_callback_ != nullptr || this->update_when_display_idle_) {
lv_display_add_event_cb(this->disp_, render_end_cb, LV_EVENT_REFR_READY, this);
}
#if LV_USE_LOG
lv_log_register_print_cb([](lv_log_level_t level, const char *buf) {
auto next = strchr(buf, ')');
if (next != nullptr)
buf = next + 1;
while (isspace(*buf))
buf++;
if (level >= sizeof(LOG_LEVEL_MAP) / sizeof(LOG_LEVEL_MAP[0]))
level = sizeof(LOG_LEVEL_MAP) / sizeof(LOG_LEVEL_MAP[0]) - 1;
esp_log_printf_(LOG_LEVEL_MAP[level], TAG, 0, "%.*s", (int) strlen(buf) - 1, buf);
});
#endif
// Rotation will be handled by our drawing function, so reset the display rotation.
for (auto *disp : this->displays_)
disp->set_rotation(display::DISPLAY_ROTATION_0_DEGREES);
this->show_page(0, LV_SCR_LOAD_ANIM_NONE, 0);
lv_display_trigger_activity(this->disp_);
// CRITICAL: Configure buffers at the VERY END of setup()
// This avoids deadlock while ensuring buffers are ready before any callbacks execute
lv_display_set_buffers(this->disp_, this->draw_buf_, nullptr, this->buf_bytes_,
this->full_refresh_ ? LV_DISPLAY_RENDER_MODE_FULL : LV_DISPLAY_RENDER_MODE_PARTIAL);
this->buffers_configured_ = true;
}
void LvglComponent::update() {
// update indicators
if (this->is_paused()) {
return;
}
this->idle_callbacks_.call(lv_display_get_inactive_time(this->disp_));
}
void LvglComponent::loop() {
if (!this->buffers_configured_)
return; // setup() not complete or failed, skip rendering
if (!this->loop_started_) {
this->loop_started_ = true;
ESP_LOGD(TAG, "LVGL loop started - system is now fully ready");
}
if (this->is_paused()) {
if (this->paused_ && this->show_snow_)
this->write_random_();
} else {
lv_timer_handler();
}
}
#ifdef USE_LVGL_ANIMIMG
void lv_animimg_stop(lv_obj_t *obj) {
int32_t duration = lv_animimg_get_duration(obj);
lv_animimg_set_duration(obj, 0);
lv_animimg_start(obj);
lv_animimg_set_duration(obj, duration);
}
#endif
void LvglComponent::static_flush_cb(lv_display_t *disp_drv, const lv_area_t *area, uint8_t *color_p) {
reinterpret_cast<LvglComponent *>(lv_display_get_user_data(disp_drv))->flush_cb_(disp_drv, area, color_p);
}
/**
* Function to apply colors to ticks based on position
* @param e The event data
* @param color_start The color to apply to the first tick
* @param color_end The color to apply to the last tick
*/
void lv_scale_draw_event_cb(lv_event_t *e, int32_t range_start, int32_t range_end, lv_color_t color_start,
lv_color_t color_end, bool local) {
auto *scale = static_cast<lv_obj_t *>(lv_event_get_target(e));
lv_draw_task_t *task = lv_event_get_draw_task(e);
if (lv_draw_task_get_type(task) == LV_DRAW_TASK_TYPE_LINE) {
auto *line_dsc = static_cast<lv_draw_line_dsc_t *>(lv_draw_task_get_draw_dsc(task));
auto tick_idx = line_dsc->base.id1;
// Convert tick index to scale value
auto total_ticks = lv_scale_get_total_tick_count(scale);
auto scale_min = lv_scale_get_range_min_value(scale);
auto scale_max = lv_scale_get_range_max_value(scale);
int32_t tick_value;
if (total_ticks > 1) {
tick_value = scale_min + (int32_t) tick_idx * (scale_max - scale_min) / (total_ticks - 1);
} else {
tick_value = scale_min;
}
if (tick_value >= range_start && tick_value <= range_end) {
int32_t range;
int32_t pos;
if (local) {
range = range_end - range_start;
pos = tick_value - range_start;
} else {
range = scale_max - scale_min;
pos = tick_value - scale_min;
}
if (range == 0)
range = 1;
auto ratio = (pos * 255) / range;
line_dsc->color = lv_color_mix(color_end, color_start, ratio);
}
}
}
static void lv_container_constructor(const lv_obj_class_t *class_p, lv_obj_t *obj) {
LV_TRACE_OBJ_CREATE("begin");
LV_UNUSED(class_p);
}
// Container class. Name is based on LVGL naming convention but upper case to keep ESPHome clang-tidy happy
const lv_obj_class_t LV_CONTAINER_CLASS = {
.base_class = &lv_obj_class,
.constructor_cb = lv_container_constructor,
.name = "lv_container",
};
lv_obj_t *lv_container_create(lv_obj_t *parent) {
lv_obj_t *obj = lv_obj_class_create_obj(&LV_CONTAINER_CLASS, parent);
lv_obj_class_init_obj(obj);
return obj;
}
} // namespace esphome::lvgl
lv_result_t lv_mem_test_core() { return LV_RESULT_OK; }
void lv_mem_init() {}
void lv_mem_deinit() {}
#if defined(USE_HOST) || defined(USE_RP2040) || defined(USE_ESP8266)
// Memory alignment for draw buffers on non-ESP32 platforms.
// We use 64-byte alignment for optimal performance even though LV_DRAW_BUF_ALIGN
// is set to 4 (to avoid warnings from LVGL's internal stack/static buffers).
// Standard malloc() only guarantees 8-16 byte alignment, so we implement
// our own aligned allocation.
static constexpr size_t LVGL_ALIGNMENT = 64;
// Store original pointer before aligned address for proper freeing
void *lv_malloc_core(size_t size) {
if (size == 0)
return nullptr;
// Allocate extra space for alignment and to store original pointer
size_t total_size = size + LVGL_ALIGNMENT + sizeof(void *);
void *raw = malloc(total_size); // NOLINT
if (raw == nullptr) {
ESP_LOGE(esphome::lvgl::TAG, "Failed to allocate %zu bytes", size);
return nullptr;
}
// Calculate aligned pointer (leaving space for original pointer storage)
uintptr_t raw_addr = reinterpret_cast<uintptr_t>(raw);
uintptr_t aligned_addr = (raw_addr + sizeof(void *) + LVGL_ALIGNMENT - 1) & ~(LVGL_ALIGNMENT - 1);
void *aligned = reinterpret_cast<void *>(aligned_addr);
// Store original pointer just before aligned address
reinterpret_cast<void **>(aligned)[-1] = raw;
return aligned;
}
void lv_free_core(void *ptr) {
if (ptr == nullptr)
return;
// Retrieve and free the original pointer
void *raw = reinterpret_cast<void **>(ptr)[-1];
free(raw); // NOLINT
}
void *lv_realloc_core(void *ptr, size_t size) {
if (ptr == nullptr)
return lv_malloc_core(size);
if (size == 0) {
lv_free_core(ptr);
return nullptr;
}
// Allocate new aligned buffer and copy data
void *new_ptr = lv_malloc_core(size);
if (new_ptr == nullptr)
return nullptr;
// We don't know the old size exactly, so copy min(new_size, old_usable_size).
// On most platforms, malloc_usable_size() returns the actual allocated size.
// Fall back to new size if unavailable (safe: reads at most what was allocated).
#if defined(__GLIBC__) || defined(__ANDROID__)
size_t old_size = malloc_usable_size(reinterpret_cast<void **>(ptr)[-1]);
// Subtract alignment overhead to get usable size from aligned pointer
size_t overhead = reinterpret_cast<uintptr_t>(ptr) - reinterpret_cast<uintptr_t>(reinterpret_cast<void **>(ptr)[-1]);
old_size = (old_size > overhead) ? old_size - overhead : 0;
#else
size_t old_size = size; // conservative fallback: may read less than available
#endif
memcpy(new_ptr, ptr, (size < old_size) ? size : old_size);
lv_free_core(ptr);
return new_ptr;
}
void lv_mem_monitor_core(lv_mem_monitor_t *mon_p) { memset(mon_p, 0, sizeof(lv_mem_monitor_t)); }
#endif
#ifdef USE_ESP32
static unsigned cap_bits = MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT; // NOLINT
void lv_mem_monitor_core(lv_mem_monitor_t *mon_p) {
multi_heap_info_t heap_info;
heap_caps_get_info(&heap_info, cap_bits);
mon_p->total_size = heap_info.total_allocated_bytes + heap_info.total_free_bytes;
mon_p->free_size = heap_info.total_free_bytes;
mon_p->max_used = heap_info.total_allocated_bytes;
mon_p->free_biggest_size = heap_info.largest_free_block;
mon_p->used_cnt = heap_info.allocated_blocks;
mon_p->free_cnt = heap_info.free_blocks;
mon_p->used_pct = heap_info.allocated_blocks * 100 / (heap_info.allocated_blocks + heap_info.free_blocks);
mon_p->frag_pct = 0;
}
void *lv_malloc_core(size_t size) {
void *ptr;
// Use 64-byte alignment for optimal ESP32 PSRAM/cache performance.
// Note: LV_DRAW_BUF_ALIGN is set to 4 to avoid LVGL warnings from
// internal stack/static buffers, but heap allocations use 64-byte alignment.
constexpr size_t LVGL_ALIGNMENT = 64;
// BUGFIX: Don't modify global cap_bits - use local variable
unsigned caps = cap_bits;
// Try PSRAM first
ptr = heap_caps_aligned_alloc(LVGL_ALIGNMENT, size, caps);
if (ptr == nullptr) {
// Fallback to internal RAM if PSRAM allocation fails
caps = MALLOC_CAP_8BIT;
ptr = heap_caps_aligned_alloc(LVGL_ALIGNMENT, size, caps);
}
if (ptr == nullptr) {
ESP_LOGE(esphome::lvgl::TAG, "Failed to allocate %zu bytes (64-byte aligned)", size);
return nullptr;
}
// Log only very large buffers (>1MB) for debugging
if (size > 1000000) {
ESP_LOGI(esphome::lvgl::TAG, "Large buffer allocated: %zu bytes at %p", size, ptr);
}
return ptr;
}
void lv_free_core(void *ptr) {
ESP_LOGV(esphome::lvgl::TAG, "free %p", ptr);
if (ptr == nullptr)
return;
heap_caps_free(ptr);
}
void *lv_realloc_core(void *ptr, size_t size) {
ESP_LOGV(esphome::lvgl::TAG, "realloc %p: %zu", ptr, size);
if (ptr == nullptr)
return lv_malloc_core(size);
if (size == 0) {
lv_free_core(ptr);
return nullptr;
}
// CRITICAL: heap_caps_realloc does NOT preserve 64-byte alignment!
// We must allocate a new aligned buffer and copy the data
void *new_ptr = lv_malloc_core(size);
if (new_ptr == nullptr)
return nullptr;
// Copy data to new buffer using heap_caps_get_allocated_size for safe bounds
size_t old_size = heap_caps_get_allocated_size(ptr);
memcpy(new_ptr, ptr, (size < old_size) ? size : old_size);
lv_free_core(ptr);
return new_ptr;
}
#endif