Lua Development Guide

This guide documents the Lua runtime inside the Siebenschläfer™ display engine: the script execution model, the lvgl binding for building layouts, the mbedtls cryptography module, the dormouse template helpers, and the standard libraries available on the device.

It targets advanced layout authors who go beyond the Layout Designer's property dialogs and write custom Lua in the script editor (see the Lua Script Settings section of the user manual).

Version note: the display runs Lua 5.1 (eLua-based) with LVGL 9 bindings generated for the engine firmware. Several language features that exist in modern Lua (5.2+) are not available — see Lua 5.1 constraints.

1. Execution model

Every content push to a display consists of two scripts:

ScriptRunsPurpose
Controls scriptafter LVGL initBuilds the actual UI (widgets, styles, data binding).
User scriptright after the controls scriptYour custom code, starting at the -- Add additional commands below marker in the editor.
The controls script is fully given by the WYSIWYG Layout Designer: it is generated from the controls you place on the canvas and is not edited by hand. All custom code goes into the user script. The controls script is assembled from two concatenated parts:
  • Controls section — widget creation for every placed element.
  • Details section — properties (text binding, fonts, positions).
  • Widgets created by the designer are available as globals named _, e.g. label_1, scale_3, chart_2. Reference them in your user script to change anything the designer cannot express.

    Scripts run top to bottom; after the last statement the engine renders the screen once (a single frame) and refreshes the e-paper panel, then the device sleeps. There is no render loop and no interactive event loop on the device — timers and events only do anything in the web preview (§3.5, §3.7). New content arrives when the backend pushes it.

    Injected globals

    Available in every script:

    GlobalContent
    dataRaw payload string of the data source (JSON or XML, unparsed).
    FirmwareVersionEngine firmware version string.
    DisplayNameUser-assigned device name.
    DisplaySerialDevice serial number.
    OrientationIsHorizontaltrue/false.
    TimeZonePOSIX timezone string of the display's location.

    2. The dormouse module

    dormouse is the template support library. The generated script always starts with:

    _G["dormouse"] = require "dormouse"
    _G.dormouse.loadData(data)
    FunctionDescription
    dormouse.loadData(data)Parses the global data string: JSON ({/[ → decoded table) or XML (< → table). Anything else is stored as a plain string. Encrypted payloads (scep1: prefix) are decrypted automatically first — see §7.
    dormouse.bindingDataThe parsed data table (empty table when there is no data).
    dormouse.bind(text)Expands {{placeholder}} templates in text against bindingData (via lupa) and returns the result.
    dormouse.createFont(name, size)Returns an lvgl.Font, cached per name+size.
    dormouse.tryDecrypt(data)Returns data unchanged unless it starts with M.encryptionPrefix; then decrypts with the key from M.keyPath → plaintext, or nil + error.
    dormouse.loadKey()Reads + base64-decodes the AES key from M.keyPath (A:/key.txt), cached.
    dormouse.encryptionErrorSet by loadData when decryption failed (then bindingData is empty).
    dormouse.encryptionPrefixMagic prefix of encrypted payloads, "scep1:".
    dormouse.keyPathKey file location, "A:/key.txt" (base64 of the raw key, one line).
    Example — data-driven text:
    -- bindingData comes from a JSON source: {"symbol": "GOLD", "close": 3418.0}
    label_1.text = dormouse.bind("{{symbol}}: {{close}}")
    

    local price = dormouse.bindingData.close -- real number, not string
    scale_3:set_range(math.floor(price - 100), math.floor(price + 100))

    JSON / XML access directly

    If you prefer explicit parsing:

    local json = require "json"
    local payload = json.decode(data)             -- data is the raw string
    

    for i, row in ipairs(payload.data) do
    print(row.open, row.close)
    end

    For XML: require "xml2lua" + require "xmlhandler.tree" (tree handler). The same modules are used internally by loadData.


    3. The lvgl module

    All drawing goes through the global lvgl table (LVGL 9 binding). The screen root is lvgl._root; passing nil as a parent attaches a widget to it. The panel resolution is 800 × 480 (or 480 × 800 in portrait).

    3.1 Creating widgets

    A constructor exists per supported widget:

    local label  = lvgl.Label(nil)                 -- parent nil = screen root
    local button = lvgl.Button(label)              -- any widget as parent

    Available constructors:

    Object, Label, Line, Image, Button, Buttonmatrix, Textarea, Checkbox, Dropdown, Roller, Slider, Switch, Bar, Led, List, Table, Calendar, Chart, Scale, Arc, Arclabel, Spinner, Spinbox, Canvas, Gif, Imagebutton, Menu, Msgbox, Qrcode, Barcode, Spangroup, Tabview, Tileview, Win

    Widget-specific API (assignable properties and methods) — complete reference, excluding the generic lv_obj API of 3.2 which every widget inherits:

    WidgetProperties (assignable as w.prop = …)Methods
    Labellong_mode, recolor, text, text_selection_end, text_selection_start, text_static, translation_tag:cut_text(), :ins_text(), :set_long_mode(), :set_recolor(), :set_text(), :set_text_selection_end(), :set_text_selection_start(), :set_text_static(), :set_translation_tag()
    Imageantialias, bitmap_map_src, blend_mode, inner_align, offset_x, offset_y, pivot_x, pivot_y, rotation, scale, scale_x, scale_y, src, src_height, src_width, transformed_height, transformed_width:get_antialias(), :get_bitmap_map_src(), :get_blend_mode(), :get_inner_align(), :get_offset_x(), :get_offset_y(), :get_pivot(), :get_rotation(), :get_scale(), :get_scale_x(), :get_scale_y(), :get_src(), :get_src_height(), :get_src_width(), :get_transformed_height(), :get_transformed_width(), :set_antialias(), :set_bitmap_map_src(), :set_blend_mode(), :set_inner_align(), :set_offset_x(), :set_offset_y(), :set_pivot(), :set_pivot_x(), :set_pivot_y(), :set_rotation(), :set_scale(), :set_scale_x(), :set_scale_y(), :set_src()
    Linepoint_count, points, points_mutable, y_invert:get_point_count(), :get_points(), :get_points_mutable(), :is_point_array_mutable(), :set_points(), :set_points_mutable(), :set_y_invert()
    Chartfirst_point_center_offset, hor_div_line_count, point_count, type, update_mode, ver_div_line_count:add_cursor(), :add_series(), :get_cursor_point(), :get_first_point_center_offset(), :get_point_pos_by_id(), :get_series_color(), :hide_series(), :refresh(), :remove_cursor(), :remove_series(), :set_all_values(), :set_axis_max_value(), :set_axis_min_value(), :set_axis_range(), :set_cursor_point(), :set_cursor_pos(), :set_cursor_pos_x(), :set_cursor_pos_y(), :set_div_line_count(), :set_hor_div_line_count(), :set_next_value(), :set_point_count(), :set_series_color(), :set_series_ext_x_array(), :set_series_ext_y_array(), :set_series_value_by_id(), :set_series_values(), :set_type(), :set_update_mode(), :set_ver_div_line_count(), :set_x_start_point()
    Scaleangle_range, draw_ticks_on_top, label_show, major_tick_every, max_value, min_value, mode, post_draw, range_max_value, range_min_value, rotation, text_src, total_tick_count:add_section(), :get_angle_range(), :get_label_show(), :get_major_tick_every(), :get_mode(), :get_range_max_value(), :get_range_min_value(), :get_rotation(), :get_total_tick_count(), :set_angle_range(), :set_draw_ticks_on_top(), :set_image_needle_value(), :set_label_show(), :set_line_needle_value(), :set_major_tick_every(), :set_max_value(), :set_min_value(), :set_mode(), :set_post_draw(), :set_range(), :set_rotation(), :set_section_max_value(), :set_section_min_value(), :set_section_range(), :set_section_style_indicator(), :set_section_style_items(), :set_section_style_main(), :set_text_src(), :set_total_tick_count()
    Barmax_value, min_value, mode, orientation:get_mode(), :get_orientation(), :is_symmetrical(), :set_max_value(), :set_min_value(), :set_mode(), :set_orientation(), :set_range(), :set_start_value(), :set_value()
    Slidermax_value, min_value, mode, orientation:get_mode(), :get_orientation(), :is_symmetrical(), :set_max_value(), :set_min_value(), :set_mode(), :set_orientation(), :set_range(), :set_start_value(), :set_value()
    Arcangle_end, angle_start, bg_angle_end, bg_angle_start, bg_end_angle, bg_start_angle, change_rate, end_angle, knob_offset, max_value, min_value, mode, rotation, start_angle, value:get_angle_end(), :get_angle_start(), :get_bg_angle_end(), :get_bg_angle_start(), :set_angles(), :set_bg_angles(), :set_bg_end_angle(), :set_bg_start_angle(), :set_change_rate(), :set_end_angle(), :set_knob_offset(), :set_max_value(), :set_min_value(), :set_mode(), :set_range(), :set_rotation(), :set_start_angle(), :set_value()
    Arclabelangle_size, angle_start, center_offset_x, center_offset_y, dir, offset, radius, recolor, text, text_horizontal_align, text_static, text_vertical_align:get_angle_size(), :get_angle_start(), :get_center_offset_x(), :get_center_offset_y(), :get_radius(), :get_recolor(), :get_text_horizontal_align(), :get_text_vertical_align(), :set_angle_size(), :set_angle_start(), :set_center_offset_x(), :set_center_offset_y(), :set_dir(), :set_offset(), :set_radius(), :set_recolor(), :set_text(), :set_text_horizontal_align(), :set_text_static(), :set_text_vertical_align()
    Ledbrightness, color:off(), :on(), :set_brightness(), :set_color(), :toggle()
    Button——
    Buttonmatrixbutton_ctrl_all, ctrl_map, map, one_checked, selected_button:clear_button_ctrl(), :clear_button_ctrl_all(), :has_button_ctrl(), :set_button_ctrl(), :set_button_ctrl_all(), :set_button_width(), :set_ctrl_map(), :set_map(), :set_one_checked(), :set_selected_button()
    Checkboxtext, text_static:set_text(), :set_text_static()
    Textareaaccepted_chars, align, current_char, cursor_click_pos, cursor_pos, insert_replace, max_length, one_line, password_bullet, password_mode, password_show_time, placeholder_text, text, text_selection:add_char(), :add_text(), :clear_selection(), :cursor_down(), :cursor_left(), :cursor_right(), :cursor_up(), :delete_char(), :delete_char_forward(), :get_accepted_chars(), :get_current_char(), :get_cursor_click_pos(), :get_max_length(), :get_password_bullet(), :get_password_show_time(), :get_placeholder_text(), :get_text_selection(), :set_accepted_chars(), :set_align(), :set_cursor_click_pos(), :set_cursor_pos(), :set_insert_replace(), :set_max_length(), :set_one_line(), :set_password_bullet(), :set_password_mode(), :set_password_show_time(), :set_placeholder_text(), :set_text(), :set_text_selection()
    Spinboxcursor_pos, dec_point_pos, digit_count, digit_step_direction, max_value, min_value, rollover, step, value:decrement(), :get_rollover(), :get_step(), :get_value(), :increment(), :set_cursor_pos(), :set_dec_point_pos(), :set_digit_count(), :set_digit_format(), :set_digit_step_direction(), :set_max_value(), :set_min_value(), :set_range(), :set_rollover(), :set_step(), :set_value(), :step_next(), :step_prev()
    Dropdowndir, list, options, options_static, selected, selected_highlight, symbol, text:add_option(), :clear_options(), :close(), :get_list(), :get_option_index(), :get_selected_highlight(), :get_symbol(), :get_text(), :is_open(), :open(), :set_dir(), :set_options(), :set_options_static(), :set_selected(), :set_selected_highlight(), :set_symbol(), :set_text()
    Rollervisible_row_count:set_options(), :set_selected(), :set_selected_str(), :set_visible_row_count()
    List—:add_button(), :add_text(), :get_button_text(), :set_button_text()
    Tablecolumn_count, row_count:clear_cell_ctrl(), :get_cell_user_data(), :get_cell_value(), :get_column_count(), :get_column_width(), :get_row_count(), :get_selected_cell(), :has_cell_ctrl(), :set_cell_ctrl(), :set_cell_user_data(), :set_cell_value(), :set_column_count(), :set_column_width(), :set_row_count(), :set_selected_cell()
    Calendarday_names, shown_month, shown_year, today_day, today_month, today_year:set_day_names(), :set_highlighted_dates(), :set_month_shown(), :set_shown_month(), :set_shown_year(), :set_today_date(), :set_today_day(), :set_today_month(), :set_today_year()
    Qrcodedark_color, data, light_color, quiet_zone, size:set_dark_color(), :set_data(), :set_light_color(), :set_quiet_zone(), :set_size(), :update()
    Barcodedark_color, direction, encoding, light_color, scale, tiled:get_dark_color(), :get_light_color(), :get_scale(), :set_dark_color(), :set_direction(), :set_encoding(), :set_light_color(), :set_scale(), :set_tiled(), :update()
    Gifcolor_format, loop_count, src:get_loop_count(), :is_loaded(), :pause(), :restart(), :resume(), :set_color_format(), :set_loop_count(), :set_src()
    Imagebuttonstate:get_src_left(), :get_src_middle(), :get_src_right(), :set_src(), :set_state()
    Canvasbuf, draw_buf, image:copy_buf(), :fill_bg(), :finish_layer(), :get_buf(), :get_draw_buf(), :get_image(), :get_px(), :init_layer(), :set_buffer(), :set_draw_buf(), :set_palette(), :set_px()
    Spangroupalign, indent, max_line_height, max_lines, mode, overflow:add_span(), :delete_span(), :get_align(), :get_expand_height(), :get_expand_width(), :get_indent(), :get_max_line_height(), :get_max_lines(), :get_mode(), :get_overflow(), :get_span_by_point(), :get_span_coords(), :refresh(), :set_align(), :set_indent(), :set_max_lines(), :set_mode(), :set_overflow(), :set_span_style(), :set_span_text(), :set_span_text_static()
    Spinner—:set_anim_params()
    Switchorientation:get_orientation(), :set_orientation()
    Menucur_main_page, cur_sidebar_page, main_header, main_header_back_button, mode_header, mode_root_back_button, page, page_title, page_title_static, sidebar_header, sidebar_header_back_button, sidebar_page:back_button_is_root(), :clear_history(), :cont_create(), :get_cur_main_page(), :get_cur_sidebar_page(), :get_main_header(), :get_main_header_back_button(), :get_sidebar_header(), :get_sidebar_header_back_button(), :page_create(), :section_create(), :separator_create(), :set_load_page_event(), :set_mode_header(), :set_mode_root_back_button(), :set_page(), :set_page_title(), :set_page_title_static(), :set_sidebar_page()
    Msgboxcontent, footer, header, title:add_close_button(), :add_footer_button(), :add_header_button(), :add_text(), :add_title(), :close(), :close_async(), :get_content(), :get_footer(), :get_header(), :get_title()
    Tabviewcontent, tab_active, tab_bar, tab_bar_position, tab_bar_size, tab_count:add_tab(), :get_content(), :get_tab_active(), :get_tab_bar(), :get_tab_button(), :get_tab_count(), :rename_tab(), :set_active(), :set_tab_bar_position(), :set_tab_bar_size()
    Tileviewtile_active:add_tile(), :get_tile_active(), :set_tile(), :set_tile_by_index()
    Wincontent, header:add_button(), :add_title(), :get_content(), :get_header()
    selected_str (text of the current selection) is additionally available on all selectable widgets. Getter functions map to get_/is_ methods as listed; every set_x setter additionally has the short property form (e.g. label.text = "hi" ≙ label:set_text("hi")).

    3.2 Generic object API

    Every widget inherits the lv_obj API. Position and size use tables:

    label_1:set_pos({ x = 120, y = 40 })
    label_1:set({ width = 300, height = lvgl.SIZE_CONTENT })
    MethodDescription
    :set{ prop = value, ... }Applies a table of style properties (bg_color, text_color, width, …) with the default selector.
    :set_style(table [, selector])Local style with optional state/part selector.
    :add_style(style, selector)Attaches a shared lvgl.Style object.
    :remove_style(style) / :remove_style_all()Detach styles.
    :set_pos({x=,y=}) / :align_to(obj, type, x, y)Placement.
    :center()Center in parent.
    :add_flag(lvgl.FLAG.X) / :clear_flag(lvgl.FLAG.X)Flags (clickable, scrollable, hidden, …).
    :add_state(lvgl.STATE.CHECKED) / :clear_state(s)States.
    :delete()Remove widget (children included).
    :clean()Remove all children.
    :get_child(i) / :get_child_cnt() / :get_parent()Tree access.
    :is_visible() / :invalidate()Misc.
    Property assignment works for many setters directly (the binding maps __newindex):
    label_1.text       = "Hello"
    label_1.text_font  = dormouse.createFont("DavidLibre-Regular", 44)
    scale_3.rotation   = 900          -- 90.0 degrees (unit: 0.1°)

    3.3 Colors

    Colors accept hex strings, integers, or palette references:

    label_1:set({ text_color = "#000000", bg_color = "#ffffff", bg_opa = 255 })
    

    local blue = lvgl.palette.main(lvgl.palette.BLUE)
    local dim = lvgl.palette.lighten(lvgl.palette.RED, 4)

    lvgl.palette provides main, lighten, darken and the palette constants (RED, BLUE, GREEN, AMBER, GREY, …).

    3.4 Styles

    A style is created with a table of properties and attached with :add_style(style, selector). Mutate it later with :set{ … }:

    local box = lvgl.Style({
        bg_color = "#101010",
        border_width = 2,
        border_color = "#000000",
        radius = 8,
    })
    

    panel:add_style(box, lvgl.STATE.DEFAULT)

    box:set({ bg_color = "#202020" }) -- update every widget sharing the style

    The same property names work in both forms: style objects (lvgl.Style{ … }) and local styles (obj:set_style{ bg_color = "#101010" } / obj:set{ … }).

    Complete list of supported style properties:

    GroupProperties
    Backgroundbg_color, bg_opa, bg_grad, bg_grad_color, bg_grad_dir, bg_grad_stop, bg_main_stop, bg_image_src, bg_image_opa, bg_image_recolor, bg_image_recolor_opa, bg_image_tiled
    Borderborder_width, border_color, border_opa, border_side, border_post
    Outlineoutline_width, outline_color, outline_opa, outline_pad
    Shadowshadow_width, shadow_color, shadow_opa, shadow_spread, shadow_offset_x, shadow_offset_y
    Texttext_color, text_font, text_opa, text_align, text_decor, text_letter_space, text_line_space
    Line (Line chart/Line widget)line_width, line_color, line_opa, line_rounded, line_dash_width, line_dash_gap
    Arcarc_width, arc_color, arc_opa, arc_rounded, arc_image_src
    Imageimage_opa, image_recolor, image_recolor_opa
    Paddingpad_all, pad_hor, pad_ver, pad_top, pad_bottom, pad_left, pad_right, pad_row, pad_column, pad_gap
    Size & positionx, y, width, height, size (= width+height), min_width, min_height, max_width, max_height, translate_x, translate_y
    Transformtransform_rotation, transform_scale_x, transform_scale_y, transform_width, transform_height, transform_pivot_x, transform_pivot_y
    Layoutlayout, base_dir, align, flex, flex_flow, flex_main_place, flex_cross_place, flex_track_place, flex_grow
    Miscradius, clip_corner, opa, blend_mode, color_filter_dsc, color_filter_opa, transition, anim, anim_time
    Color-typed properties accept "#RRGGBB" strings, integers or lvgl.palette.* results; opacity properties take 0–255 or lvgl.OPA(n).

    Selectors are bitmasks combining states and parts. Lua 5.1 has no | operator — build the mask by adding the constant values (they are disjoint bits, so addition is safe):

    local checked_indicator = lvgl.STATE.CHECKED + lvgl.PART.INDICATOR
    slider_1:add_style(knob, checked_indicator)

    lvgl.STATE.DEFAULT is 0, so it can be passed directly.

    3.5 Events

    button:onevent(lvgl.EVENT.CLICKED, function(code, value)
        label_1.text = "pressed!"
    end)

    Event codes live in lvgl.EVENT: PRESSED, PRESSING, RELEASED, CLICKED, SHORT_CLICKED, LONG_PRESSED, VALUE_CHANGED, READY, SCROLL, KEY, FOCUSED, SIZE_CHANGED, DELETE, …

    Helper wrappers: :onClicked(cb), :onPressed(cb), :onShortClicked(cb) — each takes a function(code, value) callback.

    Note: the display has no input hardware — no touch layer, no buttons,
    no encoder. Nothing can trigger these events on the device itself; click and
    key events only fire in the interactive web preview (driven by your mouse).
    On the device, scripts run once per content push and nothing can interact
    with the UI — see the timer note in §3.7.

    3.6 Constants

    TableContent
    lvgl.EVENTEvent codes
    lvgl.FLAGObject flags (CLICKABLE, SCROLLABLE, HIDDEN, FLOATING, …)
    lvgl.STATEStates (DEFAULT, CHECKED, FOCUSED, PRESSED, DISABLED, …)
    lvgl.PARTParts (MAIN, SCROLLBAR, INDICATOR, CURSOR, ITEMS, …)
    lvgl.ALIGNAlignments (TOP_LEFT, CENTER, TOP_MID, BOTTOM_RIGHT, …)
    lvgl.DIRDirections
    lvgl.FLEX_FLOW, lvgl.FLEX_ALIGN, lvgl.GRID_ALIGNFlex layout
    lvgl.KEYKey codes
    lvgl.SCR_LOAD_ANIMScreen transition types
    lvgl.ROLLER_MODE, lvgl.LABEL_CONST, lvgl.SCROLLBAR_MODE, lvgl.BUILTIN_FONTWidget constants
    Top-level values and helpers:
    NameContent
    lvgl.PCT(n)Percent of the parent's size (function).
    lvgl.OPA(n)Opacity as percent (function).
    lvgl.HOR_RES(), lvgl.VER_RES()Active display width/height in pixels (functions).
    lvgl.SIZE_CONTENTSize value: fit the object to its content.
    lvgl.RADIUS_CIRCLERadius value: fully round.
    lvgl.COORD_MAX, lvgl.COORD_MINLargest/smallest representable coordinate.
    lvgl.LAYOUT_FLEX, lvgl.LAYOUT_GRIDLayout types for :set_layout().
    lvgl.ANIM_REPEAT_INFINITERepeat count for repeat_count: forever.
    lvgl.ANIM_PLAYTIME_INFINITEPlaytime value: never time out.
    lvgl.LV_ZOOM_NONEZoom value meaning 1:1 (the LV_ prefix is part of the Lua name).
    lvgl.CHART_POINT_NONESeries value marking a missing data point.
    lvgl.LABEL_DOT_NUM, lvgl.LABEL_POS_LAST, lvgl.LABEL_TEXT_SELECTION_OFFLabel sentinels (dot character, last position, no selection).
    lvgl.TABLE_CELL_NONETable cell index meaning "no cell".
    lvgl.BTNMATRIX_BTN_NONEButton-matrix index meaning "no button".
    lvgl.DROPDOWN_POS_LASTDropdown option index: last option.
    lvgl.TEXTAREA_CURSOR_LASTTextarea cursor position: end of text.

    3.7 Timers

    local t = lvgl.Timer({
        cb = function(timer)
            counter = counter + 1
            label_1.text = "tick " .. counter
        end,
        period = 1000,           -- ms; omitted => paused until set
        repeat_count = -1,       -- -1 = forever
        paused = false,
    })
    

    t:pause()
    t:resume()
    t:ready() -- fire right now

    ⚠️ The display is a battery/solar device: after the script finishes, the engine draws exactly one frame and the device goes back to sleep — there is no render loop. Timer callbacks therefore never run on the device (no lv_timer_handler is scheduled); they only fire in the interactive web preview. Never use timers as a clock or for animation on the device — update cadence is driven entirely by the backend pushing new content.

    3.8 Fonts

    TTF fonts are loaded from the SD card: A:/fonts/.ttf (rendered on the fly with tiny-ttf, cached per name+size). If the file is missing, the built-in montserrat_14 is used as fallback.
    local f = lvgl.Font("DejaVuSansMono-Bold", 50, "normal")
    label_1.text_font = f

    dormouse.createFont is the cached, preferred form. Font files live in the fonts/ folder on the display's SD card.

    3.9 Animations

    local a = slider_1:Anim({
        values = { from = 0, to = 100 },
        time = 500,
        path = "ease_in_out",   -- linear | ease_in | ease_out | ease_in_out | overshoot | bounce | step
    })
    a:start()

    Or standalone: lvgl.Anim(var, params); methods :start(), :stop(), :delete(). Like timers (§3.7), animations are driven by the render loop that does not exist on the device — they only animate in the web preview.

    3.10 Display & filesystem

    lvgl.disp — get_default(), get_scr_act(), get_scr_prev(), get_res(), load_scr(scr, anim, time, top), set_rotation(r), get_layer_top(), get_layer_sys().

    lvgl.fs — open_file("A:/icons/logo.png") (:read(n), :write(s), :seek(whence, pos), :close()), open_dir(path). Drive A: is the SD card (FatFs).

    For plain file access use the standard io library, which is also FatFs-backed:

    local f = io.open("A:/icons_svg/logo.svg", "rb")
    local content = f:read(1024)
    f:close()

    3.11 Control examples

    Each control available in the Layout Designer, rendered through the same WASM
    engine the web preview uses. Every snippet is a complete details
    script — the Layout Designer generates the lvgl.X(nil) control scripts and
    you position them here.

    Label

    label

    -- lvgl.Label: text display. text is the content, fonts come from the
    -- SD card via dormouse.createFont (cached per name + size). The SD card
    -- ships a large font set: serif, sans, monospace, and faces for other
    -- scripts (Latin-1, Japanese, Thai, Hebrew, Arabic, CJK, …).
    

    -- classic serif face
    local a = lvgl.Label(nil)
    a:set_pos({ x = 60, y = 40 })
    a.text = "The quick brown fox"
    a.text_font = dormouse.createFont("DavidLibre-Regular", 34)
    a.text_color = "#000000"

    -- humanist sans: German umlauts, degree sign, currency
    local b = lvgl.Label(nil)
    b:set_pos({ x = 60, y = 95 })
    b.text = "Grüße · 24 °C · ß § €"
    b.text_font = dormouse.createFont("NotoSans-Regular", 24)
    b.text_color = "#000000"

    -- Japanese
    local c = lvgl.Label(nil)
    c:set_pos({ x = 60, y = 140 })
    c.text = "こんにちは"
    c.text_font = dormouse.createFont("NotoSansJP-Regular", 26)
    c.text_color = "#000000"

    -- Thai
    local d = lvgl.Label(nil)
    d:set_pos({ x = 60, y = 185 })
    d.text = "สวัสดี"
    d.text_font = dormouse.createFont("NotoSerifThai-Regular", 26)
    d.text_color = "#000000"

    -- monospace for numbers and data
    local e = lvgl.Label(nil)
    e:set_pos({ x = 60, y = 230 })
    e.text = "42 °C 0123456789"
    e.text_font = dormouse.createFont("Cousine-Regular", 24)
    e.text_color = "#000000"

    Image

    image

    -- lvgl.Image: bitmap/SVG icon from the SD card. The path always uses the
    -- "A:" drive prefix; SVGs are rasterized by the built-in thorvg renderer at
    -- their native size (the shipped icon set is 24 px).
    local icons = { "sun", "cloud-sun", "cloud-rain", "cloud-snow" }
    for i = 1, #icons do
        local img = lvgl.Image(nil)
        img:set_pos({ x = 240 + (i - 1) * 80, y = 180 })
        img.src = "A:/icons/" .. icons[i] .. ".svg"
    end
    

    local cap = lvgl.Label(nil)
    cap:set_pos({ x = 240, y = 240 })
    cap.text = "img.src = \"A:/icons/.svg\""
    cap.text_font = dormouse.createFont("DavidLibre-Regular", 22)
    cap.text_color = "#000000"

    Canvas

    canvas

    -- lvgl.Canvas: raw pixel buffer. set_buffer(buf, w, h, cf) attaches a
    -- framebuffer; set_px(x, y, color, opa) writes one pixel where color is a
    -- {red=…, green=…, blue=…} table. get_px(x, y) reads one back.
    -- The seed string must contain no 0x00 bytes (the binding copies it with
    -- strcpy); real pixels are painted afterwards with fill_bg()/set_px().
    local LOGICAL = 16
    local SCALE   = 8      -- 16x16 pattern, each logical pixel an 8x8 block
    local RGB888  = 15     -- LV_COLOR_FORMAT_RGB888
    local OPAQUE  = 255    -- LV_OPA_COVER
    

    local function rgb(r, g, b) return { red = r, green = g, blue = b } end

    local W, H = LOGICAL SCALE, LOGICAL SCALE

    local cv = lvgl.Canvas(nil)
    cv:set_buffer(string.rep("\1", W H 3), W, H, RGB888)
    cv:set_pos({ x = 320, y = 160 })

    cv:fill_bg(rgb(255, 255, 255), OPAQUE)

    -- checkerboard with a red circle in the middle
    for ly = 0, LOGICAL - 1 do
    for lx = 0, LOGICAL - 1 do
    local dx, dy = lx - 7.5, ly - 7.5
    local c
    if dx dx + dy dy < 30 then
    c = rgb(220, 40, 40)
    elseif (lx % 2 == 0) == (ly % 2 == 0) then
    c = rgb(30, 30, 30)
    else
    c = rgb(255, 255, 255)
    end

    for py = ly SCALE, ly SCALE + SCALE - 1 do
    for px = lx SCALE, lx SCALE + SCALE - 1 do
    cv:set_px(px, py, c, OPAQUE)
    end
    end
    end
    end

    -- border to show the canvas bounds: set_px + get_px roundtrip check
    for x = 0, W - 1 do
    cv:set_px(x, 0, rgb(0, 0, 200), OPAQUE)
    cv:set_px(x, H - 1, rgb(0, 0, 200), OPAQUE)
    end
    for y = 0, H - 1 do
    cv:set_px(0, y, rgb(0, 0, 200), OPAQUE)
    cv:set_px(W - 1, y, rgb(0, 0, 200), OPAQUE)
    end
    assert(cv:get_px(0, 0).blue == 200)

    Calendar

    calendar

    -- lvgl.Calendar: month grid. set_shown_year()/set_shown_month(); today can be
    -- highlighted with :set_today_day()/month/year.
    local cal = lvgl.Calendar(nil)
    cal:set_pos({ x = 220, y = 80 })
    cal:set({ width = 360, height = 300 })
    cal:set_shown_year(2026)
    cal:set_shown_month(3)
    cal.text_color = "#000000"
    cal.bg_color = "#ffffff"
    cal.bg_opa = 255
    cal.border_width = 2
    cal.border_color = "#000000"

    Bar

    bar

    -- lvgl.Bar: progress bar without knob, e.g. a humidity reading.
    -- set_value(value, anim_en). The fill (indicator) color is a shared
    -- lvgl.Style on the INDICATOR part.
    local bar = lvgl.Bar(nil)
    bar:set_pos({ x = 230, y = 190 })
    bar:set({ width = 340, height = 40 })
    bar:set_range(0, 100)
    bar:set_value(72, 0)
    bar.bg_color = "#ffffff"
    bar.bg_opa = 255
    bar.border_width = 2
    bar.border_color = "#000000"
    

    local style = lvgl.Style({ bg_color = "#000000" })
    bar:add_style(style, lvgl.PART.INDICATOR)

    local lbl = lvgl.Label(nil)
    lbl:set_pos({ x = 230, y = 250 })
    lbl.text = "humidity 72 %"
    lbl.text_font = dormouse.createFont("DavidLibre-Regular", 20)
    lbl.text_color = "#000000"

    Chart

    chart

    -- lvgl.Chart: line/bar chart of a data series (here: hourly temperatures).
    -- add_series(color, axis) returns a series handle (lightuserdata) used by
    -- set_point_count()/set_next_value().
    local chart = lvgl.Chart(nil)
    chart:set_pos({ x = 200, y = 120 })
    chart:set({ width = 400, height = 220 })
    chart.type = 1   -- 0 none, 1 line, 2 bar, 3 stacked
    chart:set_div_line_count(4, 6)
    

    chart.bg_color = "#ffffff"
    chart.bg_opa = 255
    chart.border_width = 2
    chart.border_color = "#000000"

    local ser = chart:add_series({ red = 0, green = 0, blue = 0 }, 0)

    local values = { 10, 14, 13, 18, 16, 21, 19, 15 } -- °C per hour
    chart:set_point_count(#values)
    for i = 1, #values do
    chart:set_next_value(ser, values[i])
    end
    chart:refresh()

    Checkbox

    checkbox

    -- lvgl.Checkbox: check mark + label. Toggle the checked state with
    -- :add_state(lvgl.STATE.CHECKED) / :clear_state(...).
    local cb = lvgl.Checkbox(nil)
    cb:set_pos({ x = 240, y = 170 })
    cb:set({ width = 320, height = 70 })
    cb.text = "Umbrella today"
    cb.text_font = dormouse.createFont("DavidLibre-Regular", 26)
    cb.text_color = "#000000"
    cb:add_state(lvgl.STATE.CHECKED)

    Led

    led

    -- lvgl.Led: glowing circle. :on() / :off() / :toggle(), brightness 0–255.
    -- Colors are {red=…, green=…, blue=…} tables via :set_color(). On the e-paper
    -- display the glow is flattened to a filled disc — color marks the state.
    local colors = {
        { red = 220, green = 30,  blue = 30 },   -- alarm
        { red = 30,  green = 150, blue = 60 },   -- ok
        { red = 30,  green = 60,  blue = 220 },  -- info
    }
    for i = 1, #colors do
        local led = lvgl.Led(nil)
        led:set_pos({ x = 240 + (i - 1) * 130, y = 180 })
        led:set({ width = 90, height = 90 })
        led:set_color(colors[i])
        led:on()
    end

    Qrcode

    qrcode

    -- lvgl.Qrcode: QR code from a byte string. Colors are {red=…, green=…, blue=…}
    -- tables; :update(data, #data) encodes and renders.
    local qr = lvgl.Qrcode(nil)
    qr:set_pos({ x = 290, y = 110 })
    qr:set({ width = 200, height = 200 })
    qr:set_size(150)
    qr.dark_color = { red = 0, green = 0, blue = 0 }
    qr.light_color = { red = 255, green = 255, blue = 255 }
    

    local payload = "https://example.org/cafe-menu"
    qr:update(payload, string.len(payload))

    Scale

    scale

    -- lvgl.Scale: ruler with ticks, labels and an optional line needle — here a
    -- temperature gauge over -10…40 °C. set_mode: 0 top, 1 bottom, 8 round inner,
    -- 16 round outer; the needle only works in round modes on a square scale
    -- (set_line_needle_value(needle, length, value)). Tick/label styling goes on
    -- the INDICATOR part, the scale line itself on MAIN.
    local scale = lvgl.Scale(nil)
    scale:set_pos({ x = 200, y = 140 })
    scale:set({ width = 400, height = 100 })
    scale:set_range(-10, 40)
    scale.label_show = true
    scale.major_tick_every = 10
    scale.text_font = dormouse.createFont("DavidLibre-Regular", 16)
    scale.text_color = "#000000"
    

    local main = lvgl.Style({ line_width = 2, line_color = "#000000" })
    scale:add_style(main, lvgl.PART.MAIN)
    local ticks = lvgl.Style({ line_width = 2, line_color = "#000000" })
    scale:add_style(ticks, lvgl.PART.INDICATOR)

    local cap = lvgl.Label(nil)
    cap:set_pos({ x = 320, y = 60 })
    cap.text = "outdoor 21 °C"
    cap.text_font = dormouse.createFont("DavidLibre-Regular", 28)
    cap.text_color = "#000000"

    Switch

    switch

    -- lvgl.Switch: toggle. CHECKED state = "on"; the indicator style is applied
    -- to MAIN and to INDICATOR only while checked (parts + states are bitmasks,
    -- add the constants — Lua 5.1 has no |).
    local sw = lvgl.Switch(nil)
    sw:set_pos({ x = 250, y = 180 })
    sw:set({ width = 130, height = 60 })
    sw:add_state(lvgl.STATE.CHECKED)
    

    local style = lvgl.Style({ bg_color = "#000000" })
    sw:add_style(style, lvgl.PART.MAIN)
    sw:add_style(style, lvgl.PART.INDICATOR + lvgl.STATE.CHECKED)

    local lbl = lvgl.Label(nil)
    lbl:set_pos({ x = 400, y = 192 })
    lbl.text = "on"
    lbl.text_font = dormouse.createFont("DavidLibre-Regular", 26)
    lbl.text_color = "#000000"

    Textarea

    textarea

    -- lvgl.Textarea: multi-line text box. On a sleeping e-paper device it is used
    -- as a text panel (data-bound notes, lists); editing only makes sense with an
    -- attached keyboard/encoder. .text takes plain strings, \n makes new lines.
    local ta = lvgl.Textarea(nil)
    ta:set_pos({ x = 210, y = 170 })
    ta:set({ width = 380, height = 140 })
    ta.text = "Shopping list\n- bread\n- coffee\n- batteries"
    ta.text_color = "#000000"
    ta.text_font = dormouse.createFont("DavidLibre-Regular", 24)
    ta.bg_color = "#ffffff"
    ta.bg_opa = 255
    ta.border_width = 2
    ta.border_color = "#000000"

    4. The mbedtls module

    Crypto functions mirroring the mbed TLS C API. Fault tolerant: functions never raise on bad input — on failure they return nil plus an error string (mbed TLS error code as "-0xXXXX", or a usage message like "wrong key size").

    FunctionReturns
    base64_encode(data)base64 string
    base64_decode(b64)binary string
    cipher_encrypt(name, key, iv, data) / cipher_decrypt(...)ciphertext/plaintext; CBC uses PKCS7 padding
    cipher_auth_encrypt(name, key, nonce, data [, ad]) / cipher_auth_decrypt(...)AEAD; the 16-byte tag is appended to the ciphertext
    md(name, data)hash digest
    md_hmac(name, key, data)HMAC
    pkcs5_pbkdf2_hmac(name, pwd, salt, iterations, key_len)derived key
    hkdf_extract(name, salt, ikm) / hkdf_expand(name, prk, info, key_len)HKDF (RFC 5869); salt/info may be ""
    Cipher names follow mbedtls_cipher_info_from_string (case-insensitive): "AES-128-CBC", "AES-192-CTR", "AES-256-GCM", "AES-256-ECB", "AES-128-CFB128", "AES-128-OFB", key-wrap "AES-256-KW", … Hash names: "SHA256", "SHA512", "SHA3-256", "SHA1", "MD5", "RIPEMD160", …

    AEAD modes (GCM, CCM, ChaChaPoly, KW/KWP) must use the cipher_auth_* functions; non-AEAD modes must use cipher_encrypt/cipher_decrypt — mixing them returns an error instead of silently failing.

    Example: decrypting an encrypted payload

    Display data can arrive AES-encrypted end-to-end. The dormouse library does this
    transparently for payloads that carry the scep1: magic prefix (§7); for manual
    decryption of an arbitrary blob use mbedtls directly (read the key with io,
    see §5.6):

    local f = io.open("A:/key.txt", "r")
    local b64 = f:read("*l"); f:close()
    local key = mbedtls.base64_decode(b64:gsub("%s", ""))   -- 32 bytes => AES-256
    

    -- blob = 16-byte random IV prepended to the ciphertext, base64-encoded
    local blob = mbedtls.base64_decode(payload_b64)
    local plain, err = mbedtls.cipher_decrypt("AES-256-CBC", key,
    blob:sub(1, 16), blob:sub(17))
    label_1.text = plain or ("decrypt failed: " .. err)

    Example: hashes and KDFs

    local sum = mbedtls.md("SHA256", "hello")                  -- 32 raw bytes
    print(mbedtls.base64_encode(sum))
    

    local mac = mbedtls.md_hmac("SHA256", "secret", "message")
    local dk = mbedtls.pkcs5_pbkdf2_hmac("SHA256", "pw", "salt", 4096, 32)
    local prk = mbedtls.hkdf_extract("SHA256", "salt", "input key material")
    local okm = mbedtls.hkdf_expand("SHA256", prk, "context info", 16)

    local sealed, e = mbedtls.cipher_auth_encrypt("AES-128-GCM", key16, nonce12, "data", "assoc")
    -- sealed = ciphertext .. 16-byte tag


    5. Standard libraries

    The engine opens the full eLua/Lua 5.1 library set — base, table, string, math, io, os, debug — plus the additions package and lpeg (PEG patterns) and the globals ipairs, pairs, require, module, newproxy, _VERSION. What is not there: coroutine, bit/bit32, bitarray, string.pack/unpack, term/cpu/uart/… (the eLua hardware modules).

    5.1 base

    FunctionWhat it doesExample
    assert(v [, msg])Errors unless v is truthy; returns vassert(f, "key file missing") collectgarbage([opt [, arg]])GC control; "count" returns used KB (float)print(collectgarbage("count")) dofile(path)Load + run a FatFs script, returns its valuesdofile("A:/lua/setup.lua") error(msg [, level])Raise a runtime errorerror("bad payload") gcinfo()eLua: used memory in KB (integer)print(gcinfo()) getfenv([f]) / setfenv([f, t])Lua 5.1 function environmentssetfenv(fn, env) getmetatable(obj) / setmetatable(t, mt)Metatable accesssetmetatable(t, { __index = d }) load(string \func [, name])Compile a chunk, returns function or nil, errlocal f = load("return 42") loadfile(path)Compile a FatFs file, returns function or nil, errlocal f = loadfile("A:/lua/util.lua") loadstring(s [, name])Same as load with a stringlocal f = loadstring("return 1+1")() next(t [, key])Next key, value pair; also pairs internalk, v = next(t) pcall(f, ...)Protected call → ok, result…local ok, err = pcall(fn) print(...)Writes to the firmware log (WASM console / debug log callback)print("tick", t) rawequal(a, b) / rawget(t, k) / rawset(t, k, v)Bypass metamethodsrawset(t, "x", 1) select(n \"#", ...)Varargs slice / countn = select("#", ...) tonumber(e [, base])String → number, nil on failuretonumber("ff", 16) → 255 tostring(v)Value → stringtostring(42) → "42" type(v)Type name as stringtype(f) → "userdata" unpack(list [, i [, j]])Table → argument listf(unpack({1, 2, 3})) xpcall(f, handler, ...)Protected call with message handlerxpcall(fn, traceback) ipairs(t) / pairs(t)Array / general iteratorsfor i, v in ipairs(rows) do require(name)Load from package.path — on-device A:/lua/.lua (also preloaded modules)require "dormouse" module(...)Old module system (exists, do not use)— newproxy([bool])Fresh empty userdata (with metatable)— _VERSION"Lua 5.1"—

    5.2 string

    All Lua 5.1 pattern functions; patterns are not PCRE — magic chars (. % + - * ? ( ) [ ^ $) must be escaped with %. Negative indices count from the end.

    FunctionWhat it doesExample
    byte(s [, i [, j]])Character code(s)string.byte("A") → 65
    char(...)Code(s) → charactersstring.char(65, 66) → "AB"
    dump(fn)Function → bytecode string—
    find(s, pat [, init [, plain]])start, end of match (captured groups returned after); plain=true disables patternsstring.find("a.bc", "b.c", 1, true)
    format(fmt, ...)C-style format: %d %s %x %.Nf %%string.format("%.2f%%", 66.6) → "66.60%"
    gmatch(s, pat) / gfind (alias)Iterator over all matchesfor w in s:gmatch("%a+") do
    gsub(s, pat, repl [, n])Replace; returns s2, count(s:gsub("%s+", " "))
    len(s)Byte lengthstring.len("ab") → 2
    lower(s) / upper(s)ASCII case("ON"):lower() → "on"
    match(s, pat [, init])First capture (or whole match)string.match("v1.2", "v(%d+)") → "1"
    rep(s, n [, sep])Repetitionstring.rep("ab", 2, "-") → "ab-ab"
    reverse(s)Reversedstring.reverse("abc") → "cba"
    sub(s [, i [, j]])Substring, inclusive indices, negatives OKstring.sub("abc", -1) → "c"

    5.3 table

    Lua 5.1 set — includes the legacy 5.0 functions that were removed in later Lua:

    FunctionWhat it doesExample
    concat(list [, sep [, i [, j]]])Join string/number partstable.concat({1, 2}, ",") → "1,2"
    foreach(t, fn)Call fn(k, v) for every pairtable.foreach(t, print)
    foreachi(t, fn)Call fn(i, v) in array ordertable.foreachi(t, print)
    getn(t) / maxn(t)Array length / highest numeric indextable.maxn({[5] = 1}) → 5
    insert(t [, pos,] v)Insert (append at #t + 1)table.insert(t, 4, "x")
    remove(t [, pos])Remove at pos (default #t), returns valuetable.remove(t)
    setn(t, n)Set stored length (legacy)—
    sort(t [, comp])In-place comparison sort (not stable); comp(a, b) = a before btable.sort(t, function(a, b) return a.v < b.v end)

    5.4 math

    Full eLua set — note that exp, log10, pow, mod, atan2, cosh etc. do exist here (they were only removed in Lua 5.4).

    GroupFunctionsExample
    Trigsin cos tan asin acos atan atan2 sinh cosh tanhmath.atan2(1, 1) → 0.7854
    Anglesdeg radmath.deg(math.pi) → 180
    Roundingabs floor ceilmath.floor(2.9) → 2
    Powerspow sqrt exp log log10math.pow(2, 10) → 1024, math.log10(1000) → 3
    Remaindermod fmod frexp ldexp modfmath.fmod(7, 3) → 1, math.modf(3.75) → 3, 0.75
    Aggregatesmin maxmath.min(lo, r.low)
    Randomrandom([m [, n]]) randomseed(x)math.randomseed(42); math.random(1, 6)
    Constantspi, huge (inf)math.pi r r

    5.5 os

    FunctionWhat it does on the deviceExample
    time([table])Epoch seconds from the RTC-synchronized clock; with a date table → epochos.time() → 1794746017 date([fmt [, time]])Formatted date; "!" prefixes UTC, "t" returns a table {year, month, day, hour, min, sec, wday, yday, isdst}os.date("!%Y-%m-%d %H:%M") difftime(t2 [, t1])t2 - t1 secondsos.difftime(now, start) clock()CPU seconds since startlocal t0 = os.clock() remove(path)Stub on the firmware (returns nil, file stays)— rename(a, b)Stub on the firmware (returns nil, files unchanged)— tmpname()Returns a /tmp/… string — no such directory, do not use— getenv(name)Always nil — no environment— execute([cmd])Not available (no shell) — do not use— setlocale(...)No-op stub— exit([code])Terminates the engine — never call—

    5.6 io — FatFs file access

    The io library reads and writes files on the SD card (FatFs). Paths use the
    A: volume prefix (A:/key.txt, A:/settings.txt). Modes follow standard
    Lua 5.1: "r" read (default), "w" write/create (truncates), "a" append,
    "r+" read/write, "w+" read/write create; the "b"/"t" suffixes are
    accepted but make no difference.

    FunctionWhat it doesExample
    open(path [, mode])→ file handle, or nil, errmsglocal f = io.open("A:/key.txt", "r")
    lines(path)Line iterator over a file (opens/closes it for you)for line in io.lines("A:/cfg.txt") do
    read/write/close/flush([h])The handle methods below, applied to the default input/output file or an explicit handleio.close(f)
    input([file]) / output([file])Get/set the default input/output handleio.input(f)
    type(obj)"file", "closed file", or nil for non-filesassert(io.type(f) == "file")
    popen(cmd) / tmpfile()Present but non-functional (no shell, no temp dir) — do not use—
    Handle methods:
    MethodWhat it doesExample
    :read(...)Per request: "a"/"all" (rest of file), "l"/"line" (default, without newline), "n" (number), n (n bytes); multiple requests → multiple returns; nil at EOFlocal key = f:read("l") :write(...)Write strings/numbers; returns the handle, or nil + errmsgf:write("hi\n") :seek([whence [, pos]])"set" \"cur" \"end" (default "cur"); returns the new positionlocal size = f:seek("end") :lines()Line iterator over an open handlefor l in f:lines() do :close()Close the handle, flushing pending writesf:close() :flush()Flush buffered writesf:flush() :setvbuf(mode [, size])Accepted, no effect on FatFs—
    -- read a config line from the SD card
    local f = io.open("A:/settings.txt", "r")
    if f then
        local mode = f:read("*l")
        f:close()
    end
    

    -- write a small status file
    local g = io.open("A:/status.txt", "w")
    if g then
    g:write("last run ", os.time(), "\n")
    g:close()
    end

    -- iterate over every line of a file
    for line in io.lines("A:/whitelist.txt") do
    print(line)
    end

    There is no console I/O: io.write/io.output (stdout) are not connected —
    use print for logging, which goes to the firmware log. For directory
    listing or low-level byte access use the lvgl.fs binding (§3.10).

    5.7 debug

    Full Lua 5.1 debug set — useful in the WASM simulator and via the log callback:

    FunctionWhat it doesExample
    traceback([msg [, level]])Stack string appended to msgprint(debug.traceback("here")) getinfo([level \fn [, what]])Function info table (source, currentline, what, namewhat, …)debug.getinfo(1).currentline getlocal(level, idx) / setlocal(level, idx, v)Local of a stack leveldebug.getlocal(1, 1) → "x", 5 getupvalue(fn, idx) / setupvalue(fn, idx, v)Upvalue accessdebug.getupvalue(closure, 1) gethook / sethook([fn [, mask [, count]]])Execution hooks— getregistry()Registry table— debugThe registry itself (eLua)—

    5.8 package & lpeg

    package exists mostly for require:

    lpeg (Lua PEGs, eLua default): P S R V C Cb Cc Cf Cg Cmt Ct Cp Cs Carg (patterns/captures), lpeg.match(p, s), lpeg.type(p), lpeg.locale(). Use it for anything string.find patterns can't express (nested/quantified structures):
    -- PEGs match anchored at the start of the subject string
    local num = lpeg.R("09") ^ 1
    print(lpeg.match(lpeg.C(num), "42.5"))               -- "42"
    

    -- capture a named group from a prefix pattern
    local cap = lpeg.Ct(lpeg.Cg(lpeg.P("sensor:") * lpeg.C(num), "value"))
    local t = lpeg.match(cap, "sensor:42.5")
    print(t.value) -- "42"


    6. Lua 5.1 constraints

    The device interpreter is Lua 5.1 — the following will fail to compile:

    FeatureUse instead
    Integer division //math.floor(a / b) Bitwise a & b, a \b, ~xno bit/bit32/bitarray library — precompute constants as plain numbers goto / labelsrestructure with flags / functions # on tables with nil holesmaintain an explicit length coroutine.*not loaded — restructure without yields bit32.*, string.pack/string.unpackLua 5.2+ — not present UTF-8 source escapes \xNNLua 5.1 escapes are decimal: \123 Also: C-like concatenation of numbers is auto-converted in .., but string.find patterns (not PCRE) — . matches any char and magic characters must be escaped with %.

    7. End-to-end encrypted data payload example

    Display data usually travels over the internet in clear text. The dormouse
    library supports an encrypted transport format that protects the payload
    end-to-end: only a display holding the matching key file on its SD card can
    read it — the backend, gateway and LoRa link only ever see opaque base64.

    The format

    scep1::
  • scep1: — magic prefix (dormouse.encryptionPrefix). Without it the data is treated as plain JSON/XML as usual.
  • — any mbedtls cipher name (AES-256-CBC, AES-128-CBC, AES-256-CTR, …). May be omitted; dormouse then defaults to AES--CBC.
  • The base64 blob is a random 16-byte IV prepended to the ciphertext (CBC uses PKCS7 padding).
  • dormouse.loadData(data) detects the prefix, reads the key from A:/key.txt on the SD card (one line: base64 of the raw key), decrypts and binds the plaintext — dormouse.bindingData then contains the normal JSON/XML table. On failure dormouse.bindingData stays empty and dormouse.encryptionError explains why (missing key, wrong key, bad base64, …).

    1. Generate the key (one-time, on your server/Linux box)

    openssl rand -base64 32 > key.txt    # 32 crypto-random bytes => AES-256

    Copy key.txt to the root of the display's SD card (next to lua/ and
    icons/). Use openssl rand -base64 16 for AES-128. Keep the file — every
    display that should read the data needs the same key.

    2. Encrypt the data before sending it

    JSON='{"temperature": 24.1, "humidity": 62}'
    KEY=$(openssl base64 -d -A < key.txt | od -An -tx1 | tr -d ' \n')
    openssl rand 16 > iv.bin; IV=$(od -An -tx1 -v iv.bin | tr -d ' \n')
    { cat iv.bin; printf '%s' "$JSON" | openssl enc -aes-256-cbc -K "$KEY" -iv "$IV"; } \
      | openssl base64 -A | sed 's/^/scep1:AES-256-CBC:/' > payload.txt

    payload.txt now contains scep1:AES-256-CBC:3dZ9kK… — that whole string is
    the data-source content. openssl rand 16 gives a **fresh random IV per
    message** (mandatory — never reuse one), which is also written as the first 16
    bytes of the blob, exactly where dormouse expects it. Works in sh/bash;
    for AES-128 use a 16-byte key and -aes-128-cbc.

    3. Push the payload to the update endpoint

    Replace {ResourceLink} and {Token} with the values shown on your data
    source page (see Manual §8.5 — the token endpoint needs no bearer token):

    curl -X PUT "https://www.siebenschläfer-display.eu/api/databindings/update/{ResourceLink}/{Token}" \
      -H "Content-Type: text/plain" \
      --data-binary 'scep1:AES-256-CBC:3dZ9kK…'

    4. The user script

    Nothing special is required — encryption is transparent: the generated script
    header already decrypts scep1: payloads via dormouse.loadData(data). In
    your user script you only handle the result:

    -- Add additional commands below
    

    if dormouse.encryptionError then
    label_status.text = "locked: " .. dormouse.encryptionError
    else
    label_temp.text = dormouse.bind("{{temperature}} °C")
    end

    And the dynamic-range variant combining all of §3:

    -- Add additional commands below
    

    -- 1. Dynamic range from the (decrypted) data source
    local rows = dormouse.bindingData.data
    local lo, hi = nil, nil
    for i = 1, #rows do
    local r = rows[i]
    lo = lo and math.min(lo, r.low) or r.low
    hi = hi and math.max(hi, r.high) or r.high
    end
    scale_3:set_mode(2)
    scale_3:set_range(math.floor(lo - 5), math.floor(hi + 5))

    -- 2. Draw one line per data point
    for i = math.max(1, #rows - 40), #rows do
    local r = rows[i]
    local g = lvgl.Line(nil)
    local y = (r.close - lo) / (hi - lo) * 300
    g:set_pos({ x = 120 + i * 5, y = 400 - y })
    g:set({ width = 3, height = 2, bg_color = "#000000", bg_opa = 255 })
    end

    -- 3. Show a decrypted status line, with an error indicator
    if dormouse.encryptionError then
    label_status.text = "offline: " .. dormouse.encryptionError
    else
    label_status.text = dormouse.bind("{{symbol}} {{close}}")
    end