[lvgl] Roller and Dropdown enhancements; (#7608)

This commit is contained in:
Clyde Stubbs 2024-10-17 12:03:48 +11:00 committed by GitHub
parent 5ad68e926d
commit fcfc76b01b
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
16 changed files with 218 additions and 107 deletions

View file

@ -271,7 +271,8 @@ async def to_code(config):
await disp_update(f"{lv_component}->get_disp()", config) await disp_update(f"{lv_component}->get_disp()", config)
# At this point only the setup code should be generated # At this point only the setup code should be generated
assert LvContext.added_lambda_count == 1 assert LvContext.added_lambda_count == 1
Widget.set_completed() # Set this directly since we are limited in how many methods can be added to the Widget class.
Widget.widgets_completed = True
async with LvContext(lv_component): async with LvContext(lv_component):
await generate_triggers(lv_component) await generate_triggers(lv_component)
await generate_page_triggers(lv_component, config) await generate_page_triggers(lv_component, config)

View file

@ -477,6 +477,7 @@ CONF_ROWS = "rows"
CONF_SCALE_LINES = "scale_lines" CONF_SCALE_LINES = "scale_lines"
CONF_SCROLLBAR_MODE = "scrollbar_mode" CONF_SCROLLBAR_MODE = "scrollbar_mode"
CONF_SELECTED_INDEX = "selected_index" CONF_SELECTED_INDEX = "selected_index"
CONF_SELECTED_TEXT = "selected_text"
CONF_SHOW_SNOW = "show_snow" CONF_SHOW_SNOW = "show_snow"
CONF_SPIN_TIME = "spin_time" CONF_SPIN_TIME = "spin_time"
CONF_SRC = "src" CONF_SRC = "src"

View file

@ -5,6 +5,8 @@
#include "lvgl_hal.h" #include "lvgl_hal.h"
#include "lvgl_esphome.h" #include "lvgl_esphome.h"
#include <numeric>
namespace esphome { namespace esphome {
namespace lvgl { namespace lvgl {
static const char *const TAG = "lvgl"; static const char *const TAG = "lvgl";
@ -263,6 +265,39 @@ LVEncoderListener::LVEncoderListener(lv_indev_type_t type, uint16_t lpt, uint16_
} }
#endif // USE_LVGL_KEY_LISTENER #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.length() > 0 ? "\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_event_send(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_event_send(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 #ifdef USE_LVGL_BUTTONMATRIX
void LvButtonMatrixType::set_obj(lv_obj_t *lv_obj) { void LvButtonMatrixType::set_obj(lv_obj_t *lv_obj) {
LvCompound::set_obj(lv_obj); LvCompound::set_obj(lv_obj);

View file

@ -18,11 +18,9 @@
#include "esphome/core/component.h" #include "esphome/core/component.h"
#include "esphome/core/log.h" #include "esphome/core/log.h"
#include <lvgl.h> #include <lvgl.h>
#include <vector>
#include <map> #include <map>
#ifdef USE_LVGL_IMAGE #include <utility>
#include "esphome/components/image/image.h" #include <vector>
#endif // USE_LVGL_IMAGE
#ifdef USE_LVGL_FONT #ifdef USE_LVGL_FONT
#include "esphome/components/font/font.h" #include "esphome/components/font/font.h"
@ -246,6 +244,7 @@ class LVEncoderListener : public Parented<LvglComponent> {
public: public:
LVEncoderListener(lv_indev_type_t type, uint16_t lpt, uint16_t lprt); LVEncoderListener(lv_indev_type_t type, uint16_t lpt, uint16_t lprt);
#ifdef USE_BINARY_SENSOR
void set_left_button(binary_sensor::BinarySensor *left_button) { void set_left_button(binary_sensor::BinarySensor *left_button) {
left_button->add_on_state_callback([this](bool state) { this->event(LV_KEY_LEFT, state); }); left_button->add_on_state_callback([this](bool state) { this->event(LV_KEY_LEFT, state); });
} }
@ -256,6 +255,7 @@ class LVEncoderListener : public Parented<LvglComponent> {
void set_enter_button(binary_sensor::BinarySensor *enter_button) { void set_enter_button(binary_sensor::BinarySensor *enter_button) {
enter_button->add_on_state_callback([this](bool state) { this->event(LV_KEY_ENTER, state); }); enter_button->add_on_state_callback([this](bool state) { this->event(LV_KEY_ENTER, state); });
} }
#endif
#ifdef USE_LVGL_ROTARY_ENCODER #ifdef USE_LVGL_ROTARY_ENCODER
void set_sensor(rotary_encoder::RotaryEncoderSensor *sensor) { void set_sensor(rotary_encoder::RotaryEncoderSensor *sensor) {
@ -292,6 +292,48 @@ class LVEncoderListener : public Parented<LvglComponent> {
}; };
#endif // USE_LVGL_KEY_LISTENER #endif // USE_LVGL_KEY_LISTENER
#if defined(USE_LVGL_DROPDOWN) || defined(LV_USE_ROLLER)
class LvSelectable : public LvCompound {
public:
virtual size_t get_selected_index() = 0;
virtual void set_selected_index(size_t index, lv_anim_enable_t anim) = 0;
void set_selected_text(const std::string &text, lv_anim_enable_t anim);
std::string get_selected_text();
std::vector<std::string> get_options() { return this->options_; }
void set_options(std::vector<std::string> options);
protected:
virtual void set_option_string(const char *options) = 0;
std::vector<std::string> options_{};
};
#ifdef USE_LVGL_DROPDOWN
class LvDropdownType : public LvSelectable {
public:
size_t get_selected_index() override { return lv_dropdown_get_selected(this->obj); }
void set_selected_index(size_t index, lv_anim_enable_t anim) override { lv_dropdown_set_selected(this->obj, index); }
protected:
void set_option_string(const char *options) override { lv_dropdown_set_options(this->obj, options); }
};
#endif // USE_LVGL_DROPDOWN
#ifdef USE_LVGL_ROLLER
class LvRollerType : public LvSelectable {
public:
size_t get_selected_index() override { return lv_roller_get_selected(this->obj); }
void set_selected_index(size_t index, lv_anim_enable_t anim) override {
lv_roller_set_selected(this->obj, index, anim);
}
void set_mode(lv_roller_mode_t mode) { this->mode_ = mode; }
protected:
void set_option_string(const char *options) override { lv_roller_set_options(this->obj, options, this->mode_); }
lv_roller_mode_t mode_{LV_ROLLER_MODE_NORMAL};
};
#endif
#endif // defined(USE_LVGL_DROPDOWN) || defined(LV_USE_ROLLER)
#ifdef USE_LVGL_BUTTONMATRIX #ifdef USE_LVGL_BUTTONMATRIX
class LvButtonMatrixType : public key_provider::KeyProvider, public LvCompound { class LvButtonMatrixType : public key_provider::KeyProvider, public LvCompound {
public: public:

View file

@ -216,7 +216,7 @@ def automation_schema(typ: LvType):
events = df.LV_EVENT_TRIGGERS + (CONF_ON_VALUE,) events = df.LV_EVENT_TRIGGERS + (CONF_ON_VALUE,)
else: else:
events = df.LV_EVENT_TRIGGERS events = df.LV_EVENT_TRIGGERS
args = [typ.get_arg_type()] if isinstance(typ, LvType) else [] args = typ.get_arg_type() if isinstance(typ, LvType) else []
args.append(lv_event_t_ptr) args.append(lv_event_t_ptr)
return { return {
cv.Optional(event): validate_automation( cv.Optional(event): validate_automation(

View file

@ -3,18 +3,10 @@ from esphome.components import select
import esphome.config_validation as cv import esphome.config_validation as cv
from esphome.const import CONF_OPTIONS from esphome.const import CONF_OPTIONS
from ..defines import CONF_ANIMATED, CONF_LVGL_ID, CONF_WIDGET from ..defines import CONF_ANIMATED, CONF_LVGL_ID, CONF_WIDGET, literal
from ..lvcode import ( from ..lvcode import LvContext
API_EVENT,
EVENT_ARG,
UPDATE_EVENT,
LambdaContext,
LvContext,
lv,
lv_add,
)
from ..schemas import LVGL_SCHEMA from ..schemas import LVGL_SCHEMA
from ..types import LV_EVENT, LvSelect, lvgl_ns from ..types import LvSelect, lvgl_ns
from ..widgets import get_widgets, wait_for_widgets from ..widgets import get_widgets, wait_for_widgets
LVGLSelect = lvgl_ns.class_("LVGLSelect", select.Select) LVGLSelect = lvgl_ns.class_("LVGLSelect", select.Select)
@ -38,20 +30,10 @@ async def to_code(config):
selector = await select.new_select(config, options=options) selector = await select.new_select(config, options=options)
paren = await cg.get_variable(config[CONF_LVGL_ID]) paren = await cg.get_variable(config[CONF_LVGL_ID])
await wait_for_widgets() await wait_for_widgets()
async with LambdaContext(EVENT_ARG) as pub_ctx:
pub_ctx.add(selector.publish_index(widget.get_value()))
async with LambdaContext([(cg.uint16, "v")]) as control:
await widget.set_property("selected", "v", animated=config[CONF_ANIMATED])
lv.event_send(widget.obj, API_EVENT, cg.nullptr)
control.add(selector.publish_index(widget.get_value()))
async with LvContext(paren) as ctx: async with LvContext(paren) as ctx:
lv_add(selector.set_control_lambda(await control.get_lambda()))
ctx.add( ctx.add(
paren.add_event_cb( selector.set_widget(
widget.obj, widget.var,
await pub_ctx.get_lambda(), literal("LV_ANIM_ON" if config[CONF_ANIMATED] else "LV_ANIM_OFF"),
LV_EVENT.VALUE_CHANGED,
UPDATE_EVENT,
) )
) )
lv_add(selector.publish_index(widget.get_value()))

View file

@ -6,58 +6,52 @@
#include "esphome/core/automation.h" #include "esphome/core/automation.h"
#include "esphome/core/component.h" #include "esphome/core/component.h"
#include "esphome/core/preferences.h" #include "esphome/core/preferences.h"
#include "../lvgl.h"
namespace esphome { namespace esphome {
namespace lvgl { namespace lvgl {
static std::vector<std::string> split_string(const std::string &str) {
std::vector<std::string> strings;
auto delimiter = std::string("\n");
std::string::size_type pos;
std::string::size_type prev = 0;
while ((pos = str.find(delimiter, prev)) != std::string::npos) {
strings.push_back(str.substr(prev, pos - prev));
prev = pos + delimiter.size();
}
// To get the last substring (or only, if delimiter is not found)
strings.push_back(str.substr(prev));
return strings;
}
class LVGLSelect : public select::Select { class LVGLSelect : public select::Select {
public: public:
void set_control_lambda(std::function<void(size_t)> lambda) { void set_widget(LvSelectable *widget, lv_anim_enable_t anim = LV_ANIM_OFF) {
this->control_lambda_ = std::move(lambda); this->widget_ = widget;
this->anim_ = anim;
this->set_options_();
lv_obj_add_event_cb(
this->widget_->obj,
[](lv_event_t *e) {
auto *it = static_cast<LVGLSelect *>(e->user_data);
it->set_options_();
},
LV_EVENT_REFRESH, this);
if (this->initial_state_.has_value()) { if (this->initial_state_.has_value()) {
this->control(this->initial_state_.value()); this->control(this->initial_state_.value());
this->initial_state_.reset(); this->initial_state_.reset();
} }
this->publish();
auto lamb = [](lv_event_t *e) {
auto *self = static_cast<LVGLSelect *>(e->user_data);
self->publish();
};
lv_obj_add_event_cb(this->widget_->obj, lamb, LV_EVENT_VALUE_CHANGED, this);
lv_obj_add_event_cb(this->widget_->obj, lamb, lv_update_event, this);
} }
void publish_index(size_t index) { void publish() { this->publish_state(this->widget_->get_selected_text()); }
auto value = this->at(index);
if (value)
this->publish_state(value.value());
}
void set_options(const char *str) { this->traits.set_options(split_string(str)); }
protected: protected:
void control(const std::string &value) override { void control(const std::string &value) override {
if (this->control_lambda_ != nullptr) { if (this->widget_ != nullptr) {
auto index = index_of(value); this->widget_->set_selected_text(value, this->anim_);
if (index)
this->control_lambda_(index.value());
} else { } else {
this->initial_state_ = value.c_str(); this->initial_state_ = value;
} }
} }
void set_options_() { this->traits.set_options(this->widget_->get_options()); }
std::function<void(size_t)> control_lambda_{}; LvSelectable *widget_{};
optional<const char *> initial_state_{}; optional<std::string> initial_state_{};
lv_anim_enable_t anim_{LV_ANIM_OFF};
}; };
} // namespace lvgl } // namespace lvgl

View file

@ -67,9 +67,9 @@ async def add_trigger(conf, lv_component, w, *events):
tid = conf[CONF_TRIGGER_ID] tid = conf[CONF_TRIGGER_ID]
trigger = cg.new_Pvariable(tid) trigger = cg.new_Pvariable(tid)
args = w.get_args() + [(lv_event_t_ptr, "event")] args = w.get_args() + [(lv_event_t_ptr, "event")]
value = w.get_value() value = w.get_values()
await automation.build_automation(trigger, args, conf) await automation.build_automation(trigger, args, conf)
async with LambdaContext(EVENT_ARG, where=tid) as context: async with LambdaContext(EVENT_ARG, where=tid) as context:
with LvConditional(w.is_selected()): with LvConditional(w.is_selected()):
lv_add(trigger.trigger(value, literal("event"))) lv_add(trigger.trigger(*value, literal("event")))
lv_add(lv_component.add_event_cb(w.obj, await context.get_lambda(), *events)) lv_add(lv_component.add_event_cb(w.obj, await context.get_lambda(), *events))

View file

@ -18,7 +18,9 @@ class LvType(cg.MockObjClass):
self.value_property = None self.value_property = None
def get_arg_type(self): def get_arg_type(self):
return self.args[0][0] if len(self.args) else None if len(self.args) == 0:
return None
return [arg[0] for arg in self.args]
class LvNumber(LvType): class LvNumber(LvType):
@ -92,11 +94,13 @@ class LvBoolean(LvType):
class LvSelect(LvType): class LvSelect(LvType):
def __init__(self, *args, **kwargs): def __init__(self, *args, **kwargs):
parens = kwargs.pop("parents", ()) + (LvCompound,)
super().__init__( super().__init__(
*args, *args,
largs=[(cg.int_, "x")], largs=[(cg.int_, "x"), (cg.std_string, "text")],
lvalue=lambda w: w.get_property("selected"), lvalue=lambda w: [w.var.get_selected_index(), w.var.get_selected_text()],
has_on_value=True, has_on_value=True,
parents=parens,
**kwargs, **kwargs,
) )

View file

@ -70,14 +70,11 @@ class LvScrActType(WidgetType):
class Widget: class Widget:
""" """
Represents a Widget. Represents a Widget.
This class has a lot of methods. Adding any more runs foul of lint checks ("too many public methods").
""" """
widgets_completed = False widgets_completed = False
@staticmethod
def set_completed():
Widget.widgets_completed = True
def __init__(self, var, wtype: WidgetType, config: dict = None): def __init__(self, var, wtype: WidgetType, config: dict = None):
self.var = var self.var = var
self.type = wtype self.type = wtype
@ -179,9 +176,20 @@ class Widget:
def get_value(self): def get_value(self):
if isinstance(self.type.w_type, LvType): if isinstance(self.type.w_type, LvType):
return self.type.w_type.value(self) result = self.type.w_type.value(self)
if isinstance(result, list):
return result[0]
return result
return self.obj return self.obj
def get_values(self):
if isinstance(self.type.w_type, LvType):
result = self.type.w_type.value(self)
if isinstance(result, list):
return result
return [result]
return [self.obj]
def get_number_value(self): def get_number_value(self):
value = self.type.mock_obj.get_value(self.obj) value = self.type.mock_obj.get_value(self.obj)
if self.scale == 1.0: if self.scale == 1.0:

View file

@ -1,4 +1,3 @@
import esphome.codegen as cg
import esphome.config_validation as cv import esphome.config_validation as cv
from esphome.const import CONF_OPTIONS from esphome.const import CONF_OPTIONS
@ -9,21 +8,24 @@ from ..defines import (
CONF_SCROLLBAR, CONF_SCROLLBAR,
CONF_SELECTED, CONF_SELECTED,
CONF_SELECTED_INDEX, CONF_SELECTED_INDEX,
CONF_SELECTED_TEXT,
CONF_SYMBOL, CONF_SYMBOL,
DIRECTIONS, DIRECTIONS,
literal, literal,
) )
from ..helpers import lvgl_components_required
from ..lv_validation import lv_int, lv_text, option_string from ..lv_validation import lv_int, lv_text, option_string
from ..lvcode import LocalVariable, lv, lv_expr from ..lvcode import LocalVariable, lv, lv_add, lv_expr
from ..schemas import part_schema from ..schemas import part_schema
from ..types import LvSelect, LvType, lv_obj_t from ..types import LvCompound, LvSelect, LvType, lv_obj_t
from . import Widget, WidgetType, set_obj_properties from . import Widget, WidgetType, set_obj_properties
from .label import CONF_LABEL from .label import CONF_LABEL
CONF_DROPDOWN = "dropdown" CONF_DROPDOWN = "dropdown"
CONF_DROPDOWN_LIST = "dropdown_list" CONF_DROPDOWN_LIST = "dropdown_list"
lv_dropdown_t = LvSelect("lv_dropdown_t") lv_dropdown_t = LvSelect("LvDropdownType", parents=(LvCompound,))
lv_dropdown_list_t = LvType("lv_dropdown_list_t") lv_dropdown_list_t = LvType("lv_dropdown_list_t")
dropdown_list_spec = WidgetType( dropdown_list_spec = WidgetType(
CONF_DROPDOWN_LIST, lv_dropdown_list_t, (CONF_MAIN, CONF_SELECTED, CONF_SCROLLBAR) CONF_DROPDOWN_LIST, lv_dropdown_list_t, (CONF_MAIN, CONF_SELECTED, CONF_SCROLLBAR)
@ -32,7 +34,8 @@ dropdown_list_spec = WidgetType(
DROPDOWN_BASE_SCHEMA = cv.Schema( DROPDOWN_BASE_SCHEMA = cv.Schema(
{ {
cv.Optional(CONF_SYMBOL): lv_text, cv.Optional(CONF_SYMBOL): lv_text,
cv.Optional(CONF_SELECTED_INDEX): cv.templatable(cv.int_), cv.Exclusive(CONF_SELECTED_INDEX, CONF_SELECTED_TEXT): lv_int,
cv.Exclusive(CONF_SELECTED_TEXT, CONF_SELECTED_TEXT): lv_text,
cv.Optional(CONF_DIR, default="BOTTOM"): DIRECTIONS.one_of, cv.Optional(CONF_DIR, default="BOTTOM"): DIRECTIONS.one_of,
cv.Optional(CONF_DROPDOWN_LIST): part_schema(dropdown_list_spec), cv.Optional(CONF_DROPDOWN_LIST): part_schema(dropdown_list_spec),
} }
@ -44,6 +47,12 @@ DROPDOWN_SCHEMA = DROPDOWN_BASE_SCHEMA.extend(
} }
) )
DROPDOWN_UPDATE_SCHEMA = DROPDOWN_BASE_SCHEMA.extend(
{
cv.Optional(CONF_OPTIONS): cv.ensure_list(option_string),
}
)
class DropdownType(WidgetType): class DropdownType(WidgetType):
def __init__(self): def __init__(self):
@ -52,18 +61,21 @@ class DropdownType(WidgetType):
lv_dropdown_t, lv_dropdown_t,
(CONF_MAIN, CONF_INDICATOR), (CONF_MAIN, CONF_INDICATOR),
DROPDOWN_SCHEMA, DROPDOWN_SCHEMA,
DROPDOWN_BASE_SCHEMA, modify_schema=DROPDOWN_UPDATE_SCHEMA,
) )
async def to_code(self, w: Widget, config): async def to_code(self, w: Widget, config):
lvgl_components_required.add(CONF_DROPDOWN)
if options := config.get(CONF_OPTIONS): if options := config.get(CONF_OPTIONS):
text = cg.safe_exp("\n".join(options)) lv_add(w.var.set_options(options))
lv.dropdown_set_options(w.obj, text)
if symbol := config.get(CONF_SYMBOL): if symbol := config.get(CONF_SYMBOL):
lv.dropdown_set_symbol(w.obj, await lv_text.process(symbol)) lv.dropdown_set_symbol(w.var.obj, await lv_text.process(symbol))
if (selected := config.get(CONF_SELECTED_INDEX)) is not None: if (selected := config.get(CONF_SELECTED_INDEX)) is not None:
value = await lv_int.process(selected) value = await lv_int.process(selected)
lv.dropdown_set_selected(w.obj, value) lv_add(w.var.set_selected_index(value, literal("LV_ANIM_OFF")))
if (selected := config.get(CONF_SELECTED_TEXT)) is not None:
value = await lv_text.process(selected)
lv_add(w.var.set_selected_text(value, literal("LV_ANIM_OFF")))
if dirn := config.get(CONF_DIR): if dirn := config.get(CONF_DIR):
lv.dropdown_set_dir(w.obj, literal(dirn)) lv.dropdown_set_dir(w.obj, literal(dirn))
if dlist := config.get(CONF_DROPDOWN_LIST): if dlist := config.get(CONF_DROPDOWN_LIST):

View file

@ -1,7 +1,7 @@
from esphome import automation from esphome import automation
from ..automation import update_to_code from ..automation import update_to_code
from ..defines import CONF_MAIN, CONF_OBJ from ..defines import CONF_MAIN, CONF_OBJ, CONF_SCROLLBAR
from ..schemas import create_modify_schema from ..schemas import create_modify_schema
from ..types import ObjUpdateAction, WidgetType, lv_obj_t from ..types import ObjUpdateAction, WidgetType, lv_obj_t
@ -12,7 +12,9 @@ class ObjType(WidgetType):
""" """
def __init__(self): def __init__(self):
super().__init__(CONF_OBJ, lv_obj_t, (CONF_MAIN,), schema={}, modify_schema={}) super().__init__(
CONF_OBJ, lv_obj_t, (CONF_MAIN, CONF_SCROLLBAR), schema={}, modify_schema={}
)
async def to_code(self, w, config): async def to_code(self, w, config):
return [] return []

View file

@ -1,4 +1,3 @@
import esphome.codegen as cg
import esphome.config_validation as cv import esphome.config_validation as cv
from esphome.const import CONF_MODE, CONF_OPTIONS from esphome.const import CONF_MODE, CONF_OPTIONS
@ -7,36 +6,40 @@ from ..defines import (
CONF_MAIN, CONF_MAIN,
CONF_SELECTED, CONF_SELECTED,
CONF_SELECTED_INDEX, CONF_SELECTED_INDEX,
CONF_SELECTED_TEXT,
CONF_VISIBLE_ROW_COUNT, CONF_VISIBLE_ROW_COUNT,
ROLLER_MODES, ROLLER_MODES,
literal, literal,
) )
from ..lv_validation import animated, lv_int, option_string from ..helpers import lvgl_components_required
from ..lvcode import lv from ..lv_validation import animated, lv_int, lv_text, option_string
from ..lvcode import lv_add
from ..types import LvSelect from ..types import LvSelect
from . import WidgetType from . import WidgetType
from .label import CONF_LABEL from .label import CONF_LABEL
CONF_ROLLER = "roller" CONF_ROLLER = "roller"
lv_roller_t = LvSelect("lv_roller_t") lv_roller_t = LvSelect("LvRollerType")
ROLLER_BASE_SCHEMA = cv.Schema( ROLLER_BASE_SCHEMA = cv.Schema(
{ {
cv.Optional(CONF_SELECTED_INDEX): cv.templatable(cv.int_), cv.Exclusive(CONF_SELECTED_INDEX, CONF_SELECTED_TEXT): lv_int,
cv.Exclusive(CONF_SELECTED_TEXT, CONF_SELECTED_TEXT): lv_text,
cv.Optional(CONF_VISIBLE_ROW_COUNT): lv_int, cv.Optional(CONF_VISIBLE_ROW_COUNT): lv_int,
cv.Optional(CONF_MODE): ROLLER_MODES.one_of,
} }
) )
ROLLER_SCHEMA = ROLLER_BASE_SCHEMA.extend( ROLLER_SCHEMA = ROLLER_BASE_SCHEMA.extend(
{ {
cv.Required(CONF_OPTIONS): cv.ensure_list(option_string), cv.Required(CONF_OPTIONS): cv.ensure_list(option_string),
cv.Optional(CONF_MODE, default="NORMAL"): ROLLER_MODES.one_of,
} }
) )
ROLLER_MODIFY_SCHEMA = ROLLER_BASE_SCHEMA.extend( ROLLER_MODIFY_SCHEMA = ROLLER_BASE_SCHEMA.extend(
{ {
cv.Optional(CONF_ANIMATED, default=True): animated, cv.Optional(CONF_ANIMATED, default=True): animated,
cv.Optional(CONF_OPTIONS): cv.ensure_list(option_string),
} }
) )
@ -52,15 +55,19 @@ class RollerType(WidgetType):
) )
async def to_code(self, w, config): async def to_code(self, w, config):
lvgl_components_required.add(CONF_ROLLER)
if mode := config.get(CONF_MODE):
mode = await ROLLER_MODES.process(mode)
lv_add(w.var.set_mode(mode))
if options := config.get(CONF_OPTIONS): if options := config.get(CONF_OPTIONS):
mode = await ROLLER_MODES.process(config[CONF_MODE]) lv_add(w.var.set_options(options))
text = cg.safe_exp("\n".join(options)) animopt = literal(config.get(CONF_ANIMATED, "LV_ANIM_OFF"))
lv.roller_set_options(w.obj, text, mode) if (selected := config.get(CONF_SELECTED_INDEX)) is not None:
animopt = literal(config.get(CONF_ANIMATED) or "LV_ANIM_OFF")
if CONF_SELECTED_INDEX in config:
if selected := config[CONF_SELECTED_INDEX]:
value = await lv_int.process(selected) value = await lv_int.process(selected)
lv.roller_set_selected(w.obj, value, animopt) lv_add(w.var.set_selected_index(value, animopt))
if (selected := config.get(CONF_SELECTED_TEXT)) is not None:
value = await lv_text.process(selected)
lv_add(w.var.set_selected_text(value, animopt))
await w.set_property( await w.set_property(
CONF_VISIBLE_ROW_COUNT, CONF_VISIBLE_ROW_COUNT,
await lv_int.process(config.get(CONF_VISIBLE_ROW_COUNT)), await lv_int.process(config.get(CONF_VISIBLE_ROW_COUNT)),

View file

@ -9,6 +9,7 @@ from ..defines import (
CONF_COLUMN, CONF_COLUMN,
CONF_DIR, CONF_DIR,
CONF_MAIN, CONF_MAIN,
CONF_SCROLLBAR,
CONF_TILE_ID, CONF_TILE_ID,
CONF_TILES, CONF_TILES,
TILE_DIRECTIONS, TILE_DIRECTIONS,
@ -56,7 +57,7 @@ class TileviewType(WidgetType):
super().__init__( super().__init__(
CONF_TILEVIEW, CONF_TILEVIEW,
lv_tileview_t, lv_tileview_t,
(CONF_MAIN,), (CONF_MAIN, CONF_SCROLLBAR),
schema=TILEVIEW_SCHEMA, schema=TILEVIEW_SCHEMA,
modify_schema={}, modify_schema={},
) )

View file

@ -44,10 +44,12 @@
#define USE_LVGL_ANIMIMG #define USE_LVGL_ANIMIMG
#define USE_LVGL_BINARY_SENSOR #define USE_LVGL_BINARY_SENSOR
#define USE_LVGL_BUTTONMATRIX #define USE_LVGL_BUTTONMATRIX
#define USE_LVGL_DROPDOWN
#define USE_LVGL_FONT #define USE_LVGL_FONT
#define USE_LVGL_IMAGE #define USE_LVGL_IMAGE
#define USE_LVGL_KEY_LISTENER #define USE_LVGL_KEY_LISTENER
#define USE_LVGL_KEYBOARD #define USE_LVGL_KEYBOARD
#define USE_LVGL_ROLLER
#define USE_LVGL_ROTARY_ENCODER #define USE_LVGL_ROTARY_ENCODER
#define USE_LVGL_TOUCHSCREEN #define USE_LVGL_TOUCHSCREEN
#define USE_MD5 #define USE_MD5

View file

@ -138,6 +138,19 @@ lvgl:
flex_align_cross: start flex_align_cross: start
flex_align_track: end flex_align_track: end
widgets: widgets:
- roller:
id: lv_roller
visible_row_count: 2
anim_time: 500ms
options:
- Nov
- Dec
selected_index: 1
on_value:
then:
- logger.log:
format: "Roller changed = %d: %s"
args: [x, text.c_str()]
- animimg: - animimg:
height: 60 height: 60
id: anim_img id: anim_img
@ -245,9 +258,13 @@ lvgl:
y: 120 y: 120
- buttonmatrix: - buttonmatrix:
on_press: on_press:
logger.log: then:
- logger.log:
format: "matrix button pressed: %d" format: "matrix button pressed: %d"
args: ["x"] args: ["x"]
- lvgl.widget.show: b_matrix
- lvgl.widget.redraw:
on_long_press: on_long_press:
lvgl.matrix.button.update: lvgl.matrix.button.update:
id: [button_a, button_e, button_c] id: [button_a, button_e, button_c]
@ -629,8 +646,6 @@ lvgl:
- First - First
- Second - Second
- Third - Third
- 4th
- 5th
- 6th - 6th
- 7th - 7th
- 8th - 8th
@ -651,8 +666,8 @@ lvgl:
bg_color: 0xFF bg_color: 0xFF
on_value: on_value:
logger.log: logger.log:
format: "Dropdown changed = %d" format: "Dropdown changed = %d: %s"
args: [x] args: [x, text.c_str()]
on_cancel: on_cancel:
logger.log: logger.log:
format: "Dropdown closed = %d" format: "Dropdown closed = %d"
@ -661,6 +676,11 @@ lvgl:
src: cat_image src: cat_image
on_click: on_click:
then: then:
- lvgl.dropdown.update:
id: lv_dropdown
options:
["First", "Second", "Third", "4th", "5th", "6th", "7th", "8th", "9th", "10th", "11th"]
selected_index: 3
- logger.log: Cat image clicked - logger.log: Cat image clicked
- lvgl.tabview.select: - lvgl.tabview.select:
id: tabview_id id: tabview_id