From 990abc210cd0e1f6a6ea8d3ab631a1db80ef6f84 Mon Sep 17 00:00:00 2001 From: Wang Beihong Date: Sun, 5 Apr 2026 21:50:06 +0800 Subject: [PATCH] =?UTF-8?q?=E7=89=B9=E6=80=A7=20(UI)=EF=BC=9A=E5=AE=9E?= =?UTF-8?q?=E7=8E=B0=E5=8C=85=E5=90=AB=E5=B1=8F=E5=B9=95=E3=80=81=E5=9B=BE?= =?UTF-8?q?=E5=83=8F=E5=92=8C=E5=AD=97=E4=BD=93=E7=9A=84=20UI=20=E7=BB=84?= =?UTF-8?q?=E4=BB=B6=20=E6=96=B0=E5=A2=9E=E8=B5=84=E6=BA=90=E6=96=87?= =?UTF-8?q?=E4=BB=B6=EF=BC=9A=E6=B7=BB=E5=8A=A0=E4=BA=86=E5=AD=97=E4=BD=93?= =?UTF-8?q?=E3=80=81=E5=9B=BE=E5=83=8F=E5=92=8C=E5=B1=8F=E5=B9=95=E7=9B=B8?= =?UTF-8?q?=E5=85=B3=E7=9A=84=E5=A4=B4=E6=96=87=E4=BB=B6=E4=B8=8E=E6=BA=90?= =?UTF-8?q?=E6=96=87=E4=BB=B6=E3=80=82=20=E5=AE=9A=E4=B9=89=E6=95=B0?= =?UTF-8?q?=E6=8D=AE=E7=BB=93=E6=9E=84=EF=BC=9A=E5=88=9B=E5=BB=BA=E4=BA=86?= =?UTF-8?q?=E7=94=A8=E4=BA=8E=E6=8F=8F=E8=BF=B0=E5=AD=97=E4=BD=93=E5=92=8C?= =?UTF-8?q?=E5=9B=BE=E5=83=8F=E7=9A=84=E6=95=B0=E6=8D=AE=E7=BB=93=E6=9E=84?= =?UTF-8?q?=E3=80=82=20=E5=AE=9E=E7=8E=B0=E4=B8=BB=E5=B1=8F=E9=80=BB?= =?UTF-8?q?=E8=BE=91=EF=BC=9A=E5=AE=9E=E7=8E=B0=E4=BA=86=E4=B8=BB=E5=B1=8F?= =?UTF-8?q?=E5=B9=95=E7=9A=84=E5=88=9B=E5=BB=BA=E5=87=BD=E6=95=B0=E4=BB=A5?= =?UTF-8?q?=E5=8F=8A=E5=91=A8=E6=9C=9F=E6=80=A7=E5=88=B7=E6=96=B0=EF=BC=88?= =?UTF-8?q?tick=EF=BC=89=E5=87=BD=E6=95=B0=E3=80=82=20=E9=9B=86=E6=88=90?= =?UTF-8?q?=20LVGL=20=E7=AE=A1=E7=90=86=EF=BC=9A=E9=9B=86=E6=88=90?= =?UTF-8?q?=E4=BA=86=20LVGL=20=E4=B8=BB=E9=A2=98=E5=88=9D=E5=A7=8B?= =?UTF-8?q?=E5=8C=96=E5=8F=8A=E5=B1=8F=E5=B9=95=E7=AE=A1=E7=90=86=E5=8A=9F?= =?UTF-8?q?=E8=83=BD=E3=80=82=20=E6=B7=BB=E5=8A=A0=20UI=20=E5=88=9D?= =?UTF-8?q?=E5=A7=8B=E5=8C=96=EF=BC=9A=E6=96=B0=E5=A2=9E=20UI=20=E5=88=9D?= =?UTF-8?q?=E5=A7=8B=E5=8C=96=E5=8F=8A=E5=88=B7=E6=96=B0=E5=87=BD=E6=95=B0?= =?UTF-8?q?=EF=BC=8C=E7=94=A8=E4=BA=8E=E7=AE=A1=E7=90=86=E7=95=8C=E9=9D=A2?= =?UTF-8?q?=E6=9B=B4=E6=96=B0=E3=80=82=20=E9=87=8D=E6=9E=84=E4=B8=BB?= =?UTF-8?q?=E5=85=A5=E5=8F=A3=EF=BC=9A=E9=87=8D=E6=9E=84=E4=B8=BB=E5=BA=94?= =?UTF-8?q?=E7=94=A8=E7=A8=8B=E5=BA=8F=E5=85=A5=E5=8F=A3=EF=BC=8C=E4=BB=A5?= =?UTF-8?q?=E6=94=AF=E6=8C=81=20UI=20=E4=BB=BB=E5=8A=A1=E5=8F=8A=20FreeRTO?= =?UTF-8?q?S=20=E5=A4=9A=E4=BB=BB=E5=8A=A1=E8=B0=83=E5=BA=A6=E3=80=82=20?= =?UTF-8?q?=E6=9B=B4=E6=96=B0=E6=9E=84=E5=BB=BA=E9=85=8D=E7=BD=AE=EF=BC=9A?= =?UTF-8?q?=E6=9B=B4=E6=96=B0=E4=BA=86=20CMakeLists=20=E5=8F=8A=E7=BB=84?= =?UTF-8?q?=E4=BB=B6=E9=85=8D=E7=BD=AE=EF=BC=8C=E4=BB=A5=E5=8C=85=E5=90=AB?= =?UTF-8?q?=E6=96=B0=E7=9A=84=E4=BE=9D=E8=B5=96=E9=A1=B9=E3=80=82?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- components/lvgl_st7789_use/CMakeLists.txt | 4 + components/lvgl_st7789_use/Kconfig.projbuild | 59 + components/lvgl_st7789_use/README.md | 114 + .../lvgl_st7789_use/include/lvgl_st7789_use.h | 80 + components/lvgl_st7789_use/lvgl_st7789_use.c | 257 + components/ui/.eez-project-build | 18 + components/ui/CMakeLists.txt | 6 + components/ui/actions.h | 14 + components/ui/eez-flow.cpp | 9901 +++++++++++++++++ components/ui/eez-flow.h | 4388 ++++++++ components/ui/fonts.h | 24 + components/ui/images.c | 5 + components/ui/images.h | 24 + components/ui/screens.c | 154 + components/ui/screens.h | 36 + components/ui/structs.h | 13 + components/ui/styles.c | 6 + components/ui/styles.h | 14 + components/ui/ui.c | 47 + components/ui/ui.h | 21 + components/ui/vars.c | 2 + components/ui/vars.h | 25 + components/ws2812/include/ws2812.h | 8 + components/ws2812/ws2812.c | 10 +- dependencies.lock | 91 +- main/CMakeLists.txt | 4 +- main/idf_component.yml | 2 + main/main.c | 14 - main/main.cpp | 50 + 29 files changed, 15373 insertions(+), 18 deletions(-) create mode 100644 components/lvgl_st7789_use/CMakeLists.txt create mode 100644 components/lvgl_st7789_use/Kconfig.projbuild create mode 100644 components/lvgl_st7789_use/README.md create mode 100644 components/lvgl_st7789_use/include/lvgl_st7789_use.h create mode 100644 components/lvgl_st7789_use/lvgl_st7789_use.c create mode 100644 components/ui/.eez-project-build create mode 100644 components/ui/CMakeLists.txt create mode 100644 components/ui/actions.h create mode 100644 components/ui/eez-flow.cpp create mode 100644 components/ui/eez-flow.h create mode 100644 components/ui/fonts.h create mode 100644 components/ui/images.c create mode 100644 components/ui/images.h create mode 100644 components/ui/screens.c create mode 100644 components/ui/screens.h create mode 100644 components/ui/structs.h create mode 100644 components/ui/styles.c create mode 100644 components/ui/styles.h create mode 100644 components/ui/ui.c create mode 100644 components/ui/ui.h create mode 100644 components/ui/vars.c create mode 100644 components/ui/vars.h delete mode 100755 main/main.c create mode 100755 main/main.cpp diff --git a/components/lvgl_st7789_use/CMakeLists.txt b/components/lvgl_st7789_use/CMakeLists.txt new file mode 100644 index 0000000..7be9341 --- /dev/null +++ b/components/lvgl_st7789_use/CMakeLists.txt @@ -0,0 +1,4 @@ +idf_component_register(SRCS "lvgl_st7789_use.c" + INCLUDE_DIRS "include" + REQUIRES driver esp_lcd esp_lvgl_port + ) \ No newline at end of file diff --git a/components/lvgl_st7789_use/Kconfig.projbuild b/components/lvgl_st7789_use/Kconfig.projbuild new file mode 100644 index 0000000..6bdb350 --- /dev/null +++ b/components/lvgl_st7789_use/Kconfig.projbuild @@ -0,0 +1,59 @@ +menu "LVGL ST7789 显示屏配置" + +config LVGL_ST7789_LCD_H_RES + int "LCD 水平分辨率 (H_RES)" + range 1 1000 + default 240 + help + LCD 屏幕的水平分辨率(像素)。 + +config LVGL_ST7789_LCD_V_RES + int "LCD 垂直分辨率 (V_RES)" + range 1 1000 + default 240 + help + LCD 屏幕的垂直分辨率(像素)。 + +config LVGL_ST7789_GPIO_SCLK + int "LCD SCLK GPIO" + range 0 39 + default 2 + help + LCD SPI 时钟引脚 GPIO 号。 + +config LVGL_ST7789_GPIO_MOSI + int "LCD MOSI GPIO" + range 0 39 + default 3 + help + LCD SPI MOSI 引脚 GPIO 号。 + +config LVGL_ST7789_GPIO_RST + int "LCD RST GPIO" + range 0 39 + default 9 + help + LCD 复位引脚 GPIO 号。 + +config LVGL_ST7789_GPIO_DC + int "LCD DC GPIO" + range 0 39 + default 8 + help + LCD 数据/命令引脚 GPIO 号。 + +config LVGL_ST7789_GPIO_CS + int "LCD CS GPIO" + range 0 39 + default 7 + help + LCD 片选引脚 GPIO 号。 + +config LVGL_ST7789_GPIO_BL + int "LCD 背光 GPIO (NC为-1)" + range -1 39 + default -1 + help + LCD 背光引脚 GPIO 号,未连接请填-1。 + +endmenu diff --git a/components/lvgl_st7789_use/README.md b/components/lvgl_st7789_use/README.md new file mode 100644 index 0000000..57f61cb --- /dev/null +++ b/components/lvgl_st7789_use/README.md @@ -0,0 +1,114 @@ +# lvgl_st7789_use 组件说明 + +`lvgl_st7789_use` 是项目中的 LCD 显示组件,基于 `esp_lcd + esp_lvgl_port`,用于快速驱动 ST7789 SPI 屏并显示 LVGL 界面。 + +--- + +## 功能概览 + +- 初始化 SPI LCD(含背光、面板、显示偏移) +- 初始化 LVGL 端口并注册显示设备 +- 默认创建一个居中标签用于快速验证显示链路 +- 提供运行时更新中心文本接口 +- 支持可配置方向、镜像与偏移 +- 支持可选三色测试图(调试用) + +--- + +## 对外 API + +头文件:`include/lvgl_st7789_use.h` + +- `esp_err_t start_lvgl_demo(void);` + - 完成 LCD + LVGL 初始化并创建默认界面 + +- `esp_err_t lvgl_st7789_set_center_text(const char *text);` + - 运行时更新中心标签文字(线程安全,内部已加锁) + +--- + +## 关键配置项(可直接改宏) + +在 `include/lvgl_st7789_use.h` 中: + +### 1) 屏幕与 SPI + +- `EXAMPLE_LCD_H_RES` / `EXAMPLE_LCD_V_RES` +- `EXAMPLE_LCD_PIXEL_CLK_HZ` +- `EXAMPLE_LCD_SPI_NUM` +- `EXAMPLE_LCD_CMD_BITS` / `EXAMPLE_LCD_PARAM_BITS` + +建议:ST7789 默认可先用 `20MHz`,如出现花屏或不稳定再降到 `10MHz` 复测。 + +### 2) 颜色校准(重点) + +- `EXAMPLE_LCD_COLOR_ORDER_BGR` +- `EXAMPLE_LCD_INVERT_COLOR` +- `EXAMPLE_LCD_SWAP_BYTES` + +说明: +- 出现“黑色发灰、红绿蓝偏紫/互串”时,优先调整这三项。 +- 建议从 `RGB + 不反色 + 不交换字节` 起步,再逐项切换。 + +### 3) 方向与偏移(重点) + +- `EXAMPLE_LCD_GAP_X` +- `EXAMPLE_LCD_GAP_Y` +- `EXAMPLE_LCD_ROT_SWAP_XY` +- `EXAMPLE_LCD_ROT_MIRROR_X` +- `EXAMPLE_LCD_ROT_MIRROR_Y` + +说明: +- 若出现“文字偏移/边缘花屏/方向反了”,优先微调上述宏,不要同时在多层重复旋转。 + +### 4) 调试项 + +- `EXAMPLE_LCD_ENABLE_COLOR_TEST` + - `1`:上电先画 RGB 三色测试图(便于确认硬件链路) + - `0`:跳过测试,直接进入 LVGL + +--- + +## 在主程序中调用 + +```c +#include "esp_check.h" +#include "lvgl_st7789_use.h" + +void app_main(void) +{ + ESP_ERROR_CHECK(start_lvgl_demo()); + ESP_ERROR_CHECK(lvgl_st7789_set_center_text("BotanicalBuddy")); +} +``` + +--- + +## 常见问题 + +### 1) 背光亮但没有内容 + +优先排查: +- 面板型号与驱动是否匹配(当前应为 ST7789) +- SPI 模式、时钟是否过高 +- 方向/偏移参数是否正确 + +### 2) 文字方向反了或显示偏移 + +优先调整: +- `EXAMPLE_LCD_ROT_*` +- `EXAMPLE_LCD_GAP_X / EXAMPLE_LCD_GAP_Y` + +### 3) 想快速确认硬件链路是否通 + +把 `EXAMPLE_LCD_ENABLE_COLOR_TEST` 设为 `1`,观察是否能显示三色图。 + +--- + +## 依赖 + +由组件 `CMakeLists.txt` 声明: + +- `driver` +- `esp_lcd` +- `esp_lvgl_port` diff --git a/components/lvgl_st7789_use/include/lvgl_st7789_use.h b/components/lvgl_st7789_use/include/lvgl_st7789_use.h new file mode 100644 index 0000000..7949316 --- /dev/null +++ b/components/lvgl_st7789_use/include/lvgl_st7789_use.h @@ -0,0 +1,80 @@ + +// SPDX-License-Identifier: MIT +#pragma once + +#include "esp_err.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/* LCD pins */ +#ifndef EXAMPLE_LCD_GPIO_SCLK +#define EXAMPLE_LCD_GPIO_SCLK CONFIG_LVGL_ST7789_GPIO_SCLK +#endif +#ifndef EXAMPLE_LCD_GPIO_MOSI +#define EXAMPLE_LCD_GPIO_MOSI CONFIG_LVGL_ST7789_GPIO_MOSI +#endif +#ifndef EXAMPLE_LCD_GPIO_RST +#define EXAMPLE_LCD_GPIO_RST CONFIG_LVGL_ST7789_GPIO_RST +#endif +#ifndef EXAMPLE_LCD_GPIO_DC +#define EXAMPLE_LCD_GPIO_DC CONFIG_LVGL_ST7789_GPIO_DC +#endif +#ifndef EXAMPLE_LCD_GPIO_CS +#define EXAMPLE_LCD_GPIO_CS CONFIG_LVGL_ST7789_GPIO_CS +#endif +#ifndef EXAMPLE_LCD_GPIO_BL +#define EXAMPLE_LCD_GPIO_BL CONFIG_LVGL_ST7789_GPIO_BL +#endif + + +/* LCD size (ST7789 240x240) */ +// 可通过 menuconfig 配置 +#ifndef EXAMPLE_LCD_H_RES +#define EXAMPLE_LCD_H_RES CONFIG_LVGL_ST7789_LCD_H_RES +#endif +#ifndef EXAMPLE_LCD_V_RES +#define EXAMPLE_LCD_V_RES CONFIG_LVGL_ST7789_LCD_V_RES +#endif + +/* LCD SPI总线配置 */ +#define EXAMPLE_LCD_SPI_NUM (SPI2_HOST) // 使用SPI2主机接口进行通信 + +/* LCD显示参数配置 */ +#define EXAMPLE_LCD_PIXEL_CLK_HZ (20 * 1000 * 1000) // ST7789常用20MHz,兼顾稳定性与刷新速度 + +/* LCD命令和参数配置 */ +#define EXAMPLE_LCD_CMD_BITS (8) // 命令位数为8位,用于发送LCD控制命令 +#define EXAMPLE_LCD_PARAM_BITS (8) // 参数位数为8位,用于发送命令参数 + +/* LCD颜色和缓冲区配置 */ +#define EXAMPLE_LCD_BITS_PER_PIXEL (16) // 每个像素使用16位颜色(RGB565格式) +#define EXAMPLE_LCD_DRAW_BUFF_DOUBLE (1) // 启用双缓冲模式,提高显示流畅度 +#define EXAMPLE_LCD_DRAW_BUFF_HEIGHT (50) // 绘图缓冲区高度为50行,影响刷新性能 + +/* ST7789颜色配置(出现偏色时优先调整这三项) */ +#define EXAMPLE_LCD_COLOR_ORDER_BGR (0) // 0: RGB, 1: BGR +#define EXAMPLE_LCD_INVERT_COLOR (1) // 0: 正常色, 1: 反色 +#define EXAMPLE_LCD_SWAP_BYTES (1) // 0: 不交换RGB565高低字节, 1: 交换 + +/* LCD背光配置 */ +#define EXAMPLE_LCD_BL_ON_LEVEL (1) // 背光开启电平为高电平(1) + +/* LCD方向/偏移配置 */ +#define EXAMPLE_LCD_GAP_X (0) +#define EXAMPLE_LCD_GAP_Y (0) +#define EXAMPLE_LCD_ROT_SWAP_XY (1) +#define EXAMPLE_LCD_ROT_MIRROR_X (1) +#define EXAMPLE_LCD_ROT_MIRROR_Y (0) + +/* 调试项:上电后是否先显示三色测试图 */ +#define EXAMPLE_LCD_ENABLE_COLOR_TEST (0) + + +esp_err_t start_lvgl_demo(void); +esp_err_t lvgl_st7789_set_center_text(const char *text); + +#ifdef __cplusplus +} +#endif diff --git a/components/lvgl_st7789_use/lvgl_st7789_use.c b/components/lvgl_st7789_use/lvgl_st7789_use.c new file mode 100644 index 0000000..914f84c --- /dev/null +++ b/components/lvgl_st7789_use/lvgl_st7789_use.c @@ -0,0 +1,257 @@ +#include +#include +#include "lvgl_st7789_use.h" +#include "freertos/FreeRTOS.h" +#include "freertos/task.h" +#include "driver/gpio.h" +#include "driver/spi_master.h" +#include "esp_err.h" +#include "esp_log.h" +#include "esp_check.h" +#include "esp_lcd_panel_io.h" +#include "esp_lcd_panel_vendor.h" +#include "esp_lcd_panel_ops.h" +#include "esp_lvgl_port.h" + +static const char *TAG = "lvgl_st7789_use"; + +static esp_lcd_panel_io_handle_t lcd_io = NULL; +static esp_lcd_panel_handle_t lcd_panel = NULL; +static lv_display_t *lvgl_disp = NULL; +static lv_obj_t *s_center_label = NULL; + +#if EXAMPLE_LCD_ENABLE_COLOR_TEST +static esp_err_t app_lcd_color_test(void) +{ + const size_t pixels = EXAMPLE_LCD_H_RES * EXAMPLE_LCD_V_RES; + uint16_t *frame = calloc(pixels, sizeof(uint16_t)); + ESP_RETURN_ON_FALSE(frame != NULL, ESP_ERR_NO_MEM, TAG, "分配测试帧缓冲失败"); + + for (int y = 0; y < EXAMPLE_LCD_V_RES; y++) { + for (int x = 0; x < EXAMPLE_LCD_H_RES; x++) { + uint16_t color; + if (x < EXAMPLE_LCD_H_RES / 3) { + color = 0xF800; // 红 + } else if (x < (EXAMPLE_LCD_H_RES * 2) / 3) { + color = 0x07E0; // 绿 + } else { + color = 0x001F; // 蓝 + } + frame[y * EXAMPLE_LCD_H_RES + x] = color; + } + } + + esp_err_t err = esp_lcd_panel_draw_bitmap(lcd_panel, 0, 0, EXAMPLE_LCD_H_RES, EXAMPLE_LCD_V_RES, frame); + free(frame); + ESP_RETURN_ON_ERROR(err, TAG, "三色测试绘制失败"); + + ESP_LOGI(TAG, "LCD三色测试图已发送"); + return ESP_OK; +} +#endif + +/** + * @brief 初始化LCD硬件和SPI接口 + * + * 该函数负责初始化LCD所需的GPIO、SPI总线,并配置LCD面板 + * 包括背光控制、SPI总线配置、面板IO配置和面板驱动安装 + * + * @return esp_err_t 初始化结果,ESP_OK表示成功 + */ +static esp_err_t app_lcd_init(void) +{ + esp_err_t ret = ESP_OK; + + if (EXAMPLE_LCD_GPIO_BL != GPIO_NUM_NC && EXAMPLE_LCD_GPIO_BL >= 0) { + gpio_config_t bk_gpio_config = { + .mode = GPIO_MODE_OUTPUT, + .pin_bit_mask = 1ULL << EXAMPLE_LCD_GPIO_BL + }; + ESP_ERROR_CHECK(gpio_config(&bk_gpio_config)); + } else { + ESP_LOGW(TAG, "背光引脚未配置(GPIO_NUM_NC 或 <0),跳过背光GPIO初始化"); + } + + ESP_LOGI(TAG, "初始化SPI总线"); + const spi_bus_config_t buscfg = { + .sclk_io_num = EXAMPLE_LCD_GPIO_SCLK, + .mosi_io_num = EXAMPLE_LCD_GPIO_MOSI, + .miso_io_num = GPIO_NUM_NC, + .quadwp_io_num = GPIO_NUM_NC, + .quadhd_io_num = GPIO_NUM_NC, + .max_transfer_sz = EXAMPLE_LCD_H_RES * EXAMPLE_LCD_DRAW_BUFF_HEIGHT * sizeof(uint16_t), + }; + ESP_RETURN_ON_ERROR(spi_bus_initialize(EXAMPLE_LCD_SPI_NUM, &buscfg, SPI_DMA_CH_AUTO), TAG, "SPI初始化失败"); + + ESP_LOGI(TAG, "安装面板IO"); + const esp_lcd_panel_io_spi_config_t io_config = { + .dc_gpio_num = EXAMPLE_LCD_GPIO_DC, + .cs_gpio_num = EXAMPLE_LCD_GPIO_CS, + .pclk_hz = EXAMPLE_LCD_PIXEL_CLK_HZ, + .lcd_cmd_bits = EXAMPLE_LCD_CMD_BITS, + .lcd_param_bits = EXAMPLE_LCD_PARAM_BITS, + .spi_mode = 0, + .trans_queue_depth = 10, + }; + ESP_GOTO_ON_ERROR(esp_lcd_new_panel_io_spi((esp_lcd_spi_bus_handle_t)EXAMPLE_LCD_SPI_NUM, &io_config, &lcd_io), err, TAG, "创建面板IO失败"); + + ESP_LOGI(TAG, "安装LCD驱动"); + const esp_lcd_panel_dev_config_t panel_config = { + .reset_gpio_num = EXAMPLE_LCD_GPIO_RST, +#if ESP_IDF_VERSION < ESP_IDF_VERSION_VAL(6, 0, 0) + .rgb_endian = EXAMPLE_LCD_COLOR_ORDER_BGR ? LCD_RGB_ENDIAN_BGR : LCD_RGB_ENDIAN_RGB, +#else + .rgb_ele_order = EXAMPLE_LCD_COLOR_ORDER_BGR ? LCD_RGB_ELEMENT_ORDER_BGR : LCD_RGB_ELEMENT_ORDER_RGB, +#endif + .bits_per_pixel = EXAMPLE_LCD_BITS_PER_PIXEL, + }; + + ESP_GOTO_ON_ERROR(esp_lcd_new_panel_st7789(lcd_io, &panel_config, &lcd_panel), err, TAG, "创建面板失败"); + ESP_GOTO_ON_ERROR(esp_lcd_panel_reset(lcd_panel), err, TAG, "面板复位失败"); + ESP_GOTO_ON_ERROR(esp_lcd_panel_init(lcd_panel), err, TAG, "面板初始化失败"); + ESP_GOTO_ON_ERROR(esp_lcd_panel_swap_xy(lcd_panel, false), err, TAG, "设置面板swap_xy失败"); + ESP_GOTO_ON_ERROR(esp_lcd_panel_mirror(lcd_panel, false, false), err, TAG, "设置面板镜像失败"); + + ESP_GOTO_ON_ERROR(esp_lcd_panel_set_gap(lcd_panel, EXAMPLE_LCD_GAP_X, EXAMPLE_LCD_GAP_Y), err, TAG, "设置显示偏移失败"); + ESP_LOGI(TAG, "面板基准参数已应用: gap=(%d,%d)", EXAMPLE_LCD_GAP_X, EXAMPLE_LCD_GAP_Y); + + ESP_GOTO_ON_ERROR(esp_lcd_panel_invert_color(lcd_panel, EXAMPLE_LCD_INVERT_COLOR), err, TAG, "设置反色失败"); + ESP_GOTO_ON_ERROR(esp_lcd_panel_disp_on_off(lcd_panel, true), err, TAG, "打开显示失败"); + + if (EXAMPLE_LCD_GPIO_BL != GPIO_NUM_NC) { + ESP_RETURN_ON_ERROR(gpio_set_level(EXAMPLE_LCD_GPIO_BL, EXAMPLE_LCD_BL_ON_LEVEL), TAG, "背光引脚置位失败"); + ESP_LOGI(TAG, "背光已打开,电平=%d", EXAMPLE_LCD_BL_ON_LEVEL); + } + + ESP_LOGI(TAG, "颜色参数: order=%s invert=%d swap_bytes=%d", + EXAMPLE_LCD_COLOR_ORDER_BGR ? "BGR" : "RGB", + EXAMPLE_LCD_INVERT_COLOR, + EXAMPLE_LCD_SWAP_BYTES); + + return ret; + +// 错误处理标签,用于清理资源 +err: + if (lcd_panel) { + esp_lcd_panel_del(lcd_panel); + lcd_panel = NULL; + } + if (lcd_io) { + esp_lcd_panel_io_del(lcd_io); + lcd_io = NULL; + } + spi_bus_free(EXAMPLE_LCD_SPI_NUM); + return ret; +} + +/** + * @brief 初始化LVGL图形库 + * + * 该函数负责初始化LVGL库,并配置显示设备 + * 包括LVGL任务配置、显示缓冲区配置和旋转设置 + * + * @return esp_err_t 初始化结果,ESP_OK表示成功 + */ +static esp_err_t app_lvgl_init(void) +{ + const lvgl_port_cfg_t lvgl_cfg = { + .task_priority = 4, + .task_stack = 8192, + .task_affinity = -1, + .task_max_sleep_ms = 500, + .timer_period_ms = 5 + }; + ESP_RETURN_ON_ERROR(lvgl_port_init(&lvgl_cfg), TAG, "LVGL端口初始化失败"); + + ESP_LOGI(TAG, "添加LCD屏幕"); + const lvgl_port_display_cfg_t disp_cfg = { + .io_handle = lcd_io, + .panel_handle = lcd_panel, + .buffer_size = EXAMPLE_LCD_H_RES * EXAMPLE_LCD_DRAW_BUFF_HEIGHT, + .double_buffer = EXAMPLE_LCD_DRAW_BUFF_DOUBLE, + .hres = EXAMPLE_LCD_H_RES, + .vres = EXAMPLE_LCD_V_RES, + .monochrome = false, +#if LVGL_VERSION_MAJOR >= 9 + .color_format = LV_COLOR_FORMAT_RGB565, +#endif + .rotation = { + .swap_xy = EXAMPLE_LCD_ROT_SWAP_XY, + .mirror_x = EXAMPLE_LCD_ROT_MIRROR_X, + .mirror_y = EXAMPLE_LCD_ROT_MIRROR_Y, + }, + .flags = { + .buff_dma = true, +#if LVGL_VERSION_MAJOR >= 9 + .swap_bytes = EXAMPLE_LCD_SWAP_BYTES, +#endif + }}; + + lvgl_disp = lvgl_port_add_disp(&disp_cfg); + ESP_RETURN_ON_FALSE(lvgl_disp != NULL, ESP_FAIL, TAG, "添加LVGL显示设备失败"); + ESP_LOGI(TAG, "LVGL旋转已应用: swap_xy=%d mirror_x=%d mirror_y=%d", + EXAMPLE_LCD_ROT_SWAP_XY, EXAMPLE_LCD_ROT_MIRROR_X, EXAMPLE_LCD_ROT_MIRROR_Y); + + return ESP_OK; +} + +/** + * @brief 创建并显示LVGL主界面 + * + * 该函数负责创建LVGL的用户界面元素,包括图像、标签和按钮 + * 并设置它们的位置和属性 + */ +static void app_main_display(void) +{ + lv_obj_t *scr = lv_scr_act(); + + lvgl_port_lock(0); + + lv_obj_set_style_bg_color(scr, lv_color_white(), 0); + lv_obj_set_style_bg_opa(scr, LV_OPA_COVER, 0); + + s_center_label = lv_label_create(scr); + lv_label_set_text(s_center_label, "BotanicalBuddy\nloading..."); + lv_label_set_recolor(s_center_label, false); + lv_label_set_long_mode(s_center_label, LV_LABEL_LONG_WRAP); + lv_obj_set_size(s_center_label, EXAMPLE_LCD_H_RES - 6, EXAMPLE_LCD_V_RES - 6); + lv_obj_set_style_text_color(s_center_label, lv_color_black(), 0); + lv_obj_set_style_text_font(s_center_label, &lv_font_montserrat_14, 0); + lv_obj_set_style_text_align(s_center_label, LV_TEXT_ALIGN_CENTER, 0); + lv_obj_set_style_pad_all(s_center_label, 0, 0); + lv_obj_align(s_center_label, LV_ALIGN_CENTER, 0, 0); + + lvgl_port_unlock(); +} + +/** + * @brief 启动LVGL演示程序 + * + * 该函数是程序的入口点,负责初始化LCD硬件、LVGL库,并显示主界面 + */ +esp_err_t lvgl_st7789_set_center_text(const char *text) +{ + ESP_RETURN_ON_FALSE(text != NULL, ESP_ERR_INVALID_ARG, TAG, "text is null"); + ESP_RETURN_ON_FALSE(s_center_label != NULL, ESP_ERR_INVALID_STATE, TAG, "label not ready"); + + lvgl_port_lock(0); + lv_label_set_text(s_center_label, text); + lv_obj_align(s_center_label, LV_ALIGN_CENTER, 0, 0); + lvgl_port_unlock(); + return ESP_OK; +} + +esp_err_t start_lvgl_demo(void) +{ + ESP_RETURN_ON_ERROR(app_lcd_init(), TAG, "LCD初始化失败"); + +#if EXAMPLE_LCD_ENABLE_COLOR_TEST + ESP_RETURN_ON_ERROR(app_lcd_color_test(), TAG, "LCD测试图绘制失败"); + vTaskDelay(pdMS_TO_TICKS(300)); +#endif + + ESP_RETURN_ON_ERROR(app_lvgl_init(), TAG, "LVGL初始化失败"); + + // app_main_display(); + return ESP_OK; +} diff --git a/components/ui/.eez-project-build b/components/ui/.eez-project-build new file mode 100644 index 0000000..f4eca06 --- /dev/null +++ b/components/ui/.eez-project-build @@ -0,0 +1,18 @@ +{ + "files": [ + "actions.h", + "eez-flow.cpp", + "eez-flow.h", + "fonts.h", + "images.c", + "images.h", + "screens.c", + "screens.h", + "structs.h", + "styles.c", + "styles.h", + "ui.c", + "ui.h", + "vars.h" + ] +} \ No newline at end of file diff --git a/components/ui/CMakeLists.txt b/components/ui/CMakeLists.txt new file mode 100644 index 0000000..96fb663 --- /dev/null +++ b/components/ui/CMakeLists.txt @@ -0,0 +1,6 @@ + +idf_component_register( + SRC_DIRS "." + INCLUDE_DIRS "." + REQUIRES lvgl esp_lvgl_port +) \ No newline at end of file diff --git a/components/ui/actions.h b/components/ui/actions.h new file mode 100644 index 0000000..5e0df4a --- /dev/null +++ b/components/ui/actions.h @@ -0,0 +1,14 @@ +#ifndef EEZ_LVGL_UI_EVENTS_H +#define EEZ_LVGL_UI_EVENTS_H + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +#ifdef __cplusplus +} +#endif + +#endif /*EEZ_LVGL_UI_EVENTS_H*/ \ No newline at end of file diff --git a/components/ui/eez-flow.cpp b/components/ui/eez-flow.cpp new file mode 100644 index 0000000..0d8d87f --- /dev/null +++ b/components/ui/eez-flow.cpp @@ -0,0 +1,9901 @@ +/* Autogenerated on February 9, 2026 10:19:04 AM from eez-framework commit 123e5b8ddf542fe522cd07c6f6d09fcb044ea1db */ +/* + * eez-framework + * + * MIT License + * Copyright 2026 Envox d.o.o. + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + * THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ +#include "eez-flow.h" + +// ----------------------------------------------------------------------------- +// core/action.cpp +// ----------------------------------------------------------------------------- +namespace eez { +void executeActionFunction(int actionId) { + eez::flow::executeLvglActionHook(actionId - 1); +} +} +// ----------------------------------------------------------------------------- +// core/alloc.cpp +// ----------------------------------------------------------------------------- +#include +#include +#include +#include +#if defined(__EMSCRIPTEN__) +#include +#include +#endif +namespace eez { +uint32_t g_freeMemoryAtStart; +uint32_t g_allocMemoryAtStart; +void initAllocHeap(uint8_t *heap, size_t heapSize) { + EEZ_UNUSED(heap); + EEZ_UNUSED(heapSize); + getAllocInfo(g_freeMemoryAtStart, g_allocMemoryAtStart); +} +void *alloc(size_t size, uint32_t id) { + EEZ_UNUSED(id); +#if LVGL_VERSION_MAJOR >= 9 + return lv_malloc(size); +#else + return lv_mem_alloc(size); +#endif +} +void free(void *ptr) { +#if LVGL_VERSION_MAJOR >= 9 + lv_free(ptr); +#else + lv_mem_free(ptr); +#endif +} +template void freeObject(T *ptr) { + ptr->~T(); +#if LVGL_VERSION_MAJOR >= 9 + lv_free(ptr); +#else + lv_mem_free(ptr); +#endif +} +void getAllocInfo(uint32_t &free, uint32_t &alloc) { +#if defined(__EMSCRIPTEN__) && LV_USE_STDLIB_MALLOC == LV_STDLIB_CLIB + size_t total_heap = emscripten_get_heap_size(); + size_t heap_break = (size_t)sbrk(0); + free = total_heap - heap_break; + alloc = heap_break - g_allocMemoryAtStart; +#else + lv_mem_monitor_t mon; + lv_mem_monitor(&mon); + free = mon.free_size; + alloc = mon.total_size - mon.free_size - g_allocMemoryAtStart; +#endif +} +} +// ----------------------------------------------------------------------------- +// core/assets.cpp +// ----------------------------------------------------------------------------- +#include +#include +#include +#define SCPI_ERROR_OUT_OF_DEVICE_MEMORY -321 +#define SCPI_ERROR_INVALID_BLOCK_DATA -161 +namespace eez { +Assets *g_mainAssets; +bool g_mainAssetsAreMutable; +void fixOffsets(Assets *assets); +bool decompressAssetsData(const uint8_t *assetsData, uint32_t assetsDataSize, Assets *decompressedAssets, uint32_t maxDecompressedAssetsSize, int *err) { + EEZ_UNUSED(assetsData); + EEZ_UNUSED(assetsDataSize); + EEZ_UNUSED(decompressedAssets); + EEZ_UNUSED(maxDecompressedAssetsSize); + *err = -1; + return false; +} +static void allocMemoryForDecompressedAssets(const uint8_t *assetsData, uint32_t assetsDataSize, uint8_t *&decompressedAssetsMemoryBuffer, uint32_t &decompressedAssetsMemoryBufferSize) { + EEZ_UNUSED(assetsDataSize); +#ifdef __GNUC__ +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Winvalid-offsetof" +#endif + auto decompressedDataOffset = offsetof(Assets, settings); +#ifdef __GNUC__ +#pragma GCC diagnostic pop +#endif + auto header = (Header *)assetsData; + assert (header->tag == HEADER_TAG_COMPRESSED); + uint32_t decompressedSize = header->decompressedSize; + decompressedAssetsMemoryBufferSize = decompressedDataOffset + decompressedSize; + decompressedAssetsMemoryBuffer = (uint8_t *)eez::alloc(decompressedAssetsMemoryBufferSize, 0x587da194); +} +void loadMainAssets(const uint8_t *assets, uint32_t assetsSize) { + auto header = (Header *)assets; + if (header->tag == HEADER_TAG) { + g_mainAssets = (Assets *)(assets + sizeof(uint32_t)); + g_mainAssetsAreMutable = false; + } else { + uint8_t *DECOMPRESSED_ASSETS_START_ADDRESS = 0; + uint32_t MAX_DECOMPRESSED_ASSETS_SIZE = 0; + allocMemoryForDecompressedAssets(assets, assetsSize, DECOMPRESSED_ASSETS_START_ADDRESS, MAX_DECOMPRESSED_ASSETS_SIZE); + g_mainAssets = (Assets *)DECOMPRESSED_ASSETS_START_ADDRESS; + g_mainAssetsAreMutable = true; + g_mainAssets->external = false; + auto decompressedSize = decompressAssetsData(assets, assetsSize, g_mainAssets, MAX_DECOMPRESSED_ASSETS_SIZE, nullptr); + assert(decompressedSize); + } +} +int getThemesCount() { + return (int)g_mainAssets->colorsDefinition->themes.count; +} +static Theme *getTheme(int i) { + if (i < 0 || i >= (int)g_mainAssets->colorsDefinition->themes.count) { + return nullptr; + } + return g_mainAssets->colorsDefinition->themes[i]; +} +const char *getThemeName(int i) { + auto theme = getTheme(i); + if (!theme) { + return ""; + } + return static_cast(theme->name); +} +uint32_t getThemeColorsCount(int themeIndex) { + auto theme = getTheme(themeIndex); + if (!theme) { + return 0; + } + return theme->colors.count; +} +const uint16_t *getThemeColors(int themeIndex) { + auto theme = getTheme(themeIndex); + if (!theme) { + static uint16_t *g_themeColors = { 0 }; + return g_themeColors; + } + return static_cast(theme->colors.items); +} +const uint16_t *getColors() { + return static_cast(g_mainAssets->colorsDefinition->colors.items); +} +} +// ----------------------------------------------------------------------------- +// core/debug.cpp +// ----------------------------------------------------------------------------- +#ifdef DEBUG +#include +#include +#include +namespace eez { +namespace debug { +void Trace(TraceType traceType, const char *format, ...) { + va_list args; + va_start(args, format); + static const size_t BUFFER_SIZE = 256; + char buffer[BUFFER_SIZE + 1]; + vsnprintf(buffer, BUFFER_SIZE, format, args); + buffer[BUFFER_SIZE] = 0; + va_end(args); + if (traceType == TRACE_TYPE_DEBUG) { + pushDebugTraceHook(buffer, strlen(buffer)); + } else if (traceType == TRACE_TYPE_INFO) { + pushInfoTraceHook(buffer, strlen(buffer)); + } else { + pushErrorTraceHook(buffer, strlen(buffer)); + } +} +} +} +extern "C" void debug_trace(const char *str, size_t len) { + eez::debug::pushDebugTraceHook(str, len); +} +#endif +// ----------------------------------------------------------------------------- +// core/memory.cpp +// ----------------------------------------------------------------------------- +#include +namespace eez { +uint8_t *DECOMPRESSED_ASSETS_START_ADDRESS; +uint8_t *FLOW_TO_DEBUGGER_MESSAGE_BUFFER; +uint8_t *ALLOC_BUFFER = 0; +uint32_t ALLOC_BUFFER_SIZE = 0; +void initMemory() { + initAssetsMemory(); + initOtherMemory(); +} +void initAssetsMemory() { +#if defined(LV_MEM_SIZE) + ALLOC_BUFFER_SIZE = LV_MEM_SIZE; +#endif +} +void initOtherMemory() { +} +uint8_t *allocBuffer(uint32_t size) { +#if LVGL_VERSION_MAJOR >= 9 + return (uint8_t *)lv_malloc(size); +#else + return (uint8_t *)lv_mem_alloc(size); +#endif +} +} +// ----------------------------------------------------------------------------- +// core/os.cpp +// ----------------------------------------------------------------------------- +#if defined(__EMSCRIPTEN__) +#include +#endif +namespace eez { +uint32_t millis() { +#if defined(__EMSCRIPTEN__) + return (uint32_t)emscripten_get_now(); +#else + return lv_tick_get(); +#endif +} +} +// ----------------------------------------------------------------------------- +// core/unit.cpp +// ----------------------------------------------------------------------------- +#include +namespace eez { +const char *g_unitNames[] = { + "", + "V", + "mV", + "A", + "mA", + "uA", + "W", + "mW", + "s", + "ms", + DEGREE_SYMBOL"C", + "rpm", + "\xb4", + "K\xb4", + "M\xb4", + "%", + "Hz", + "mHz", + "KHz", + "MHz", + "J", + "F", + "mF", + "uF", + "nF", + "pF", + "minutes", + "VA", + "VAR", + DEGREE_SYMBOL, + "Vpp", + "mVpp", + "App", + "mApp", + "uApp", +}; +const Unit g_baseUnit[] = { + UNIT_NONE, + UNIT_VOLT, + UNIT_VOLT, + UNIT_AMPER, + UNIT_AMPER, + UNIT_AMPER, + UNIT_WATT, + UNIT_WATT, + UNIT_SECOND, + UNIT_SECOND, + UNIT_CELSIUS, + UNIT_RPM, + UNIT_OHM, + UNIT_OHM, + UNIT_OHM, + UNIT_PERCENT, + UNIT_HERTZ, + UNIT_HERTZ, + UNIT_HERTZ, + UNIT_HERTZ, + UNIT_JOULE, + UNIT_FARAD, + UNIT_FARAD, + UNIT_FARAD, + UNIT_FARAD, + UNIT_FARAD, + UNIT_SECOND, + UNIT_VOLT_AMPERE, + UNIT_VOLT_AMPERE, + UNIT_DEGREE, + UNIT_VOLT_PP, + UNIT_VOLT_PP, + UNIT_AMPER_PP, + UNIT_AMPER_PP, + UNIT_AMPER_PP, +}; +const float g_unitFactor[] = { + 1.0f, + 1.0f, + 1E-3f, + 1.0f, + 1E-3f, + 1E-6f, + 1.0f, + 1E-3f, + 1.0f, + 1E-3f, + 1.0f, + 1.0f, + 1.0f, + 1E3f, + 1E6f, + 1.0f, + 1.0f, + 1E-3f, + 1E3f, + 1E6f, + 1.0f, + 1.0f, + 1E-3f, + 1E-6f, + 1E-9f, + 1E-12f, + 60.0f, + 1.0f, + 1.0f, + 1.0f, + 1.0f, + 1E-3f, + 1.0f, + 1E-3f, + 1E-6f, +}; +Unit getUnitFromName(const char *unitName) { + if (unitName) { + for (unsigned i = 0; i < sizeof(g_unitNames) / sizeof(const char *); i++) { + if (strcmp(g_unitNames[i], unitName) == 0) { + return (Unit)i; + } + } + } + return UNIT_NONE; +} +Unit getBaseUnit(Unit unit) { + if (unit == UNIT_UNKNOWN) { + return UNIT_UNKNOWN; + } + return g_baseUnit[unit]; +} +float getUnitFactor(Unit unit) { + if (unit == UNIT_UNKNOWN) { + return 1.0f; + } + return g_unitFactor[unit]; +} +static Unit getDerivedUnit(Unit unit, float factor) { + if (unit == UNIT_UNKNOWN) { + return UNIT_UNKNOWN; + } + for (size_t i = 0; i < sizeof(g_baseUnit) / sizeof(Unit); i++) { + if (g_baseUnit[i] == g_baseUnit[unit] && g_unitFactor[i] == factor) { + return (Unit)i; + } + } + return UNIT_UNKNOWN; +} +static const float FACTORS[] = { 1E-12F, 1E-9F, 1E-6F, 1E-3F, 1E0F, 1E3F, 1E6F, 1E9F, 1E12F }; +Unit findDerivedUnit(float value, Unit unit) { + Unit result; + for (int factorIndex = 1; ; factorIndex++) { + float factor = FACTORS[factorIndex]; + if (factor > 1.0F) { + break; + } + if (value < factor) { + result = getDerivedUnit(unit, FACTORS[factorIndex - 1]); + if (result != UNIT_UNKNOWN) { + return result; + } + } + } + for (int factorIndex = sizeof(FACTORS) / sizeof(float) - 1; factorIndex >= 0; factorIndex--) { + float factor = FACTORS[factorIndex]; + if (factor == 1.0F) { + break; + } + if (value >= factor) { + result = getDerivedUnit(unit, factor); + if (result != UNIT_UNKNOWN) { + return result; + } + } + } + return unit; +} +static float getSmallerFactor(float factor) { + for (int factorIndex = sizeof(FACTORS) / sizeof(float) - 1; factorIndex > 0; factorIndex--) { + float itFactor = FACTORS[factorIndex]; + if (itFactor < factor) { + return itFactor; + } + } + return FACTORS[0]; +} +Unit getSmallerUnit(Unit unit, float min, float precision) { + float factor = getUnitFactor(unit); + if (precision <= factor || min <= factor) { + return getDerivedUnit(unit, getSmallerFactor(factor)); + } + return UNIT_UNKNOWN; +} +Unit getBiggestUnit(Unit unit, float max) { + for (int factorIndex = sizeof(FACTORS) / sizeof(float) - 1; factorIndex >= 0; factorIndex--) { + float factor = FACTORS[factorIndex]; + if (max >= factor) { + auto result = getDerivedUnit(unit, factor); + if (result != UNIT_UNKNOWN) { + return result; + } + } + } + return UNIT_UNKNOWN; +} +Unit getSmallestUnit(Unit unit, float min, float precision) { + for (int factorIndex = 0; factorIndex < int(sizeof(FACTORS) / sizeof(float)); factorIndex++) { + float factor = FACTORS[factorIndex]; + if (precision <= factor || min <= factor) { + auto result = getDerivedUnit(unit, factor); + if (result != UNIT_UNKNOWN) { + return result; + } + } + } + return UNIT_UNKNOWN; +} +} +// ----------------------------------------------------------------------------- +// core/util.cpp +// ----------------------------------------------------------------------------- +#define _USE_MATH_DEFINES +#include +#include +#include +#include +namespace eez { +float remap(float x, float x1, float y1, float x2, float y2) { + return y1 + (x - x1) * (y2 - y1) / (x2 - x1); +} +float remapQuad(float x, float x1, float y1, float x2, float y2) { + float t = remap(x, x1, 0, x2, 1); + t = t * t; + x = remap(t, 0, x1, 1, x2); + return remap(x, x1, y1, x2, y2); +} +float remapOutQuad(float x, float x1, float y1, float x2, float y2) { + float t = remap(x, x1, 0, x2, 1); + t = t * (2 - t); + x = remap(t, 0, x1, 1, x2); + return remap(x, x1, y1, x2, y2); +} +float remapInOutQuad(float x, float x1, float y1, float x2, float y2) { + float t = remap(x, x1, 0, x2, 1); + t = t < .5 ? 2 * t*t : -1 + (4 - 2 * t)*t; + x = remap(t, 0, x1, 1, x2); + return remap(x, x1, y1, x2, y2); +} +float remapCubic(float x, float x1, float y1, float x2, float y2) { + float t = remap(x, x1, 0, x2, 1); + t = t * t * t; + x = remap(t, 0, x1, 1, x2); + return remap(x, x1, y1, x2, y2); +} +float remapOutCubic(float x, float x1, float y1, float x2, float y2) { + float t = remap(x, x1, 0, x2, 1); + t = t - 1; + t = 1 + t * t * t; + x = remap(t, 0, x1, 1, x2); + return remap(x, x1, y1, x2, y2); +} +float remapExp(float x, float x1, float y1, float x2, float y2) { + float t = remap(x, x1, 0, x2, 1); + t = t == 0 ? 0 : float(pow(2, 10 * (t - 1))); + x = remap(t, 0, x1, 1, x2); + return remap(x, x1, y1, x2, y2); +} +float remapOutExp(float x, float x1, float y1, float x2, float y2) { + float t = remap(x, x1, 0, x2, 1); + t = t == 1 ? 1 : float(1 - pow(2, -10 * t)); + x = remap(t, 0, x1, 1, x2); + return remap(x, x1, y1, x2, y2); +} +float clamp(float x, float min, float max) { + if (x < min) { + return min; + } + if (x > max) { + return max; + } + return x; +} +void stringCopy(char *dst, size_t maxStrLength, const char *src) { + strncpy(dst, src, maxStrLength); + dst[maxStrLength - 1] = 0; +} +void stringCopyLength(char *dst, size_t maxStrLength, const char *src, size_t length) { + size_t n = MIN(length, maxStrLength); + strncpy(dst, src, n); + dst[n] = 0; +} +void stringAppendString(char *str, size_t maxStrLength, const char *value) { + int n = maxStrLength - strlen(str) - 1; + if (n >= 0) { + strncat(str, value, n); + } +} +void stringAppendStringLength(char *str, size_t maxStrLength, const char *value, size_t length) { + int n = MIN(maxStrLength - strlen(str) - 1, length); + if (n >= 0) { + strncat(str, value, n); + } +} +void stringAppendInt(char *str, size_t maxStrLength, int value) { + auto n = strlen(str); + snprintf(str + n, maxStrLength - n, "%d", value); +} +void stringAppendUInt32(char *str, size_t maxStrLength, uint32_t value) { + auto n = strlen(str); + snprintf(str + n, maxStrLength - n, "%lu", (unsigned long)value); +} +void stringAppendInt64(char *str, size_t maxStrLength, int64_t value) { + auto n = strlen(str); + snprintf(str + n, maxStrLength - n, "%jd", value); +} +void stringAppendUInt64(char *str, size_t maxStrLength, uint64_t value) { + auto n = strlen(str); + snprintf(str + n, maxStrLength - n, "%ju", value); +} +void stringAppendFloat(char *str, size_t maxStrLength, float value) { + auto n = strlen(str); + snprintf(str + n, maxStrLength - n, "%g", value); +} +void stringAppendFloat(char *str, size_t maxStrLength, float value, int numDecimalPlaces) { + auto n = strlen(str); + snprintf(str + n, maxStrLength - n, "%.*f", numDecimalPlaces, value); +} +void stringAppendDouble(char *str, size_t maxStrLength, double value) { + auto n = strlen(str); + snprintf(str + n, maxStrLength - n, "%g", value); +} +void stringAppendDouble(char *str, size_t maxStrLength, double value, int numDecimalPlaces) { + auto n = strlen(str); + snprintf(str + n, maxStrLength - n, "%.*f", numDecimalPlaces, value); +} +void stringAppendVoltage(char *str, size_t maxStrLength, float value) { + auto n = strlen(str); + snprintf(str + n, maxStrLength - n, "%g V", value); +} +void stringAppendCurrent(char *str, size_t maxStrLength, float value) { + auto n = strlen(str); + snprintf(str + n, maxStrLength - n, "%g A", value); +} +void stringAppendPower(char *str, size_t maxStrLength, float value) { + auto n = strlen(str); + snprintf(str + n, maxStrLength - n, "%g W", value); +} +void stringAppendDuration(char *str, size_t maxStrLength, float value) { + auto n = strlen(str); + if (value > 0.1) { + snprintf(str + n, maxStrLength - n, "%g s", value); + } else { + snprintf(str + n, maxStrLength - n, "%g ms", value * 1000); + } +} +void stringAppendLoad(char *str, size_t maxStrLength, float value) { + auto n = strlen(str); + if (value < 1000) { + snprintf(str + n, maxStrLength - n, "%g ohm", value); + } else if (value < 1000000) { + snprintf(str + n, maxStrLength - n, "%g Kohm", value / 1000); + } else { + snprintf(str + n, maxStrLength - n, "%g Mohm", value / 1000000); + } +} +uint32_t crc32(const uint8_t *mem_block, size_t block_size) { + uint32_t crc = 0xFFFFFFFF; + for (size_t i = 0; i < block_size; ++i) { + uint32_t byte = mem_block[i]; + crc = crc ^ byte; + for (int j = 0; j < 8; ++j) { + uint32_t mask = -((int32_t)crc & 1); + crc = (crc >> 1) ^ (0xEDB88320 & mask); + } + } + return ~crc; +} +uint8_t toBCD(uint8_t bin) { + return ((bin / 10) << 4) | (bin % 10); +} +uint8_t fromBCD(uint8_t bcd) { + return ((bcd >> 4) & 0xF) * 10 + (bcd & 0xF); +} +float roundPrec(float a, float prec) { + float r = 1 / prec; + return roundf(a * r) / r; +} +float floorPrec(float a, float prec) { + float r = 1 / prec; + return floorf(a * r) / r; +} +float ceilPrec(float a, float prec) { + float r = 1 / prec; + return ceilf(a * r) / r; +} +bool isNaN(float x) { + return x != x; +} +bool isNaN(double x) { + return x != x; +} +bool isDigit(char ch) { + return ch >= '0' && ch <= '9'; +} +bool isHexDigit(char ch) { + return (ch >= '0' && ch <= '9') || (ch >= 'a' && ch <= 'f') || (ch >= 'A' && ch <= 'F'); +} +bool isUperCaseLetter(char ch) { + return ch >= 'A' && ch <= 'Z'; +} +char toHexDigit(int num) { + if (num >= 0 && num <= 9) { + return '0' + num; + } else { + return 'A' + (num - 10); + } +} +int fromHexDigit(char ch) { + if (ch >= '0' && ch <= '9') { + return ch - '0'; + } + if (ch >= 'a' && ch <= 'f') { + return 10 + (ch - 'a'); + } + return 10 + (ch - 'A'); +} +bool pointInsideRect(int xPoint, int yPoint, int xRect, int yRect, int wRect, int hRect) { + return xPoint >= xRect && xPoint < xRect + wRect && yPoint >= yRect && yPoint < yRect + hRect; +} +void getParentDir(const char *path, char *parentDirPath) { + int lastPathSeparatorIndex; + for (lastPathSeparatorIndex = strlen(path) - 1; + lastPathSeparatorIndex >= 0 && path[lastPathSeparatorIndex] != PATH_SEPARATOR[0]; + --lastPathSeparatorIndex) + ; + int i; + for (i = 0; i < lastPathSeparatorIndex; ++i) { + parentDirPath[i] = path[i]; + } + parentDirPath[i] = 0; +} +bool parseMacAddress(const char *macAddressStr, size_t macAddressStrLength, uint8_t *macAddress) { + int state = 0; + int a = 0; + int i = 0; + uint8_t resultMacAddress[6]; + const char *end = macAddressStr + macAddressStrLength; + for (const char *p = macAddressStr; p < end; ++p) { + if (state == 0) { + if (*p == '-' || *p == ' ') { + continue; + } else if (isHexDigit(*p)) { + a = fromHexDigit(*p); + state = 1; + } else { + return false; + } + } else if (state == 1) { + if (isHexDigit(*p)) { + if (i < 6) { + resultMacAddress[i++] = (a << 4) | fromHexDigit(*p); + state = 0; + } else { + return false; + } + } else { + return false; + } + } + } + if (state != 0 || i != 6) { + return false; + } + memcpy(macAddress, resultMacAddress, 6); + return true; +} +bool parseIpAddress(const char *ipAddressStr, size_t ipAddressStrLength, uint32_t &ipAddress) { + const char *p = ipAddressStr; + const char *q = ipAddressStr + ipAddressStrLength; + uint8_t ipAddressArray[4]; + for (int i = 0; i < 4; ++i) { + if (p == q) { + return false; + } + uint32_t part = 0; + for (int j = 0; j < 3; ++j) { + if (p == q) { + if (j > 0 && i == 3) { + break; + } else { + return false; + } + } else if (isDigit(*p)) { + part = part * 10 + (*p++ - '0'); + } else if (j > 0 && *p == '.') { + break; + } else { + return false; + } + } + if (part > 255) { + return false; + } + if ((i < 3 && *p++ != '.') || (i == 3 && p != q)) { + return false; + } + ipAddressArray[i] = part; + } + ipAddress = arrayToIpAddress(ipAddressArray); + return true; +} +int getIpAddressPartA(uint32_t ipAddress) { + return ((uint8_t *)&ipAddress)[0]; +} +void setIpAddressPartA(uint32_t *ipAddress, uint8_t value) { + ((uint8_t *)ipAddress)[0] = value; +} +int getIpAddressPartB(uint32_t ipAddress) { + return ((uint8_t *)&ipAddress)[1]; +} +void setIpAddressPartB(uint32_t *ipAddress, uint8_t value) { + ((uint8_t *)ipAddress)[1] = value; +} +int getIpAddressPartC(uint32_t ipAddress) { + return ((uint8_t *)&ipAddress)[2]; +} +void setIpAddressPartC(uint32_t *ipAddress, uint8_t value) { + ((uint8_t *)ipAddress)[2] = value; +} +int getIpAddressPartD(uint32_t ipAddress) { + return ((uint8_t *)&ipAddress)[3]; +} +void setIpAddressPartD(uint32_t *ipAddress, uint8_t value) { + ((uint8_t *)ipAddress)[3] = value; +} +void ipAddressToArray(uint32_t ipAddress, uint8_t *ipAddressArray) { + ipAddressArray[0] = getIpAddressPartA(ipAddress); + ipAddressArray[1] = getIpAddressPartB(ipAddress); + ipAddressArray[2] = getIpAddressPartC(ipAddress); + ipAddressArray[3] = getIpAddressPartD(ipAddress); +} +uint32_t arrayToIpAddress(uint8_t *ipAddressArray) { + return getIpAddress(ipAddressArray[0], ipAddressArray[1], ipAddressArray[2], ipAddressArray[3]); +} +uint32_t getIpAddress(uint8_t a, uint8_t b, uint8_t c, uint8_t d) { + uint32_t ipAddress; + setIpAddressPartA(&ipAddress, a); + setIpAddressPartB(&ipAddress, b); + setIpAddressPartC(&ipAddress, c); + setIpAddressPartD(&ipAddress, d); + return ipAddress; +} +void ipAddressToString(uint32_t ipAddress, char *ipAddressStr, size_t maxIpAddressStrLength) { + snprintf(ipAddressStr, maxIpAddressStrLength, "%d.%d.%d.%d", + getIpAddressPartA(ipAddress), getIpAddressPartB(ipAddress), + getIpAddressPartC(ipAddress), getIpAddressPartD(ipAddress)); +} +void macAddressToString(const uint8_t *macAddress, char *macAddressStr) { + for (int i = 0; i < 6; ++i) { + macAddressStr[3 * i] = toHexDigit((macAddress[i] & 0xF0) >> 4); + macAddressStr[3 * i + 1] = toHexDigit(macAddress[i] & 0xF); + macAddressStr[3 * i + 2] = i < 5 ? '-' : 0; + } +} +void formatTimeZone(int16_t timeZone, char *text, int count) { + if (timeZone == 0) { + stringCopy(text, count, "GMT"); + } else { + char sign; + int16_t value; + if (timeZone > 0) { + sign = '+'; + value = timeZone; + } else { + sign = '-'; + value = -timeZone; + } + snprintf(text, count, "%c%02d:%02d GMT", sign, value / 100, value % 100); + } +} +bool parseTimeZone(const char *timeZoneStr, size_t timeZoneLength, int16_t &timeZone) { + int state = 0; + int sign = 1; + int integerPart = 0; + int fractionPart = 0; + const char *end = timeZoneStr + timeZoneLength; + for (const char *p = timeZoneStr; p < end; ++p) { + if (*p == ' ') { + continue; + } + if (state == 0) { + if (*p == '+') { + state = 1; + } else if (*p == '-') { + sign = -1; + state = 1; + } else if (isDigit(*p)) { + integerPart = *p - '0'; + state = 2; + } else { + return false; + } + } else if (state == 1) { + if (isDigit(*p)) { + integerPart = (*p - '0'); + state = 2; + } else { + return false; + } + } else if (state == 2) { + if (*p == ':') { + state = 4; + } else if (isDigit(*p)) { + integerPart = integerPart * 10 + (*p - '0'); + state = 3; + } else { + return false; + } + } else if (state == 3) { + if (*p == ':') { + state = 4; + } else { + return false; + } + } else if (state == 4) { + if (isDigit(*p)) { + fractionPart = (*p - '0'); + state = 5; + } else { + return false; + } + } else if (state == 5) { + if (isDigit(*p)) { + fractionPart = fractionPart * 10 + (*p - '0'); + state = 6; + } else { + return false; + } + } else { + return false; + } + } + if (state != 2 && state != 3 && state != 6) { + return false; + } + int value = sign * (integerPart * 100 + fractionPart); + if (value < -1200 || value > 1400) { + return false; + } + timeZone = (int16_t)value; + return true; +} +void replaceCharacter(char *str, char ch, char repl) { + while (*str) { + if (*str == ch) { + *str = repl; + } + ++str; + } +} +int strcicmp(char const *a, char const *b) { + for (;; a++, b++) { + int d = tolower((unsigned char)*a) - tolower((unsigned char)*b); + if (d != 0 || !*a) + return d; + } +} +int strncicmp(char const *a, char const *b, int n) { + for (; n--; a++, b++) { + int d = tolower((unsigned char)*a) - tolower((unsigned char)*b); + if (d != 0 || !*a) + return d; + } + return 0; +} +bool isStringEmpty(char const *s) { + for (; *s; s++) { + if (!isspace(*s)) { + return false; + } + } + return true; +} +bool startsWith(const char *str, const char *prefix) { + if (!str || !prefix) + return false; + size_t strLen = strlen(str); + size_t prefixLen = strlen(prefix); + if (prefixLen > strLen) + return false; + return strncmp(str, prefix, prefixLen) == 0; +} +bool startsWithNoCase(const char *str, const char *prefix) { + if (!str || !prefix) + return false; + size_t strLen = strlen(str); + size_t prefixLen = strlen(prefix); + if (prefixLen > strLen) + return false; + return strncicmp(str, prefix, prefixLen) == 0; +} +bool endsWith(const char *str, const char *suffix) { + if (!str || !suffix) + return false; + size_t strLen = strlen(str); + size_t suffixLen = strlen(suffix); + if (suffixLen > strLen) + return false; + return strncmp(str + strLen - suffixLen, suffix, suffixLen) == 0; +} +bool endsWithNoCase(const char *str, const char *suffix) { + if (!str || !suffix) + return false; + size_t strLen = strlen(str); + size_t suffixLen = strlen(suffix); + if (suffixLen > strLen) + return false; + return strncicmp(str + strLen - suffixLen, suffix, suffixLen) == 0; +} +void formatBytes(uint64_t bytes, char *text, int count) { + if (bytes == 0) { + stringCopy(text, count, "0 Bytes"); + } else { + double c = 1024.0; + const char *e[] = { "Bytes", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB" }; + uint64_t f = (uint64_t)floor(log((double)bytes) / log(c)); + double g = round((bytes / pow(c, (double)f)) * 100) / 100; + snprintf(text, count, "%g %s", g, e[f]); + } +} +void getFileName(const char *path, char *fileName, unsigned fileNameSize) { + const char *a = strrchr(path, '/'); + if (a) { + a++; + } else { + a = path; + } + const char *b = path + strlen(path); + unsigned n = b - a; + n = MIN(fileNameSize - 1, n); + if (n > 0) { + memcpy(fileName, a, n); + } + fileName[n] = 0; +} +void getBaseFileName(const char *path, char *baseName, unsigned baseNameSize) { + const char *a = strrchr(path, '/'); + if (a) { + a++; + } else { + a = path; + } + const char *b = strrchr(path, '.'); + if (!b || !(b >= a)) { + b = path + strlen(path); + } + unsigned n = b - a; + n = MIN(baseNameSize - 1, n); + if (n > 0) { + memcpy(baseName, a, n); + } + baseName[n] = 0; +} +} +#if defined(M_PI) +static const float PI_FLOAT = (float)M_PI; +#else +static const float PI_FLOAT = (float)3.14159265358979323846; +#endif +static const float c1 = 1.70158f; +static const float c2 = c1 * 1.525f; +static const float c3 = c1 + 1.0f; +static const float c4 = (2 * PI_FLOAT) / 3; +static const float c5 = (2 * PI_FLOAT) / 4.5f; +extern "C" float eez_linear(float x) { + return x; +} +extern "C" float eez_easeInQuad(float x) { + return x * x; +} +extern "C" float eez_easeOutQuad(float x) { + return 1 - (1 - x) * (1 - x); +} +extern "C" float eez_easeInOutQuad(float x) { + return x < 0.5f ? 2 * x * x : 1 - powf(-2 * x + 2, 2) / 2; +} +extern "C" float eez_easeInCubic(float x) { + return x * x * x; +} +extern "C" float eez_easeOutCubic(float x) { + return 1 - powf(1 - x, 3); +} +extern "C" float eez_easeInOutCubic(float x) { + return x < 0.5f ? 4 * x * x * x : 1 - powf(-2 * x + 2, 3) / 2; +} +extern "C" float eez_easeInQuart(float x) { + return x * x * x * x; +} +extern "C" float eez_easeOutQuart(float x) { + return 1 - powf(1 - x, 4); +} +extern "C" float eez_easeInOutQuart(float x) { + return x < 0.5 ? 8 * x * x * x * x : 1 - powf(-2 * x + 2, 4) / 2; +} +extern "C" float eez_easeInQuint(float x) { + return x * x * x * x * x; +} +extern "C" float eez_easeOutQuint(float x) { + return 1 - powf(1 - x, 5); +} +extern "C" float eez_easeInOutQuint(float x) { + return x < 0.5f ? 16 * x * x * x * x * x : 1 - powf(-2 * x + 2, 5) / 2; +} +extern "C" float eez_easeInSine(float x) { + return 1 - cosf((x * PI_FLOAT) / 2); +} +extern "C" float eez_easeOutSine(float x) { + return sinf((x * PI_FLOAT) / 2); +} +extern "C" float eez_easeInOutSine(float x) { + return -(cosf(PI_FLOAT * x) - 1) / 2; +} +extern "C" float eez_easeInExpo(float x) { + return x == 0 ? 0 : powf(2, 10 * x - 10); +} +extern "C" float eez_easeOutExpo(float x) { + return x == 1 ? 1 : 1 - powf(2, -10 * x); +} +extern "C" float eez_easeInOutExpo(float x) { + return x == 0 + ? 0 + : x == 1 + ? 1 + : x < 0.5 + ? powf(2, 20 * x - 10) / 2 + : (2 - powf(2, -20 * x + 10)) / 2; +} +extern "C" float eez_easeInCirc(float x) { + return 1 - sqrtf(1 - powf(x, 2)); +} +extern "C" float eez_easeOutCirc(float x) { + return sqrtf(1 - powf(x - 1, 2)); +} +extern "C" float eez_easeInOutCirc(float x) { + return x < 0.5 + ? (1 - sqrtf(1 - powf(2 * x, 2))) / 2 + : (sqrtf(1 - powf(-2 * x + 2, 2)) + 1) / 2; +} +extern "C" float eez_easeInBack(float x) { + return c3 * x * x * x - c1 * x * x; +} +extern "C" float eez_easeOutBack(float x) { + return 1 + c3 * powf(x - 1, 3) + c1 * powf(x - 1, 2); +} +extern "C" float eez_easeInOutBack(float x) { + return x < 0.5 + ? (powf(2 * x, 2) * ((c2 + 1) * 2 * x - c2)) / 2 + : (powf(2 * x - 2, 2) * ((c2 + 1) * (x * 2 - 2) + c2) + 2) / 2; +} +extern "C" float eez_easeInElastic(float x) { + return x == 0 + ? 0 + : x == 1 + ? 1 + : -powf(2, 10 * x - 10) * sinf((x * 10 - 10.75f) * c4); +} +extern "C" float eez_easeOutElastic(float x) { + return x == 0 + ? 0 + : x == 1 + ? 1 + : powf(2, -10 * x) * sinf((x * 10 - 0.75f) * c4) + 1; +} +extern "C" float eez_easeInOutElastic(float x) { + return x == 0 + ? 0 + : x == 1 + ? 1 + : x < 0.5 + ? -(powf(2, 20 * x - 10) * sinf((20 * x - 11.125f) * c5)) / 2 + : (powf(2, -20 * x + 10) * sinf((20 * x - 11.125f) * c5)) / 2 + 1; +} +extern "C" float eez_easeOutBounce(float x); +extern "C" float eez_easeInBounce(float x) { + return 1 - eez_easeOutBounce(1 - x); +} +extern "C" float eez_easeOutBounce(float x) { + static const float n1 = 7.5625f; + static const float d1 = 2.75f; + if (x < 1 / d1) { + return n1 * x * x; + } else if (x < 2 / d1) { + x -= 1.5f / d1; + return n1 * x * x + 0.75f; + } else if (x < 2.5f / d1) { + x -= 2.25f / d1; + return n1 * x * x + 0.9375f; + } else { + x -= 2.625f / d1; + return n1 * x * x + 0.984375f; + } +}; +extern "C" float eez_easeInOutBounce(float x) { + return x < 0.5 + ? (1 - eez_easeOutBounce(1 - 2 * x)) / 2 + : (1 + eez_easeOutBounce(2 * x - 1)) / 2; +} +namespace eez { +EasingFuncType g_easingFuncs[] = { + eez_linear, + eez_easeInQuad, + eez_easeOutQuad, + eez_easeInOutQuad, + eez_easeInCubic, + eez_easeOutCubic, + eez_easeInOutCubic, + eez_easeInQuart, + eez_easeOutQuart, + eez_easeInOutQuart, + eez_easeInQuint, + eez_easeOutQuint, + eez_easeInOutQuint, + eez_easeInSine, + eez_easeOutSine, + eez_easeInOutSine, + eez_easeInExpo, + eez_easeOutExpo, + eez_easeInOutExpo, + eez_easeInCirc, + eez_easeOutCirc, + eez_easeInOutCirc, + eez_easeInBack, + eez_easeOutBack, + eez_easeInOutBack, + eez_easeInElastic, + eez_easeOutElastic, + eez_easeInOutElastic, + eez_easeInBounce, + eez_easeOutBounce, + eez_easeInOutBounce, +}; +} +// ----------------------------------------------------------------------------- +// core/value.cpp +// ----------------------------------------------------------------------------- +#include +#include +#include +#include +#include +namespace eez { +static bool compare_UNDEFINED_value(const Value &a, const Value &b) { + return b.type == VALUE_TYPE_UNDEFINED && a.int32Value == b.int32Value; +} +static void UNDEFINED_value_to_text(const Value &value, char *text, int count) { + EEZ_UNUSED(value); + EEZ_UNUSED(count); + *text = 0; +} +static const char *UNDEFINED_value_type_name(const Value &value) { + EEZ_UNUSED(value); + return "undefined"; +} +static bool compare_NULL_value(const Value &a, const Value &b) { + EEZ_UNUSED(a); + return b.type == VALUE_TYPE_NULL; +} +static void NULL_value_to_text(const Value &value, char *text, int count) { + EEZ_UNUSED(value); + EEZ_UNUSED(count); + *text = 0; +} +static const char *NULL_value_type_name(const Value &value) { + EEZ_UNUSED(value); + return "null"; +} +static bool compare_BOOLEAN_value(const Value &a, const Value &b) { + return a.type == b.type && a.getInt() == b.getInt(); +} +static void BOOLEAN_value_to_text(const Value &value, char *text, int count) { + if (value.getInt()) { + stringCopy(text, count, "true"); + } else { + stringCopy(text, count, "false"); + } +} +static const char *BOOLEAN_value_type_name(const Value &value) { + EEZ_UNUSED(value); + return "boolean"; +} +static bool compare_INT8_value(const Value &a, const Value &b) { + return a.type == b.type && a.getInt8() == b.getInt8(); +} +static void INT8_value_to_text(const Value &value, char *text, int count) { + stringAppendInt(text, count, value.getInt8()); +} +static const char *INT8_value_type_name(const Value &value) { + EEZ_UNUSED(value); + return "int8"; +} +static bool compare_UINT8_value(const Value &a, const Value &b) { + return a.type == b.type && a.getUInt8() == b.getUInt8(); +} +static void UINT8_value_to_text(const Value &value, char *text, int count) { + stringAppendUInt32(text, count, value.getUInt8()); +} +static const char *UINT8_value_type_name(const Value &value) { + EEZ_UNUSED(value); + return "uint8"; +} +static bool compare_INT16_value(const Value &a, const Value &b) { + return a.type == b.type && a.getInt16() == b.getInt16(); +} +static void INT16_value_to_text(const Value &value, char *text, int count) { + stringAppendInt(text, count, value.getInt16()); +} +static const char *INT16_value_type_name(const Value &value) { + EEZ_UNUSED(value); + return "int16"; +} +static bool compare_UINT16_value(const Value &a, const Value &b) { + return a.type == b.type && a.getUInt16() == b.getUInt16(); +} +static void UINT16_value_to_text(const Value &value, char *text, int count) { + stringAppendUInt32(text, count, value.getUInt16()); +} +static const char *UINT16_value_type_name(const Value &value) { + EEZ_UNUSED(value); + return "uint16"; +} +static bool compare_INT32_value(const Value &a, const Value &b) { + return a.type == b.type && a.getInt32() == b.getInt32(); +} +static void INT32_value_to_text(const Value &value, char *text, int count) { + stringAppendInt(text, count, value.getInt32()); +} +static const char *INT32_value_type_name(const Value &value) { + EEZ_UNUSED(value); + return "int32"; +} +static bool compare_UINT32_value(const Value &a, const Value &b) { + return a.type == b.type && a.getUInt32() == b.getUInt32(); +} +static void UINT32_value_to_text(const Value &value, char *text, int count) { + stringAppendUInt32(text, count, value.getUInt32()); +} +static const char *UINT32_value_type_name(const Value &value) { + EEZ_UNUSED(value); + return "uint32"; +} +static bool compare_INT64_value(const Value &a, const Value &b) { + return a.type == b.type && a.getInt64() == b.getInt64(); +} +static void INT64_value_to_text(const Value &value, char *text, int count) { + stringAppendInt64(text, count, value.getInt64()); +} +static const char *INT64_value_type_name(const Value &value) { + EEZ_UNUSED(value); + return "int64"; +} +static bool compare_UINT64_value(const Value &a, const Value &b) { + return a.type == b.type && a.getUInt64() == b.getUInt64(); +} +static void UINT64_value_to_text(const Value &value, char *text, int count) { + stringAppendUInt64(text, count, value.getUInt64()); +} +static const char *UINT64_value_type_name(const Value &value) { + EEZ_UNUSED(value); + return "uint64"; +} +static bool compare_FLOAT_value(const Value &a, const Value &b) { + return a.type == b.type && a.getUnit() == b.getUnit() && a.getFloat() == b.getFloat() && a.getOptions() == b.getOptions(); +} +static void FLOAT_value_to_text(const Value &value, char *text, int count) { + text[0] = 0; + float floatValue = value.getFloat(); +#if defined(INFINITY_SYMBOL) + if (isinf(floatValue)) { + snprintf(text, count, INFINITY_SYMBOL); + return; + } +#endif + Unit unit = value.getUnit(); + bool appendDotZero = unit == UNIT_VOLT || unit == UNIT_VOLT_PP || unit == UNIT_AMPER || unit == UNIT_AMPER_PP || unit == UNIT_WATT; + uint16_t options = value.getOptions(); + bool fixedDecimals = (options & FLOAT_OPTIONS_FIXED_DECIMALS) != 0; + if (floatValue != 0) { + if (!fixedDecimals) { + unit = findDerivedUnit(floatValue, unit); + floatValue /= getUnitFactor(unit); + } + } else { + floatValue = 0; + } + if (!isNaN(floatValue)) { + if ((value.getOptions() & FLOAT_OPTIONS_LESS_THEN) != 0) { + stringAppendString(text, count, "< "); + appendDotZero = false; + } + if (fixedDecimals) { + stringAppendFloat(text, count, floatValue, FLOAT_OPTIONS_GET_NUM_FIXED_DECIMALS(options)); + } else { + if (unit == UNIT_WATT || unit == UNIT_MILLI_WATT) { + stringAppendFloat(text, count, floatValue, 2); + } else { + stringAppendFloat(text, count, floatValue); + } + int n = strlen(text); + int decimalPointIndex; + for (decimalPointIndex = 0; decimalPointIndex < n; ++decimalPointIndex) { + if (text[decimalPointIndex] == '.') { + break; + } + } + if (decimalPointIndex == n) { + if (appendDotZero) { + stringAppendString(text, count, ".0"); + } + } else if (decimalPointIndex == n - 1) { + if (appendDotZero) { + stringAppendString(text, count, "0"); + } else { + text[decimalPointIndex] = 0; + } + } else { + if (appendDotZero) { + for (int j = n - 1; j > decimalPointIndex + 1 && text[j] == '0'; j--) { + text[j] = 0; + } + } else { + for (int j = n - 1; j >= decimalPointIndex && (text[j] == '0' || text[j] == '.'); j--) { + text[j] = 0; + } + } + } + } + const char *unitName = getUnitName(unit); + if (unitName && *unitName) { + stringAppendString(text, count, " "); + stringAppendString(text, count, unitName); + } + } else { + text[0] = 0; + } +} +static const char *FLOAT_value_type_name(const Value &value) { + EEZ_UNUSED(value); + return "float"; +} +static bool compare_DOUBLE_value(const Value &a, const Value &b) { + return a.type == b.type && a.getUnit() == b.getUnit() && a.getDouble() == b.getDouble() && a.getOptions() == b.getOptions(); +} +static void DOUBLE_value_to_text(const Value &value, char *text, int count) { + text[0] = 0; + double doubleValue = value.getDouble(); +#if defined(INFINITY_SYMBOL) + if (isinf(doubleValue)) { + snprintf(text, count, INFINITY_SYMBOL); + return; + } +#endif + Unit unit = value.getUnit(); + bool appendDotZero = unit == UNIT_VOLT || unit == UNIT_VOLT_PP || unit == UNIT_AMPER || unit == UNIT_AMPER_PP || unit == UNIT_WATT; + uint16_t options = value.getOptions(); + bool fixedDecimals = (options & FLOAT_OPTIONS_FIXED_DECIMALS) != 0; + if (doubleValue != 0) { + if (!fixedDecimals) { + unit = findDerivedUnit(fabs(doubleValue), unit); + doubleValue /= getUnitFactor(unit); + } + } else { + doubleValue = 0; + } + if (!isNaN(doubleValue)) { + if ((value.getOptions() & FLOAT_OPTIONS_LESS_THEN) != 0) { + stringAppendString(text, count, "< "); + appendDotZero = false; + } + if (fixedDecimals) { + stringAppendFloat(text, count, doubleValue, FLOAT_OPTIONS_GET_NUM_FIXED_DECIMALS(options)); + } else { + if (unit == UNIT_WATT || unit == UNIT_MILLI_WATT) { + stringAppendDouble(text, count, doubleValue, 2); + } else { + stringAppendDouble(text, count, doubleValue); + } + int n = strlen(text); + int decimalPointIndex; + for (decimalPointIndex = 0; decimalPointIndex < n; ++decimalPointIndex) { + if (text[decimalPointIndex] == '.') { + break; + } + } + if (decimalPointIndex == n) { + if (appendDotZero) { + stringAppendString(text, count, ".0"); + } + } else if (decimalPointIndex == n - 1) { + if (appendDotZero) { + stringAppendString(text, count, "0"); + } else { + text[decimalPointIndex] = 0; + } + } else { + if (appendDotZero) { + for (int j = n - 1; j > decimalPointIndex + 1 && text[j] == '0'; j--) { + text[j] = 0; + } + } else { + for (int j = n - 1; j >= decimalPointIndex && (text[j] == '0' || text[j] == '.'); j--) { + text[j] = 0; + } + } + } + } + const char *unitName = getUnitName(unit); + if (unitName && *unitName) { + stringAppendString(text, count, " "); + stringAppendString(text, count, unitName); + } + } else { + text[0] = 0; + } +} +static const char *DOUBLE_value_type_name(const Value &value) { + EEZ_UNUSED(value); + return "double"; +} +static bool compare_STRING_value(const Value &a, const Value &b) { + if (!b.isString()) { + return false; + } + const char *astr = a.getString(); + const char *bstr = b.getString(); + if (!astr && !bstr) { + return true; + } + if ((!astr && bstr) || (astr && !bstr)) { + return false; + } + return strcmp(astr, bstr) == 0; +} +static void STRING_value_to_text(const Value &value, char *text, int count) { + const char *str = value.getString(); + if (str) { + stringCopy(text, count, str); + } else { + text[0] = 0; + } +} +static const char *STRING_value_type_name(const Value &value) { + EEZ_UNUSED(value); + return "string"; +} +static bool compare_STRING_ASSET_value(const Value &a, const Value &b) { + return compare_STRING_value(a, b); +} +static void STRING_ASSET_value_to_text(const Value &value, char *text, int count) { + STRING_value_to_text(value, text, count); +} +static const char *STRING_ASSET_value_type_name(const Value &value) { + EEZ_UNUSED(value); + return "string"; +} +static bool compare_ARRAY_value(const Value &a, const Value &b) { + return a.type == b.type && a.arrayValue == b.arrayValue; +} +static void ARRAY_value_to_text(const Value &value, char *text, int count) { + EEZ_UNUSED(value); + EEZ_UNUSED(count); + text[0] = 0; +} +static const char *ARRAY_value_type_name(const Value &value) { + EEZ_UNUSED(value); + return "array"; +} +static bool compare_ARRAY_ASSET_value(const Value &a, const Value &b) { + return a.type == b.type && a.int32Value == b.int32Value; +} +static void ARRAY_ASSET_value_to_text(const Value &value, char *text, int count) { + EEZ_UNUSED(value); + EEZ_UNUSED(count); + text[0] = 0; +} +static const char *ARRAY_ASSET_value_type_name(const Value &value) { + EEZ_UNUSED(value); + return "array"; +} +static bool compare_ARRAY_REF_value(const Value &a, const Value &b) { + return a.type == b.type && a.refValue == b.refValue; +} +static void ARRAY_REF_value_to_text(const Value &value, char *text, int count) { + EEZ_UNUSED(value); + EEZ_UNUSED(count); + text[0] = 0; +} +static const char *ARRAY_REF_value_type_name(const Value &value) { + EEZ_UNUSED(value); + return "array"; +} +static bool compare_STRING_REF_value(const Value &a, const Value &b) { + return compare_STRING_value(a, b); +} +static void STRING_REF_value_to_text(const Value &value, char *text, int count) { + STRING_value_to_text(value, text, count); +} +static const char *STRING_REF_value_type_name(const Value &value) { + EEZ_UNUSED(value); + return "string"; +} +static bool compare_BLOB_REF_value(const Value &a, const Value &b) { + return a.type == b.type && a.refValue == b.refValue; +} +static void BLOB_REF_value_to_text(const Value &value, char *text, int count) { + snprintf(text, count, "blob (size=%d)", value.getInt()); +} +static const char *BLOB_REF_value_type_name(const Value &value) { + EEZ_UNUSED(value); + return "blob"; +} +static bool compare_STREAM_value(const Value &a, const Value &b) { + return a.type == b.type && a.int32Value == b.int32Value; +} +static void STREAM_value_to_text(const Value &value, char *text, int count) { + snprintf(text, count, "stream (id=%d)", value.getInt()); +} +static const char *STREAM_value_type_name(const Value &value) { + EEZ_UNUSED(value); + return "stream"; +} +static bool compare_WIDGET_value(const Value &a, const Value &b) { + return a.type == b.type && a.getVoidPointer() == b.getVoidPointer(); +} +static void WIDGET_value_to_text(const Value &value, char *text, int count) { + snprintf(text, count, "widget (%p)", value.getVoidPointer()); +} +static const char *WIDGET_value_type_name(const Value &value) { + EEZ_UNUSED(value); + return "widget"; +} +static bool compare_JSON_value(const Value &a, const Value &b) { + return a.type == b.type && a.int32Value == b.int32Value; +} +static void JSON_value_to_text(const Value &value, char *text, int count) { + snprintf(text, count, "json (id=%d)", value.getInt()); +} +static const char *JSON_value_type_name(const Value &value) { + EEZ_UNUSED(value); + return "json"; +} +static bool compare_JSON_MEMBER_VALUE_value(const Value &a, const Value &b) { + return a.getValue() == b.getValue(); +} +static void JSON_MEMBER_VALUE_value_to_text(const Value &value, char *text, int count) { + value.getValue().toText(text, count); +} +static const char *JSON_MEMBER_VALUE_value_type_name(const Value &value) { + auto value2 = value.getValue(); + return g_valueTypeNames[value2.type](value2); +} +static bool compare_EVENT_value(const Value &a, const Value &b) { + return a.type == b.type && a.getVoidPointer() == b.getVoidPointer(); +} +static void EVENT_value_to_text(const Value &value, char *text, int count) { + snprintf(text, count, "event (%p)", value.getVoidPointer()); +} +static const char *EVENT_value_type_name(const Value &value) { + EEZ_UNUSED(value); + return "event"; +} +static const char *PROPERTY_REF_value_type_name(const Value &value) { + EEZ_UNUSED(value); + return "property-ref"; +} +static bool compare_PROPERTY_REF_value(const Value &a, const Value &b) { + return a.type == b.type && a.refValue == b.refValue; +} +static void PROPERTY_REF_value_to_text(const Value &value, char *text, int count) { + snprintf(text, count, "property-ref (flowState=%p, component=%d, property=%d)", + (void *)value.getPropertyRef()->flowState, value.getPropertyRef()->componentIndex, value.getPropertyRef()->propertyIndex); +} +static bool compare_DATE_value(const Value &a, const Value &b) { + return a.type == b.type && a.doubleValue == b.doubleValue; +} +static void DATE_value_to_text(const Value &value, char *text, int count) { + flow::date::toLocaleString((flow::date::Date)value.getDouble(), text, count); +} +static const char *DATE_value_type_name(const Value &value) { + EEZ_UNUSED(value); + return "date"; +} +static bool compare_VERSIONED_STRING_value(const Value &a, const Value &b) { + return a.type == b.type && a.unit == b.unit; +} +static void VERSIONED_STRING_value_to_text(const Value &value, char *text, int count) { + const char *str = value.getString(); + if (str) { + stringCopy(text, count, str); + } else { + text[0] = 0; + } +} +static const char *VERSIONED_STRING_value_type_name(const Value &value) { + EEZ_UNUSED(value); + return "versioned-string"; +} +static bool compare_VALUE_PTR_value(const Value &a, const Value &b) { + return a.type == b.type && (a.pValueValue == b.pValueValue || (a.pValueValue && b.pValueValue && *a.pValueValue == *b.pValueValue)); +} +static void VALUE_PTR_value_to_text(const Value &value, char *text, int count) { + if (value.pValueValue) { + value.pValueValue->toText(text, count); + } else { + text[0] = 0; + } +} +static const char *VALUE_PTR_value_type_name(const Value &value) { + if (value.pValueValue) { + return g_valueTypeNames[value.pValueValue->type](value.pValueValue); + } else { + return "null"; + } +} +static bool compare_ARRAY_ELEMENT_VALUE_value(const Value &a, const Value &b) { + return a.getValue() == b.getValue(); +} +static void ARRAY_ELEMENT_VALUE_value_to_text(const Value &value, char *text, int count) { + value.getValue().toText(text, count); +} +static const char *ARRAY_ELEMENT_VALUE_value_type_name(const Value &value) { + auto value2 = value.getValue(); + return g_valueTypeNames[value2.type](value2); +} +static bool compare_FLOW_OUTPUT_value(const Value &a, const Value &b) { + return a.type == b.type && a.getUInt16() == b.getUInt16(); +} +static void FLOW_OUTPUT_value_to_text(const Value &value, char *text, int count) { + EEZ_UNUSED(value); + EEZ_UNUSED(count); + text[0] = 0; +} +static const char *FLOW_OUTPUT_value_type_name(const Value &value) { + EEZ_UNUSED(value); + return "internal"; +} +static bool compare_NATIVE_VARIABLE_value(const Value &a, const Value &b) { + EEZ_UNUSED(a); + EEZ_UNUSED(b); + return false; +} +static void NATIVE_VARIABLE_value_to_text(const Value &value, char *text, int count) { + EEZ_UNUSED(value); + EEZ_UNUSED(count); + *text = 0; +} +static const char *NATIVE_VARIABLE_value_type_name(const Value &value) { + EEZ_UNUSED(value); + return ""; +} +static bool compare_ERROR_value(const Value &a, const Value &b) { + EEZ_UNUSED(a); + EEZ_UNUSED(b); + return false; +} +static void ERROR_value_to_text(const Value &value, char *text, int count) { + EEZ_UNUSED(value); + EEZ_UNUSED(count); + *text = 0; +} +static const char *ERROR_value_type_name(const Value &value) { + EEZ_UNUSED(value); + return "error"; +} +static bool compare_RANGE_value(const Value &a, const Value &b) { + return a.type == b.type && a.getUInt32() == b.getUInt32(); +} +static void RANGE_value_to_text(const Value &value, char *text, int count) { + EEZ_UNUSED(value); + EEZ_UNUSED(count); + text[0] = 0; +} +static const char *RANGE_value_type_name(const Value &value) { + EEZ_UNUSED(value); + return "internal"; +} +static bool compare_POINTER_value(const Value &a, const Value &b) { + return a.type == b.type && a.getVoidPointer() == b.getVoidPointer(); +} +static void POINTER_value_to_text(const Value &value, char *text, int count) { + EEZ_UNUSED(value); + EEZ_UNUSED(count); + text[0] = 0; +} +static const char *POINTER_value_type_name(const Value &value) { + EEZ_UNUSED(value); + return "internal"; +} +static bool compare_ENUM_value(const Value &a, const Value &b) { + EEZ_UNUSED(a); + EEZ_UNUSED(b); + return false; +} +static void ENUM_value_to_text(const Value &value, char *text, int count) { + EEZ_UNUSED(value); + EEZ_UNUSED(count); + *text = 0; +} +static const char *ENUM_value_type_name(const Value &value) { + EEZ_UNUSED(value); + return "internal"; +} +static bool compare_YT_DATA_GET_VALUE_FUNCTION_POINTER_value(const Value &a, const Value &b) { + return a.type == b.type && a.getUInt32() == b.getUInt32(); +} +static bool compare_IP_ADDRESS_value(const Value &a, const Value &b) { + return a.type == b.type && a.getUInt32() == b.getUInt32(); +} +static void IP_ADDRESS_value_to_text(const Value &value, char *text, int count) { + ipAddressToString(value.getUInt32(), text, count); +} +static const char *IP_ADDRESS_value_type_name(const Value &value) { + EEZ_UNUSED(value); + return "internal"; +} +static bool compare_TIME_ZONE_value(const Value &a, const Value &b) { + return a.type == b.type && a.getInt16() == b.getInt16(); +} +static void TIME_ZONE_value_to_text(const Value &value, char *text, int count) { + formatTimeZone(value.getInt16(), text, count); +} +static const char *TIME_ZONE_value_type_name(const Value &value) { + EEZ_UNUSED(value); + return "internal"; +} +static void YT_DATA_GET_VALUE_FUNCTION_POINTER_value_to_text(const Value &value, char *text, int count) { + EEZ_UNUSED(value); + EEZ_UNUSED(count); + text[0] = 0; +} +static const char *YT_DATA_GET_VALUE_FUNCTION_POINTER_value_type_name(const Value &value) { + EEZ_UNUSED(value); + return "internal"; +} +#define VALUE_TYPE(NAME) bool compare_##NAME##_value(const Value &a, const Value &b); +VALUE_TYPES +#undef VALUE_TYPE +#define VALUE_TYPE(NAME) compare_##NAME##_value, +CompareValueFunction g_valueTypeCompareFunctions[] = { + VALUE_TYPES +}; +#undef VALUE_TYPE +#define VALUE_TYPE(NAME) void NAME##_value_to_text(const Value &value, char *text, int count); +VALUE_TYPES +#undef VALUE_TYPE +#define VALUE_TYPE(NAME) NAME##_value_to_text, +ValueToTextFunction g_valueTypeToTextFunctions[] = { + VALUE_TYPES +}; +#undef VALUE_TYPE +#define VALUE_TYPE(NAME) const char * NAME##_value_type_name(const Value &value); +VALUE_TYPES +#undef VALUE_TYPE +#define VALUE_TYPE(NAME) NAME##_value_type_name, +ValueTypeNameFunction g_valueTypeNames[] = { + VALUE_TYPES +}; +#undef VALUE_TYPE +ArrayValueRef::~ArrayValueRef() { + eez::flow::onArrayValueFree(&arrayValue); + for (uint32_t i = 1; i < arrayValue.arraySize; i++) { + (arrayValue.values + i)->~Value(); + } +} +bool assignValue(Value &dstValue, const Value &srcValue, uint32_t dstValueType) { + if (dstValueType == VALUE_TYPE_BOOLEAN) { + dstValue = Value(srcValue.toBool(), VALUE_TYPE_BOOLEAN); + } else if (Value::isInt32OrLess(dstValueType)) { + dstValue = Value((int)srcValue.toInt32(), (ValueType)dstValueType); + } else if (dstValueType == VALUE_TYPE_FLOAT) { + dstValue = Value(srcValue.toFloat(), VALUE_TYPE_FLOAT); + } else if (dstValueType == VALUE_TYPE_DOUBLE) { + dstValue = Value(srcValue.toDouble(), VALUE_TYPE_DOUBLE); + } else if (dstValueType == VALUE_TYPE_STRING) { + dstValue = srcValue.toString(0x30a91156); + } else if (dstValue.isBoolean()) { + dstValue.int32Value = srcValue.toBool(); + } else if (dstValue.isInt32OrLess()) { + dstValue.int32Value = srcValue.toInt32(); + } else if (dstValue.isFloat()) { + dstValue.floatValue = srcValue.toFloat(); + } else if (dstValue.isDouble()) { + dstValue.doubleValue = srcValue.toDouble(); + } else if (dstValue.isString()) { + dstValue = srcValue.toString(0x30a91156); + } else { + dstValue = srcValue; + } + return true; +} +uint16_t getPageIndexFromValue(const Value &value) { + return value.getFirstUInt16(); +} +uint16_t getNumPagesFromValue(const Value &value) { + return value.getSecondUInt16(); +} +Value MakeRangeValue(uint16_t from, uint16_t to) { + Value value; + value.type = VALUE_TYPE_RANGE; + value.pairOfUint16Value.first = from; + value.pairOfUint16Value.second = to; + return value; +} +Value MakeEnumDefinitionValue(uint8_t enumValue, uint8_t enumDefinition) { + Value value; + value.type = VALUE_TYPE_ENUM; + value.enumValue.enumValue = enumValue; + value.enumValue.enumDefinition = enumDefinition; + return value; +} +const char *Value::getString() const { + auto value = getValue(); + if (value.type == VALUE_TYPE_STRING_REF) { + return ((StringRef *)value.refValue)->str; + } + if (value.type == VALUE_TYPE_STRING) { + return value.strValue; + } + return nullptr; +} +const ArrayValue *Value::getArray() const { + if (type == VALUE_TYPE_ARRAY) { + return arrayValue; + } + if (type == VALUE_TYPE_ARRAY_ASSET) { + return (ArrayValue *)((uint8_t *)&int32Value + int32Value); + } + return &((ArrayValueRef *)refValue)->arrayValue; +} +ArrayValue *Value::getArray() { + if (type == VALUE_TYPE_ARRAY) { + return arrayValue; + } + if (type == VALUE_TYPE_ARRAY_ASSET) { + return (ArrayValue *)((uint8_t *)&int32Value + int32Value); + } + return &((ArrayValueRef *)refValue)->arrayValue; +} +double Value::toDouble(int *err) const { + if (isIndirectValueType()) { + return getValue().toDouble(err); + } + if (err) { + *err = 0; + } + if (type == VALUE_TYPE_DOUBLE) { + return doubleValue; + } + if (type == VALUE_TYPE_FLOAT) { + return floatValue; + } + if (type == VALUE_TYPE_INT8) { + return int8Value; + } + if (type == VALUE_TYPE_UINT8) { + return uint8Value; + } + if (type == VALUE_TYPE_INT16) { + return int16Value; + } + if (type == VALUE_TYPE_UINT16) { + return uint16Value; + } + if (type == VALUE_TYPE_INT32 || type == VALUE_TYPE_BOOLEAN) { + return int32Value; + } + if (type == VALUE_TYPE_UINT32) { + return uint32Value; + } + if (type == VALUE_TYPE_INT64) { + return (double)int64Value; + } + if (type == VALUE_TYPE_UINT64) { + return (double)uint64Value; + } + if (type == VALUE_TYPE_DATE) { + return doubleValue; + } + if (isString()) { + const char *pStart = getString(); + char *pEnd; + double value = strtod(pStart, &pEnd); + while (isspace(*pEnd)) { + pEnd++; + } + if (*pEnd == '\0') { + return value; + } + } + if (err) { + *err = 1; + } + return NAN; +} +float Value::toFloat(int *err) const { + if (isIndirectValueType()) { + return getValue().toFloat(err); + } + if (err) { + *err = 0; + } + if (type == VALUE_TYPE_DOUBLE) { + return (float)doubleValue; + } + if (type == VALUE_TYPE_FLOAT) { + return floatValue; + } + if (type == VALUE_TYPE_INT8) { + return int8Value; + } + if (type == VALUE_TYPE_UINT8) { + return uint8Value; + } + if (type == VALUE_TYPE_INT16) { + return int16Value; + } + if (type == VALUE_TYPE_UINT16) { + return uint16Value; + } + if (type == VALUE_TYPE_INT32 || type == VALUE_TYPE_BOOLEAN) { + return (float)int32Value; + } + if (type == VALUE_TYPE_UINT32) { + return (float)uint32Value; + } + if (type == VALUE_TYPE_INT64) { + return (float)int64Value; + } + if (type == VALUE_TYPE_UINT64) { + return (float)uint64Value; + } + if (isString()) { + const char *pStart = getString(); + char *pEnd; + float value = strtof(pStart, &pEnd); + while (isspace(*pEnd)) { + pEnd++; + } + if (*pEnd == '\0') { + return value; + } + } + if (err) { + *err = 1; + } + return NAN; +} +int32_t Value::toInt32(int *err) const { + if (isIndirectValueType()) { + return getValue().toInt32(err); + } + if (err) { + *err = 0; + } + if (type == VALUE_TYPE_INT32 || type == VALUE_TYPE_BOOLEAN) { + return int32Value; + } + if (type == VALUE_TYPE_UINT32) { + return (int32_t)uint32Value; + } + if (type == VALUE_TYPE_INT8) { + return int8Value; + } + if (type == VALUE_TYPE_UINT8) { + return uint8Value; + } + if (type == VALUE_TYPE_INT16) { + return int16Value; + } + if (type == VALUE_TYPE_UINT16) { + return uint16Value; + } + if (type == VALUE_TYPE_INT64) { + return (int32_t)int64Value; + } + if (type == VALUE_TYPE_UINT64) { + return (int32_t)uint64Value; + } + if (type == VALUE_TYPE_VALUE_PTR) { + return pValueValue->toInt32(err); + } + if (type == VALUE_TYPE_DOUBLE) { + return (int32_t)doubleValue; + } + if (type == VALUE_TYPE_FLOAT) { + return (int32_t)floatValue; + } + if (isString()) { + const char *pStart = getString(); + char *pEnd; + int value = strtol(pStart, &pEnd, 10); + while (isspace(*pEnd)) { + pEnd++; + } + if (*pEnd == '\0') { + return value; + } + } + if (err) { + *err = 1; + } + return 0; +} +int64_t Value::toInt64(int *err) const { + if (isIndirectValueType()) { + return getValue().toInt64(err); + } + if (err) { + *err = 0; + } + if (type == VALUE_TYPE_DOUBLE) { + return (int64_t)doubleValue; + } + if (type == VALUE_TYPE_FLOAT) { + return (int64_t)floatValue; + } + if (type == VALUE_TYPE_INT8) { + return int8Value; + } + if (type == VALUE_TYPE_UINT8) { + return uint8Value; + } + if (type == VALUE_TYPE_INT16) { + return int16Value; + } + if (type == VALUE_TYPE_UINT16) { + return uint16Value; + } + if (type == VALUE_TYPE_INT32 || type == VALUE_TYPE_BOOLEAN) { + return int32Value; + } + if (type == VALUE_TYPE_UINT32) { + return uint32Value; + } + if (type == VALUE_TYPE_INT64) { + return int64Value; + } + if (type == VALUE_TYPE_UINT64) { + return (int64_t)uint64Value; + } + if (isString()) { + const char *pStart = getString(); + char *pEnd; + int64_t value = strtol(pStart, &pEnd, 10); + while (isspace(*pEnd)) { + pEnd++; + } + if (*pEnd == '\0') { + return value; + } + } + if (err) { + *err = 1; + } + return 0; +} +bool Value::toBool(int *err) const { + if (isIndirectValueType()) { + return getValue().toBool(err); + } + if (err) { + *err = 0; + } + if (type == VALUE_TYPE_UNDEFINED || type == VALUE_TYPE_NULL) { + return false; + } + if (type == VALUE_TYPE_DOUBLE) { + return doubleValue != 0; + } + if (type == VALUE_TYPE_FLOAT) { + return floatValue != 0; + } + if (type == VALUE_TYPE_INT8) { + return int8Value != 0; + } + if (type == VALUE_TYPE_UINT8) { + return uint8Value != 0; + } + if (type == VALUE_TYPE_INT16) { + return int16Value != 0; + } + if (type == VALUE_TYPE_UINT16) { + return uint16Value != 0; + } + if (type == VALUE_TYPE_INT32 || type == VALUE_TYPE_BOOLEAN) { + return int32Value != 0; + } + if (type == VALUE_TYPE_UINT32) { + return uint32Value != 0; + } + if (type == VALUE_TYPE_INT64) { + return int64Value != 0; + } + if (type == VALUE_TYPE_UINT64) { + return uint64Value != 0; + } + if (type == VALUE_TYPE_DATE) { + return doubleValue != 0; + } + if (isString()) { + const char *str = getString(); + return str && *str; + } + if (isBlob()) { + auto blobRef = getBlob(); + return blobRef->len > 0; + } + if (isArray()) { + auto array = getArray(); + return array->arraySize != 0; + } + if (isJson()) { + return int32Value != 0; + } + if (isWidget()) { + return pVoidValue != 0; + } + if (err) { + *err = 1; + } + return false; +} +Value Value::toString(uint32_t id) const { + if (isIndirectValueType()) { + return getValue().toString(id); + } + if (isString()) { + return *this; + } + char tempStr[64]; +#ifdef _MSC_VER +#pragma warning(push) +#pragma warning(disable : 4474) +#endif + if (type == VALUE_TYPE_DOUBLE) { + snprintf(tempStr, sizeof(tempStr), "%g", doubleValue); + } else if (type == VALUE_TYPE_FLOAT) { + snprintf(tempStr, sizeof(tempStr), "%g", floatValue); + } else if (type == VALUE_TYPE_INT8) { + snprintf(tempStr, sizeof(tempStr), "%" PRId8 "", int8Value); + } else if (type == VALUE_TYPE_UINT8) { + snprintf(tempStr, sizeof(tempStr), "%" PRIu8 "", uint8Value); + } else if (type == VALUE_TYPE_INT16) { + snprintf(tempStr, sizeof(tempStr), "%" PRId16 "", int16Value); + } else if (type == VALUE_TYPE_UINT16) { + snprintf(tempStr, sizeof(tempStr), "%" PRIu16 "", uint16Value); + } else if (type == VALUE_TYPE_INT32) { + snprintf(tempStr, sizeof(tempStr), "%" PRId32 "", int32Value); + } else if (type == VALUE_TYPE_UINT32) { + snprintf(tempStr, sizeof(tempStr), "%" PRIu32 "", uint32Value); + } else if (type == VALUE_TYPE_INT64) { +#ifdef PRId64 + snprintf(tempStr, sizeof(tempStr), "%" PRId64 "", int64Value); +#else + snprintf(tempStr, sizeof(tempStr), "%" PRId32 "", (int32_t)int64Value); +#endif + } else if (type == VALUE_TYPE_UINT64) { +#ifdef PRIu64 + snprintf(tempStr, sizeof(tempStr), "%" PRIu64 "", uint64Value); +#else + snprintf(tempStr, sizeof(tempStr), "%" PRIu32 "", (uint32_t)uint64Value); +#endif + } else { + toText(tempStr, sizeof(tempStr)); + } +#ifdef _MSC_VER +#pragma warning(pop) +#endif + return makeStringRef(tempStr, strlen(tempStr), id); +} +Value Value::makeStringRef(const char *str, int len, uint32_t id) { + auto stringRef = ObjectAllocator::allocate(id); + if (stringRef == nullptr) { + return Value(0, VALUE_TYPE_NULL); + } + if (len == -1) { + len = strlen(str); + } + stringRef->str = (char *)alloc(len + 1, id + 1); + if (stringRef->str == nullptr) { + ObjectAllocator::deallocate(stringRef); + return Value(0, VALUE_TYPE_NULL); + } + stringCopyLength(stringRef->str, len + 1, str, len); + stringRef->str[len] = 0; + stringRef->refCounter = 1; + Value value; + value.type = VALUE_TYPE_STRING_REF; + value.options = VALUE_OPTIONS_REF; + value.refValue = stringRef; + return value; +} +Value Value::concatenateString(const Value &str1, const Value &str2) { + auto stringRef = ObjectAllocator::allocate(0xbab14c6a);; + if (stringRef == nullptr) { + return Value(0, VALUE_TYPE_NULL); + } + auto newStrLen = strlen(str1.getString()) + strlen(str2.getString()) + 1; + stringRef->str = (char *)alloc(newStrLen, 0xb5320162); + if (stringRef->str == nullptr) { + ObjectAllocator::deallocate(stringRef); + return Value(0, VALUE_TYPE_NULL); + } + stringCopy(stringRef->str, newStrLen, str1.getString()); + stringAppendString(stringRef->str, newStrLen, str2.getString()); + stringRef->refCounter = 1; + Value value; + value.type = VALUE_TYPE_STRING_REF; + value.options = VALUE_OPTIONS_REF; + value.refValue = stringRef; + return value; +} +Value Value::makeArrayRef(int arraySize, int arrayType, uint32_t id) { + auto ptr = alloc(sizeof(ArrayValueRef) + (arraySize > 0 ? arraySize - 1 : 0) * sizeof(Value), id); + if (ptr == nullptr) { + return Value(0, VALUE_TYPE_NULL); + } + ArrayValueRef *arrayRef = new (ptr) ArrayValueRef; + arrayRef->arrayValue.arraySize = arraySize; + arrayRef->arrayValue.arrayType = arrayType; + for (int i = 1; i < arraySize; i++) { + new (arrayRef->arrayValue.values + i) Value(); + } + arrayRef->refCounter = 1; + Value value; + value.type = VALUE_TYPE_ARRAY_REF; + value.options = VALUE_OPTIONS_REF; + value.refValue = arrayRef; + return value; +} +Value Value::makeArrayElementRef(Value arrayValue, int elementIndex, uint32_t id) { + auto arrayElementValueRef = ObjectAllocator::allocate(id); + if (arrayElementValueRef == nullptr) { + return Value(0, VALUE_TYPE_NULL); + } + arrayElementValueRef->arrayValue = arrayValue; + arrayElementValueRef->elementIndex = elementIndex; + arrayElementValueRef->refCounter = 1; + Value value; + value.type = VALUE_TYPE_ARRAY_ELEMENT_VALUE; + value.options = VALUE_OPTIONS_REF; + value.refValue = arrayElementValueRef; + return value; +} +Value Value::makeJsonMemberRef(Value jsonValue, Value propertyName, uint32_t id) { + auto jsonMemberValueRef = ObjectAllocator::allocate(id); + if (jsonMemberValueRef == nullptr) { + return Value(0, VALUE_TYPE_NULL); + } + jsonMemberValueRef->jsonValue = jsonValue; + jsonMemberValueRef->propertyName = propertyName; + jsonMemberValueRef->refCounter = 1; + Value value; + value.type = VALUE_TYPE_JSON_MEMBER_VALUE; + value.options = VALUE_OPTIONS_REF; + value.refValue = jsonMemberValueRef; + return value; +} +Value Value::makeBlobRef(const uint8_t *blob, uint32_t len, uint32_t id) { + auto blobRef = ObjectAllocator::allocate(id); + if (blobRef == nullptr) { + return Value(0, VALUE_TYPE_NULL); + } + blobRef->blob = (uint8_t *)alloc(len, id + 1); + if (blobRef->blob == nullptr) { + ObjectAllocator::deallocate(blobRef); + return Value(0, VALUE_TYPE_NULL); + } + blobRef->len = len; + if (blob) { + memcpy(blobRef->blob, blob, len); + } else { + memset(blobRef->blob, 0, len); + } + blobRef->refCounter = 1; + Value value; + value.type = VALUE_TYPE_BLOB_REF; + value.options = VALUE_OPTIONS_REF; + value.refValue = blobRef; + return value; +} +Value Value::makeBlobRef(const uint8_t *blob1, uint32_t len1, const uint8_t *blob2, uint32_t len2, uint32_t id) { + auto blobRef = ObjectAllocator::allocate(id); + if (blobRef == nullptr) { + return Value(0, VALUE_TYPE_NULL); + } + blobRef->blob = (uint8_t *)alloc(len1 + len2, id + 1); + if (blobRef->blob == nullptr) { + ObjectAllocator::deallocate(blobRef); + return Value(0, VALUE_TYPE_NULL); + } + blobRef->len = len1 + len2; + memcpy(blobRef->blob, blob1, len1); + memcpy(blobRef->blob + len1, blob2, len2); + blobRef->refCounter = 1; + Value value; + value.type = VALUE_TYPE_BLOB_REF; + value.options = VALUE_OPTIONS_REF; + value.refValue = blobRef; + return value; +} +Value Value::makeLVGLEventRef(uint32_t code, void *currentTarget, void *target, int32_t userData, uint32_t key, int32_t gestureDir, int32_t rotaryDiff, uint32_t id) { + auto lvglEventRef = ObjectAllocator::allocate(id); + if (lvglEventRef == nullptr) { + return Value(0, VALUE_TYPE_NULL); + } + lvglEventRef->code = code; + lvglEventRef->currentTarget = currentTarget; + lvglEventRef->target = target; + lvglEventRef->userData = userData; + lvglEventRef->key = key; + lvglEventRef->gestureDir = gestureDir; + lvglEventRef->rotaryDiff = rotaryDiff; + lvglEventRef->refCounter = 1; + Value value; + value.type = VALUE_TYPE_EVENT; + value.options = VALUE_OPTIONS_REF; + value.refValue = lvglEventRef; + return value; +} +Value Value::makePropertyRef(flow::FlowState *flowState, int componentIndex, int propertyIndex, uint32_t id) { + auto propertyRef = ObjectAllocator::allocate(id); + if (propertyRef == nullptr) { + return Value(0, VALUE_TYPE_NULL); + } + propertyRef->flowState = flowState; + propertyRef->componentIndex = componentIndex; + propertyRef->propertyIndex = propertyIndex; + propertyRef->refCounter = 1; + Value value; + value.type = VALUE_TYPE_PROPERTY_REF; + value.options = VALUE_OPTIONS_REF; + value.refValue = propertyRef; + return value; +} +Value Value::evalProperty() const { + auto propertyRef = getPropertyRef(); + Value value; + flow::evalProperty(propertyRef->flowState, propertyRef->componentIndex, propertyRef->propertyIndex, value, flow::FlowError::Plain("Failed to evaluate an user property in UserWidget")); + return value; +} +Value Value::clone() { + if (isArray()) { + auto array = getArray(); + auto resultArrayValue = makeArrayRef(array->arraySize, array->arrayType, 0x0ea48dcb); + auto resultArray = resultArrayValue.getArray(); + for (uint32_t elementIndex = 0; elementIndex < array->arraySize; elementIndex++) { + auto elementValue = array->values[elementIndex].clone(); + if (elementValue.isError()) { + return elementValue; + } + resultArray->values[elementIndex] = elementValue; + } + return resultArrayValue; + } else if (isString()) { + return makeStringRef(getString(), -1, 0x91846ff3); + } + return *this; +} +Value getVar(int16_t id) { + auto native_var = native_vars[id]; + if (native_var.type == NATIVE_VAR_TYPE_INTEGER) { + auto get = (int32_t (*)())native_var.get; + return Value((int)get(), VALUE_TYPE_INT32); + } + if (native_var.type == NATIVE_VAR_TYPE_BOOLEAN) { + auto get = (bool (*)())native_var.get; + return Value(get(), VALUE_TYPE_BOOLEAN); + } + if (native_var.type == NATIVE_VAR_TYPE_FLOAT) { + auto get = (float (*)())native_var.get; + return Value(get(), VALUE_TYPE_FLOAT); + } + if (native_var.type == NATIVE_VAR_TYPE_DOUBLE) { + auto get = (double (*)())native_var.get; + return Value(get(), VALUE_TYPE_DOUBLE); + } + if (native_var.type == NATIVE_VAR_TYPE_STRING) { + auto get = (const char *(*)())native_var.get; + return Value(get(), VALUE_TYPE_STRING); + } + return Value(); +} +void setVar(int16_t id, const Value& value) { + auto native_var = native_vars[id]; + if (native_var.type == NATIVE_VAR_TYPE_INTEGER) { + auto set = (void (*)(int32_t))native_var.set; + set(value.toInt32(nullptr)); + } + if (native_var.type == NATIVE_VAR_TYPE_BOOLEAN) { + auto set = (void (*)(bool))native_var.set; + set(value.toBool(nullptr)); + } + if (native_var.type == NATIVE_VAR_TYPE_FLOAT) { + auto set = (void (*)(float))native_var.set; + set(value.toFloat(nullptr)); + } + if (native_var.type == NATIVE_VAR_TYPE_DOUBLE) { + auto set = (void (*)(double))native_var.set; + set(value.toDouble(nullptr)); + } + if (native_var.type == NATIVE_VAR_TYPE_STRING) { + auto set = (void (*)(const char *))native_var.set; + set(value.getString()); + } +} +} +// ----------------------------------------------------------------------------- +// flow/components.cpp +// ----------------------------------------------------------------------------- +#include +#include +namespace eez { +namespace flow { +void executeStartComponent(FlowState *flowState, unsigned componentIndex); +void executeEndComponent(FlowState *flowState, unsigned componentIndex); +void executeInputComponent(FlowState *flowState, unsigned componentIndex); +void executeOutputComponent(FlowState *flowState, unsigned componentIndex); +void executeWatchVariableComponent(FlowState *flowState, unsigned componentIndex); +void executeEvalExprComponent(FlowState *flowState, unsigned componentIndex); +void executeSetVariableComponent(FlowState *flowState, unsigned componentIndex); +void executeSwitchComponent(FlowState *flowState, unsigned componentIndex); +void executeCompareComponent(FlowState *flowState, unsigned componentIndex); +void executeIsTrueComponent(FlowState *flowState, unsigned componentIndex); +void executeConstantComponent(FlowState *flowState, unsigned componentIndex); +void executeLogComponent(FlowState *flowState, unsigned componentIndex); +void executeCallActionComponent(FlowState *flowState, unsigned componentIndex); +void executeDelayComponent(FlowState *flowState, unsigned componentIndex); +void executeErrorComponent(FlowState *flowState, unsigned componentIndex); +void executeCatchErrorComponent(FlowState *flowState, unsigned componentIndex); +void executeCounterComponent(FlowState *flowState, unsigned componentIndex); +void executeLoopComponent(FlowState *flowState, unsigned componentIndex); +void executeShowPageComponent(FlowState *flowState, unsigned componentIndex); +void executeSelectLanguageComponent(FlowState *flowState, unsigned componentIndex); +void executeAnimateComponent(FlowState *flowState, unsigned componentIndex); +void executeSetColorThemeComponent(FlowState *flowState, unsigned componentIndex); +void executeNoopComponent(FlowState *flowState, unsigned componentIndex); +void executeOnEventComponent(FlowState *flowState, unsigned componentIndex); +void executeLVGLComponent(FlowState *flowState, unsigned componentIndex); +void executeLVGLUserWidgetComponent(FlowState *flowState, unsigned componentIndex); +void executeSortArrayComponent(FlowState *flowState, unsigned componentIndex); +void executeTestAndSetComponent(FlowState *flowState, unsigned componentIndex); +void executeMQTTInitComponent(FlowState *flowState, unsigned componentIndex); +void executeMQTTConnectComponent(FlowState *flowState, unsigned componentIndex); +void executeMQTTDisconnectComponent(FlowState *flowState, unsigned componentIndex); +void executeMQTTEventComponent(FlowState *flowState, unsigned componentIndex); +void executeMQTTSubscribeComponent(FlowState *flowState, unsigned componentIndex); +void executeMQTTUnsubscribeComponent(FlowState *flowState, unsigned componentIndex); +void executeMQTTPublishComponent(FlowState *flowState, unsigned componentIndex); +void executeLabelInComponent(FlowState *flowState, unsigned componentIndex); +void executeLabelOutComponent(FlowState *flowState, unsigned componentIndex); +void executeLVGLApiComponent(FlowState *flowState, unsigned componentIndex); +typedef void (*ExecuteComponentFunctionType)(FlowState *flowState, unsigned componentIndex); +static ExecuteComponentFunctionType g_executeComponentFunctions[] = { + executeStartComponent, + executeEndComponent, + executeInputComponent, + executeOutputComponent, + executeWatchVariableComponent, + executeEvalExprComponent, + executeSetVariableComponent, + executeSwitchComponent, + executeCompareComponent, + executeIsTrueComponent, + executeConstantComponent, + executeLogComponent, + executeCallActionComponent, + executeDelayComponent, + executeErrorComponent, + executeCatchErrorComponent, + executeCounterComponent, + executeLoopComponent, + executeShowPageComponent, + nullptr, + nullptr, + nullptr, + nullptr, + executeNoopComponent, + nullptr, + executeSelectLanguageComponent, + nullptr, + executeAnimateComponent, + executeOnEventComponent, + executeLVGLComponent, + nullptr, + executeSortArrayComponent, + executeLVGLUserWidgetComponent, + executeTestAndSetComponent, + executeMQTTInitComponent, + executeMQTTConnectComponent, + executeMQTTDisconnectComponent, + executeMQTTEventComponent, + executeMQTTSubscribeComponent, + executeMQTTUnsubscribeComponent, + executeMQTTPublishComponent, + executeLabelInComponent, + executeLabelOutComponent, + executeLVGLApiComponent, + executeSetColorThemeComponent, +}; +void registerComponent(ComponentTypes componentType, ExecuteComponentFunctionType executeComponentFunction) { + if (componentType >= defs_v3::COMPONENT_TYPE_START_ACTION) { + g_executeComponentFunctions[componentType - defs_v3::COMPONENT_TYPE_START_ACTION] = executeComponentFunction; + } +} +bool hasExecFunc(FlowState *flowState, unsigned componentIndex) { + auto component = flowState->flow->components[componentIndex]; + if (component->type >= defs_v3::FIRST_DASHBOARD_ACTION_COMPONENT_TYPE) { + return false; + } else if (component->type >= defs_v3::COMPONENT_TYPE_START_ACTION) { + auto executeComponentFunction = g_executeComponentFunctions[component->type - defs_v3::COMPONENT_TYPE_START_ACTION]; + return executeComponentFunction != nullptr; + } + return false; +} +void executeComponent(FlowState *flowState, unsigned componentIndex) { + auto component = flowState->flow->components[componentIndex]; + if (component->type >= defs_v3::FIRST_DASHBOARD_ACTION_COMPONENT_TYPE) { + return; + } else if (component->type >= defs_v3::COMPONENT_TYPE_START_ACTION) { + auto executeComponentFunction = g_executeComponentFunctions[component->type - defs_v3::COMPONENT_TYPE_START_ACTION]; + if (executeComponentFunction != nullptr) { + executeComponentFunction(flowState, componentIndex); + return; + } + } + char errorMessage[100]; + snprintf(errorMessage, sizeof(errorMessage), "Unknown component at index = %d, type = %d\n", componentIndex, component->type); + throwError(flowState, componentIndex, errorMessage); +} +} +} +// ----------------------------------------------------------------------------- +// flow/components/animate.cpp +// ----------------------------------------------------------------------------- +namespace eez { +namespace flow { +struct AnimateComponenentExecutionState : public ComponenentExecutionState { + float startPosition; + float endPosition; + float speed; + uint32_t startTimestamp; +}; +void executeAnimateComponent(FlowState *flowState, unsigned componentIndex) { + FlowState *timelineFlowState = flowState; + while (timelineFlowState->isAction && timelineFlowState->parentFlowState) { + timelineFlowState = timelineFlowState->parentFlowState; + } + auto state = (AnimateComponenentExecutionState *)flowState->componenentExecutionStates[componentIndex]; + if (!state) { + Value fromValue; + if (!evalProperty(flowState, componentIndex, defs_v3::ANIMATE_ACTION_COMPONENT_PROPERTY_FROM, fromValue, FlowError::Property("Animate", "From"))) { + return; + } + Value toValue; + if (!evalProperty(flowState, componentIndex, defs_v3::ANIMATE_ACTION_COMPONENT_PROPERTY_TO, toValue, FlowError::Property("Animate", "To"))) { + return; + } + Value speedValue; + if (!evalProperty(flowState, componentIndex, defs_v3::ANIMATE_ACTION_COMPONENT_PROPERTY_SPEED, speedValue, FlowError::Property("Animate", "Speed"))) { + return; + } + float from = fromValue.toFloat(); + float to = toValue.toFloat(); + float speed = speedValue.toFloat(); + if (speed == 0) { + timelineFlowState->timelinePosition = to; + onFlowStateTimelineChanged(flowState); + propagateValueThroughSeqout(flowState, componentIndex); + } else { + state = allocateComponentExecutionState(flowState, componentIndex); + state->startPosition = from; + state->endPosition = to; + state->speed = speed; + state->startTimestamp = millis(); + if (!addToQueue(flowState, componentIndex, -1, -1, -1, true)) { + return; + } + } + } else { + float currentTime; + if (state->startPosition < state->endPosition) { + currentTime = state->startPosition + state->speed * (millis() - state->startTimestamp) / 1000.0f; + if (currentTime >= state->endPosition) { + currentTime = state->endPosition; + } + } else { + currentTime = state->startPosition - state->speed * (millis() - state->startTimestamp) / 1000.0f; + if (currentTime <= state->endPosition) { + currentTime = state->endPosition; + } + } + timelineFlowState->timelinePosition = currentTime; + onFlowStateTimelineChanged(flowState); + if (currentTime == state->endPosition) { + deallocateComponentExecutionState(flowState, componentIndex); + propagateValueThroughSeqout(flowState, componentIndex); + } else { + if (!addToQueue(flowState, componentIndex, -1, -1, -1, true)) { + return; + } + } + } +} +} +} +// ----------------------------------------------------------------------------- +// flow/components/call_action.cpp +// ----------------------------------------------------------------------------- +#include +namespace eez { +namespace flow { +FlowState *g_executeActionFlowState; +unsigned g_executeActionComponentIndex; +void executeCallAction(FlowState *flowState, unsigned componentIndex, int flowIndex, const Value& inputValue) { + if (flowIndex >= (int)flowState->assets->flowDefinition->flows.count) { + g_executeActionFlowState = flowState; + g_executeActionComponentIndex = componentIndex; + executeActionFunction(flowIndex - flowState->assets->flowDefinition->flows.count); + if ((int)componentIndex != -1 && !flowState->componenentAsyncStates[componentIndex]) { + propagateValueThroughSeqout(flowState, componentIndex); + } + return; + } + FlowState *actionFlowState = initActionFlowState(flowIndex, flowState, componentIndex, inputValue); + if ((int)componentIndex != -1) { + for (uint32_t i = 0; i < actionFlowState->flow->userPropertiesAssignable.count; i++) { + auto isAssignable = actionFlowState->flow->userPropertiesAssignable.items[i]; + Value value; + if (isAssignable) { + if (!evalAssignableProperty(flowState, componentIndex, i, value, FlowError::UserProperty("CallAction", i))) { + break; + } + if (value.getType() == VALUE_TYPE_FLOW_OUTPUT) { + value = Value::makePropertyRef(flowState, componentIndex, i, 0x5696e703); + } + } else { + if (!evalProperty(flowState, componentIndex, i, value, FlowError::UserAssignableProperty("CallAction", i))) { + break; + } + } + auto propValuePtr = actionFlowState->values + actionFlowState->flow->componentInputs.count + i; + *propValuePtr = value; + onValueChanged(propValuePtr); + } + } + if (canFreeFlowState(actionFlowState)) { + freeFlowState(actionFlowState); + if ((int)componentIndex != -1) { + propagateValueThroughSeqout(flowState, componentIndex); + } + } +} +void executeCallActionComponent(FlowState *flowState, unsigned componentIndex) { + auto component = (CallActionActionComponent *)flowState->flow->components[componentIndex]; + auto flowIndex = component->flowIndex; + if (flowIndex < 0) { + throwError(flowState, componentIndex, FlowError::Plain("Invalid action flow index in CallAction")); + return; + } + executeCallAction(flowState, componentIndex, flowIndex, Value()); +} +} +} +// ----------------------------------------------------------------------------- +// flow/components/catch_error.cpp +// ----------------------------------------------------------------------------- +namespace eez { +namespace flow { +void executeCatchErrorComponent(FlowState *flowState, unsigned componentIndex) { + auto catchErrorComponentExecutionState = (CatchErrorComponenentExecutionState *)flowState->componenentExecutionStates[componentIndex]; + propagateValue(flowState, componentIndex, 1, catchErrorComponentExecutionState->message); + deallocateComponentExecutionState(flowState, componentIndex); + propagateValueThroughSeqout(flowState, componentIndex); +} +} +} +// ----------------------------------------------------------------------------- +// flow/components/compare.cpp +// ----------------------------------------------------------------------------- +namespace eez { +namespace flow { +struct CompareActionComponent : public Component { + uint8_t conditionInstructions[1]; +}; +void executeCompareComponent(FlowState *flowState, unsigned componentIndex) { + auto component = (CompareActionComponent *)flowState->flow->components[componentIndex]; + Value conditionValue; + if (!evalExpression(flowState, componentIndex, component->conditionInstructions, conditionValue, FlowError::Property("Compare", "Condition"))) { + return; + } + int err; + bool result = conditionValue.toBool(&err); + if (err == 0) { + if (result) { + propagateValue(flowState, componentIndex, 1, Value(true, VALUE_TYPE_BOOLEAN)); + } else { + propagateValue(flowState, componentIndex, 2, Value(false, VALUE_TYPE_BOOLEAN)); + } + } else { + throwError(flowState, componentIndex, FlowError::PropertyConvert("Compare", "Condition", "boolean")); + return; + } + propagateValueThroughSeqout(flowState, componentIndex); +} +} +} +// ----------------------------------------------------------------------------- +// flow/components/constant.cpp +// ----------------------------------------------------------------------------- +namespace eez { +namespace flow { +struct ConstantActionComponent : public Component { + uint16_t valueIndex; +}; +void executeConstantComponent(FlowState *flowState, unsigned componentIndex) { + auto component = (ConstantActionComponent *)flowState->flow->components[componentIndex]; + auto &sourceValue = *flowState->assets->flowDefinition->constants[component->valueIndex]; + propagateValue(flowState, componentIndex, 1, sourceValue); + propagateValueThroughSeqout(flowState, componentIndex); +} +} +} +// ----------------------------------------------------------------------------- +// flow/components/counter.cpp +// ----------------------------------------------------------------------------- +namespace eez { +namespace flow { +struct CounterComponenentExecutionState : public ComponenentExecutionState { + int counter; +}; +void executeCounterComponent(FlowState *flowState, unsigned componentIndex) { + auto counterComponenentExecutionState = (CounterComponenentExecutionState *)flowState->componenentExecutionStates[componentIndex]; + if (!counterComponenentExecutionState) { + Value counterValue; + if (!evalProperty(flowState, componentIndex, defs_v3::COUNTER_ACTION_COMPONENT_PROPERTY_COUNT_VALUE, counterValue, FlowError::Property("Counter", "Count value"))) { + return; + } + counterComponenentExecutionState = allocateComponentExecutionState(flowState, componentIndex); + counterComponenentExecutionState->counter = counterValue.getInt(); + } + if (counterComponenentExecutionState->counter > 0) { + counterComponenentExecutionState->counter--; + propagateValueThroughSeqout(flowState, componentIndex); + } else { + deallocateComponentExecutionState(flowState, componentIndex); + propagateValue(flowState, componentIndex, 1); + } +} +} +} +// ----------------------------------------------------------------------------- +// flow/components/delay.cpp +// ----------------------------------------------------------------------------- +namespace eez { +namespace flow { +struct DelayComponenentExecutionState : public ComponenentExecutionState { + uint32_t waitUntil; +}; +void executeDelayComponent(FlowState *flowState, unsigned componentIndex) { + auto delayComponentExecutionState = (DelayComponenentExecutionState *)flowState->componenentExecutionStates[componentIndex]; + if (!delayComponentExecutionState) { + Value value; + if (!evalProperty(flowState, componentIndex, defs_v3::DELAY_ACTION_COMPONENT_PROPERTY_MILLISECONDS, value, FlowError::Property("Delay", "Milliseconds"))) { + return; + } + double milliseconds = value.toDouble(); + if (!isNaN(milliseconds)) { + delayComponentExecutionState = allocateComponentExecutionState(flowState, componentIndex); + delayComponentExecutionState->waitUntil = millis() + (uint32_t)floor(milliseconds); + } else { + throwError(flowState, componentIndex, FlowError::PropertyInvalid("Delay", "Milliseconds")); + return; + } + if (!addToQueue(flowState, componentIndex, -1, -1, -1, true)) { + return; + } + } else { + if (millis() >= delayComponentExecutionState->waitUntil) { + deallocateComponentExecutionState(flowState, componentIndex); + propagateValueThroughSeqout(flowState, componentIndex); + } else { + if (!addToQueue(flowState, componentIndex, -1, -1, -1, true)) { + return; + } + } + } +} +} +} +// ----------------------------------------------------------------------------- +// flow/components/end.cpp +// ----------------------------------------------------------------------------- +namespace eez { +namespace flow { +void executeEndComponent(FlowState *flowState, unsigned componentIndex) { + EEZ_UNUSED(componentIndex); + if (flowState->parentFlowState && flowState->isAction) { + if (flowState->parentComponentIndex != -1) { + propagateValueThroughSeqout(flowState->parentFlowState, flowState->parentComponentIndex); + } + } else { + stopScriptHook(); + } +} +} +} +// ----------------------------------------------------------------------------- +// flow/components/error.cpp +// ----------------------------------------------------------------------------- +namespace eez { +namespace flow { +void executeErrorComponent(FlowState *flowState, unsigned componentIndex) { + Value expressionValue; + if (!evalProperty(flowState, componentIndex, defs_v3::EVAL_EXPR_ACTION_COMPONENT_PROPERTY_EXPRESSION, expressionValue, FlowError::Property("Error", "Message"))) { + return; + } + throwError(flowState, componentIndex, FlowError::Plain(expressionValue.getString())); +} +} +} +// ----------------------------------------------------------------------------- +// flow/components/expr_eval.cpp +// ----------------------------------------------------------------------------- +namespace eez { +namespace flow { +void executeEvalExprComponent(FlowState *flowState, unsigned componentIndex) { + Value expressionValue; + if (!evalProperty(flowState, componentIndex, defs_v3::EVAL_EXPR_ACTION_COMPONENT_PROPERTY_EXPRESSION, expressionValue, FlowError::Property("Evalute", "Expression"))) { + return; + } + propagateValue(flowState, componentIndex, 1, expressionValue); + propagateValueThroughSeqout(flowState, componentIndex); +} +} +} +// ----------------------------------------------------------------------------- +// flow/components/input.cpp +// ----------------------------------------------------------------------------- +#include +namespace eez { +namespace flow { +bool getCallActionValue(FlowState *flowState, unsigned componentIndex, Value &value) { + auto component = flowState->flow->components[componentIndex]; + if (!flowState->parentFlowState) { + throwError(flowState, componentIndex, FlowError::Plain("No parentFlowState in Input")); + return false; + } + if (!flowState->parentComponent) { + if (flowState->parentComponentIndex == -1) { + value = flowState->inputValue; + return true; + } + throwError(flowState, componentIndex, FlowError::Plain("No parentComponent in Input")); + return false; + } + auto callActionComponent = (CallActionActionComponent *)flowState->parentComponent; + uint8_t callActionComponentInputIndex = callActionComponent->inputsStartIndex; + if (component->type == defs_v3::COMPONENT_TYPE_INPUT_ACTION) { + auto inputActionComponent = (InputActionComponent *)component; + callActionComponentInputIndex += inputActionComponent->inputIndex; + } else { + callActionComponentInputIndex -= 1; + } + if (callActionComponentInputIndex >= callActionComponent->inputs.count) { + throwError(flowState, componentIndex, FlowError::Plain("Invalid input index in Input")); + return false; + } + auto &parentComponentInputs = callActionComponent->inputs; + auto parentFlowInputIndex = parentComponentInputs[callActionComponentInputIndex]; + auto parentFlow = flowState->assets->flowDefinition->flows[flowState->parentFlowState->flowIndex]; + if (parentFlowInputIndex >= parentFlow->componentInputs.count) { + throwError(flowState, componentIndex, FlowError::Plain("Invalid input index of parent component in Input")); + return false; + } + value = flowState->parentFlowState->values[parentFlowInputIndex]; + return true; +} +void executeInputComponent(FlowState *flowState, unsigned componentIndex) { + Value value; + if (getCallActionValue(flowState, componentIndex, value)) { + auto inputActionComponentExecutionState = (InputActionComponentExecutionState *)flowState->componenentExecutionStates[componentIndex]; + if (!inputActionComponentExecutionState) { + inputActionComponentExecutionState = allocateComponentExecutionState(flowState, componentIndex); + } + propagateValue(flowState, componentIndex, 0, value); + inputActionComponentExecutionState->value = value; + } +} +} +} +// ----------------------------------------------------------------------------- +// flow/components/is_true.cpp +// ----------------------------------------------------------------------------- +namespace eez { +namespace flow { +void executeIsTrueComponent(FlowState *flowState, unsigned componentIndex) { + Value srcValue; + if (!evalProperty(flowState, componentIndex, defs_v3::IS_TRUE_ACTION_COMPONENT_PROPERTY_VALUE, srcValue, FlowError::Property("IsTrue", "Value"))) { + return; + } + int err; + bool result = srcValue.toBool(&err); + if (err == 0) { + if (result) { + propagateValue(flowState, componentIndex, 1, Value(true, VALUE_TYPE_BOOLEAN)); + } else { + propagateValue(flowState, componentIndex, 2, Value(false, VALUE_TYPE_BOOLEAN)); + } + } else { + throwError(flowState, componentIndex, FlowError::PropertyConvert("IsTrue", "Value", "boolean")); + return; + } + propagateValueThroughSeqout(flowState, componentIndex); +} +} +} +// ----------------------------------------------------------------------------- +// flow/components/label_in.cpp +// ----------------------------------------------------------------------------- +namespace eez { +namespace flow { +void executeLabelInComponent(FlowState *flowState, unsigned componentIndex) { + EEZ_UNUSED(flowState); + EEZ_UNUSED(componentIndex); +} +} +} +// ----------------------------------------------------------------------------- +// flow/components/label_out.cpp +// ----------------------------------------------------------------------------- +namespace eez { +namespace flow { +struct LabelOutActionComponent : public Component { + int16_t labelInComponentIndex; +}; +void executeLabelOutComponent(FlowState *flowState, unsigned componentIndex) { + auto component = (LabelOutActionComponent *)flowState->flow->components[componentIndex]; + if (component->labelInComponentIndex != -1) { + propagateValueThroughSeqout(flowState, component->labelInComponentIndex); + } +} +} +} +// ----------------------------------------------------------------------------- +// flow/components/line_chart_widget.cpp +// ----------------------------------------------------------------------------- +// ----------------------------------------------------------------------------- +// flow/components/log.cpp +// ----------------------------------------------------------------------------- +namespace eez { +namespace flow { +void executeLogComponent(FlowState *flowState, unsigned componentIndex) { + Value value; + if (!evalProperty(flowState, componentIndex, defs_v3::LOG_ACTION_COMPONENT_PROPERTY_VALUE, value, FlowError::Property("Log", "Message"))) { + return; + } + Value strValue = value.toString(0x0f9812ee); + const char *valueStr = strValue.getString(); + if (valueStr && *valueStr) { + logInfo(flowState, componentIndex, valueStr); + } + propagateValueThroughSeqout(flowState, componentIndex); +} +} +} +// ----------------------------------------------------------------------------- +// flow/components/loop.cpp +// ----------------------------------------------------------------------------- +namespace eez { +namespace flow { +struct LoopComponenentExecutionState : public ComponenentExecutionState { + Value dstValue; + Value toValue; + Value currentValue; +}; +void executeLoopComponent(FlowState *flowState, unsigned componentIndex) { + auto component = flowState->flow->components[componentIndex]; + auto loopComponentExecutionState = (LoopComponenentExecutionState *)flowState->componenentExecutionStates[componentIndex]; + static const unsigned START_INPUT_INDEX = 0; + auto startInputIndex = component->inputs[START_INPUT_INDEX]; + if (flowState->values[startInputIndex].type != VALUE_TYPE_UNDEFINED) { + if (loopComponentExecutionState) { + deallocateComponentExecutionState(flowState, componentIndex); + loopComponentExecutionState = nullptr; + } + } else { + if (!loopComponentExecutionState) { + return; + } + } + Value stepValue; + if (!evalProperty(flowState, componentIndex, defs_v3::LOOP_ACTION_COMPONENT_PROPERTY_STEP, stepValue, FlowError::Property("Loop", "Step"))) { + return; + } + Value currentValue; + if (!loopComponentExecutionState) { + Value dstValue; + if (!evalAssignableProperty(flowState, componentIndex, defs_v3::LOOP_ACTION_COMPONENT_PROPERTY_VARIABLE, dstValue, FlowError::Property("Loop", "Variable"))) { + return; + } + Value fromValue; + if (!evalProperty(flowState, componentIndex, defs_v3::LOOP_ACTION_COMPONENT_PROPERTY_FROM, fromValue, FlowError::Property("Loop", "From"))) { + return; + } + Value toValue; + if (!evalProperty(flowState, componentIndex, defs_v3::LOOP_ACTION_COMPONENT_PROPERTY_TO, toValue, FlowError::Property("Loop", "To"))) { + return; + } + loopComponentExecutionState = allocateComponentExecutionState(flowState, componentIndex); + loopComponentExecutionState->dstValue = dstValue; + loopComponentExecutionState->toValue = toValue; + currentValue = fromValue; + } else { + if (loopComponentExecutionState->dstValue.getType() == VALUE_TYPE_FLOW_OUTPUT) { + currentValue = op_add(loopComponentExecutionState->currentValue, stepValue); + } else { + currentValue = op_add(loopComponentExecutionState->dstValue, stepValue); + } + } + if (loopComponentExecutionState->dstValue.getType() == VALUE_TYPE_FLOW_OUTPUT) { + loopComponentExecutionState->currentValue = currentValue; + } else { + assignValue(flowState, componentIndex, loopComponentExecutionState->dstValue, currentValue); + } + bool condition; + if (stepValue.toDouble(nullptr) > 0) { + condition = op_great(currentValue, loopComponentExecutionState->toValue).toBool(); + } else { + condition = op_less(currentValue, loopComponentExecutionState->toValue).toBool(); + } + if (condition) { + deallocateComponentExecutionState(flowState, componentIndex); + propagateValue(flowState, componentIndex, 1); + } else { + if (loopComponentExecutionState->dstValue.getType() == VALUE_TYPE_FLOW_OUTPUT) { + assignValue(flowState, componentIndex, loopComponentExecutionState->dstValue, currentValue); + } + propagateValueThroughSeqout(flowState, componentIndex); + } +} +} +} +// ----------------------------------------------------------------------------- +// flow/components/lvgl.cpp +// ----------------------------------------------------------------------------- +#include +#include +namespace eez { +namespace flow { +static void anim_callback_set_x(void *obj, int32_t v) { lv_obj_set_x((lv_obj_t *)obj, v); } +static int32_t anim_callback_get_x(lv_anim_t * a) { return lv_obj_get_x_aligned((lv_obj_t *)a->user_data); } +static void anim_callback_set_y(void *obj, int32_t v) { lv_obj_set_y((lv_obj_t *)obj, v); } +static int32_t anim_callback_get_y(lv_anim_t * a) { return lv_obj_get_y_aligned((lv_obj_t *)a->user_data); } +static void anim_callback_set_width(void *obj, int32_t v) { lv_obj_set_width((lv_obj_t *)obj, v); } +static int32_t anim_callback_get_width(lv_anim_t * a) { return lv_obj_get_width((lv_obj_t *)a->user_data); } +static void anim_callback_set_height(void *obj, int32_t v) { lv_obj_set_height((lv_obj_t *)obj, v); } +static int32_t anim_callback_get_height(lv_anim_t * a) { return lv_obj_get_height((lv_obj_t *)a->user_data); } +static void anim_callback_set_opacity(void *obj, int32_t v) { lv_obj_set_style_opa((lv_obj_t *)obj, v, LV_PART_MAIN); } +static int32_t anim_callback_get_opacity(lv_anim_t * a) { return lv_obj_get_style_opa((lv_obj_t *)a->user_data, LV_PART_MAIN); } +static void anim_callback_set_image_zoom(void *obj, int32_t v) { lv_img_set_zoom((lv_obj_t *)obj, v); } +static int32_t anim_callback_get_image_zoom(lv_anim_t * a) { return lv_img_get_zoom((lv_obj_t *)a->user_data); } +static void anim_callback_set_image_angle(void *obj, int32_t v) { lv_img_set_angle((lv_obj_t *)obj, v); } +static int32_t anim_callback_get_image_angle(lv_anim_t * a) { return lv_img_get_angle((lv_obj_t *)a->user_data); } +lv_anim_exec_xcb_t anim_set_callbacks[] = { + anim_callback_set_x, + anim_callback_set_y, + anim_callback_set_width, + anim_callback_set_height, + anim_callback_set_opacity, + anim_callback_set_image_zoom, + anim_callback_set_image_angle +}; +lv_anim_get_value_cb_t anim_get_callbacks[] = { + anim_callback_get_x, + anim_callback_get_y, + anim_callback_get_width, + anim_callback_get_height, + anim_callback_get_opacity, + anim_callback_get_image_zoom, + anim_callback_get_image_angle +}; +int32_t (*anim_path_callbacks[])(const lv_anim_t *a) = { + lv_anim_path_linear, + lv_anim_path_ease_in, + lv_anim_path_ease_out, + lv_anim_path_ease_in_out, + lv_anim_path_overshoot, + lv_anim_path_bounce +}; +enum PropertyCode { + NONE, + ARC_VALUE, + BAR_VALUE, + BASIC_X, + BASIC_Y, + BASIC_WIDTH, + BASIC_HEIGHT, + BASIC_OPACITY, + BASIC_HIDDEN, + BASIC_CHECKED, + BASIC_DISABLED, + DROPDOWN_SELECTED, + IMAGE_IMAGE, + IMAGE_ANGLE, + IMAGE_ZOOM, + LABEL_TEXT, + ROLLER_SELECTED, + SLIDER_VALUE, + KEYBOARD_TEXTAREA +}; +enum GroupActions { + GROUP_ACTION_SET_WRAP = 0, + GROUP_ACTION_FOCUS_OBJ = 1, + GROUP_ACTION_FOCUS_NEXT = 2, + GROUP_ACTION_FOCUS_PREVIOUS = 3, + GROUP_ACTION_FOCUS_FREEZE = 4, + GROUP_ACTION_SET_EDITING = 5 +}; +struct LVGLExecutionState : public ComponenentExecutionState { + uint32_t actionIndex; +}; +void executeLVGLComponent(FlowState *flowState, unsigned componentIndex) { + auto component = (LVGLComponent *)flowState->flow->components[componentIndex]; + auto executionState = (LVGLExecutionState *)flowState->componenentExecutionStates[componentIndex]; + for (uint32_t actionIndex = executionState ? executionState->actionIndex : 0; actionIndex < component->actions.count; actionIndex++) { + auto general = (LVGLComponent_ActionType *)component->actions[actionIndex]; + if (general->action == CHANGE_SCREEN) { + auto specific = (LVGLComponent_ChangeScreen_ActionType *)general; + if (specific->screen == -1) { + eez_flow_pop_screen((lv_scr_load_anim_t)specific->fadeMode, specific->speed, specific->delay); + } else { + eez_flow_push_screen(specific->screen, (lv_scr_load_anim_t)specific->fadeMode, specific->speed, specific->delay); + } + } else if (general->action == PLAY_ANIMATION) { + auto specific = (LVGLComponent_PlayAnimation_ActionType *)general; + auto target = getLvglObjectFromIndexHook(flowState->lvglWidgetStartIndex + specific->target); + if (!target) { + if (!executionState) { + executionState = allocateComponentExecutionState(flowState, componentIndex); + } + executionState->actionIndex = actionIndex; + addToQueue(flowState, componentIndex, -1, -1, -1, true); + return; + } + lv_anim_t anim; + lv_anim_init(&anim); + lv_anim_set_time(&anim, specific->time); + lv_anim_set_user_data(&anim, target); + lv_anim_set_var(&anim, target); + lv_anim_set_exec_cb(&anim, anim_set_callbacks[specific->property]); + lv_anim_set_values(&anim, specific->start, specific->end); + lv_anim_set_path_cb(&anim, anim_path_callbacks[specific->path]); + lv_anim_set_delay(&anim, specific->delay); + lv_anim_set_early_apply(&anim, specific->flags & ANIMATION_ITEM_FLAG_INSTANT ? true : false); + if (specific->flags & ANIMATION_ITEM_FLAG_RELATIVE) { + lv_anim_set_get_value_cb(&anim, anim_get_callbacks[specific->property]); + } + lv_anim_start(&anim); + } else if (general->action == SET_PROPERTY) { + auto specific = (LVGLComponent_SetProperty_ActionType *)general; + auto target = getLvglObjectFromIndexHook(flowState->lvglWidgetStartIndex + specific->target); + if (!target) { + if (!executionState) { + executionState = allocateComponentExecutionState(flowState, componentIndex); + } + executionState->actionIndex = actionIndex; + addToQueue(flowState, componentIndex, -1, -1, -1, true); + return; + } + if (specific->property == KEYBOARD_TEXTAREA) { + auto textarea = specific->textarea != -1 ? getLvglObjectFromIndexHook(flowState->lvglWidgetStartIndex + specific->textarea) : nullptr; + if (!textarea) { + if (!executionState) { + executionState = allocateComponentExecutionState(flowState, componentIndex); + } + executionState->actionIndex = actionIndex; + addToQueue(flowState, componentIndex, -1, -1, -1, true); + return; + } + lv_keyboard_set_textarea(target, textarea); + } else { + Value value; + if (!evalExpression(flowState, componentIndex, specific->value, value, FlowError::PropertyInAction("LVGL Set Property", "Value", actionIndex))) { + return; + } + if (specific->property == IMAGE_IMAGE || specific->property == LABEL_TEXT) { + const char *strValue = value.toString(0xe42b3ca2).getString(); + if (specific->property == IMAGE_IMAGE) { + const void *src = getLvglImageByNameHook(strValue); + if (src) { + lv_img_set_src(target, src); + } else { + throwError(flowState, componentIndex, FlowError::NotFoundInAction("Image", strValue, "LVGL Set Property", actionIndex)); + } + } else { + lv_label_set_text(target, strValue ? strValue : ""); + } + } else if (specific->property == BASIC_HIDDEN) { + int err; + bool booleanValue = value.toBool(&err); + if (err) { + throwError(flowState, componentIndex, FlowError::PropertyInActionConvert("LVGL Set Property", "Value", "boolean", actionIndex)); + return; + } + lv_obj_flag_t flag = LV_OBJ_FLAG_HIDDEN; + if (booleanValue) lv_obj_add_flag(target, flag); + else lv_obj_clear_flag(target, flag); + } else if (specific->property == BASIC_CHECKED || specific->property == BASIC_DISABLED) { + int err; + bool booleanValue = value.toBool(&err); + if (err) { + throwError(flowState, componentIndex, FlowError::PropertyInActionConvert("LVGL Set Property", "Value", "boolean", actionIndex)); + return; + } + lv_state_t state = specific->property == BASIC_CHECKED ? LV_STATE_CHECKED : LV_STATE_DISABLED; + if (booleanValue) lv_obj_add_state(target, state); + else lv_obj_clear_state(target, state); + } else { + int err; + int32_t intValue = value.toInt32(&err); + if (err) { + throwError(flowState, componentIndex, FlowError::PropertyInActionConvert("LVGL Set Property", "Value", "integer", actionIndex)); + return; + } + if (specific->property == ARC_VALUE) { + lv_arc_set_value(target, intValue); + } else if (specific->property == BAR_VALUE) { + lv_bar_set_value(target, intValue, specific->animated ? LV_ANIM_ON : LV_ANIM_OFF); + } else if (specific->property == BASIC_X) { + lv_obj_set_x(target, intValue); + } else if (specific->property == BASIC_Y) { + lv_obj_set_y(target, intValue); + } else if (specific->property == BASIC_WIDTH) { + lv_obj_set_width(target, intValue); + } else if (specific->property == BASIC_HEIGHT) { + lv_obj_set_height(target, intValue); + } else if (specific->property == BASIC_OPACITY) { + lv_obj_set_style_opa(target, intValue, LV_PART_MAIN); + } else if (specific->property == DROPDOWN_SELECTED) { + lv_dropdown_set_selected(target, intValue); + } else if (specific->property == IMAGE_ANGLE) { + lv_img_set_angle(target, intValue); + } else if (specific->property == IMAGE_ZOOM) { + lv_img_set_zoom(target, intValue); + } else if (specific->property == ROLLER_SELECTED) { + lv_roller_set_selected(target, intValue, specific->animated ? LV_ANIM_ON : LV_ANIM_OFF); + } else if (specific->property == SLIDER_VALUE) { + lv_slider_set_value(target, intValue, specific->animated ? LV_ANIM_ON : LV_ANIM_OFF); + } + } + } + lv_obj_update_layout(target); + } else if (general->action == ADD_STYLE) { + auto specific = (LVGLComponent_AddStyle_ActionType *)general; + auto target = getLvglObjectFromIndexHook(flowState->lvglWidgetStartIndex + specific->target); + if (!target) { + if (!executionState) { + executionState = allocateComponentExecutionState(flowState, componentIndex); + } + executionState->actionIndex = actionIndex; + addToQueue(flowState, componentIndex, -1, -1, -1, true); + return; + } else { + lvglObjAddStyleHook(target, specific->style); + } + } else if (general->action == REMOVE_STYLE) { + auto specific = (LVGLComponent_RemoveStyle_ActionType *)general; + auto target = getLvglObjectFromIndexHook(flowState->lvglWidgetStartIndex + specific->target); + if (!target) { + if (!executionState) { + executionState = allocateComponentExecutionState(flowState, componentIndex); + } + executionState->actionIndex = actionIndex; + addToQueue(flowState, componentIndex, -1, -1, -1, true); + return; + } else { + lvglObjRemoveStyleHook(target, specific->style); + } + } else if (general->action == ADD_FLAG) { + auto specific = (LVGLComponent_AddFlag_ActionType *)general; + auto target = getLvglObjectFromIndexHook(flowState->lvglWidgetStartIndex + specific->target); + if (!target) { + if (!executionState) { + executionState = allocateComponentExecutionState(flowState, componentIndex); + } + executionState->actionIndex = actionIndex; + addToQueue(flowState, componentIndex, -1, -1, -1, true); + return; + } else { + lv_obj_add_flag(target, (lv_obj_flag_t)specific->flag); + } + } else if (general->action == CLEAR_FLAG) { + auto specific = (LVGLComponent_ClearFlag_ActionType *)general; + auto target = getLvglObjectFromIndexHook(flowState->lvglWidgetStartIndex + specific->target); + if (!target) { + if (!executionState) { + executionState = allocateComponentExecutionState(flowState, componentIndex); + } + executionState->actionIndex = actionIndex; + addToQueue(flowState, componentIndex, -1, -1, -1, true); + return; + } else { + lv_obj_clear_flag(target, (lv_obj_flag_t)specific->flag); + } + } else if (general->action == GROUP) { + auto specific = (LVGLComponent_Group_ActionType *)general; + if (specific->groupAction == GROUP_ACTION_SET_WRAP) { + auto target = getLvglGroupFromIndexHook(specific->target); + if (target) { + lv_group_set_wrap(target, specific->enable ? true : false); + } + } else if (specific->groupAction == GROUP_ACTION_FOCUS_OBJ) { + auto target = getLvglObjectFromIndexHook(flowState->lvglWidgetStartIndex + specific->target); + if (!target) { + if (!executionState) { + executionState = allocateComponentExecutionState(flowState, componentIndex); + } + executionState->actionIndex = actionIndex; + addToQueue(flowState, componentIndex, -1, -1, -1, true); + return; + } else { + lv_group_focus_obj(target); + } + } else if (specific->groupAction == GROUP_ACTION_FOCUS_NEXT) { + auto target = getLvglGroupFromIndexHook(specific->target); + if (target) { + lv_group_focus_next(target); + } + } else if (specific->groupAction == GROUP_ACTION_FOCUS_PREVIOUS) { + auto target = getLvglGroupFromIndexHook(specific->target); + if (target) { + lv_group_focus_prev(target); + } + } else if (specific->groupAction == GROUP_ACTION_FOCUS_FREEZE) { + auto target = getLvglGroupFromIndexHook(specific->target); + if (target) { + lv_group_focus_freeze(target, specific->enable ? true : false); + } + } else { + auto target = getLvglGroupFromIndexHook(specific->target); + if (target) { + lv_group_set_editing(target, specific->enable ? true : false); + } + } + } else if (general->action == ADD_STATE) { + auto specific = (LVGLComponent_AddState_ActionType *)general; + auto target = getLvglObjectFromIndexHook(flowState->lvglWidgetStartIndex + specific->target); + if (!target) { + if (!executionState) { + executionState = allocateComponentExecutionState(flowState, componentIndex); + } + executionState->actionIndex = actionIndex; + addToQueue(flowState, componentIndex, -1, -1, -1, true); + return; + } else { + lv_obj_add_state(target, (lv_state_t)specific->state); + } + } else if (general->action == CLEAR_STATE) { + auto specific = (LVGLComponent_ClearState_ActionType *)general; + auto target = getLvglObjectFromIndexHook(flowState->lvglWidgetStartIndex + specific->target); + if (!target) { + if (!executionState) { + executionState = allocateComponentExecutionState(flowState, componentIndex); + } + executionState->actionIndex = actionIndex; + addToQueue(flowState, componentIndex, -1, -1, -1, true); + return; + } else { + lv_obj_clear_state(target, (lv_state_t)specific->state); + } + } + } + propagateValueThroughSeqout(flowState, componentIndex); +} +static char *g_fullObjectNameBuffer = nullptr; +static size_t g_fullObjectNameBufferLength = 0; +const char *getFullObjectName(FlowState *flowState, const char *objectName) { + int lvglWidgetStartIndex = 0; + for (FlowState *fs = flowState; fs; fs = fs->parentFlowState) { + lvglWidgetStartIndex += fs->lvglWidgetStartIndex; + } + if (lvglWidgetStartIndex == 0) { + return objectName; + } + const char *prefix = getLvglObjectNameFromIndexHook(lvglWidgetStartIndex - 1); + size_t prefixLength = strlen(prefix); + size_t objectNameLength = strlen(objectName); + size_t totalLength = prefixLength + 2 + objectNameLength + 1; + if (g_fullObjectNameBufferLength < totalLength) { + if (g_fullObjectNameBuffer) { + eez::free(g_fullObjectNameBuffer); + } + g_fullObjectNameBuffer = (char *)eez::alloc(totalLength, 0xe4145ae4); + g_fullObjectNameBufferLength = totalLength; + } + strcpy(g_fullObjectNameBuffer, prefix); + strcat(g_fullObjectNameBuffer, "__"); + strcat(g_fullObjectNameBuffer, objectName); + return g_fullObjectNameBuffer; +} +#define ACTION_START(NAME) static void NAME(FlowState *flowState, unsigned componentIndex, const ListOfAssetsPtr &properties, uint32_t actionIndex) { \ + const char *actionName = #NAME; \ + int propIndex = 0; +#define INT8_PROP(NAME) \ + Value NAME##Value; \ + if (!evalExpression(flowState, componentIndex, properties[propIndex]->evalInstructions, NAME##Value, FlowError::PropertyInAction(#NAME, actionName, actionIndex))) { \ + return; \ + }\ + propIndex++; \ + int8_t NAME = NAME##Value.getInt8(); +#define UINT8_PROP(NAME) \ + Value NAME##Value; \ + if (!evalExpression(flowState, componentIndex, properties[propIndex]->evalInstructions, NAME##Value, FlowError::PropertyInAction(#NAME, actionName, actionIndex))) { \ + return; \ + }\ + propIndex++; \ + uint8_t NAME = NAME##Value.getUInt8(); +#define INT16_PROP(NAME) \ + Value NAME##Value; \ + if (!evalExpression(flowState, componentIndex, properties[propIndex]->evalInstructions, NAME##Value, FlowError::PropertyInAction(#NAME, actionName, actionIndex))) { \ + return; \ + }\ + propIndex++; \ + int16_t NAME = NAME##Value.getInt16(); +#define UINT16_PROP(NAME) \ + Value NAME##Value; \ + if (!evalExpression(flowState, componentIndex, properties[propIndex]->evalInstructions, NAME##Value, FlowError::PropertyInAction(#NAME, actionName, actionIndex))) { \ + return; \ + }\ + propIndex++; \ + uint16_t NAME = NAME##Value.getUInt16(); +#define INT32_PROP(NAME) \ + Value NAME##Value; \ + if (!evalExpression(flowState, componentIndex, properties[propIndex]->evalInstructions, NAME##Value, FlowError::PropertyInAction(#NAME, actionName, actionIndex))) { \ + return; \ + }\ + propIndex++; \ + int32_t NAME = NAME##Value.getInt(); +#define UINT32_PROP(NAME) \ + Value NAME##Value; \ + if (!evalExpression(flowState, componentIndex, properties[propIndex]->evalInstructions, NAME##Value, FlowError::PropertyInAction(#NAME, actionName, actionIndex))) { \ + return; \ + }\ + propIndex++; \ + uint32_t NAME = NAME##Value.getUInt32(); +#define BOOL_PROP(NAME) \ + Value NAME##Value; \ + if (!evalExpression(flowState, componentIndex, properties[propIndex]->evalInstructions, NAME##Value, FlowError::PropertyInAction(#NAME, actionName, actionIndex))) { \ + return; \ + }\ + propIndex++; \ + int32_t NAME = NAME##Value.getBoolean(); +#define STR_PROP(NAME) \ + Value NAME##Value; \ + if (!evalExpression(flowState, componentIndex, properties[propIndex]->evalInstructions, NAME##Value, FlowError::PropertyInAction(#NAME, actionName, actionIndex))) { \ + return; \ + }\ + propIndex++; \ + const char *NAME = NAME##Value.toString(0xe42b3ca2).getString(); +#define SCREEN_PROP(NAME) \ + Value NAME##Value; \ + if (!evalExpression(flowState, componentIndex, properties[propIndex]->evalInstructions, NAME##Value, FlowError::PropertyInAction(#NAME, actionName, actionIndex))) { \ + return; \ + }\ + propIndex++; \ + int32_t NAME; \ + if (NAME##Value.isString()) { \ + const char *screenName = NAME##Value.getString(); \ + NAME = getLvglScreenByNameHook(screenName); \ + if (NAME == 0) { \ + throwError(flowState, componentIndex, FlowError::NotFoundInAction("Screen", screenName, actionName, actionIndex)); \ + return; \ + } \ + } else { \ + NAME = NAME##Value.getInt(); \ + } +#define WIDGET_PROP(NAME) \ + Value NAME##Value; \ + if (!evalExpression(flowState, componentIndex, properties[propIndex]->evalInstructions, NAME##Value, FlowError::PropertyInAction(#NAME, actionName, actionIndex))) { \ + return; \ + }\ + propIndex++; \ + lv_obj_t *NAME; \ + if (NAME##Value.isWidget()) { \ + NAME = (lv_obj_t *)NAME##Value.getWidget(); \ + } else if (NAME##Value.isString()) { \ + const char *objectName = NAME##Value.getString(); \ + const char *fullObjectName = getFullObjectName(flowState, objectName); \ + int32_t widgetIndex = getLvglObjectByNameHook(fullObjectName); \ + if (widgetIndex == -1) { \ + throwError(flowState, componentIndex, FlowError::NotFoundInAction("Widget", objectName, actionName, actionIndex)); \ + return; \ + } \ + NAME = getLvglObjectFromIndexHook(widgetIndex); \ + } else { \ + int32_t widgetIndex = NAME##Value.getInt(); \ + for (FlowState *fs = flowState; fs; fs = fs->parentFlowState) widgetIndex += fs->lvglWidgetStartIndex; \ + NAME = getLvglObjectFromIndexHook(widgetIndex); \ + } \ + if (!NAME) { \ + throwError(flowState, componentIndex, FlowError::NullInAction("Widget", actionName, actionIndex)); \ + return; \ + } +#define GROUP_PROP(NAME) \ + Value NAME##Value; \ + if (!evalExpression(flowState, componentIndex, properties[propIndex]->evalInstructions, NAME##Value, FlowError::PropertyInAction(#NAME, actionName, actionIndex))) { \ + return; \ + }\ + propIndex++; \ + lv_group_t *NAME; \ + if (NAME##Value.isString()) { \ + const char *groupName = NAME##Value.getString(); \ + int32_t NAME##_GroupIndex = getLvglGroupByNameHook(groupName); \ + if (NAME##_GroupIndex == -1) { \ + throwError(flowState, componentIndex, FlowError::NotFoundInAction("Group", groupName, actionName, actionIndex)); \ + return; \ + } \ + NAME = getLvglGroupFromIndexHook(NAME##_GroupIndex); \ + } else { \ + int32_t NAME##_GroupIndex = NAME##Value.getInt(); \ + NAME = getLvglGroupFromIndexHook(NAME##_GroupIndex); \ + } \ + if (!NAME) { \ + throwError(flowState, componentIndex, FlowError::NullInAction("Group", actionName, actionIndex)); \ + return; \ + } +#define STYLE_PROP(NAME) \ + Value NAME##Value; \ + if (!evalExpression(flowState, componentIndex, properties[propIndex]->evalInstructions, NAME##Value, FlowError::PropertyInAction(#NAME, actionName, actionIndex))) { \ + return; \ + }\ + propIndex++; \ + int32_t NAME; \ + if (NAME##Value.isString()) { \ + const char *styleName = NAME##Value.getString(); \ + NAME = getLvglStyleByNameHook(styleName); \ + if (NAME == -1) { \ + throwError(flowState, componentIndex, FlowError::NotFoundInAction("Style", styleName, actionName, actionIndex)); \ + return; \ + } \ + } else { \ + NAME = NAME##Value.getInt(); \ + } +#define RESULT(NAME, VALUE) \ + Value NAME##Value; \ + if (!evalAssignableExpression(flowState, componentIndex, properties[propIndex]->evalInstructions, NAME##Value, FlowError::PropertyAssignInAction(#NAME, actionName, actionIndex))) { \ + return; \ + }\ + propIndex++; \ + assignValue(flowState, componentIndex, NAME##Value, VALUE); +#define ACTION_END } +ACTION_START(changeScreen) + SCREEN_PROP(screen); + INT32_PROP(fadeMode); + UINT32_PROP(speed); + UINT32_PROP(delay); + if (properties.count > 4) { + BOOL_PROP(useStack); + if (useStack) { + eez_flow_push_screen(screen, (lv_scr_load_anim_t)fadeMode, speed, delay); + } else { + eez::flow::replacePageHook(screen, (lv_scr_load_anim_t)fadeMode, speed, delay); + } + } else { + eez_flow_push_screen(screen, (lv_scr_load_anim_t)fadeMode, speed, delay); + } +ACTION_END +ACTION_START(changeToPreviousScreen) + INT32_PROP(fadeMode); + UINT32_PROP(speed); + UINT32_PROP(delay); + eez_flow_pop_screen((lv_scr_load_anim_t)fadeMode, speed, delay); +ACTION_END +ACTION_START(objSetX) + WIDGET_PROP(obj); + INT32_PROP(x); +#if LVGL_VERSION_MAJOR >= 9 + lv_obj_set_x(obj, x); +#else + lv_obj_set_x(obj, (lv_coord_t)x); +#endif +ACTION_END +ACTION_START(objGetX) + WIDGET_PROP(obj); +#if LVGL_VERSION_MAJOR >= 9 + int32_t x = (int32_t)lv_obj_get_x(obj); +#else + int32_t x = lv_obj_get_x(obj); +#endif + RESULT(result, Value((int)x, VALUE_TYPE_INT32)); +ACTION_END +ACTION_START(objSetY) + WIDGET_PROP(obj); + INT32_PROP(y); +#if LVGL_VERSION_MAJOR >= 9 + lv_obj_set_y(obj, y); +#else + lv_obj_set_y(obj, (lv_coord_t)y); +#endif +ACTION_END +ACTION_START(objGetY) + WIDGET_PROP(obj); +#if LVGL_VERSION_MAJOR >= 9 + int32_t y = (int32_t)lv_obj_get_y(obj); +#else + int32_t y = lv_obj_get_y(obj); +#endif + RESULT(result, Value((int)y, VALUE_TYPE_INT32)); +ACTION_END +ACTION_START(objGetDisplayX) + WIDGET_PROP(obj); + lv_area_t area; + lv_obj_get_coords(obj, &area); + RESULT(result, Value((int)area.x1, VALUE_TYPE_INT32)); +ACTION_END +ACTION_START(objGetDisplayY) + WIDGET_PROP(obj); + lv_area_t area; + lv_obj_get_coords(obj, &area); + RESULT(result, Value((int)area.y1, VALUE_TYPE_INT32)); +ACTION_END +ACTION_START(objSetWidth) + WIDGET_PROP(obj); + INT32_PROP(width); +#if LVGL_VERSION_MAJOR >= 9 + lv_obj_set_width(obj, width); +#else + lv_obj_set_width(obj, (lv_coord_t)width); +#endif +ACTION_END +ACTION_START(objGetWidth) + WIDGET_PROP(obj); +#if LVGL_VERSION_MAJOR >= 9 + int32_t width = (int32_t)lv_obj_get_width(obj); +#else + int32_t width = lv_obj_get_width(obj); +#endif + RESULT(result, Value((int)width, VALUE_TYPE_INT32)); +ACTION_END +ACTION_START(objSetHeight) + WIDGET_PROP(obj); + INT32_PROP(height); +#if LVGL_VERSION_MAJOR >= 9 + lv_obj_set_height(obj, height); +#else + lv_obj_set_height(obj, (lv_coord_t)height); +#endif +ACTION_END +ACTION_START(objGetHeight) + WIDGET_PROP(obj); +#if LVGL_VERSION_MAJOR >= 9 + int32_t height = (int32_t)lv_obj_get_height(obj); +#else + int32_t height = lv_obj_get_height(obj); +#endif + RESULT(result, Value((int)height, VALUE_TYPE_INT32)); +ACTION_END +ACTION_START(objStyleSetProperty) + WIDGET_PROP(obj); + UINT32_PROP(property); + if (property == LV_STYLE_TEXT_FONT) { + STR_PROP(str); + const void *ptr = getLvglFontByNameHook(str); + if (ptr) { + UINT32_PROP(part); + UINT32_PROP(state); + lv_style_value_t style_value; + style_value.ptr = ptr; + lv_obj_set_local_style_prop(obj, (lv_style_prop_t)property, style_value, part | state); + } else { + throwError(flowState, componentIndex, FlowError::NotFoundInAction("Font", str, "objStyleSetProperty", actionIndex)); + } + } else if ( +#if LVGL_VERSION_MAJOR >= 9 + property == LV_STYLE_BG_IMAGE_SRC || + property == LV_STYLE_ARC_IMAGE_SRC +#else + property == LV_STYLE_BG_IMG_SRC || + property == LV_STYLE_ARC_IMG_SRC +#endif + ) { + STR_PROP(str); + const void *ptr = getLvglImageByNameHook(str); + if (ptr) { + UINT32_PROP(part); + UINT32_PROP(state); + lv_style_value_t style_value; + style_value.ptr = ptr; + lv_obj_set_local_style_prop(obj, (lv_style_prop_t)property, style_value, part | state); + } else { + throwError(flowState, componentIndex, FlowError::NotFoundInAction("Font", str, "objStyleSetProperty", actionIndex)); + } + } else if ( + property == LV_STYLE_BG_COLOR || + property == LV_STYLE_BG_GRAD_COLOR || +#if LVGL_VERSION_MAJOR >= 9 + property == LV_STYLE_BG_IMAGE_RECOLOR || +#else + property == LV_STYLE_BG_IMG_RECOLOR || +#endif + property == LV_STYLE_BORDER_COLOR || + property == LV_STYLE_OUTLINE_COLOR || + property == LV_STYLE_SHADOW_COLOR || + property == LV_STYLE_IMG_RECOLOR || + property == LV_STYLE_LINE_COLOR || + property == LV_STYLE_ARC_COLOR || + property == LV_STYLE_TEXT_COLOR + ) { + UINT32_PROP(value); + UINT32_PROP(part); + UINT32_PROP(state); + lv_style_value_t style_value; + style_value.color = lv_color_hex(value); + lv_obj_set_local_style_prop(obj, (lv_style_prop_t)property, style_value, part | state); + } else { + UINT32_PROP(value); + UINT32_PROP(part); + UINT32_PROP(state); + lv_style_value_t style_value; + style_value.num = value; + lv_obj_set_local_style_prop(obj, (lv_style_prop_t)property, style_value, part | state); + } + lv_obj_update_layout(obj); +ACTION_END +ACTION_START(objSetStyleOpa) + WIDGET_PROP(obj); + INT32_PROP(opa); + lv_obj_set_style_opa(obj, (lv_opa_t)opa, LV_PART_MAIN); +ACTION_END +ACTION_START(objGetStyleOpa) + WIDGET_PROP(obj); + int32_t opa = (int32_t)lv_obj_get_style_opa(obj, LV_PART_MAIN); + RESULT(result, Value((int)opa, VALUE_TYPE_INT32)); +ACTION_END +ACTION_START(objAddStyle) + WIDGET_PROP(obj); + STYLE_PROP(style); + lvglObjAddStyleHook(obj, style); +ACTION_END +ACTION_START(objRemoveStyle) + WIDGET_PROP(obj); + STYLE_PROP(style); + lvglObjRemoveStyleHook(obj, style); +ACTION_END +ACTION_START(objSetFlagHidden) + WIDGET_PROP(obj); + BOOL_PROP(hidden); + if (hidden) lv_obj_add_flag(obj, LV_OBJ_FLAG_HIDDEN); + else lv_obj_clear_flag(obj, LV_OBJ_FLAG_HIDDEN); +ACTION_END +ACTION_START(objAddFlag) + WIDGET_PROP(obj); + INT32_PROP(flag); + lv_obj_add_flag(obj, (lv_obj_flag_t)flag); +ACTION_END +ACTION_START(objClearFlag) + WIDGET_PROP(obj); + INT32_PROP(flag); + lv_obj_clear_flag(obj, (lv_obj_flag_t)flag); +ACTION_END +ACTION_START(objHasFlag) + WIDGET_PROP(obj); + INT32_PROP(flag); + bool result = lv_obj_has_flag(obj, (lv_obj_flag_t)flag); + RESULT(result, Value(result, VALUE_TYPE_BOOLEAN)); +ACTION_END +ACTION_START(objSetStateChecked) + WIDGET_PROP(obj); + BOOL_PROP(checked); + if (checked) lv_obj_add_state(obj, LV_STATE_CHECKED); + else lv_obj_clear_state(obj, LV_STATE_CHECKED); +ACTION_END +ACTION_START(objSetStateDisabled) + WIDGET_PROP(obj); + BOOL_PROP(disabled); + if (disabled) lv_obj_add_state(obj, LV_STATE_DISABLED); + else lv_obj_clear_state(obj, LV_STATE_DISABLED); +ACTION_END +ACTION_START(objAddState) + WIDGET_PROP(obj); + INT32_PROP(state); + lv_obj_add_state(obj, (lv_state_t)state); +ACTION_END +ACTION_START(objClearState) + WIDGET_PROP(obj); + INT32_PROP(state); + lv_obj_clear_state(obj, (lv_state_t)state); +ACTION_END +ACTION_START(objHasState) + WIDGET_PROP(obj); + INT32_PROP(flag); + bool result = lv_obj_has_state(obj, (lv_state_t)flag); + RESULT(result, Value(result, VALUE_TYPE_BOOLEAN)); +ACTION_END +ACTION_START(arcSetValue) + WIDGET_PROP(obj); + INT32_PROP(value); + lv_arc_set_value(obj, value); +ACTION_END +ACTION_START(arcRotateObjToAngle) + WIDGET_PROP(arcObj); + WIDGET_PROP(obj); + INT32_PROP(offset); + lv_arc_rotate_obj_to_angle(arcObj, obj, offset); +ACTION_END +ACTION_START(barSetValue) + WIDGET_PROP(obj); + INT32_PROP(value); + BOOL_PROP(animated); + lv_bar_set_value(obj, value, animated ? LV_ANIM_ON : LV_ANIM_OFF); +ACTION_END +ACTION_START(dropdownSetSelected) + WIDGET_PROP(obj); + UINT32_PROP(value); +#if LVGL_VERSION_MAJOR >= 9 + lv_dropdown_set_selected(obj, value); +#else + lv_dropdown_set_selected(obj, (uint16_t)value); +#endif +ACTION_END +ACTION_START(imageSetSrc) + WIDGET_PROP(obj); + STR_PROP(str); + const void *src = getLvglImageByNameHook(str); + if (src) { + lv_img_set_src(obj, src); + } else { + throwError(flowState, componentIndex, FlowError::NotFoundInAction("Image", str, "imageSetSrc", actionIndex)); + } +ACTION_END +ACTION_START(imageSetAngle) + WIDGET_PROP(obj); + INT16_PROP(angle); + lv_img_set_angle(obj, angle); +ACTION_END +ACTION_START(imageSetZoom) + WIDGET_PROP(obj); + UINT16_PROP(zoom); + lv_img_set_zoom(obj, zoom); +ACTION_END +ACTION_START(labelSetText) + WIDGET_PROP(obj); + STR_PROP(text); + lv_label_set_text(obj, text); +ACTION_END +ACTION_START(qrCodeUpdate) + WIDGET_PROP(obj); + STR_PROP(text); +#if LV_USE_QRCODE + lv_qrcode_update(obj, text, strlen(text)); +#else + EEZ_UNUSED(obj); + EEZ_UNUSED(text); +#endif +ACTION_END +ACTION_START(rollerSetSelected) + WIDGET_PROP(obj); + UINT32_PROP(selected); + BOOL_PROP(animated); +#if LVGL_VERSION_MAJOR >= 9 + lv_roller_set_selected(obj, selected, animated ? LV_ANIM_ON : LV_ANIM_OFF); +#else + lv_roller_set_selected(obj, (uint16_t)selected, animated ? LV_ANIM_ON : LV_ANIM_OFF); +#endif +ACTION_END +ACTION_START(sliderSetValue) + WIDGET_PROP(obj); + INT32_PROP(value); + BOOL_PROP(animated); + lv_slider_set_value(obj, value, animated ? LV_ANIM_ON : LV_ANIM_OFF); +ACTION_END +ACTION_START(sliderSetValueLeft) + WIDGET_PROP(obj); + INT32_PROP(valueLeft); + BOOL_PROP(animated); + lv_slider_set_left_value(obj, valueLeft, animated ? LV_ANIM_ON : LV_ANIM_OFF); +ACTION_END +ACTION_START(sliderSetRange) + WIDGET_PROP(obj); + INT32_PROP(min); + INT32_PROP(max); + lv_slider_set_range(obj, min, max); +ACTION_END +ACTION_START(keyboardSetTextarea) + WIDGET_PROP(obj); + WIDGET_PROP(textarea); + lv_keyboard_set_textarea(obj, textarea); +ACTION_END +ACTION_START(groupFocusObj) + WIDGET_PROP(obj); + lv_group_focus_obj(obj); +ACTION_END +ACTION_START(groupFocusNext) + GROUP_PROP(group); + lv_group_focus_next(group); +ACTION_END +ACTION_START(groupFocusPrev) + GROUP_PROP(group); + lv_group_focus_prev(group); +ACTION_END +ACTION_START(groupGetFocused) + GROUP_PROP(group); + lv_obj_t *obj = lv_group_get_focused(group); + RESULT(result, Value(obj, VALUE_TYPE_WIDGET)); +ACTION_END +ACTION_START(groupFocusFreeze) + GROUP_PROP(group); + BOOL_PROP(enabled); + lv_group_focus_freeze(group, enabled); +ACTION_END +ACTION_START(groupSetWrap) + GROUP_PROP(group); + BOOL_PROP(enabled); + lv_group_set_wrap(group, enabled); +ACTION_END +ACTION_START(groupSetEditing) + GROUP_PROP(group); + BOOL_PROP(enabled); + lv_group_set_editing(group, enabled); +ACTION_END +#define ANIM_PROPS \ + WIDGET_PROP(obj); \ + INT32_PROP(start); \ + INT32_PROP(end); \ + INT32_PROP(delay); \ + INT32_PROP(time); \ + BOOL_PROP(relative); \ + BOOL_PROP(instant); \ + INT32_PROP(path); +static void playAnimation(lv_obj_t *obj, + int32_t start, + int32_t end, + int32_t delay, + int32_t time, + bool relative, + bool instant, + int32_t path, + lv_anim_exec_xcb_t set_callback, + lv_anim_get_value_cb_t get_callback +) { + lv_anim_t anim; + lv_anim_init(&anim); + lv_anim_set_time(&anim, time); + lv_anim_set_user_data(&anim, obj); + lv_anim_set_var(&anim, obj); + lv_anim_set_exec_cb(&anim, set_callback); + lv_anim_set_values(&anim, start, end); + lv_anim_set_path_cb(&anim, anim_path_callbacks[path]); + lv_anim_set_delay(&anim, delay); + lv_anim_set_early_apply(&anim, instant ? true : false); + if (relative) { + lv_anim_set_get_value_cb(&anim, get_callback); + } + lv_anim_start(&anim); +} +ACTION_START(animX) + ANIM_PROPS; + playAnimation(obj, start, end, delay, time, relative, instant, path, anim_callback_set_x, anim_callback_get_x); +ACTION_END +ACTION_START(animY) + ANIM_PROPS; + playAnimation(obj, start, end, delay, time, relative, instant, path, anim_callback_set_y, anim_callback_get_y); +ACTION_END +ACTION_START(animWidth) + ANIM_PROPS; + playAnimation(obj, start, end, delay, time, relative, instant, path, anim_callback_set_width, anim_callback_get_width); +ACTION_END +ACTION_START(animHeight) + ANIM_PROPS; + playAnimation(obj, start, end, delay, time, relative, instant, path, anim_callback_set_height, anim_callback_get_height); +ACTION_END +ACTION_START(animOpacity) + ANIM_PROPS; + playAnimation(obj, start, end, delay, time, relative, instant, path, anim_callback_set_opacity, anim_callback_get_opacity); +ACTION_END +ACTION_START(animImageZoom) + ANIM_PROPS; + playAnimation(obj, start, end, delay, time, relative, instant, path, anim_callback_set_image_zoom, anim_callback_get_image_zoom); +ACTION_END +ACTION_START(animImageAngle) + ANIM_PROPS; + playAnimation(obj, start, end, delay, time, relative, instant, path, anim_callback_set_image_angle, anim_callback_get_image_angle); +ACTION_END +ACTION_START(createScreen) + SCREEN_PROP(screen); + eez_flow_create_screen(screen); +ACTION_END +ACTION_START(deleteScreen) + SCREEN_PROP(screen); + eez_flow_delete_screen(screen); +ACTION_END +ACTION_START(isScreenCreated) + SCREEN_PROP(screen); + bool isCreated = eez_flow_is_screen_created(screen); + RESULT(result, Value(isCreated, VALUE_TYPE_BOOLEAN)); +ACTION_END +ACTION_START(calendarSetTodayDate) + WIDGET_PROP(obj); + UINT32_PROP(year); + UINT32_PROP(month); + UINT32_PROP(day); + lv_calendar_set_today_date(obj, year, month, day); +ACTION_END +ACTION_START(calendarSetShowedDate) + WIDGET_PROP(obj); + UINT32_PROP(year); + UINT32_PROP(month); + lv_calendar_set_showed_date(obj, year, month); +ACTION_END +ACTION_START(calendarSetHighlightedDate) + WIDGET_PROP(obj); + UINT32_PROP(year); + UINT32_PROP(month); + UINT32_PROP(day); + lv_calendar_date_t d; + d.year = year; + d.month = month; + d.day = day; + lv_calendar_set_highlighted_dates(obj, &d, 1); +ACTION_END +ACTION_START(calendarGetPressedDate) + WIDGET_PROP(obj); + lv_calendar_date_t d; + lv_calendar_get_pressed_date(obj, &d); + RESULT(year, Value((int)d.year, VALUE_TYPE_INT32)); + RESULT(month, Value((int)d.month, VALUE_TYPE_INT32)); + RESULT(day, Value((int)d.day, VALUE_TYPE_INT32)); +ACTION_END +ACTION_START(buttonMatrixSetButtonCtrl) + WIDGET_PROP(obj); + UINT32_PROP(buttonID); + UINT32_PROP(ctrl); +#if LVGL_VERSION_MAJOR >= 9 + lv_buttonmatrix_set_button_ctrl(obj, buttonID, (lv_buttonmatrix_ctrl_t)ctrl); +#else + lv_btnmatrix_set_btn_ctrl(obj, buttonID, (lv_btnmatrix_ctrl_t)ctrl); +#endif +ACTION_END +ACTION_START(buttonMatrixClearButtonCtrl) + WIDGET_PROP(obj); + UINT32_PROP(buttonID); + UINT32_PROP(ctrl); +#if LVGL_VERSION_MAJOR >= 9 + lv_buttonmatrix_clear_button_ctrl(obj, buttonID, (lv_buttonmatrix_ctrl_t)ctrl); +#else + lv_btnmatrix_set_btn_ctrl(obj, buttonID, (lv_btnmatrix_ctrl_t)ctrl); +#endif +ACTION_END +ACTION_START(tabviewSetActiveTab) + WIDGET_PROP(obj); + UINT32_PROP(tabIndex); + BOOL_PROP(animated); +#if LVGL_VERSION_MAJOR >= 9 + lv_tabview_set_active(obj, tabIndex, animated ? LV_ANIM_ON : LV_ANIM_OFF); +#else + lv_tabview_set_act(obj, tabIndex, animated ? LV_ANIM_ON : LV_ANIM_OFF); +#endif +ACTION_END +ACTION_START(tabviewGetActiveTab) + WIDGET_PROP(obj); +#if LVGL_VERSION_MAJOR >= 9 + uint32_t tabIndex = lv_tabview_get_tab_active(obj); +#else + uint32_t tabIndex = (uint32_t)lv_tabview_get_tab_act(obj); +#endif + RESULT(result, Value((int)tabIndex, VALUE_TYPE_INT32)); +ACTION_END +typedef void (*ActionType)(FlowState *flowState, unsigned componentIndex, const ListOfAssetsPtr &properties, uint32_t actionIndex); +static ActionType actions[] = { + &changeScreen, + &changeToPreviousScreen, + &objSetX, + &objGetX, + &objSetY, + &objGetY, + &objSetWidth, + &objGetWidth, + &objSetHeight, + &objGetHeight, + &objSetStyleOpa, + &objGetStyleOpa, + &objAddStyle, + &objRemoveStyle, + &objSetFlagHidden, + &objAddFlag, + &objClearFlag, + &objHasFlag, + &objSetStateChecked, + &objSetStateDisabled, + &objAddState, + &objClearState, + &objHasState, + &arcSetValue, + &barSetValue, + &dropdownSetSelected, + &imageSetSrc, + &imageSetAngle, + &imageSetZoom, + &labelSetText, + &rollerSetSelected, + &sliderSetValue, + &keyboardSetTextarea, + &groupFocusObj, + &groupFocusNext, + &groupFocusPrev, + &groupGetFocused, + &groupFocusFreeze, + &groupSetWrap, + &groupSetEditing, + &animX, + &animY, + &animWidth, + &animHeight, + &animOpacity, + &animImageZoom, + &animImageAngle, + &createScreen, + &deleteScreen, + &isScreenCreated, + &calendarSetTodayDate, + &calendarSetShowedDate, + &calendarSetHighlightedDate, + &calendarGetPressedDate, + &buttonMatrixSetButtonCtrl, + &buttonMatrixClearButtonCtrl, + &sliderSetValueLeft, + &sliderSetRange, + &qrCodeUpdate, + &objStyleSetProperty, + &tabviewSetActiveTab, + &tabviewGetActiveTab, + &arcRotateObjToAngle, + &objGetDisplayX, + &objGetDisplayY +}; +struct LVGLApiExecutionState : public ComponenentExecutionState { + uint32_t actionIndex; +}; +void executeLVGLApiComponent(FlowState *flowState, unsigned componentIndex) { + auto component = (LVGLApiComponent *)flowState->flow->components[componentIndex]; + auto executionState = (LVGLApiExecutionState *)flowState->componenentExecutionStates[componentIndex]; + for (uint32_t actionIndex = executionState ? executionState->actionIndex : 0; actionIndex < component->actions.count; actionIndex++) { + auto actionType = (LVGLApiComponent_ActionType *)component->actions[actionIndex]; + (*actions[actionType->action])(flowState, componentIndex, actionType->properties, actionIndex); + } + propagateValueThroughSeqout(flowState, componentIndex); +} +} +} +// ----------------------------------------------------------------------------- +// flow/components/lvgl_user_widget.cpp +// ----------------------------------------------------------------------------- +namespace eez { +namespace flow { +struct LVGLUserWidgetComponent : public Component { + int16_t flowIndex; + uint8_t inputsStartIndex; + uint8_t outputsStartIndex; + int32_t widgetStartIndex; +}; +LVGLUserWidgetExecutionState *createUserWidgetFlowState(FlowState *flowState, unsigned userWidgetWidgetComponentIndex) { + auto component = (LVGLUserWidgetComponent *)flowState->flow->components[userWidgetWidgetComponentIndex]; + auto userWidgetFlowState = initPageFlowState(flowState->assets, component->flowIndex, flowState, userWidgetWidgetComponentIndex); + userWidgetFlowState->lvglWidgetStartIndex = component->widgetStartIndex; + auto offset = defs_v3::LVGL_USER_WIDGET_WIDGET_USER_PROPERTIES_START; + for (uint32_t i = offset; i < component->properties.count; i++) { + Value value = Value::makePropertyRef(flowState, userWidgetWidgetComponentIndex, i, 0x5166d8a4); + auto propValuePtr = userWidgetFlowState->values + userWidgetFlowState->flow->componentInputs.count + (i - offset); + *propValuePtr = value; + onValueChanged(propValuePtr); + } + auto userWidgetWidgetExecutionState = allocateComponentExecutionState(flowState, userWidgetWidgetComponentIndex); + userWidgetWidgetExecutionState->flowState = userWidgetFlowState; + return userWidgetWidgetExecutionState; +} +void executeLVGLUserWidgetComponent(FlowState *flowState, unsigned componentIndex) { + auto userWidgetWidgetExecutionState = (LVGLUserWidgetExecutionState *)flowState->componenentExecutionStates[componentIndex]; + if (!userWidgetWidgetExecutionState) { + userWidgetWidgetExecutionState = createUserWidgetFlowState(flowState, componentIndex); + } + auto userWidgetFlowState = userWidgetWidgetExecutionState->flowState; + for ( + unsigned userWidgetComponentIndex = 0; + userWidgetComponentIndex < userWidgetFlowState->flow->components.count; + userWidgetComponentIndex++ + ) { + auto userWidgetComponent = userWidgetFlowState->flow->components[userWidgetComponentIndex]; + if (userWidgetComponent->type == defs_v3::COMPONENT_TYPE_INPUT_ACTION) { + auto inputActionComponentExecutionState = (InputActionComponentExecutionState *)userWidgetFlowState->componenentExecutionStates[userWidgetComponentIndex]; + if (inputActionComponentExecutionState) { + Value value; + if (getCallActionValue(userWidgetFlowState, userWidgetComponentIndex, value)) { + if (inputActionComponentExecutionState->value != value) { + addToQueue(userWidgetWidgetExecutionState->flowState, userWidgetComponentIndex, -1, -1, -1, false); + inputActionComponentExecutionState->value = value; + } + } else { + return; + } + } + } else if (userWidgetComponent->type == defs_v3::COMPONENT_TYPE_START_ACTION) { + Value value; + if (getCallActionValue(userWidgetFlowState, userWidgetComponentIndex, value)) { + if (value.getType() != VALUE_TYPE_UNDEFINED) { + addToQueue(userWidgetWidgetExecutionState->flowState, userWidgetComponentIndex, -1, -1, -1, false); + } + } else { + return; + } + } + } +} +} +} +// ----------------------------------------------------------------------------- +// flow/components/mqtt.cpp +// ----------------------------------------------------------------------------- +#include +namespace eez { +namespace flow { +struct MQTTEventActionComponenent : public Component { + int16_t connectEventOutputIndex; + int16_t reconnectEventOutputIndex; + int16_t closeEventOutputIndex; + int16_t disconnectEventOutputIndex; + int16_t offlineEventOutputIndex; + int16_t endEventOutputIndex; + int16_t errorEventOutputIndex; + int16_t messageEventOutputIndex; +}; +struct MQTTEvent { + int16_t outputIndex; + Value value; + MQTTEvent *next; +}; +struct MQTTEventActionComponenentExecutionState : public ComponenentExecutionState { + FlowState *flowState; + unsigned componentIndex; + MQTTEvent *firstEvent; + MQTTEvent *lastEvent; + MQTTEventActionComponenentExecutionState() : firstEvent(nullptr), lastEvent(nullptr) {} + virtual ~MQTTEventActionComponenentExecutionState() override; + void addEvent(int16_t outputIndex, Value value = Value(VALUE_TYPE_NULL)) { + auto event = ObjectAllocator::allocate(0xe1b95933); + event->outputIndex = outputIndex; + event->value = value; + event->next = nullptr; + if (!firstEvent) { + firstEvent = event; + lastEvent = event; + } else { + lastEvent->next = event; + lastEvent = event; + } + } + MQTTEvent *removeEvent() { + auto event = firstEvent; + if (event) { + firstEvent = event->next; + if (!firstEvent) { + lastEvent = nullptr; + } + } + return event; + } +}; +struct MQTTConnectionEventHandler { + MQTTEventActionComponenentExecutionState *componentExecutionState; + MQTTConnectionEventHandler *next; + MQTTConnectionEventHandler *prev; +}; +struct MQTTConnection { + void *handle; + MQTTConnectionEventHandler *firstEventHandler; + MQTTConnectionEventHandler *lastEventHandler; + MQTTConnection *next; + MQTTConnection *prev; +}; +MQTTConnection *g_firstMQTTConnection = nullptr; +MQTTConnection *g_lastMQTTConnection = nullptr; +static MQTTConnection *addConnection(void *handle) { + auto connection = ObjectAllocator::allocate(0x95d9f5d1); + if (!connection) { + return nullptr; + } + connection->handle = handle; + connection->firstEventHandler = nullptr; + connection->lastEventHandler = nullptr; + if (!g_firstMQTTConnection) { + g_firstMQTTConnection = connection; + g_lastMQTTConnection = connection; + connection->prev = nullptr; + connection->next = nullptr; + } else { + g_lastMQTTConnection->next = connection; + connection->prev = g_lastMQTTConnection; + connection->next = nullptr; + g_lastMQTTConnection = connection; + } + return connection; +} +static MQTTConnection *findConnection(void *handle) { + for (auto connection = g_firstMQTTConnection; connection; connection = connection->next) { + if (connection->handle == handle) { + return connection; + } + } + return nullptr; +} +static void deleteConnection(void *handle) { + auto connection = findConnection(handle); + if (!connection) { + return; + } + while (connection->firstEventHandler) { + deallocateComponentExecutionState( + connection->firstEventHandler->componentExecutionState->flowState, + connection->firstEventHandler->componentExecutionState->componentIndex + ); + } + eez_mqtt_deinit(connection->handle); + if (connection->prev) { + connection->prev->next = connection->next; + } else { + g_firstMQTTConnection = connection->next; + } + if (connection->next) { + connection->next->prev = connection->prev; + } else { + g_lastMQTTConnection = connection->prev; + } + ObjectAllocator::deallocate(connection); +} +static MQTTConnectionEventHandler *addConnectionEventHandler(void *handle, MQTTEventActionComponenentExecutionState *componentExecutionState) { + auto connection = findConnection(handle); + if (!connection) { + return nullptr; + } + auto eventHandler = ObjectAllocator::allocate(0x75ccf1eb); + if (!eventHandler) { + return nullptr; + } + eventHandler->componentExecutionState = componentExecutionState; + if (!connection->firstEventHandler) { + connection->firstEventHandler = eventHandler; + connection->lastEventHandler = eventHandler; + eventHandler->prev = nullptr; + eventHandler->next = nullptr; + } else { + connection->lastEventHandler->next = eventHandler; + eventHandler->prev = connection->lastEventHandler; + eventHandler->next = nullptr; + connection->lastEventHandler = eventHandler; + } + return eventHandler; +} +static void removeEventHandler(MQTTEventActionComponenentExecutionState *componentExecutionState) { + for (auto connection = g_firstMQTTConnection; connection; connection = connection->next) { + for (auto eventHandler = connection->firstEventHandler; eventHandler; eventHandler = eventHandler->next) { + if (eventHandler->componentExecutionState == componentExecutionState) { + if (eventHandler->prev) { + eventHandler->prev->next = eventHandler->next; + } else { + connection->firstEventHandler = eventHandler->next; + } + if (eventHandler->next) { + eventHandler->next->prev = eventHandler->prev; + } else { + connection->lastEventHandler = eventHandler->prev; + } + ObjectAllocator::deallocate(eventHandler); + return; + } + } + } +} +void onFreeMQTTConnection(ArrayValue *mqttConnectionValue) { + void *handle = mqttConnectionValue->values[defs_v3::OBJECT_TYPE_MQTT_CONNECTION_FIELD_ID].getVoidPointer(); + deleteConnection(handle); +} +MQTTEventActionComponenentExecutionState::~MQTTEventActionComponenentExecutionState() { + removeEventHandler(this); + while (firstEvent) { + auto event = removeEvent(); + ObjectAllocator::deallocate(event); + } +} +void executeMQTTInitComponent(FlowState *flowState, unsigned componentIndex) { + Value connectionDstValue; + if (!evalAssignableProperty(flowState, componentIndex, defs_v3::MQTT_INIT_ACTION_COMPONENT_PROPERTY_CONNECTION, connectionDstValue, FlowError::Property("MQTTInit", "Connection"))) { + return; + } + Value protocolValue; + if (!evalProperty(flowState, componentIndex, defs_v3::MQTT_INIT_ACTION_COMPONENT_PROPERTY_PROTOCOL, protocolValue, FlowError::Property("MQTTInit", "Protocol"))) { + return; + } + if (!protocolValue.isString()) { + throwError(flowState, componentIndex, FlowError::Plain("Protocol must be a string")); + return; + } + Value hostValue; + if (!evalProperty(flowState, componentIndex, defs_v3::MQTT_INIT_ACTION_COMPONENT_PROPERTY_HOST, hostValue, FlowError::Property("MQTTInit", "Host"))) { + return; + } + if (!hostValue.isString()) { + throwError(flowState, componentIndex, FlowError::Plain("Host must be a string")); + return; + } + Value portValue; + if (!evalProperty(flowState, componentIndex, defs_v3::MQTT_INIT_ACTION_COMPONENT_PROPERTY_PORT, portValue, FlowError::Property("MQTTInit", "Port"))) { + return; + } + if (portValue.getType() != VALUE_TYPE_INT32) { + throwError(flowState, componentIndex, FlowError::Plain("Port must be an integer")); + return; + } + Value usernameValue; + if (!evalProperty(flowState, componentIndex, defs_v3::MQTT_INIT_ACTION_COMPONENT_PROPERTY_USER_NAME, usernameValue, FlowError::Property("MQTTInit", "Username"))) { + return; + } + if (usernameValue.getType() != VALUE_TYPE_UNDEFINED && !usernameValue.isString()) { + throwError(flowState, componentIndex, FlowError::Plain("Username must be a string")); + return; + } + Value passwordValue; + if (!evalProperty(flowState, componentIndex, defs_v3::MQTT_INIT_ACTION_COMPONENT_PROPERTY_PASSWORD, passwordValue, FlowError::Property("MQTTInit", "Password"))) { + return; + } + if (passwordValue.getType() != VALUE_TYPE_UNDEFINED && !passwordValue.isString()) { + throwError(flowState, componentIndex, FlowError::Plain("Password must be a string")); + return; + } + void *handle; + auto result = eez_mqtt_init(protocolValue.getString(), hostValue.getString(), portValue.getInt32(), usernameValue.getString(), passwordValue.getString(), &handle); + if (result != MQTT_ERROR_OK) { + char errorMessage[256]; + snprintf(errorMessage, sizeof(errorMessage), "Failed to initialize MQTT connection with error code: %d", (int)result); + throwError(flowState, componentIndex, FlowError::Plain(errorMessage)); + return; + } + addConnection(handle); + Value connectionValue = Value::makeArrayRef(defs_v3::OBJECT_TYPE_MQTT_CONNECTION_NUM_FIELDS, defs_v3::OBJECT_TYPE_MQTT_CONNECTION, 0x51ba2203); + auto connectionArray = connectionValue.getArray(); + connectionArray->values[defs_v3::OBJECT_TYPE_MQTT_CONNECTION_FIELD_PROTOCOL] = protocolValue; + connectionArray->values[defs_v3::OBJECT_TYPE_MQTT_CONNECTION_FIELD_HOST] = hostValue; + connectionArray->values[defs_v3::OBJECT_TYPE_MQTT_CONNECTION_FIELD_PORT] = portValue; + connectionArray->values[defs_v3::OBJECT_TYPE_MQTT_CONNECTION_FIELD_USER_NAME] = usernameValue; + connectionArray->values[defs_v3::OBJECT_TYPE_MQTT_CONNECTION_FIELD_PASSWORD] = passwordValue; + connectionArray->values[defs_v3::OBJECT_TYPE_MQTT_CONNECTION_FIELD_IS_CONNECTED] = Value(false, VALUE_TYPE_BOOLEAN); + connectionArray->values[defs_v3::OBJECT_TYPE_MQTT_CONNECTION_FIELD_ID] = Value(handle, VALUE_TYPE_POINTER); + Value statusValue = Value::makeArrayRef(defs_v3::SYSTEM_STRUCTURE_OBJECT_VARIABLE_STATUS_NUM_FIELDS, defs_v3::SYSTEM_STRUCTURE_OBJECT_VARIABLE_STATUS, 0x51ba2203); + auto statusArray = statusValue.getArray(); + statusArray->values[defs_v3::SYSTEM_STRUCTURE_OBJECT_VARIABLE_STATUS_FIELD_LABEL] = Value("", VALUE_TYPE_STRING); + statusArray->values[defs_v3::SYSTEM_STRUCTURE_OBJECT_VARIABLE_STATUS_FIELD_IMAGE] = Value("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABgAAAAYCAYAAADgdz34AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsIAAA7CARUoSoAAAAItSURBVEhL1dZNSBVRGMbxmcjCiFz14aJVlKtcVFjUJghCIlq5aBHoQiwoyJaRCzdRUUhQUIuIyKiEdoLuolCQEgQzyk8KjTZhidEnwe3/nJl3ermc8m5c9MCPmTtn5rz3zMw596alUilZzqzIt8uWYgRpmp5ncxQ/4YelL/EJ9/AQ87CkOIMT4VOS/MIq9NDvuXBEBfIiL/VxCW/Qjmr4tMG+mMwU/boCW7ETB3EKdzEFu8h7jr3w0XUandrHYwViWYdDeAT/DeUbTsPnAL5jOlZAw9b9+1v2oB++iFyGzzFER9CHEfTiAhpRg/KcxGf4Ilfh0xIrMAN/kUyjE7Xw2Yc5+HM7UCRWQJ35C7x3aIVPPWbhzzuCkFgBPczj6MIQyh+q3MEaWBqgOWLteo03IVrAR5NrF26jvJCe1VpYmuHbr2PJAj778Qq+kx74ZeYBrO0r6mMF9CbcQAs264CLHvIgrBM5C8s2LMDabsUK6P7ZCR9wCf413YgXsHMWsR2Wa7C2iViBcXeCGcYWWHbjC6y9G5Yd0CzW8ehEixWQUWyA5QqsTROuDopW1gHoeFGgkt8Dve8Xs92Qm9DtUfQ2Hc52Q8ePs90/qfQHR+uLXltFE/JpthuiBc7yLN9qNCGVFqhCU7Yb8iTfKrpFWnWVt/iBaAF18q9o/bFM5FtFr/D6bDf5CBUoVmVf4D40fD3s12V0XPd9NZT30OSbzK2Eokk2Bk28kP/9X0WS/AaVCm1sgeHGuwAAAABJRU5ErkJggg==", VALUE_TYPE_STRING); + statusArray->values[defs_v3::SYSTEM_STRUCTURE_OBJECT_VARIABLE_STATUS_FIELD_COLOR] = Value("gray", VALUE_TYPE_STRING); + statusArray->values[defs_v3::SYSTEM_STRUCTURE_OBJECT_VARIABLE_STATUS_FIELD_ERROR] = Value(); + connectionArray->values[defs_v3::OBJECT_TYPE_MQTT_CONNECTION_FIELD_STATUS] = statusValue; + assignValue(flowState, componentIndex, connectionDstValue, connectionValue); + propagateValueThroughSeqout(flowState, componentIndex); +} +void executeMQTTConnectComponent(FlowState *flowState, unsigned componentIndex) { + Value connectionValue; + if (!evalProperty(flowState, componentIndex, defs_v3::MQTT_CONNECT_ACTION_COMPONENT_PROPERTY_CONNECTION, connectionValue, FlowError::Property("MQTTConnect", "Connection"))) { + return; + } + if (!connectionValue.isArray() || connectionValue.getArray()->arrayType != defs_v3::OBJECT_TYPE_MQTT_CONNECTION) { + throwError(flowState, componentIndex, FlowError::Plain("Connection must be a object:MQTTConnection")); + return; + } + auto connectionArray = connectionValue.getArray(); + void *handle = connectionArray->values[defs_v3::OBJECT_TYPE_MQTT_CONNECTION_FIELD_ID].getVoidPointer(); + auto result = eez_mqtt_connect(handle); + if (result != MQTT_ERROR_OK) { + char errorMessage[256]; + snprintf(errorMessage, sizeof(errorMessage), "Failed to connect to MQTT broker with error code: %d", (int)result); + throwError(flowState, componentIndex, FlowError::Plain(errorMessage)); + return; + } + propagateValueThroughSeqout(flowState, componentIndex); +} +void executeMQTTDisconnectComponent(FlowState *flowState, unsigned componentIndex) { + Value connectionValue; + if (!evalProperty(flowState, componentIndex, defs_v3::MQTT_DISCONNECT_ACTION_COMPONENT_PROPERTY_CONNECTION, connectionValue, FlowError::Property("MQTTDisconnect", "Connection"))) { + return; + } + if (!connectionValue.isArray() || connectionValue.getArray()->arrayType != defs_v3::OBJECT_TYPE_MQTT_CONNECTION) { + throwError(flowState, componentIndex, FlowError::Plain("Connection must be a object:MQTTConnection")); + return; + } + auto connectionArray = connectionValue.getArray(); + void *handle = connectionArray->values[defs_v3::OBJECT_TYPE_MQTT_CONNECTION_FIELD_ID].getVoidPointer(); + auto result = eez_mqtt_disconnect(handle); + if (result != MQTT_ERROR_OK) { + char errorMessage[256]; + snprintf(errorMessage, sizeof(errorMessage), "Failed to disconnect from MQTT broker with error code: %d", (int)result); + throwError(flowState, componentIndex, FlowError::Plain(errorMessage)); + return; + } + propagateValueThroughSeqout(flowState, componentIndex); +} +void executeMQTTEventComponent(FlowState *flowState, unsigned componentIndex) { + Value connectionValue; + if (!evalProperty(flowState, componentIndex, defs_v3::MQTT_EVENT_ACTION_COMPONENT_PROPERTY_CONNECTION, connectionValue, FlowError::Property("MQTTEvent", "Connection"))) { + return; + } + if (!connectionValue.isArray() || connectionValue.getArray()->arrayType != defs_v3::OBJECT_TYPE_MQTT_CONNECTION) { + throwError(flowState, componentIndex, FlowError::Plain("Connection must be a object:MQTTConnection")); + return; + } + auto componentExecutionState = (MQTTEventActionComponenentExecutionState *)flowState->componenentExecutionStates[componentIndex]; + if (!componentExecutionState) { + componentExecutionState = allocateComponentExecutionState(flowState, componentIndex); + componentExecutionState->flowState = flowState; + componentExecutionState->componentIndex = componentIndex; + auto connectionArray = connectionValue.getArray(); + void *handle = connectionArray->values[defs_v3::OBJECT_TYPE_MQTT_CONNECTION_FIELD_ID].getVoidPointer(); + addConnectionEventHandler(handle, componentExecutionState); + propagateValueThroughSeqout(flowState, componentIndex); + addToQueue(flowState, componentIndex, -1, -1, -1, true); + } else { + auto event = componentExecutionState->removeEvent(); + if (event) { + propagateValue(flowState, componentIndex, event->outputIndex, event->value); + ObjectAllocator::deallocate(event); + } else { + addToQueue(flowState, componentIndex, -1, -1, -1, true); + } + } +} +void executeMQTTSubscribeComponent(FlowState *flowState, unsigned componentIndex) { + Value connectionValue; + if (!evalProperty(flowState, componentIndex, defs_v3::MQTT_SUBSCRIBE_ACTION_COMPONENT_PROPERTY_CONNECTION, connectionValue, FlowError::Property("MQTTSubscribe", "Connection"))) { + return; + } + if (!connectionValue.isArray() || connectionValue.getArray()->arrayType != defs_v3::OBJECT_TYPE_MQTT_CONNECTION) { + throwError(flowState, componentIndex, FlowError::Plain("Connection must be a object:MQTTConnection")); + return; + } + Value topicValue; + if (!evalProperty(flowState, componentIndex, defs_v3::MQTT_SUBSCRIBE_ACTION_COMPONENT_PROPERTY_TOPIC, topicValue, FlowError::Property("MQTTSubscribe", "Topic"))) { + return; + } + if (!topicValue.isString()) { + throwError(flowState, componentIndex, FlowError::Plain("Topic must be a string")); + return; + } + auto connectionArray = connectionValue.getArray(); + void *handle = connectionArray->values[defs_v3::OBJECT_TYPE_MQTT_CONNECTION_FIELD_ID].getVoidPointer(); + auto result = eez_mqtt_subscribe(handle, topicValue.getString()); + if (result != MQTT_ERROR_OK) { + char errorMessage[256]; + snprintf(errorMessage, sizeof(errorMessage), "Failed to subscribe to MQTT topic with error code: %d", (int)result); + throwError(flowState, componentIndex, FlowError::Plain(errorMessage)); + return; + } + propagateValueThroughSeqout(flowState, componentIndex); +} +void executeMQTTUnsubscribeComponent(FlowState *flowState, unsigned componentIndex) { + Value connectionValue; + if (!evalProperty(flowState, componentIndex, defs_v3::MQTT_UNSUBSCRIBE_ACTION_COMPONENT_PROPERTY_CONNECTION, connectionValue, FlowError::Property("MQTTUnsubscribe", "Connection"))) { + return; + } + if (!connectionValue.isArray() || connectionValue.getArray()->arrayType != defs_v3::OBJECT_TYPE_MQTT_CONNECTION) { + throwError(flowState, componentIndex, FlowError::Plain("Connection must be a object:MQTTConnection")); + return; + } + Value topicValue; + if (!evalProperty(flowState, componentIndex, defs_v3::MQTT_UNSUBSCRIBE_ACTION_COMPONENT_PROPERTY_TOPIC, topicValue, FlowError::Property("MQTTUnsubscribe", "Topic"))) { + return; + } + if (!topicValue.isString()) { + throwError(flowState, componentIndex, FlowError::Plain("Topic must be a string")); + return; + } + auto connectionArray = connectionValue.getArray(); + void *handle = connectionArray->values[defs_v3::OBJECT_TYPE_MQTT_CONNECTION_FIELD_ID].getVoidPointer(); + auto result = eez_mqtt_unsubscribe(handle, topicValue.getString()); + if (result != MQTT_ERROR_OK) { + char errorMessage[256]; + snprintf(errorMessage, sizeof(errorMessage), "Failed to unsubscribe from MQTT topic with error code: %d", (int)result); + throwError(flowState, componentIndex, FlowError::Plain(errorMessage)); + return; + } + propagateValueThroughSeqout(flowState, componentIndex); +} +void executeMQTTPublishComponent(FlowState *flowState, unsigned componentIndex) { + Value connectionValue; + if (!evalProperty(flowState, componentIndex, defs_v3::MQTT_PUBLISH_ACTION_COMPONENT_PROPERTY_CONNECTION, connectionValue, FlowError::Property("MQTTPublish", "Connection"))) { + return; + } + if (!connectionValue.isArray() || connectionValue.getArray()->arrayType != defs_v3::OBJECT_TYPE_MQTT_CONNECTION) { + throwError(flowState, componentIndex, FlowError::Plain("Connection must be a object:MQTTConnection")); + return; + } + Value topicValue; + if (!evalProperty(flowState, componentIndex, defs_v3::MQTT_PUBLISH_ACTION_COMPONENT_PROPERTY_TOPIC, topicValue, FlowError::Property("MQTTPublish", "Topic"))) { + return; + } + if (!topicValue.isString()) { + throwError(flowState, componentIndex, FlowError::Plain("Topic must be a string")); + return; + } + Value payloadValue; + if (!evalProperty(flowState, componentIndex, defs_v3::MQTT_PUBLISH_ACTION_COMPONENT_PROPERTY_PAYLOAD, payloadValue, FlowError::Property("MQTTPublish", "Payload"))) { + return; + } + if (!payloadValue.isString()) { + throwError(flowState, componentIndex, FlowError::Plain("Payload must be a string")); + return; + } + auto connectionArray = connectionValue.getArray(); + void *handle = connectionArray->values[defs_v3::OBJECT_TYPE_MQTT_CONNECTION_FIELD_ID].getVoidPointer(); + auto result = eez_mqtt_publish(handle, topicValue.getString(), payloadValue.getString()); + if (result != MQTT_ERROR_OK) { + char errorMessage[256]; + snprintf(errorMessage, sizeof(errorMessage), "Failed to subscribe to MQTT topic with error code: %d", (int)result); + throwError(flowState, componentIndex, FlowError::Plain(errorMessage)); + return; + } + propagateValueThroughSeqout(flowState, componentIndex); +} +} +} +#ifndef EEZ_MQTT_ADAPTER +int eez_mqtt_init(const char *protocol, const char *host, int port, const char *username, const char *password, void **handle) { + EEZ_UNUSED(protocol); + EEZ_UNUSED(host); + EEZ_UNUSED(port); + EEZ_UNUSED(username); + EEZ_UNUSED(password); + EEZ_UNUSED(handle); + return MQTT_ERROR_NOT_IMPLEMENTED; +} +int eez_mqtt_deinit(void *handle) { + EEZ_UNUSED(handle); + return MQTT_ERROR_NOT_IMPLEMENTED; +} +int eez_mqtt_connect(void *handle) { + EEZ_UNUSED(handle); + return MQTT_ERROR_NOT_IMPLEMENTED; +} +int eez_mqtt_disconnect(void *handle) { + EEZ_UNUSED(handle); + return MQTT_ERROR_NOT_IMPLEMENTED; +} +int eez_mqtt_subscribe(void *handle, const char *topic) { + EEZ_UNUSED(handle); + EEZ_UNUSED(topic); + return MQTT_ERROR_NOT_IMPLEMENTED; +} +int eez_mqtt_unsubscribe(void *handle, const char *topic) { + EEZ_UNUSED(handle); + EEZ_UNUSED(topic); + return MQTT_ERROR_NOT_IMPLEMENTED; +} +int eez_mqtt_publish(void *handle, const char *topic, const char *payload) { + EEZ_UNUSED(handle); + EEZ_UNUSED(topic); + EEZ_UNUSED(payload); + return MQTT_ERROR_NOT_IMPLEMENTED; +} +#endif +// ----------------------------------------------------------------------------- +// flow/components/noop.cpp +// ----------------------------------------------------------------------------- +namespace eez { +namespace flow { +void executeNoopComponent(FlowState *flowState, unsigned componentIndex) { + propagateValueThroughSeqout(flowState, componentIndex); +} +} +} +// ----------------------------------------------------------------------------- +// flow/components/on_event.cpp +// ----------------------------------------------------------------------------- +namespace eez { +namespace flow { +void executeOnEventComponent(FlowState *flowState, unsigned componentIndex) { + propagateValue(flowState, componentIndex, 1, flowState->eventValue); + propagateValueThroughSeqout(flowState, componentIndex); +} +} +} +// ----------------------------------------------------------------------------- +// flow/components/output.cpp +// ----------------------------------------------------------------------------- +namespace eez { +namespace flow { +struct OutputActionComponent : public Component { + uint8_t outputIndex; +}; +void executeOutputComponent(FlowState *flowState, unsigned componentIndex) { + auto component = (OutputActionComponent *)flowState->flow->components[componentIndex]; + if (!flowState->parentFlowState) { + throwError(flowState, componentIndex, FlowError::Plain("No parentFlowState in Output")); + return; + } + if (!flowState->parentComponent) { + throwError(flowState, componentIndex, FlowError::Plain("No parentComponent in Output")); + return; + } + auto inputIndex = component->inputs[0]; + if (inputIndex >= flowState->flow->componentInputs.count) { + throwError(flowState, componentIndex, FlowError::Plain("Invalid input index in Output")); + return; + } + auto value = flowState->values[inputIndex]; + auto callActionComponent = (CallActionActionComponent *)flowState->parentComponent; + uint8_t parentComponentOutputIndex = callActionComponent->outputsStartIndex + component->outputIndex; + if (parentComponentOutputIndex >= flowState->parentComponent->outputs.count) { + throwError(flowState, componentIndex, FlowError::Plain("Output action component, invalid output index")); + return; + } + propagateValue(flowState->parentFlowState, flowState->parentComponentIndex, parentComponentOutputIndex, value); +} +} +} +// ----------------------------------------------------------------------------- +// flow/components/select_language.cpp +// ----------------------------------------------------------------------------- +#include +#include +namespace eez { +namespace flow { +void executeSelectLanguageComponent(FlowState *flowState, unsigned componentIndex) { + Value languageValue; + if (!evalProperty(flowState, componentIndex, defs_v3::SELECT_LANGUAGE_ACTION_COMPONENT_PROPERTY_LANGUAGE, languageValue, FlowError::Property("SelectLanguage", "Language"))) { + return; + } + const char *language = languageValue.getString(); + auto &languages = flowState->assets->languages; + for (uint32_t languageIndex = 0; languageIndex < languages.count; languageIndex++) { + if (strcmp(languages[languageIndex]->languageID, language) == 0) { + g_selectedLanguage = languageIndex; + propagateValueThroughSeqout(flowState, componentIndex); + return; + } + } + char message[256]; + snprintf(message, sizeof(message), "Unknown language %s", language); + throwError(flowState, componentIndex, FlowError::Plain(message)); +} +} +} +// ----------------------------------------------------------------------------- +// flow/components/set_color_theme.cpp +// ----------------------------------------------------------------------------- +#include +#include +namespace eez { +namespace flow { +void executeSetColorThemeComponent(FlowState *flowState, unsigned componentIndex) { + Value themeValue; + if (!evalProperty(flowState, componentIndex, defs_v3::SET_COLOR_THEME_ACTION_COMPONENT_PROPERTY_THEME, themeValue, FlowError::Property("SetColorTheme", "Theme"))) { + return; + } + const char *theme = themeValue.getString(); + lvglSetColorThemeHook(theme); +} +} +} +// ----------------------------------------------------------------------------- +// flow/components/set_variable.cpp +// ----------------------------------------------------------------------------- +#include +namespace eez { +namespace flow { +void executeSetVariableComponent(FlowState *flowState, unsigned componentIndex) { + auto component = (SetVariableActionComponent *)flowState->flow->components[componentIndex]; + for (uint32_t entryIndex = 0; entryIndex < component->entries.count; entryIndex++) { + auto entry = component->entries[entryIndex]; + Value dstValue; + if (!evalAssignableExpression(flowState, componentIndex, entry->variable, dstValue, FlowError::PropertyInArray("SetVariable", "Variable", entryIndex))) { + return; + } + Value srcValue; + if (!evalExpression(flowState, componentIndex, entry->value, srcValue, FlowError::PropertyInArray("SetVariable", "Value", entryIndex))) { + return; + } + assignValue(flowState, componentIndex, dstValue, srcValue); + } + propagateValueThroughSeqout(flowState, componentIndex); +} +} +} +// ----------------------------------------------------------------------------- +// flow/components/show_page.cpp +// ----------------------------------------------------------------------------- +namespace eez { +namespace flow { +struct ShowPageActionComponent : public Component { + int16_t page; +}; +void executeShowPageComponent(FlowState *flowState, unsigned componentIndex) { + auto component = (ShowPageActionComponent *)flowState->flow->components[componentIndex]; + replacePageHook(component->page, 0, 0, 0); + propagateValueThroughSeqout(flowState, componentIndex); +} +} +} +// ----------------------------------------------------------------------------- +// flow/components/sort_array.cpp +// ----------------------------------------------------------------------------- +#include +#include +namespace eez { +namespace flow { +SortArrayActionComponent *g_sortArrayActionComponent; +static int elementCompare(const void *a, const void *b) { + auto aValue = *(const Value *)a; + auto bValue = *(const Value *)b; + if (g_sortArrayActionComponent->arrayType != -1) { + if (!aValue.isArray()) { + return 0; + } + auto aArray = aValue.getArray(); + if ((uint32_t)g_sortArrayActionComponent->structFieldIndex >= aArray->arraySize) { + return 0; + } + aValue = aArray->values[g_sortArrayActionComponent->structFieldIndex]; + if (!bValue.isArray()) { + return 0; + } + auto bArray = bValue.getArray(); + if ((uint32_t)g_sortArrayActionComponent->structFieldIndex >= bArray->arraySize) { + return 0; + } + bValue = bArray->values[g_sortArrayActionComponent->structFieldIndex]; + } + int result; + if (aValue.isString() && bValue.isString()) { + if (g_sortArrayActionComponent->flags & SORT_ARRAY_FLAG_IGNORE_CASE) { + result = utf8casecmp(aValue.getString(), bValue.getString()); + } else { + result = utf8cmp(aValue.getString(), bValue.getString()); + } + } else { + int err; + float aDouble = aValue.toDouble(&err); + if (err) { + return 0; + } + float bDouble = bValue.toDouble(&err); + if (err) { + return 0; + } + auto diff = aDouble - bDouble; + result = diff < 0 ? -1 : diff > 0 ? 1 : 0; + } + if (!(g_sortArrayActionComponent->flags & SORT_ARRAY_FLAG_ASCENDING)) { + result = -result; + } + return result; +} +void sortArray(SortArrayActionComponent *component, ArrayValue *array) { + g_sortArrayActionComponent = component; + qsort(&array->values[0], array->arraySize, sizeof(Value), elementCompare); +} +void executeSortArrayComponent(FlowState *flowState, unsigned componentIndex) { + auto component = (SortArrayActionComponent *)flowState->flow->components[componentIndex]; + Value srcArrayValue; + if (!evalProperty(flowState, componentIndex, defs_v3::SORT_ARRAY_ACTION_COMPONENT_PROPERTY_ARRAY, srcArrayValue, FlowError::Property("SortArray", "Array"))) { + return; + } + if (!srcArrayValue.isArray()) { + throwError(flowState, componentIndex, FlowError::Plain("SortArray: not an array\n")); + return; + } + auto arrayValue = srcArrayValue.clone(); + auto array = arrayValue.getArray(); + if (component->arrayType != -1) { + if (array->arrayType != (uint32_t)component->arrayType) { + throwError(flowState, componentIndex, FlowError::Plain("SortArray: invalid array type\n")); + return; + } + if (component->structFieldIndex < 0) { + throwError(flowState, componentIndex, FlowError::Plain("SortArray: invalid struct field index\n")); + } + } else { + if (array->arrayType != defs_v3::ARRAY_TYPE_INTEGER && array->arrayType != defs_v3::ARRAY_TYPE_FLOAT && array->arrayType != defs_v3::ARRAY_TYPE_DOUBLE && array->arrayType != defs_v3::ARRAY_TYPE_STRING) { + throwError(flowState, componentIndex, FlowError::Plain("SortArray: array type is neither array:integer or array:float or array:double or array:string\n")); + return; + } + } + sortArray(component, array); + propagateValue(flowState, componentIndex, component->outputs.count - 1, arrayValue); +} +} +} +// ----------------------------------------------------------------------------- +// flow/components/start.cpp +// ----------------------------------------------------------------------------- +namespace eez { +namespace flow { +void executeStartComponent(FlowState *flowState, unsigned componentIndex) { + propagateValueThroughSeqout(flowState, componentIndex); +} +} +} +// ----------------------------------------------------------------------------- +// flow/components/switch.cpp +// ----------------------------------------------------------------------------- +#include +namespace eez { +namespace flow { +void executeSwitchComponent(FlowState *flowState, unsigned componentIndex) { + auto component = (SwitchActionComponent *)flowState->flow->components[componentIndex]; + for (uint32_t testIndex = 0; testIndex < component->tests.count; testIndex++) { + auto test = component->tests[testIndex]; + Value conditionValue; + if (!evalExpression(flowState, componentIndex, test->condition, conditionValue, FlowError::PropertyInArray("Switch", "Test condition", testIndex))) { + return; + } + int err; + bool result = conditionValue.toBool(&err); + if (err) { + throwError(flowState, componentIndex, FlowError::PropertyInArrayConvert("Switch", "Test condition", "boolean", testIndex)); + return; + } + if (result) { + Value outputValue; + if (!evalExpression(flowState, componentIndex, test->outputValue, outputValue, FlowError::PropertyInArray("Switch", "Test output", testIndex))) { + return; + } + propagateValue(flowState, componentIndex, test->outputIndex, outputValue); + break; + } + } + propagateValueThroughSeqout(flowState, componentIndex); +} +} +} +// ----------------------------------------------------------------------------- +// flow/components/test_and_set.cpp +// ----------------------------------------------------------------------------- +namespace eez { +namespace flow { +void executeTestAndSetComponent(FlowState *flowState, unsigned componentIndex) { + Value dstValue; + if (!evalAssignableProperty(flowState, componentIndex, defs_v3::TEST_AND_SET_ACTION_COMPONENT_PROPERTY_VARIABLE, dstValue, FlowError::Property("TestAndSet", "Variable"))) { + return; + } + if (dstValue.getValue().type != VALUE_TYPE_BOOLEAN) { + throwError(flowState, componentIndex, FlowError::PropertyConvert("TestAndSet", "Variable", "boolean")); + return; + } + if (!dstValue.getValue().getBoolean()) { + assignValue(flowState, componentIndex, dstValue, Value(true, VALUE_TYPE_BOOLEAN)); + propagateValueThroughSeqout(flowState, componentIndex); + } else { + addToQueue(flowState, componentIndex, -1, -1, -1, true); + } +} +} +} +// ----------------------------------------------------------------------------- +// flow/components/watch_variable.cpp +// ----------------------------------------------------------------------------- +#include +namespace eez { +namespace flow { +struct WatchVariableComponenentExecutionState : public ComponenentExecutionState { + Value value; + WatchListNode *node; +}; +void executeWatchVariableComponent(FlowState *flowState, unsigned componentIndex) { + auto watchVariableComponentExecutionState = (WatchVariableComponenentExecutionState *)flowState->componenentExecutionStates[componentIndex]; + Value value; + if (!evalProperty(flowState, componentIndex, defs_v3::WATCH_VARIABLE_ACTION_COMPONENT_PROPERTY_VARIABLE, value, FlowError::Property("WatchVariable", "Variable"))) { + return; + } + if (!watchVariableComponentExecutionState) { + watchVariableComponentExecutionState = allocateComponentExecutionState(flowState, componentIndex); + watchVariableComponentExecutionState->value = value.type == VALUE_TYPE_STRING ? value.clone() : value; + watchVariableComponentExecutionState->node = watchListAdd(flowState, componentIndex); + propagateValue(flowState, componentIndex, 1, value); + } else { + if (value != watchVariableComponentExecutionState->value) { + watchVariableComponentExecutionState->value = value.type == VALUE_TYPE_STRING ? value.clone() : value; + propagateValue(flowState, componentIndex, 1, value); + } + } +} +} +} +// ----------------------------------------------------------------------------- +// flow/date.cpp +// ----------------------------------------------------------------------------- +#include +namespace eez { +namespace flow { +namespace date { +#define SECONDS_PER_MINUTE 60UL +#define SECONDS_PER_HOUR (SECONDS_PER_MINUTE * 60) +#define SECONDS_PER_DAY (SECONDS_PER_HOUR * 24) +#define LEAP_YEAR(Y) \ + (((1970 + Y) > 0) && !((1970 + Y) % 4) && (((1970 + Y) % 100) || !((1970 + Y) % 400))) +static const uint8_t monthDays[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; +enum Week { Last, First, Second, Third, Fourth }; +enum DayOfWeek { Sun = 1, Mon, Tue, Wed, Thu, Fri, Sat }; +enum Month { Jan = 1, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec }; +struct TimeChangeRule { + Week week; + DayOfWeek dow; + uint8_t month; + uint8_t hours; +}; +static struct { + TimeChangeRule dstStart; + TimeChangeRule dstEnd; +} g_dstRules[] = { + { { Last, Sun, Mar, 2 }, { Last, Sun, Oct, 3 } }, + { { Second, Sun, Mar, 2 }, { First, Sun, Nov, 2 } }, + { { First, Sun, Oct, 2 }, { First, Sun, Apr, 3 } }, +}; +Format g_localeFormat = FORMAT_DMY_24; +int g_timeZone = 0; +DstRule g_dstRule = DST_RULE_OFF; +static void convertTime24to12(int &hours, bool &am); +static bool isDst(Date time, DstRule dstRule); +static uint8_t dayOfWeek(int y, int m, int d); +static Date timeChangeRuleToLocal(TimeChangeRule &r, int year); +Date now() { + return utcToLocal(getDateNowHook()); +} +void toString(Date time, char *str, uint32_t strLen) { + int year, month, day, hours, minutes, seconds, milliseconds; + breakDate(time, year, month, day, hours, minutes, seconds, milliseconds); + snprintf(str, strLen, "%04d-%02d-%02dT%02d:%02d:%02d.%06d", year, month, day, hours, minutes, seconds, milliseconds); +} +void toLocaleString(Date time, char *str, uint32_t strLen) { + int year, month, day, hours, minutes, seconds, milliseconds; + breakDate(time, year, month, day, hours, minutes, seconds, milliseconds); + if (g_localeFormat == FORMAT_DMY_24) { + snprintf(str, strLen, "%02d-%02d-%02d %02d:%02d:%02d.%03d", day, month, year, hours, minutes, seconds, milliseconds); + } else if (g_localeFormat == FORMAT_MDY_24) { + snprintf(str, strLen, "%02d-%02d-%02d %02d:%02d:%02d.%03d", month, day, year, hours, minutes, seconds, milliseconds); + } else if (g_localeFormat == FORMAT_DMY_12) { + bool am; + convertTime24to12(hours, am); + snprintf(str, strLen, "%02d-%02d-%02d %02d:%02d:%02d.%03d %s", day, month, year, hours, minutes, seconds, milliseconds, am ? "AM" : "PM"); + } else if (g_localeFormat == FORMAT_MDY_12) { + bool am; + convertTime24to12(hours, am); + snprintf(str, strLen, "%02d-%02d-%02d %02d:%02d:%02d.%03d %s", month, day, year, hours, minutes, seconds, milliseconds, am ? "AM" : "PM"); + } +} +Date fromString(const char *str) { + int year = 0, month = 0, day = 0, hours = 0, minutes = 0, seconds = 0, milliseconds = 0; + sscanf(str, "%d-%d-%dT%d:%d:%d.%d", &year, &month, &day, &hours, &minutes, &seconds, &milliseconds); + return makeDate(year, month, day, hours, minutes, seconds, milliseconds); +} +Date makeDate(int year, int month, int day, int hours, int minutes, int seconds, int milliseconds) { + year -= 1970; + Date time = year * 365 * SECONDS_PER_DAY; + for (int i = 0; i < year; i++) { + if (LEAP_YEAR(i)) { + time += SECONDS_PER_DAY; + } + } + for (int i = 1; i < month; i++) { + if ((i == 2) && LEAP_YEAR(year)) { + time += SECONDS_PER_DAY * 29; + } else { + time += SECONDS_PER_DAY * monthDays[i - 1]; + } + } + time += (day - 1) * SECONDS_PER_DAY; + time += hours * SECONDS_PER_HOUR; + time += minutes * SECONDS_PER_MINUTE; + time += seconds; + time *= 1000; + time += milliseconds; + return time; +} +void breakDate(Date time, int &result_year, int &result_month, int &result_day, int &result_hours, int &result_minutes, int &result_seconds, int &result_milliseconds) { + uint8_t year; + uint8_t month, monthLength; + uint32_t days; + result_milliseconds = time % 1000; + time /= 1000; + result_seconds = time % 60; + time /= 60; + result_minutes = time % 60; + time /= 60; + result_hours = time % 24; + time /= 24; + year = 0; + days = 0; + while ((unsigned)(days += (LEAP_YEAR(year) ? 366 : 365)) <= time) { + year++; + } + result_year = year + 1970; + days -= LEAP_YEAR(year) ? 366 : 365; + time -= days; + days = 0; + month = 0; + monthLength = 0; + for (month = 0; month < 12; ++month) { + if (month == 1) { + if (LEAP_YEAR(year)) { + monthLength = 29; + } else { + monthLength = 28; + } + } else { + monthLength = monthDays[month]; + } + if (time >= monthLength) { + time -= monthLength; + } else { + break; + } + } + result_month = month + 1; + result_day = time + 1; +} +int getYear(Date time) { + int year, month, day, hours, minutes, seconds, milliseconds; + breakDate(time, year, month, day, hours, minutes, seconds, milliseconds); + return year; +} +int getMonth(Date time) { + int year, month, day, hours, minutes, seconds, milliseconds; + breakDate(time, year, month, day, hours, minutes, seconds, milliseconds); + return month; +} +int getDay(Date time) { + int year, month, day, hours, minutes, seconds, milliseconds; + breakDate(time, year, month, day, hours, minutes, seconds, milliseconds); + return day; +} +int getHours(Date time) { + int year, month, day, hours, minutes, seconds, milliseconds; + breakDate(time, year, month, day, hours, minutes, seconds, milliseconds); + return hours; +} +int getMinutes(Date time) { + int year, month, day, hours, minutes, seconds, milliseconds; + breakDate(time, year, month, day, hours, minutes, seconds, milliseconds); + return minutes; +} +int getSeconds(Date time) { + int year, month, day, hours, minutes, seconds, milliseconds; + breakDate(time, year, month, day, hours, minutes, seconds, milliseconds); + return seconds; +} +int getMilliseconds(Date time) { + int year, month, day, hours, minutes, seconds, milliseconds; + breakDate(time, year, month, day, hours, minutes, seconds, milliseconds); + return milliseconds; +} +Date utcToLocal(Date utc) { + Date local = utc + ((g_timeZone / 100) * 60 + g_timeZone % 100) * 60L * 1000L; + if (isDst(local, g_dstRule)) { + local += SECONDS_PER_HOUR * 1000L; + } + return local; +} +Date localToUtc(Date local) { + Date utc = local - ((g_timeZone / 100) * 60 + g_timeZone % 100) * 60L * 1000L; + if (isDst(local, g_dstRule)) { + utc -= SECONDS_PER_HOUR * 1000L; + } + return utc; +} +static void convertTime24to12(int &hours, bool &am) { + if (hours == 0) { + hours = 12; + am = true; + } else if (hours < 12) { + am = true; + } else if (hours == 12) { + am = false; + } else { + hours = hours - 12; + am = false; + } +} +static bool isDst(Date local, DstRule dstRule) { + if (dstRule == DST_RULE_OFF) { + return false; + } + int year, month, day, hours, minutes, seconds, milliseconds; + breakDate(local, year, month, day, hours, minutes, seconds, milliseconds); + Date dstStart = timeChangeRuleToLocal(g_dstRules[dstRule - 1].dstStart, year); + Date dstEnd = timeChangeRuleToLocal(g_dstRules[dstRule - 1].dstEnd, year); + return (dstStart < dstEnd && (local >= dstStart && local < dstEnd)) || + (dstStart > dstEnd && (local >= dstStart || local < dstEnd)); +} +static uint8_t dayOfWeek(int y, int m, int d) { + static int t[] = { 0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4 }; + if (m < 3) { + --y; + } + return (y + y / 4 - y / 100 + y / 400 + t[m - 1] + d) % 7 + 1; +} +static Date timeChangeRuleToLocal(TimeChangeRule &r, int year) { + uint8_t month = r.month; + uint8_t week = r.week; + if (week == 0) { + if (++month > 12) { + month = 1; + ++year; + } + week = 1; + } + Date time = makeDate(year, month, 1, r.hours, 0, 0, 0); + uint8_t dow = dayOfWeek(year, month, 1); + time += (7 * (week - 1) + (r.dow - dow + 7) % 7) * SECONDS_PER_DAY; + if (r.week == 0) { + time -= 7 * SECONDS_PER_DAY; + } + return time; +} +} +} +} +// ----------------------------------------------------------------------------- +// flow/debugger.cpp +// ----------------------------------------------------------------------------- +#include +#include +#include +#include +namespace eez { +namespace flow { +#define MAX_ARRAY_SIZE_TRANSFERRED_IN_DEBUGGER 1000 +enum MessagesToDebugger { + MESSAGE_TO_DEBUGGER_STATE_CHANGED, + MESSAGE_TO_DEBUGGER_ADD_TO_QUEUE, + MESSAGE_TO_DEBUGGER_REMOVE_FROM_QUEUE, + MESSAGE_TO_DEBUGGER_GLOBAL_VARIABLE_INIT, + MESSAGE_TO_DEBUGGER_LOCAL_VARIABLE_INIT, + MESSAGE_TO_DEBUGGER_COMPONENT_INPUT_INIT, + MESSAGE_TO_DEBUGGER_VALUE_CHANGED, + MESSAGE_TO_DEBUGGER_FLOW_STATE_CREATED, + MESSAGE_TO_DEBUGGER_FLOW_STATE_TIMELINE_CHANGED, + MESSAGE_TO_DEBUGGER_FLOW_STATE_DESTROYED, + MESSAGE_TO_DEBUGGER_FLOW_STATE_ERROR, + MESSAGE_TO_DEBUGGER_LOG, + MESSAGE_TO_DEBUGGER_PAGE_CHANGED, + MESSAGE_TO_DEBUGGER_COMPONENT_EXECUTION_STATE_CHANGED, + MESSAGE_TO_DEBUGGER_COMPONENT_ASYNC_STATE_CHANGED +}; +enum MessagesFromDebugger { + MESSAGE_FROM_DEBUGGER_RESUME, + MESSAGE_FROM_DEBUGGER_PAUSE, + MESSAGE_FROM_DEBUGGER_SINGLE_STEP, + MESSAGE_FROM_DEBUGGER_ADD_BREAKPOINT, + MESSAGE_FROM_DEBUGGER_REMOVE_BREAKPOINT, + MESSAGE_FROM_DEBUGGER_ENABLE_BREAKPOINT, + MESSAGE_FROM_DEBUGGER_DISABLE_BREAKPOINT, + MESSAGE_FROM_DEBUGGER_MODE +}; +enum LogItemType { + LOG_ITEM_TYPE_FATAL, + LOG_ITEM_TYPE_ERROR, + LOG_ITEM_TYPE_WARNING , + LOG_ITEM_TYPE_SCPI, + LOG_ITEM_TYPE_INFO, + LOG_ITEM_TYPE_DEBUG +}; +enum DebuggerState { + DEBUGGER_STATE_RESUMED, + DEBUGGER_STATE_PAUSED, + DEBUGGER_STATE_SINGLE_STEP, + DEBUGGER_STATE_STOPPED, +}; +bool g_debuggerIsConnected; +static uint32_t g_messageSubsciptionFilter = 0xFFFFFFFF; +static DebuggerState g_debuggerState; +static bool g_skipNextBreakpoint; +static char g_inputFromDebugger[64]; +static unsigned g_inputFromDebuggerPosition; +int g_debuggerMode = DEBUGGER_MODE_RUN; +void setDebuggerMessageSubsciptionFilter(uint32_t filter) { + g_messageSubsciptionFilter = filter; +} +static bool isSubscribedTo(MessagesToDebugger messageType) { + if (g_debuggerIsConnected && (g_messageSubsciptionFilter & (1 << messageType)) != 0) { + startToDebuggerMessageHook(); + return true; + } + return false; +} +static void setDebuggerState(DebuggerState newState) { + if (newState != g_debuggerState) { + g_debuggerState = newState; + if (isSubscribedTo(MESSAGE_TO_DEBUGGER_STATE_CHANGED)) { + char buffer[256]; + snprintf(buffer, sizeof(buffer), "%d\t%d\n", + MESSAGE_TO_DEBUGGER_STATE_CHANGED, + g_debuggerState + ); + writeDebuggerBufferHook(buffer, strlen(buffer)); + } + } +} +void onDebuggerClientConnected() { + g_debuggerIsConnected = true; + g_skipNextBreakpoint = false; + g_inputFromDebuggerPosition = 0; + setDebuggerState(DEBUGGER_STATE_PAUSED); +} +void onDebuggerClientDisconnected() { + g_debuggerIsConnected = false; + setDebuggerState(DEBUGGER_STATE_RESUMED); +} +void processDebuggerInput(char *buffer, uint32_t length) { + for (uint32_t i = 0; i < length; i++) { + if (buffer[i] == '\n') { + int messageFromDebugger = g_inputFromDebugger[0] - '0'; + if (messageFromDebugger == MESSAGE_FROM_DEBUGGER_RESUME) { + setDebuggerState(DEBUGGER_STATE_RESUMED); + } else if (messageFromDebugger == MESSAGE_FROM_DEBUGGER_PAUSE) { + setDebuggerState(DEBUGGER_STATE_PAUSED); + } else if (messageFromDebugger == MESSAGE_FROM_DEBUGGER_SINGLE_STEP) { + setDebuggerState(DEBUGGER_STATE_SINGLE_STEP); + } else if ( + messageFromDebugger >= MESSAGE_FROM_DEBUGGER_ADD_BREAKPOINT && + messageFromDebugger <= MESSAGE_FROM_DEBUGGER_DISABLE_BREAKPOINT + ) { + char *p; + auto flowIndex = (uint32_t)strtol(g_inputFromDebugger + 2, &p, 10); + auto componentIndex = (uint32_t)strtol(p + 1, nullptr, 10); + auto assets = g_firstFlowState->assets; + auto flowDefinition = static_cast(assets->flowDefinition); + if (flowIndex < flowDefinition->flows.count) { + auto flow = flowDefinition->flows[flowIndex]; + if (componentIndex < flow->components.count) { + auto component = flow->components[componentIndex]; + component->breakpoint = messageFromDebugger == MESSAGE_FROM_DEBUGGER_ADD_BREAKPOINT || + messageFromDebugger == MESSAGE_FROM_DEBUGGER_ENABLE_BREAKPOINT ? 1 : 0; + } else { + ErrorTrace("Invalid breakpoint component index\n"); + } + } else { + ErrorTrace("Invalid breakpoint flow index\n"); + } + } else if (messageFromDebugger == MESSAGE_FROM_DEBUGGER_MODE) { + g_debuggerMode = strtol(g_inputFromDebugger + 2, nullptr, 10); + } + g_inputFromDebuggerPosition = 0; + } else { + if (g_inputFromDebuggerPosition < sizeof(g_inputFromDebugger)) { + g_inputFromDebugger[g_inputFromDebuggerPosition++] = buffer[i]; + } else if (g_inputFromDebuggerPosition == sizeof(g_inputFromDebugger)) { + ErrorTrace("Input from debugger buffer overflow\n"); + } + } + } +} +bool canExecuteStep(FlowState *&flowState, unsigned &componentIndex) { + if (!g_debuggerIsConnected) { + return true; + } + if (!isSubscribedTo(MESSAGE_TO_DEBUGGER_ADD_TO_QUEUE)) { + return true; + } + if (g_debuggerState == DEBUGGER_STATE_PAUSED) { + return false; + } + if (g_debuggerState == DEBUGGER_STATE_SINGLE_STEP) { + g_skipNextBreakpoint = false; + setDebuggerState(DEBUGGER_STATE_PAUSED); + return true; + } + auto component = flowState->flow->components[componentIndex]; + if (g_skipNextBreakpoint) { + if (component->breakpoint) { + g_skipNextBreakpoint = false; + } + } else { + if (component->breakpoint) { + g_skipNextBreakpoint = true; + setDebuggerState(DEBUGGER_STATE_PAUSED); + return false; + } + } + return true; +} +#if defined(__EMSCRIPTEN__) +char outputBuffer[1024 * 1024]; +#else +char outputBuffer[64]; +#endif +int outputBufferPosition = 0; +#define WRITE_TO_OUTPUT_BUFFER(ch) \ + outputBuffer[outputBufferPosition++] = ch; \ + if (outputBufferPosition == sizeof(outputBuffer)) { \ + writeDebuggerBufferHook(outputBuffer, outputBufferPosition); \ + outputBufferPosition = 0; \ + } +#define FLUSH_OUTPUT_BUFFER() \ + if (outputBufferPosition > 0) { \ + writeDebuggerBufferHook(outputBuffer, outputBufferPosition); \ + outputBufferPosition = 0; \ + } +static void writeValueAddr(const void *pValue) { + char tmpStr[32]; + snprintf(tmpStr, sizeof(tmpStr), "%p", pValue); + auto len = strlen(tmpStr); + for (size_t i = 0; i < len; i++) { + WRITE_TO_OUTPUT_BUFFER(tmpStr[i]); + } +} +static void writeString(const char *str) { + WRITE_TO_OUTPUT_BUFFER('"'); + while (true) { + utf8_int32_t cp; + str = utf8codepoint(str, &cp); + if (!cp) { + break; + } + if (cp == '"') { + WRITE_TO_OUTPUT_BUFFER('\\'); + WRITE_TO_OUTPUT_BUFFER('"'); + } else if (cp == '\t') { + WRITE_TO_OUTPUT_BUFFER('\\'); + WRITE_TO_OUTPUT_BUFFER('t'); + } else if (cp == '\n') { + WRITE_TO_OUTPUT_BUFFER('\\'); + WRITE_TO_OUTPUT_BUFFER('n'); + } else if (cp >= 32 && cp < 127) { + WRITE_TO_OUTPUT_BUFFER(cp); + } else { + char temp[32]; + snprintf(temp, sizeof(temp), "\\u%04x", (int)cp); + for (size_t i = 0; i < strlen(temp); i++) { + WRITE_TO_OUTPUT_BUFFER(temp[i]); + } + } + } + WRITE_TO_OUTPUT_BUFFER('"'); + WRITE_TO_OUTPUT_BUFFER('\n'); + FLUSH_OUTPUT_BUFFER(); +} +static void writeArrayType(uint32_t arrayType) { + char tmpStr[32]; + snprintf(tmpStr, sizeof(tmpStr), "%x", (int)arrayType); + auto len = strlen(tmpStr); + for (size_t i = 0; i < len; i++) { + WRITE_TO_OUTPUT_BUFFER(tmpStr[i]); + } +} +static void writeArray(const ArrayValue *arrayValue) { + WRITE_TO_OUTPUT_BUFFER('{'); + writeValueAddr(arrayValue); + WRITE_TO_OUTPUT_BUFFER(','); + writeArrayType(arrayValue->arraySize); + WRITE_TO_OUTPUT_BUFFER(','); + writeArrayType(arrayValue->arrayType); + auto transferredSize = arrayValue->arraySize > MAX_ARRAY_SIZE_TRANSFERRED_IN_DEBUGGER ? MAX_ARRAY_SIZE_TRANSFERRED_IN_DEBUGGER : arrayValue->arraySize; + for (uint32_t i = 0; i < transferredSize; i++) { + WRITE_TO_OUTPUT_BUFFER(','); + writeValueAddr(&arrayValue->values[i]); + } + WRITE_TO_OUTPUT_BUFFER('}'); + WRITE_TO_OUTPUT_BUFFER('\n'); + FLUSH_OUTPUT_BUFFER(); + for (uint32_t i = 0; i < transferredSize; i++) { + onValueChanged(&arrayValue->values[i]); + } +} +static void writeHex(char *dst, uint8_t *src, size_t srcLength) { + *dst++ = 'H'; + for (size_t i = 0; i < srcLength; i++) { + *dst++ = toHexDigit(src[i] / 16); + *dst++ = toHexDigit(src[i] % 16); + } + *dst++ = 0; +} +static void writeValue(const Value &value) { + char tempStr[64]; +#ifdef _MSC_VER +#pragma warning(push) +#pragma warning(disable : 4474) +#endif + switch (value.getType()) { + case VALUE_TYPE_UNDEFINED: + stringCopy(tempStr, sizeof(tempStr) - 1, "undefined"); + break; + case VALUE_TYPE_NULL: + stringCopy(tempStr, sizeof(tempStr) - 1, "null"); + break; + case VALUE_TYPE_BOOLEAN: + stringCopy(tempStr, sizeof(tempStr) - 1, value.getBoolean() ? "true" : "false"); + break; + case VALUE_TYPE_INT8: + snprintf(tempStr, sizeof(tempStr) - 1, "%" PRId8 "", value.int8Value); + break; + case VALUE_TYPE_UINT8: + snprintf(tempStr, sizeof(tempStr) - 1, "%" PRIu8 "", value.uint8Value); + break; + case VALUE_TYPE_INT16: + snprintf(tempStr, sizeof(tempStr) - 1, "%" PRId16 "", value.int16Value); + break; + case VALUE_TYPE_UINT16: + snprintf(tempStr, sizeof(tempStr) - 1, "%" PRIu16 "", value.uint16Value); + break; + case VALUE_TYPE_INT32: + snprintf(tempStr, sizeof(tempStr) - 1, "%" PRId32 "", value.int32Value); + break; + case VALUE_TYPE_UINT32: + snprintf(tempStr, sizeof(tempStr) - 1, "%" PRIu32 "", value.uint32Value); + break; + case VALUE_TYPE_INT64: +#ifdef PRId64 + snprintf(tempStr, sizeof(tempStr) - 1, "%" PRId64 "", value.int64Value); +#else + snprintf(tempStr, sizeof(tempStr) - 1, "%" PRId32 "", (int32_t)value.int64Value); +#endif + break; + case VALUE_TYPE_UINT64: +#ifdef PRIu64 + snprintf(tempStr, sizeof(tempStr) - 1, "%" PRIu64 "", value.uint64Value); +#else + snprintf(tempStr, sizeof(tempStr) - 1, "%" PRIu32 "", (uint32_t)value.uint64Value); +#endif + break; + case VALUE_TYPE_DOUBLE: + writeHex(tempStr, (uint8_t *)&value.doubleValue, sizeof(double)); + break; + case VALUE_TYPE_FLOAT: + writeHex(tempStr, (uint8_t *)&value.floatValue, sizeof(float)); + break; + case VALUE_TYPE_STRING: + case VALUE_TYPE_STRING_ASSET: + case VALUE_TYPE_STRING_REF: + writeString(value.getString()); + return; + case VALUE_TYPE_ARRAY: + case VALUE_TYPE_ARRAY_ASSET: + case VALUE_TYPE_ARRAY_REF: + writeArray(value.getArray()); + return; + case VALUE_TYPE_BLOB_REF: + snprintf(tempStr, sizeof(tempStr) - 1, "@%d", (int)((BlobRef *)value.refValue)->len); + break; + case VALUE_TYPE_STREAM: + snprintf(tempStr, sizeof(tempStr) - 1, ">%d", (int)(value.int32Value)); + break; + case VALUE_TYPE_JSON: + snprintf(tempStr, sizeof(tempStr) - 1, "#%d", (int)(value.int32Value)); + break; + case VALUE_TYPE_DATE: + tempStr[0] = '!'; + writeHex(tempStr + 1, (uint8_t *)&value.doubleValue, sizeof(double)); + break; + case VALUE_TYPE_POINTER: + snprintf(tempStr, sizeof(tempStr) - 1, "%p", value.getVoidPointer()); + break; + case VALUE_TYPE_WIDGET: + snprintf(tempStr, sizeof(tempStr) - 1, "*p%p", value.getVoidPointer()); + break; + case VALUE_TYPE_EVENT: + snprintf(tempStr, sizeof(tempStr) - 1, "!!%p", value.getVoidPointer()); + break; + default: + tempStr[0] = 0; + break; + } +#ifdef _MSC_VER +#pragma warning(pop) +#endif + stringAppendString(tempStr, sizeof(tempStr), "\n"); + writeDebuggerBufferHook(tempStr, strlen(tempStr)); +} +void onStarted(Assets *assets) { + if (!assets->external && isSubscribedTo(MESSAGE_TO_DEBUGGER_GLOBAL_VARIABLE_INIT)) { + auto flowDefinition = static_cast(assets->flowDefinition); + if (g_globalVariables) { + for (uint32_t i = 0; i < g_globalVariables->count; i++) { + auto pValue = g_globalVariables->values + i; + char buffer[256]; + snprintf(buffer, sizeof(buffer), "%d\t%d\t%p\t", + MESSAGE_TO_DEBUGGER_GLOBAL_VARIABLE_INIT, + (int)i, + (const void *)pValue + ); + writeDebuggerBufferHook(buffer, strlen(buffer)); + writeValue(*pValue); + } + } else { + for (uint32_t i = 0; i < flowDefinition->globalVariables.count; i++) { + auto pValue = flowDefinition->globalVariables[i]; + char buffer[256]; + snprintf(buffer, sizeof(buffer), "%d\t%d\t%p\t", + MESSAGE_TO_DEBUGGER_GLOBAL_VARIABLE_INIT, + (int)i, + (const void *)pValue + ); + writeDebuggerBufferHook(buffer, strlen(buffer)); + writeValue(*pValue); + } + } + } +} +void onStopped() { + setDebuggerState(DEBUGGER_STATE_STOPPED); +} +void onAddToQueue(FlowState *flowState, int sourceComponentIndex, int sourceOutputIndex, unsigned targetComponentIndex, int targetInputIndex) { + if (isSubscribedTo(MESSAGE_TO_DEBUGGER_ADD_TO_QUEUE)) { + uint32_t free; + uint32_t alloc; + getAllocInfo(free, alloc); + char buffer[256]; + snprintf(buffer, sizeof(buffer), "%d\t%d\t%d\t%d\t%d\t%d\t%u\t%u\n", + MESSAGE_TO_DEBUGGER_ADD_TO_QUEUE, + (int)flowState->flowStateIndex, + sourceComponentIndex, + sourceOutputIndex, + targetComponentIndex, + targetInputIndex, + (unsigned int)free, + (unsigned int)alloc + ); + writeDebuggerBufferHook(buffer, strlen(buffer)); + } +} +void onRemoveFromQueue() { + if (isSubscribedTo(MESSAGE_TO_DEBUGGER_REMOVE_FROM_QUEUE)) { + char buffer[256]; + snprintf(buffer, sizeof(buffer), "%d\n", + MESSAGE_TO_DEBUGGER_REMOVE_FROM_QUEUE + ); + writeDebuggerBufferHook(buffer, strlen(buffer)); + } +} +void onValueChanged(const Value *pValue) { + if (isSubscribedTo(MESSAGE_TO_DEBUGGER_VALUE_CHANGED)) { + char buffer[256]; + snprintf(buffer, sizeof(buffer), "%d\t%p\t", + MESSAGE_TO_DEBUGGER_VALUE_CHANGED, + (const void *)pValue + ); + writeDebuggerBufferHook(buffer, strlen(buffer)); + writeValue(pValue->getValue()); + } +} +void onFlowStateCreated(FlowState *flowState) { + if (isSubscribedTo(MESSAGE_TO_DEBUGGER_FLOW_STATE_CREATED)) { + char buffer[256]; + snprintf(buffer, sizeof(buffer), "%d\t%d\t%d\t%d\t%d\n", + MESSAGE_TO_DEBUGGER_FLOW_STATE_CREATED, + (int)flowState->flowStateIndex, + (int)flowState->flowIndex, + (int)(flowState->parentFlowState ? flowState->parentFlowState->flowStateIndex : -1), + (int)flowState->parentComponentIndex + ); + writeDebuggerBufferHook(buffer, strlen(buffer)); + } + if (isSubscribedTo(MESSAGE_TO_DEBUGGER_LOCAL_VARIABLE_INIT)) { + auto flow = flowState->flow; + for (uint32_t i = 0; i < flow->localVariables.count; i++) { + auto pValue = &flowState->values[flow->componentInputs.count + i]; + char buffer[256]; + snprintf(buffer, sizeof(buffer), "%d\t%d\t%d\t%p\t", + MESSAGE_TO_DEBUGGER_LOCAL_VARIABLE_INIT, + (int)flowState->flowStateIndex, + (int)i, + (const void *)pValue + ); + writeDebuggerBufferHook(buffer, strlen(buffer)); + writeValue(*pValue); + } + } + if (isSubscribedTo(MESSAGE_TO_DEBUGGER_COMPONENT_INPUT_INIT)) { + auto flow = flowState->flow; + for (uint32_t i = 0; i < flow->componentInputs.count; i++) { + auto pValue = &flowState->values[i]; + char buffer[256]; + snprintf(buffer, sizeof(buffer), "%d\t%d\t%d\t%p\t", + MESSAGE_TO_DEBUGGER_COMPONENT_INPUT_INIT, + (int)flowState->flowStateIndex, + (int)i, + (const void *)pValue + ); + writeDebuggerBufferHook(buffer, strlen(buffer)); + writeValue(*pValue); + } + } +} +void onFlowStateDestroyed(FlowState *flowState) { + if (isSubscribedTo(MESSAGE_TO_DEBUGGER_FLOW_STATE_DESTROYED)) { + char buffer[256]; + snprintf(buffer, sizeof(buffer), "%d\t%d\n", + MESSAGE_TO_DEBUGGER_FLOW_STATE_DESTROYED, + (int)flowState->flowStateIndex + ); + writeDebuggerBufferHook(buffer, strlen(buffer)); + } +} +void onFlowStateTimelineChanged(FlowState *flowState) { + if (isSubscribedTo(MESSAGE_TO_DEBUGGER_FLOW_STATE_TIMELINE_CHANGED)) { + char buffer[256]; + snprintf(buffer, sizeof(buffer), "%d\t%d\t%g\n", + MESSAGE_TO_DEBUGGER_FLOW_STATE_TIMELINE_CHANGED, + (int)flowState->flowStateIndex, + flowState->timelinePosition + ); + writeDebuggerBufferHook(buffer, strlen(buffer)); + } +} +void onFlowError(FlowState *flowState, int componentIndex, const char *errorMessage) { + if (isSubscribedTo(MESSAGE_TO_DEBUGGER_FLOW_STATE_ERROR)) { + char buffer[256]; + snprintf(buffer, sizeof(buffer), "%d\t%d\t%d\t", + MESSAGE_TO_DEBUGGER_FLOW_STATE_ERROR, + (int)flowState->flowStateIndex, + componentIndex + ); + writeDebuggerBufferHook(buffer, strlen(buffer)); + writeString(errorMessage); + } + if (onFlowErrorHook) { + onFlowErrorHook(flowState, componentIndex, errorMessage); + } +} +void onComponentExecutionStateChanged(FlowState *flowState, int componentIndex) { + if (isSubscribedTo(MESSAGE_TO_DEBUGGER_COMPONENT_EXECUTION_STATE_CHANGED)) { + char buffer[256]; + snprintf(buffer, sizeof(buffer), "%d\t%d\t%d\t%p\n", + MESSAGE_TO_DEBUGGER_COMPONENT_EXECUTION_STATE_CHANGED, + (int)flowState->flowStateIndex, + componentIndex, + (void *)flowState->componenentExecutionStates[componentIndex] + ); + writeDebuggerBufferHook(buffer, strlen(buffer)); + } +} +void onComponentAsyncStateChanged(FlowState *flowState, int componentIndex) { + if (isSubscribedTo(MESSAGE_TO_DEBUGGER_COMPONENT_ASYNC_STATE_CHANGED)) { + char buffer[256]; + snprintf(buffer, sizeof(buffer), "%d\t%d\t%d\t%d\n", + MESSAGE_TO_DEBUGGER_COMPONENT_ASYNC_STATE_CHANGED, + (int)flowState->flowStateIndex, + componentIndex, + flowState->componenentAsyncStates[componentIndex] ? 1 : 0 + ); + writeDebuggerBufferHook(buffer, strlen(buffer)); + } +} +static void writeLogMessage(const char *str) { + for (const char *p = str; *p; p++) { + if (*p == '\t') { + WRITE_TO_OUTPUT_BUFFER('\\'); + WRITE_TO_OUTPUT_BUFFER('t'); + } if (*p == '\n') { + WRITE_TO_OUTPUT_BUFFER('\\'); + WRITE_TO_OUTPUT_BUFFER('n'); + } else { + WRITE_TO_OUTPUT_BUFFER(*p); + } + } + WRITE_TO_OUTPUT_BUFFER('\n'); + FLUSH_OUTPUT_BUFFER(); +} +static void writeLogMessage(const char *str, size_t len) { + for (size_t i = 0; i < len; i++) { + if (str[i] == '\t') { + WRITE_TO_OUTPUT_BUFFER('\\'); + WRITE_TO_OUTPUT_BUFFER('t'); + } if (str[i] == '\n') { + WRITE_TO_OUTPUT_BUFFER('\\'); + WRITE_TO_OUTPUT_BUFFER('n'); + } else { + WRITE_TO_OUTPUT_BUFFER(str[i]); + } + } + WRITE_TO_OUTPUT_BUFFER('\n'); + FLUSH_OUTPUT_BUFFER(); +} +void logInfo(FlowState *flowState, unsigned componentIndex, const char *message) { + LV_LOG_USER("EEZ-FLOW: %s", message); + if (isSubscribedTo(MESSAGE_TO_DEBUGGER_LOG)) { + char buffer[256]; + snprintf(buffer, sizeof(buffer), "%d\t%d\t%d\t%d\t", + MESSAGE_TO_DEBUGGER_LOG, + LOG_ITEM_TYPE_INFO, + (int)flowState->flowStateIndex, + componentIndex + ); + writeDebuggerBufferHook(buffer, strlen(buffer)); + writeLogMessage(message); + } +} +void logScpiCommand(FlowState *flowState, unsigned componentIndex, const char *cmd) { + if (isSubscribedTo(MESSAGE_TO_DEBUGGER_LOG)) { + char buffer[256]; + snprintf(buffer, sizeof(buffer), "%d\t%d\t%d\t%d\tSCPI COMMAND: ", + MESSAGE_TO_DEBUGGER_LOG, + LOG_ITEM_TYPE_SCPI, + (int)flowState->flowStateIndex, + componentIndex + ); + writeDebuggerBufferHook(buffer, strlen(buffer)); + writeLogMessage(cmd); + } +} +void logScpiQuery(FlowState *flowState, unsigned componentIndex, const char *query) { + if (isSubscribedTo(MESSAGE_TO_DEBUGGER_LOG)) { + char buffer[256]; + snprintf(buffer, sizeof(buffer), "%d\t%d\t%d\t%d\tSCPI QUERY: ", + MESSAGE_TO_DEBUGGER_LOG, + LOG_ITEM_TYPE_SCPI, + (int)flowState->flowStateIndex, + componentIndex + ); + writeDebuggerBufferHook(buffer, strlen(buffer)); + writeLogMessage(query); + } +} +void logScpiQueryResult(FlowState *flowState, unsigned componentIndex, const char *resultText, size_t resultTextLen) { + if (isSubscribedTo(MESSAGE_TO_DEBUGGER_LOG)) { + char buffer[256]; + snprintf(buffer, sizeof(buffer) - 1, "%d\t%d\t%d\t%d\tSCPI QUERY RESULT: ", + MESSAGE_TO_DEBUGGER_LOG, + LOG_ITEM_TYPE_SCPI, + (int)flowState->flowStateIndex, + componentIndex + ); + writeDebuggerBufferHook(buffer, strlen(buffer)); + writeLogMessage(resultText, resultTextLen); + } +} +void onPageChanged(int previousPageId, int activePageId, bool activePageIsFromStack, bool previousPageIsStillOnStack) { + if (flow::isFlowStopped()) { + return; + } + if (previousPageId == activePageId) { + return; + } + if (!previousPageIsStillOnStack) { + if (previousPageId > 0) { + auto flowState = getPageFlowState(g_mainAssets, previousPageId - 1); + if (flowState) { + onEvent(flowState, FLOW_EVENT_CLOSE_PAGE, Value()); + } + } + } + if (!activePageIsFromStack) { + if (activePageId > 0) { + auto flowState = getPageFlowState(g_mainAssets, activePageId - 1); + if (flowState) { + onEvent(flowState, FLOW_EVENT_OPEN_PAGE, Value()); + } + } + } + if (isSubscribedTo(MESSAGE_TO_DEBUGGER_PAGE_CHANGED)) { + char buffer[256]; + snprintf(buffer, sizeof(buffer), "%d\t%d\n", + MESSAGE_TO_DEBUGGER_PAGE_CHANGED, + activePageId + ); + writeDebuggerBufferHook(buffer, strlen(buffer)); + } +} +} +} +// ----------------------------------------------------------------------------- +// flow/expression.cpp +// ----------------------------------------------------------------------------- +#include +namespace eez { +namespace flow { +EvalStack g_stack; +static void evalExpression(FlowState *flowState, const uint8_t *instructions, int *numInstructionBytes) { + auto flowDefinition = static_cast(flowState->assets->flowDefinition); + auto flow = flowState->flow; + int i = 0; + while (true) { + uint16_t instruction = instructions[i] + (instructions[i + 1] << 8); + auto instructionType = instruction & EXPR_EVAL_INSTRUCTION_TYPE_MASK; + auto instructionArg = instruction & EXPR_EVAL_INSTRUCTION_PARAM_MASK; + if (instructionType == EXPR_EVAL_INSTRUCTION_TYPE_PUSH_CONSTANT) { + g_stack.push(*flowDefinition->constants[instructionArg]); + } else if (instructionType == EXPR_EVAL_INSTRUCTION_TYPE_PUSH_INPUT) { + g_stack.push(flowState->values[instructionArg]); + } else if (instructionType == EXPR_EVAL_INSTRUCTION_TYPE_PUSH_LOCAL_VAR) { + g_stack.push(&flowState->values[flow->componentInputs.count + instructionArg]); + } else if (instructionType == EXPR_EVAL_INSTRUCTION_TYPE_PUSH_GLOBAL_VAR) { + if ((uint32_t)instructionArg < flowDefinition->globalVariables.count) { + if (g_globalVariables && !flowState->assets->external) { + g_stack.push(g_globalVariables->values + instructionArg); + } else { + g_stack.push(flowDefinition->globalVariables[instructionArg]); + } + } else { + g_stack.push(Value((int)(instructionArg - flowDefinition->globalVariables.count + 1), VALUE_TYPE_NATIVE_VARIABLE)); + } + } else if (instructionType == EXPR_EVAL_INSTRUCTION_TYPE_PUSH_OUTPUT) { + g_stack.push(Value((uint16_t)instructionArg, VALUE_TYPE_FLOW_OUTPUT)); + } else if (instructionType == EXPR_EVAL_INSTRUCTION_ARRAY_ELEMENT) { + auto elementIndexValue = g_stack.pop().getValue(); + auto arrayValue = g_stack.pop().getValue(); + if (arrayValue.getType() == VALUE_TYPE_UNDEFINED || arrayValue.getType() == VALUE_TYPE_NULL) { + g_stack.push(Value(0, VALUE_TYPE_UNDEFINED)); + } else { + if (arrayValue.isArray()) { + auto array = arrayValue.getArray(); + int err; + auto elementIndex = elementIndexValue.toInt32(&err); + if (!err) { + if (elementIndex >= 0 && elementIndex < (int)array->arraySize) { + g_stack.push(Value::makeArrayElementRef(arrayValue, elementIndex, 0x132e0e2f)); + } else { + g_stack.push(Value::makeError()); + g_stack.setErrorMessage("Array element index out of bounds\n"); + } + } else { + g_stack.push(Value::makeError()); + g_stack.setErrorMessage("Integer value expected for array element index\n"); + } + } else if (arrayValue.isBlob()) { + auto blobRef = arrayValue.getBlob(); + int err; + auto elementIndex = elementIndexValue.toInt32(&err); + if (!err) { + if (elementIndex >= 0 && elementIndex < (int)blobRef->len) { + g_stack.push(Value::makeArrayElementRef(arrayValue, elementIndex, 0x132e0e2f)); + } else { + g_stack.push(Value::makeError()); + g_stack.setErrorMessage("Blob element index out of bounds\n"); + } + } else { + g_stack.push(Value::makeError()); + g_stack.setErrorMessage("Integer value expected for blob element index\n"); + } + } else { + g_stack.push(Value::makeError()); + g_stack.setErrorMessage("Array value expected\n"); + } + } + } else if (instructionType == EXPR_EVAL_INSTRUCTION_TYPE_OPERATION) { + g_evalOperations[instructionArg](g_stack); + } else { + if (instruction == EXPR_EVAL_INSTRUCTION_TYPE_END_WITH_DST_VALUE_TYPE) { + i += 2; + if (g_stack.sp == 1) { + auto finalResult = g_stack.pop(); + #define VALUE_TYPE (instructions[i] + (instructions[i + 1] << 8) + (instructions[i + 2] << 16) + (instructions[i + 3] << 24)) + if (finalResult.getType() == VALUE_TYPE_VALUE_PTR) { + finalResult.dstValueType = VALUE_TYPE; + } else if (finalResult.getType() == VALUE_TYPE_ARRAY_ELEMENT_VALUE) { + auto arrayElementValue = (ArrayElementValue *)finalResult.refValue; + arrayElementValue->dstValueType = VALUE_TYPE; + } + g_stack.push(finalResult); + } + i += 4; + break; + } else { + i += 2; + break; + } + } + i += 2; + } + if (numInstructionBytes) { + *numInstructionBytes = i; + } +} +bool evalExpression(FlowState *flowState, int componentIndex, const uint8_t *instructions, Value &result, const FlowError &errorMessage, int *numInstructionBytes, const int32_t *iterators) { + size_t savedSp = g_stack.sp; + FlowState *savedFlowState = g_stack.flowState; + int savedComponentIndex = g_stack.componentIndex; + const int32_t *savedIterators = g_stack.iterators; + const char *savedErrorMessage = g_stack.errorMessage; + g_stack.flowState = flowState; + g_stack.componentIndex = componentIndex; + g_stack.iterators = iterators; + g_stack.errorMessage = nullptr; + evalExpression(flowState, instructions, numInstructionBytes); + g_stack.flowState = savedFlowState; + g_stack.componentIndex = savedComponentIndex; + g_stack.iterators = savedIterators; + g_stack.errorMessage = savedErrorMessage; + if (g_stack.sp == savedSp + 1) { + result = g_stack.pop().getValue(); + if (!result.isError()) { + return true; + } + } + FlowError flowError = errorMessage.setDescription(g_stack.errorMessage); + throwError(flowState, componentIndex, flowError); + return false; +} +bool evalAssignableExpression(FlowState *flowState, int componentIndex, const uint8_t *instructions, Value &result, const FlowError &errorMessage, int *numInstructionBytes, const int32_t *iterators) { + FlowState *savedFlowState = g_stack.flowState; + int savedComponentIndex = g_stack.componentIndex; + const int32_t *savedIterators = g_stack.iterators; + const char *savedErrorMessage = g_stack.errorMessage; + g_stack.flowState = flowState; + g_stack.componentIndex = componentIndex; + g_stack.iterators = iterators; + g_stack.errorMessage = nullptr; + evalExpression(flowState, instructions, numInstructionBytes); + g_stack.flowState = savedFlowState; + g_stack.componentIndex = savedComponentIndex; + g_stack.iterators = savedIterators; + g_stack.errorMessage = savedErrorMessage; + if (g_stack.sp == 1) { + auto finalResult = g_stack.pop(); + if ( + finalResult.getType() == VALUE_TYPE_VALUE_PTR || + finalResult.getType() == VALUE_TYPE_NATIVE_VARIABLE || + finalResult.getType() == VALUE_TYPE_FLOW_OUTPUT || + finalResult.getType() == VALUE_TYPE_ARRAY_ELEMENT_VALUE || + finalResult.getType() == VALUE_TYPE_JSON_MEMBER_VALUE + ) { + result = finalResult; + return true; + } + } + errorMessage.setDescription(g_stack.errorMessage); + throwError(flowState, componentIndex, errorMessage); + return false; +} +bool evalProperty(FlowState *flowState, int componentIndex, int propertyIndex, Value &result, const FlowError &errorMessage, int *numInstructionBytes, const int32_t *iterators) { + if (componentIndex < 0 || componentIndex >= (int)flowState->flow->components.count) { + char message[256]; + snprintf(message, sizeof(message), "invalid component index %d in flow at index %d", componentIndex, flowState->flowIndex); + FlowError flowError = errorMessage.setDescription(message); + throwError(flowState, componentIndex, flowError); + return false; + } + auto component = flowState->flow->components[componentIndex]; + if (propertyIndex < 0 || propertyIndex >= (int)component->properties.count) { + char message[256]; + snprintf(message, sizeof(message), "invalid property index %d in component at index %d in flow at index %d", propertyIndex, componentIndex, flowState->flowIndex); + FlowError flowError = errorMessage.setDescription(message); + throwError(flowState, componentIndex, flowError); + return false; + } + return evalExpression(flowState, componentIndex, component->properties[propertyIndex]->evalInstructions, result, errorMessage, numInstructionBytes, iterators); +} +bool evalAssignableProperty(FlowState *flowState, int componentIndex, int propertyIndex, Value &result, const FlowError &errorMessage, int *numInstructionBytes, const int32_t *iterators) { + if (componentIndex < 0 || componentIndex >= (int)flowState->flow->components.count) { + char message[256]; + snprintf(message, sizeof(message), "invalid component index %d in flow at index %d", componentIndex, flowState->flowIndex); + FlowError flowError = errorMessage.setDescription(message); + throwError(flowState, componentIndex, flowError); + return false; + } + auto component = flowState->flow->components[componentIndex]; + if (propertyIndex < 0 || propertyIndex >= (int)component->properties.count) { + char message[256]; + snprintf(message, sizeof(message), "invalid property index %d in component at index %d in flow at index %d", propertyIndex, componentIndex, flowState->flowIndex); + FlowError flowError = errorMessage.setDescription(message); + throwError(flowState, componentIndex, flowError); + return false; + } + return evalAssignableExpression(flowState, componentIndex, component->properties[propertyIndex]->evalInstructions, result, errorMessage, numInstructionBytes, iterators); +} +} +} +// ----------------------------------------------------------------------------- +// flow/flow.cpp +// ----------------------------------------------------------------------------- +#include +namespace eez { +namespace flow { +#if defined(__EMSCRIPTEN__) +uint32_t g_wasmModuleId = 0; +#endif +#if !defined(EEZ_FLOW_TICK_MAX_DURATION_MS) +#define EEZ_FLOW_TICK_MAX_DURATION_MS 5 +#endif +static const uint32_t FLOW_TICK_MAX_DURATION_MS = EEZ_FLOW_TICK_MAX_DURATION_MS; +static unsigned g_tick_max_duration_count = 0; +int g_selectedLanguage = 0; +FlowState *g_firstFlowState; +FlowState *g_lastFlowState; +static bool g_isStopping = false; +static bool g_isStopped = true; +static void doStop(); +unsigned start(Assets *assets) { + auto flowDefinition = static_cast(assets->flowDefinition); + if (flowDefinition->flows.count == 0) { + return 0; + } + g_isStopped = false; + g_isStopping = false; + initGlobalVariables(assets); + if (!assets->external) { + queueReset(); + watchListReset(); + } + scpiComponentInitHook(); + onStarted(assets); + return 1; +} +void tick() { + if (isFlowStopped()) { + return; + } + if (g_isStopping) { + doStop(); + return; + } + uint32_t startTickCount = millis(); + visitWatchList(); + auto queueSizeAtTickStart = getQueueSize(); + for (size_t i = 0; i < queueSizeAtTickStart || g_numNonContinuousTaskInQueue > 0; i++) { + FlowState *flowState; + unsigned componentIndex; + bool continuousTask; + if (!peekNextTaskFromQueue(flowState, componentIndex, continuousTask)) { + break; + } + if (!flowState) { + removeNextTaskFromQueue(); + continue; + } + if (!continuousTask && !canExecuteStep(flowState, componentIndex)) { + break; + } + removeNextTaskFromQueue(); + flowState->executingComponentIndex = componentIndex; + if (flowState->error) { + deallocateComponentExecutionState(flowState, componentIndex); + } else { + if (continuousTask) { + if (i < queueSizeAtTickStart) { + executeComponent(flowState, componentIndex); + } else { + addToQueue(flowState, componentIndex, -1, -1, -1, true); + } + } else { + executeComponent(flowState, componentIndex); + } + } + if (isFlowStopped() || g_isStopping) { + break; + } + resetSequenceInputs(flowState); + if (canFreeFlowState(flowState)) { + freeFlowState(flowState); + } + if ((i + 1) % 5 == 0) { + if (millis() - startTickCount >= FLOW_TICK_MAX_DURATION_MS) { + g_tick_max_duration_count++; + break; + } + } + } + finishToDebuggerMessageHook(); + for (FlowState *flowState = g_firstFlowState; flowState; ) { + FlowState* nextFlowState = flowState->nextSibling; + if (flowState->deleteOnNextTick) { + freeFlowState(flowState); + } + flowState = nextFlowState; + } +} +void stop(Assets* assets) { + if (!assets) { + assets = g_mainAssets; + } + if (assets->external) { + for (FlowState *flowState = g_firstFlowState; flowState; flowState = flowState->nextSibling) { + if (flowState->assets == assets) { + flowState->deleteOnNextTick = true; + } + } + } else { + g_isStopping = true; + } +} +void doStop() { + onStopped(); + finishToDebuggerMessageHook(); + g_debuggerIsConnected = false; + freeAllChildrenFlowStates(g_firstFlowState); + g_firstFlowState = nullptr; + g_lastFlowState = nullptr; + g_isStopped = true; + queueReset(); + watchListReset(); +} +bool isFlowStopped() { + return g_isStopped; +} +unsigned getTickMaxDurationCounter() { + return g_tick_max_duration_count; +} +FlowState *getPageFlowState(Assets *assets, int16_t pageIndex) { + if (!assets->flowDefinition) { + return nullptr; + } + if (isFlowStopped()) { + return nullptr; + } + FlowState *flowState; + for (flowState = g_firstFlowState; flowState; flowState = flowState->nextSibling) { + if (flowState->flowIndex == pageIndex) { + break; + } + } + if (flowState) { + flowState->deleteOnNextTick = false; + } else { + flowState = initPageFlowState(assets, pageIndex, nullptr, 0); + } + return flowState; +} +int getPageIndex(FlowState *flowState) { + return flowState->flowIndex; +} +int getPageIndexIncludeParents(FlowState *flowState) { + if (flowState->parentFlowState) { + return getPageIndexIncludeParents(flowState->parentFlowState); + } + return flowState->flowIndex; +} +void deletePageFlowState(Assets *assets, int16_t pageIndex) { + EEZ_UNUSED(assets); + for (FlowState *flowState = g_firstFlowState; flowState; flowState = flowState->nextSibling) { + if (flowState->flowIndex == pageIndex) { + flowState->deleteOnNextTick = true; + return; + } + } +} +Value getGlobalVariable(uint32_t globalVariableIndex) { + return getGlobalVariable(g_mainAssets, globalVariableIndex); +} +Value getGlobalVariable(Assets *assets, uint32_t globalVariableIndex) { + if (globalVariableIndex < assets->flowDefinition->globalVariables.count) { + return g_globalVariables && !assets->external ? g_globalVariables->values[globalVariableIndex] : *assets->flowDefinition->globalVariables[globalVariableIndex]; + } + return Value(); +} +void setGlobalVariable(uint32_t globalVariableIndex, const Value &value) { + setGlobalVariable(g_mainAssets, globalVariableIndex, value); +} +void setGlobalVariable(Assets *assets, uint32_t globalVariableIndex, const Value &value) { + if (globalVariableIndex < assets->flowDefinition->globalVariables.count) { + if (g_globalVariables && !assets->external) { + g_globalVariables->values[globalVariableIndex] = value; + } else { + *assets->flowDefinition->globalVariables[globalVariableIndex] = value; + } + } +} +Value getUserProperty(unsigned propertyIndex) { + Value value; + evalProperty(g_executeActionFlowState, g_executeActionComponentIndex, propertyIndex, value, FlowError::PropertyNum("CallAction", propertyIndex)); + return value; +} +void setUserProperty(unsigned propertyIndex, const Value &value) { + Value dstValue; + if (!evalAssignableProperty(g_executeActionFlowState, g_executeActionComponentIndex, propertyIndex, dstValue, FlowError::PropertyInArray("CallAction", "Assignable property", propertyIndex))) { + return; + } + assignValue(g_executeActionFlowState, g_executeActionComponentIndex, dstValue, value); +} +AsyncAction *beginAsyncExecution() { + startAsyncExecution(g_executeActionFlowState, g_executeActionComponentIndex); + AsyncAction *asyncAction = (AsyncAction *) alloc(sizeof(AsyncAction), 0xcb44f51e); + asyncAction->flowState = g_executeActionFlowState; + asyncAction->componentIndex = g_executeActionComponentIndex; + return asyncAction; +} +void endAsyncExecution(AsyncAction *asyncAction) { + endAsyncExecution(asyncAction->flowState, asyncAction->componentIndex); + propagateValueThroughSeqout(asyncAction->flowState, asyncAction->componentIndex); + eez::free(asyncAction); +} +Value getUserPropertyAsync(AsyncAction *asyncAction, unsigned propertyIndex) { + Value value; + evalProperty(asyncAction->flowState, asyncAction->componentIndex, propertyIndex, value, FlowError::PropertyNum("CallAction", propertyIndex)); + return value; +} +void setUserPropertyAsync(AsyncAction *asyncAction, unsigned propertyIndex, const Value &value) { + Value dstValue; + if (!evalAssignableProperty(asyncAction->flowState, asyncAction->componentIndex, propertyIndex, dstValue, FlowError::PropertyInArray("CallAction", "Assignable property", propertyIndex))) { + return; + } + assignValue(g_executeActionFlowState, g_executeActionComponentIndex, dstValue, value); +} +void onArrayValueFree(ArrayValue *arrayValue) { + if (arrayValue->arrayType == defs_v3::OBJECT_TYPE_MQTT_CONNECTION) { + onFreeMQTTConnection(arrayValue); + } +} +} +} +// ----------------------------------------------------------------------------- +// flow/hooks.cpp +// ----------------------------------------------------------------------------- +#include +#include +#if !defined(EEZ_DISABLE_DATE_NOW_DEFAULT_IMPLEMENTATION) +#include +#endif +namespace eez { +namespace flow { +static void replacePage(int16_t pageId, uint32_t animType, uint32_t speed, uint32_t delay) { + EEZ_UNUSED(pageId); + EEZ_UNUSED(animType); + EEZ_UNUSED(speed); + EEZ_UNUSED(delay); +} +static void showKeyboard(Value label, Value initialText, Value minChars, Value maxChars, bool isPassword, void(*onOk)(char *), void(*onCancel)()) { + EEZ_UNUSED(label); + EEZ_UNUSED(initialText); + EEZ_UNUSED(minChars); + EEZ_UNUSED(maxChars); + EEZ_UNUSED(isPassword); + EEZ_UNUSED(onOk); + EEZ_UNUSED(onCancel); +} +static void showKeypad(Value label, Value initialValue, Value min, Value max, Unit unit, void(*onOk)(float), void(*onCancel)()) { + EEZ_UNUSED(label); + EEZ_UNUSED(initialValue); + EEZ_UNUSED(min); + EEZ_UNUSED(max); + EEZ_UNUSED(unit); + EEZ_UNUSED(onOk); + EEZ_UNUSED(onCancel); +} +static void stopScript() { + assert(false); +} +static void scpiComponentInit() { +} +static void startToDebuggerMessage() { +} +static void writeDebuggerBuffer(const char *buffer, uint32_t length) { + EEZ_UNUSED(buffer); + EEZ_UNUSED(length); +} +static void finishToDebuggerMessage() { +} +static void onDebuggerInputAvailable() { +} +void (*replacePageHook)(int16_t pageId, uint32_t animType, uint32_t speed, uint32_t delay) = replacePage; +void (*showKeyboardHook)(Value label, Value initialText, Value minChars, Value maxChars, bool isPassword, void(*onOk)(char *), void(*onCancel)()) = showKeyboard; +void (*showKeypadHook)(Value label, Value initialValue, Value min, Value max, Unit unit, void(*onOk)(float), void(*onCancel)()) = showKeypad; +void (*stopScriptHook)() = stopScript; +void (*scpiComponentInitHook)() = scpiComponentInit; +void (*startToDebuggerMessageHook)() = startToDebuggerMessage; +void (*writeDebuggerBufferHook)(const char *buffer, uint32_t length) = writeDebuggerBuffer; +void (*finishToDebuggerMessageHook)() = finishToDebuggerMessage; +void (*onDebuggerInputAvailableHook)() = onDebuggerInputAvailable; +static lv_obj_t *getLvglObjectFromIndex(int32_t index) { + EEZ_UNUSED(index); + return 0; +} +static lv_group_t *getLvglGroupFromIndex(int32_t index) { + EEZ_UNUSED(index); + return 0; +} +static int32_t getLvglScreenByName(const char *name) { + EEZ_UNUSED(name); + return -1; +} +static int32_t getLvglObjectByName(const char *name) { + EEZ_UNUSED(name); + return -1; +} +static int32_t getLvglGroupByName(const char *name) { + EEZ_UNUSED(name); + return -1; +} +static int32_t getLvglStyleByName(const char *name) { + EEZ_UNUSED(name); + return -1; +} +static const void *getLvglImageByName(const char *name) { + EEZ_UNUSED(name); + return 0; +} +static const void *getLvglFontByName(const char *name) { + EEZ_UNUSED(name); + return 0; +} +static const char *getLvglObjectNameFromIndex(int32_t index) { + EEZ_UNUSED(index); + return 0; +} +static void executeLvglAction(int actionIndex) { + EEZ_UNUSED(actionIndex); +} +static void lvglObjAddStyle(lv_obj_t *object, int32_t styleIndex) { + EEZ_UNUSED(object); + EEZ_UNUSED(styleIndex); +} +static void lvglObjRemoveStyle(lv_obj_t *object, int32_t styleIndex) { + EEZ_UNUSED(object); + EEZ_UNUSED(styleIndex); +} +static void lvglSetColorTheme(const char *themeName) { + EEZ_UNUSED(themeName); +} +lv_obj_t *(*getLvglObjectFromIndexHook)(int32_t index) = getLvglObjectFromIndex; +lv_group_t *(*getLvglGroupFromIndexHook)(int32_t index) = getLvglGroupFromIndex; +int32_t (*getLvglScreenByNameHook)(const char *name) = getLvglScreenByName; +int32_t (*getLvglObjectByNameHook)(const char *name) = getLvglObjectByName; +int32_t (*getLvglGroupByNameHook)(const char *name) = getLvglGroupByName; +int32_t (*getLvglStyleByNameHook)(const char *name) = getLvglStyleByName; +const void *(*getLvglImageByNameHook)(const char *name) = getLvglImageByName; +const void *(*getLvglFontByNameHook)(const char *name) = getLvglFontByName; +const char *(*getLvglObjectNameFromIndexHook)(int32_t index) = getLvglObjectNameFromIndex; +void (*executeLvglActionHook)(int actionIndex) = executeLvglAction; +void (*lvglObjAddStyleHook)(lv_obj_t *object, int32_t styleIndex) = lvglObjAddStyle; +void (*lvglObjRemoveStyleHook)(lv_obj_t *object, int32_t styleIndex) = lvglObjRemoveStyle; +void (*lvglSetColorThemeHook)(const char *themeName) = lvglSetColorTheme; +#if !defined(EEZ_DISABLE_DATE_NOW_DEFAULT_IMPLEMENTATION) +static double getDateNowDefaultImplementation() { + using namespace std::chrono; + milliseconds ms = duration_cast(system_clock::now().time_since_epoch()); + return (double)ms.count(); +} +double (*getDateNowHook)() = getDateNowDefaultImplementation; +#else +double (*getDateNowHook)() = nullptr; +#endif +void (*onFlowErrorHook)(FlowState *flowState, int componentIndex, const char *errorMessage) = nullptr; +} +} +// ----------------------------------------------------------------------------- +// flow/lvgl_api.cpp +// ----------------------------------------------------------------------------- +#include +static void replacePageHook(int16_t pageId, uint32_t animType, uint32_t speed, uint32_t delay); +extern "C" void create_screens(); +extern "C" void tick_screen(int screen_index); +static const char **g_screenNames; +static size_t g_numScreens; +static lv_obj_t **g_objects; +static const char **g_objectNames; +static size_t g_numObjects; +static lv_group_t **g_groups; +static const char **g_groupNames; +static size_t g_numGroups; +static const char **g_styleNames; +static size_t g_numStyles; +static const ext_img_desc_t *g_images; +static size_t g_numImages; +static const ext_font_desc_t *g_fonts; +static size_t g_numFonts; +static ActionExecFunc *g_actions; +int16_t g_currentScreen = -1; +static const char **g_themeNames; +static size_t g_numThemes; +static void (*g_changeColorTheme)(uint32_t themeIndex); +static uint32_t g_selectedThemeIndex; +static uint32_t *g_themeColors; +static size_t g_numColorsPerTheme; +static void (*g_createScreenFunc)(int screenIndex); +static void (*g_deleteScreenFunc)(int screenIndex); +static lv_obj_t *getLvglObjectFromIndex(int32_t index) { + if (index >= 0 && (uint32_t)index < g_numObjects) { + return g_objects[index]; + } + return 0; +} +static lv_group_t *getLvglGroupFromIndex(int32_t index) { + if (index >= 0 && (uint32_t)index < g_numGroups) { + return g_groups[index]; + } + return 0; +} +static int32_t getLvglScreenByName(const char *name) { + for (size_t i = 0; i < g_numScreens; i++) { + if (strcmp(g_screenNames[i], name) == 0) { + return i + 1; + } + } + return -1; +} +static int32_t getLvglObjectByName(const char *name) { + for (size_t i = 0; i < g_numObjects; i++) { + if (strcmp(g_objectNames[i], name) == 0) { + return i; + } + } + return -1; +} +static int32_t getLvglGroupByName(const char *name) { + for (size_t i = 0; i < g_numGroups; i++) { + if (strcmp(g_groupNames[i], name) == 0) { + return i; + } + } + return -1; +} +static int32_t getLvglStyleByName(const char *name) { + for (size_t i = 0; i < g_numStyles; i++) { + if (strcmp(g_styleNames[i], name) == 0) { + return i; + } + } + return -1; +} +static const void *getLvglImageByName(const char *name) { + for (size_t i = 0; i < g_numImages; i++) { + if (strcmp(g_images[i].name, name) == 0) { + return g_images[i].img_dsc; + } + } + return 0; +} +static const void *getLvglFontByName(const char *name) { + for (size_t i = 0; i < g_numFonts; i++) { + if (strcmp(g_fonts[i].name, name) == 0) { + return g_fonts[i].font_ptr; + } + } + return 0; +} +static const char *getLvglObjectNameFromIndex(int32_t index) { + if (index >= 0 && index < (int32_t)g_numObjects) { + return g_objectNames[index]; + } + return 0; +} +uint8_t g_lastLVGLEventUserDataBuffer[64]; +uint8_t g_lastLVGLEventParamBuffer[64]; +static lv_event_t g_lastLVGLEvent; +static void executeLvglAction(int actionIndex) { + g_actions[actionIndex](&g_lastLVGLEvent); +} +EM_PORT_API(void) eez_flow_init_themes(const char **themeNames, size_t numThemes, void (*changeColorTheme)(uint32_t themeIndex), uint32_t *themeColors, size_t numColorsPerTheme) { + g_themeNames = themeNames; + g_numThemes = numThemes; + g_changeColorTheme = changeColorTheme; + g_themeColors = themeColors; + g_numColorsPerTheme = numColorsPerTheme; +} +void eez_flow_init_fonts(const ext_font_desc_t *fonts, size_t numFonts) { + g_fonts = fonts; + g_numFonts = numFonts; +} +void eez_flow_set_create_screen_func(void (*createScreenFunc)(int screenIndex)) { + g_createScreenFunc = createScreenFunc; +} +void eez_flow_set_delete_screen_func(void (*deleteScreenFunc)(int screenIndex)) { + g_deleteScreenFunc = deleteScreenFunc; +} +void eez_flow_set_theme(const char *themeName) { + for (uint32_t i = 0; i < g_numThemes; i++) { + if (strcmp(themeName, g_themeNames[i]) == 0) { + g_selectedThemeIndex = i; + if (g_changeColorTheme) { + g_changeColorTheme(g_selectedThemeIndex); + } + return; + } + } +} +#if !defined(EEZ_LVGL_SCREEN_STACK_SIZE) +#define EEZ_LVGL_SCREEN_STACK_SIZE 10 +#endif +int16_t g_screenStack[EEZ_LVGL_SCREEN_STACK_SIZE]; +unsigned g_screenStackPosition = 0; +extern "C" int16_t eez_flow_get_current_screen() { + return g_currentScreen + 1; +} +static bool isScreenCreated(int screenIndex) { + return eez::flow::getLvglObjectFromIndexHook(screenIndex) != 0; +} +static void createScreen(int screenIndex) { + if (g_createScreenFunc && !isScreenCreated(screenIndex)) { + g_createScreenFunc(screenIndex); + } +} +static void deleteScreen(int screenIndex) { + if (g_deleteScreenFunc && isScreenCreated(screenIndex)) { + g_deleteScreenFunc(screenIndex); + } +} +extern "C" void eez_flow_set_screen(int16_t screenId, lv_scr_load_anim_t animType, uint32_t speed, uint32_t delay) { + g_screenStackPosition = 0; + eez::flow::replacePageHook(screenId, animType, speed, delay); +} +extern "C" void eez_flow_push_screen(int16_t screenId, lv_scr_load_anim_t animType, uint32_t speed, uint32_t delay) { + if (g_screenStackPosition == EEZ_LVGL_SCREEN_STACK_SIZE) { + for (unsigned i = 1; i < EEZ_LVGL_SCREEN_STACK_SIZE; i++) { + g_screenStack[i - 1] = g_screenStack[i]; + } + g_screenStackPosition--; + } + g_screenStack[g_screenStackPosition++] = g_currentScreen + 1; + eez::flow::replacePageHook(screenId, animType, speed, delay); +} +extern "C" void eez_flow_pop_screen(lv_scr_load_anim_t animType, uint32_t speed, uint32_t delay) { + if (g_screenStackPosition > 0) { + g_screenStackPosition--; + eez::flow::replacePageHook(g_screenStack[g_screenStackPosition], animType, speed, delay); + } +} +void eez_flow_create_screen(int16_t screenId) { + int16_t screenIndex = screenId - 1; + createScreen(screenIndex); +} +void eez_flow_delete_screen(int16_t screenId) { + int16_t screenIndex = screenId - 1; + deleteScreen(screenIndex); +} +bool eez_flow_is_screen_created(int16_t screenId) { + int16_t screenIndex = screenId - 1; + return isScreenCreated(screenIndex); +} +static void on_screen_unloaded(lv_event_t *e) { + if (lv_event_get_code(e) == LV_EVENT_SCREEN_UNLOADED) { + int16_t screenIndex = (int16_t)(lv_uintptr_t)lv_event_get_user_data(e); + deleteScreen(screenIndex); + } +} +void eez_flow_delete_screen_on_unload(int screenIndex) { + lv_obj_add_event_cb( + eez::flow::getLvglObjectFromIndexHook(screenIndex), + on_screen_unloaded, + LV_EVENT_SCREEN_UNLOADED, + (void*)(lv_uintptr_t)(screenIndex) + ); +} +extern "C" void eez_flow_init(const uint8_t *assets, uint32_t assetsSize, lv_obj_t **objects, size_t numObjects, const ext_img_desc_t *images, size_t numImages, ActionExecFunc *actions) { + g_objects = objects; + g_numObjects = numObjects; + g_images = images; + g_numImages = numImages; + g_actions = actions; + eez::initAssetsMemory(); + eez::loadMainAssets(assets, assetsSize); + eez::initOtherMemory(); + eez::initAllocHeap(eez::ALLOC_BUFFER, eez::ALLOC_BUFFER_SIZE); + eez::flow::replacePageHook = replacePageHook; + eez::flow::getLvglObjectFromIndexHook = getLvglObjectFromIndex; + eez::flow::getLvglScreenByNameHook = getLvglScreenByName; + eez::flow::getLvglObjectByNameHook = getLvglObjectByName; + eez::flow::getLvglGroupByNameHook = getLvglGroupByName; + eez::flow::getLvglStyleByNameHook = getLvglStyleByName; + eez::flow::getLvglImageByNameHook = getLvglImageByName; + eez::flow::getLvglFontByNameHook = getLvglFontByName; + eez::flow::getLvglObjectNameFromIndexHook = getLvglObjectNameFromIndex; + eez::flow::executeLvglActionHook = executeLvglAction; + eez::flow::getLvglGroupFromIndexHook = getLvglGroupFromIndex; + eez::flow::lvglSetColorThemeHook = eez_flow_set_theme; + eez::flow::start(eez::g_mainAssets); + create_screens(); + replacePageHook(1, 0, 0, 0); +} +extern "C" void eez_flow_init_styles( + void (*add_style)(lv_obj_t *obj, int32_t styleIndex), + void (*remove_style)(lv_obj_t *obj, int32_t styleIndex) +) { + eez::flow::lvglObjAddStyleHook = add_style; + eez::flow::lvglObjRemoveStyleHook = remove_style; +} +void eez_flow_init_groups(lv_group_t **groups, size_t numGroups) { + g_groups = groups; + g_numGroups = numGroups; +} +void eez_flow_init_screen_names(const char **screenNames, size_t numScreens) { + g_screenNames = screenNames; + g_numScreens = numScreens; +} +void eez_flow_init_object_names(const char **objectNames, size_t numObjects) { + g_objectNames = objectNames; + EEZ_UNUSED(numObjects); +} +void eez_flow_init_group_names(const char **groupNames, size_t numGroups) { + g_groupNames = groupNames; + EEZ_UNUSED(numGroups); +} +void eez_flow_init_style_names(const char **styleNames, size_t numStyles) { + g_styleNames = styleNames; + g_numStyles = numStyles; +} +extern "C" void eez_flow_tick() { + eez::flow::tick(); +} +extern "C" bool eez_flow_is_stopped() { + return eez::flow::isFlowStopped(); +} +namespace eez { +ActionExecFunc g_actionExecFunctions[] = { 0 }; +} +void replacePageHook(int16_t pageId, uint32_t animType, uint32_t speed, uint32_t delay) { + int16_t screenIndex = pageId - 1; + createScreen(screenIndex); + lv_obj_t *screen = eez::flow::getLvglObjectFromIndexHook(screenIndex); + if (!screen) { + return; + } + eez::flow::onPageChanged(g_currentScreen + 1, pageId); + g_currentScreen = screenIndex; + lv_scr_load_anim(screen, (lv_scr_load_anim_t)animType, speed, delay, false); +} +extern "C" void flowOnPageLoaded(unsigned pageIndex) { + eez::flow::getPageFlowState(eez::g_mainAssets, pageIndex); +} +extern "C" void flowPropagateValue(void *flowState, unsigned componentIndex, unsigned outputIndex) { + eez::flow::propagateValue((eez::flow::FlowState *)flowState, componentIndex, outputIndex); +} +extern "C" void flowPropagateValueInt32(void *flowState, unsigned componentIndex, unsigned outputIndex, int32_t value) { + eez::flow::propagateValue((eez::flow::FlowState *)flowState, componentIndex, outputIndex, eez::Value((int)value, eez::VALUE_TYPE_INT32)); +} +extern "C" void flowPropagateValueUint32(void *flowState, unsigned componentIndex, unsigned outputIndex, uint32_t value) { + eez::flow::propagateValue((eez::flow::FlowState *)flowState, componentIndex, outputIndex, eez::Value(value, eez::VALUE_TYPE_UINT32)); +} +EM_PORT_API(void) flowPropagateValueLVGLEvent(void *flowState, unsigned componentIndex, unsigned outputIndex, lv_event_t *event) { + lv_event_code_t event_code = lv_event_get_code(event); + uint32_t code = (uint32_t)event_code; + void *currentTarget = (void *)lv_event_get_current_target(event); + void *target = (void *)lv_event_get_target(event); + void *userDataPointer = lv_event_get_user_data(event); + int32_t userData = (intptr_t)userDataPointer; + uint32_t key = 0; + if (event_code == LV_EVENT_KEY || (event_code == LV_EVENT_VALUE_CHANGED && +#if LVGL_VERSION_MAJOR >= 9 + lv_obj_check_type((lv_obj_t*)target, &lv_buttonmatrix_class) +#else + lv_obj_check_type((lv_obj_t*)target, &lv_btnmatrix_class) +#endif + )) { + uint32_t *param = (uint32_t *)lv_event_get_param(event); + key = param ? *param : 0; + } + int32_t gestureDir = (int32_t)LV_DIR_NONE; + if (event_code == LV_EVENT_GESTURE) { +#if LVGL_VERSION_MAJOR >= 9 + lv_indev_wait_release(lv_indev_active()); +#else + lv_indev_wait_release(lv_indev_get_act()); +#endif + gestureDir = (int32_t)lv_indev_get_gesture_dir( +#if LVGL_VERSION_MAJOR >= 9 + lv_indev_active() +#else + lv_indev_get_act() +#endif + ); + } + int32_t rotaryDiff = 0; +#if LVGL_VERSION_MAJOR >= 9 + if (event_code == LV_EVENT_ROTARY) { + rotaryDiff = lv_event_get_rotary_diff(event); + } +#endif + eez::flow::propagateValue( + (eez::flow::FlowState *)flowState, componentIndex, outputIndex, + eez::Value::makeLVGLEventRef( + code, currentTarget, target, userData, key, gestureDir, rotaryDiff, 0xe7f23624 + ) + ); + g_lastLVGLEvent = *event; + if (event->user_data) { + g_lastLVGLEvent.user_data = &g_lastLVGLEventUserDataBuffer; + memcpy(&g_lastLVGLEventUserDataBuffer, event->user_data, sizeof(g_lastLVGLEventUserDataBuffer)); + } + if (event->param) { + g_lastLVGLEvent.param = &g_lastLVGLEventParamBuffer; + memcpy(&g_lastLVGLEventParamBuffer, event->param, sizeof(g_lastLVGLEventParamBuffer)); + } +} +#ifndef EEZ_LVGL_TEMP_STRING_BUFFER_SIZE +#define EEZ_LVGL_TEMP_STRING_BUFFER_SIZE 1024 +#endif +static char textValue[EEZ_LVGL_TEMP_STRING_BUFFER_SIZE]; +extern "C" const char *_evalTextProperty(void *flowState, unsigned componentIndex, unsigned propertyIndex, const char *errorMessage, const char *file, int line) { + eez::Value value; + if (!eez::flow::evalProperty((eez::flow::FlowState *)flowState, componentIndex, propertyIndex, value, eez::flow::FlowError::Plain(errorMessage, file, line))) { + return ""; + } + value.toText(textValue, sizeof(textValue)); + return textValue; +} +extern "C" int32_t _evalIntegerProperty(void *flowState, unsigned componentIndex, unsigned propertyIndex, const char *errorMessage, const char *file, int line) { + eez::Value value; + if (!eez::flow::evalProperty((eez::flow::FlowState *)flowState, componentIndex, propertyIndex, value, eez::flow::FlowError::Plain(errorMessage, file, line))) { + return 0; + } + int err; + int32_t intValue = value.toInt32(&err); + if (err) { + eez::flow::throwError((eez::flow::FlowState *)flowState, componentIndex, errorMessage); + return 0; + } + return intValue; +} +extern "C" uint32_t _evalUnsignedIntegerProperty(void *flowState, unsigned componentIndex, unsigned propertyIndex, const char *errorMessage, const char *file, int line) { + eez::Value value; + if (!eez::flow::evalProperty((eez::flow::FlowState *)flowState, componentIndex, propertyIndex, value, eez::flow::FlowError::Plain(errorMessage, file, line))) { + return 0; + } + int err; + uint32_t intValue = (uint32_t)value.toInt32(&err); + if (err) { + eez::flow::throwError((eez::flow::FlowState *)flowState, componentIndex, errorMessage); + return 0; + } + return intValue; +} +extern "C" bool _evalBooleanProperty(void *flowState, unsigned componentIndex, unsigned propertyIndex, const char *errorMessage, const char *file, int line) { + eez::Value value; + if (!eez::flow::evalProperty((eez::flow::FlowState *)flowState, componentIndex, propertyIndex, value, eez::flow::FlowError::Plain(errorMessage, file, line))) { + return 0; + } + int err; + bool booleanValue = value.toBool(&err); + if (err) { + eez::flow::throwError((eez::flow::FlowState *)flowState, componentIndex, errorMessage); + return 0; + } + return booleanValue; +} +const char *_evalStringArrayPropertyAndJoin(void *flowState, unsigned componentIndex, unsigned propertyIndex, const char *errorMessage, const char *separator, const char *file, int line) { + eez::Value value; + if (!eez::flow::evalProperty((eez::flow::FlowState *)flowState, componentIndex, propertyIndex, value, eez::flow::FlowError::Plain(errorMessage, file, line))) { + return ""; + } + if (value.isArray()) { + auto array = value.getArray(); + textValue[0] = 0; + size_t textPosition = 0; + size_t separatorLength = strlen(separator); + for (uint32_t elementIndex = 0; elementIndex < array->arraySize; elementIndex++) { + if (elementIndex > 0) { + eez::stringAppendString(textValue + textPosition, sizeof(textValue) - textPosition, separator); + textPosition += separatorLength; + } + array->values[elementIndex].toText(textValue + textPosition, sizeof(textValue) - textPosition); + textPosition = strlen(textValue); + } + return textValue; + } else if (value.isString()) { + value.toText(textValue, sizeof(textValue)); + return textValue; + } + return ""; +} +extern "C" void _assignStringProperty(void *flowState, unsigned componentIndex, unsigned propertyIndex, const char *value, const char *errorMessage, const char *file, int line) { + auto component = ((eez::flow::FlowState *)flowState)->flow->components[componentIndex]; + eez::Value dstValue; + if (!eez::flow::evalAssignableExpression((eez::flow::FlowState *)flowState, componentIndex, component->properties[propertyIndex]->evalInstructions, dstValue, eez::flow::FlowError::Plain(errorMessage, file, line))) { + return; + } + eez::Value srcValue = eez::Value::makeStringRef(value, -1, 0x3eefcf0d); + eez::flow::assignValue((eez::flow::FlowState *)flowState, componentIndex, dstValue, srcValue); +} +extern "C" void _assignIntegerProperty(void *flowState, unsigned componentIndex, unsigned propertyIndex, int32_t value, const char *errorMessage, const char *file, int line) { + auto component = ((eez::flow::FlowState *)flowState)->flow->components[componentIndex]; + eez::Value dstValue; + if (!eez::flow::evalAssignableExpression((eez::flow::FlowState *)flowState, componentIndex, component->properties[propertyIndex]->evalInstructions, dstValue, eez::flow::FlowError::Plain(errorMessage, file, line))) { + return; + } + eez::Value srcValue((int)value, eez::VALUE_TYPE_INT32); + eez::flow::assignValue((eez::flow::FlowState *)flowState, componentIndex, dstValue, srcValue); +} +extern "C" void _assignBooleanProperty(void *flowState, unsigned componentIndex, unsigned propertyIndex, bool value, const char *errorMessage, const char *file, int line) { + auto component = ((eez::flow::FlowState *)flowState)->flow->components[componentIndex]; + eez::Value dstValue; + if (!eez::flow::evalAssignableExpression((eez::flow::FlowState *)flowState, componentIndex, component->properties[propertyIndex]->evalInstructions, dstValue, eez::flow::FlowError::Plain(errorMessage, file, line))) { + return; + } + eez::Value srcValue(value, eez::VALUE_TYPE_BOOLEAN); + eez::flow::assignValue((eez::flow::FlowState *)flowState, componentIndex, dstValue, srcValue); +} +extern "C" float getTimelinePosition(void *flowState) { + return ((eez::flow::FlowState *)flowState)->timelinePosition; +} +void *getFlowState(void *flowState, unsigned userWidgetComponentIndexOrPageIndex) { + if (!flowState) { + return eez::flow::getPageFlowState(eez::g_mainAssets, userWidgetComponentIndexOrPageIndex); + } + auto executionState = (eez::flow::LVGLUserWidgetExecutionState *)((eez::flow::FlowState *)flowState)->componenentExecutionStates[userWidgetComponentIndexOrPageIndex]; + if (!executionState) { + executionState = eez::flow::createUserWidgetFlowState((eez::flow::FlowState *)flowState, userWidgetComponentIndexOrPageIndex); + } + return executionState->flowState; +} +void deletePageFlowState(unsigned pageIndex) { + eez::flow::deletePageFlowState(eez::g_mainAssets, (int16_t)pageIndex); +} +extern "C" int compareRollerOptions(lv_roller_t *roller, const char *new_val, const char *cur_val, lv_roller_mode_t mode) { + EEZ_UNUSED(mode); + uint32_t new_option_count = 1; + for (int i = 0; ; i++) { + if (new_val[i] == '\0') { + if (cur_val[i] != '\0' && cur_val[i] != '\n') { + return 1; + } + break; + } + if (new_val[i] != cur_val[i]) { + return 1; + } + if (new_val[i] == '\n') { + new_option_count++; + } + } +#if LVGL_VERSION_MAJOR >= 9 + return lv_roller_get_option_count((const lv_obj_t *)roller) == new_option_count ? 0 : 1; +#else + return lv_roller_get_option_cnt((const lv_obj_t *)roller) == new_option_count ? 0 : 1; +#endif +} +uint32_t eez_flow_get_selected_theme_index() { + return g_selectedThemeIndex; +} +uint32_t eez_flow_get_theme_color(uint32_t colorIndex) { + return *(g_themeColors + g_selectedThemeIndex * g_numColorsPerTheme + colorIndex); +} +// ----------------------------------------------------------------------------- +// flow/operations.cpp +// ----------------------------------------------------------------------------- +#include +#include +#include +#include +#include +int g_eezFlowLvlgMeterTickIndex = 0; +namespace eez { +namespace flow { +Value op_add(const Value& a1, const Value& b1) { + if (a1.isError()) { + return a1; + } + if (b1.isError()) { + return b1; + } + auto a = a1.getValue(); + auto b = b1.getValue(); + if (a.isBlob() || b.isBlob()) { + if (a.isBlob()) { + if (b.isUndefinedOrNull()) { + return a; + } + if (!b.isBlob()) { + return Value::makeError(); + } + } else { + if (a.isUndefinedOrNull()) { + return b; + } + return Value::makeError(); + } + auto aBlob = a.getBlob(); + auto bBlob = b.getBlob(); + return Value::makeBlobRef(aBlob->blob, aBlob->len, bBlob->blob, bBlob->len, 0xc622dd24); + } + auto a_valid = a.isString() || a.isDouble() || a.isFloat() || a.isInt64() || a.isInt32OrLess(); + auto b_valid = b.isString() || b.isDouble() || b.isFloat() || b.isInt64() || b.isInt32OrLess(); + if (!a_valid && !b_valid) { + return Value::makeError(); + } + if (a.isString() || b.isString()) { + Value value1 = a.toString(0x84eafaa8); + Value value2 = b.toString(0xd273cab6); + auto res = Value::concatenateString(value1, value2); + char str1[128]; + res.toText(str1, sizeof(str1)); + return res; + } + if (a.isDouble() || b.isDouble()) { + return Value(a.toDouble() + b.toDouble(), VALUE_TYPE_DOUBLE); + } + if (a.isFloat() || b.isFloat()) { + return Value(a.toFloat() + b.toFloat(), VALUE_TYPE_FLOAT); + } + if (a.isInt64() || b.isInt64()) { + return Value(a.toInt64() + b.toInt64(), VALUE_TYPE_INT64); + } + return Value((int)(a.int32Value + b.int32Value), VALUE_TYPE_INT32); +} +Value op_sub(const Value& a1, const Value& b1) { + if (a1.isError()) { + return a1; + } + if (b1.isError()) { + return b1; + } + auto a = a1.getValue(); + auto b = b1.getValue(); + if (!(a.isDouble() || a.isFloat() || a.isInt64() || a.isInt32OrLess())) { + return Value::makeError(); + } + if (!(b.isDouble() || b.isFloat() || b.isInt64() || b.isInt32OrLess())) { + return Value::makeError(); + } + if (a.isDouble() || b.isDouble()) { + return Value(a.toDouble() - b.toDouble(), VALUE_TYPE_DOUBLE); + } + if (a.isFloat() || b.isFloat()) { + return Value(a.toFloat() - b.toFloat(), VALUE_TYPE_FLOAT); + } + if (a.isInt64() || b.isInt64()) { + return Value(a.toInt64() - b.toInt64(), VALUE_TYPE_INT64); + } + return Value((int)(a.int32Value - b.int32Value), VALUE_TYPE_INT32); +} +Value op_mul(const Value& a1, const Value& b1) { + if (a1.isError()) { + return a1; + } + if (b1.isError()) { + return b1; + } + auto a = a1.getValue(); + auto b = b1.getValue(); + if (!(a.isDouble() || a.isFloat() || a.isInt64() || a.isInt32OrLess())) { + return Value::makeError(); + } + if (!(b.isDouble() || b.isFloat() || b.isInt64() || b.isInt32OrLess())) { + return Value::makeError(); + } + if (a.isDouble() || b.isDouble()) { + return Value(a.toDouble() * b.toDouble(), VALUE_TYPE_DOUBLE); + } + if (a.isFloat() || b.isFloat()) { + return Value(a.toFloat() * b.toFloat(), VALUE_TYPE_FLOAT); + } + if (a.isInt64() || b.isInt64()) { + return Value(a.toInt64() * b.toInt64(), VALUE_TYPE_INT64); + } + return Value((int)(a.int32Value * b.int32Value), VALUE_TYPE_INT32); +} +Value op_div(const Value& a1, const Value& b1) { + if (a1.isError()) { + return a1; + } + if (b1.isError()) { + return b1; + } + auto a = a1.getValue(); + auto b = b1.getValue(); + if (!(a.isDouble() || a.isFloat() || a.isInt64() || a.isInt32OrLess())) { + return Value::makeError(); + } + if (!(b.isDouble() || b.isFloat() || b.isInt64() || b.isInt32OrLess())) { + return Value::makeError(); + } + if (a.isDouble() || b.isDouble()) { + return Value(a.toDouble() / b.toDouble(), VALUE_TYPE_DOUBLE); + } + if (a.isFloat() || b.isFloat()) { + return Value(a.toFloat() / b.toFloat(), VALUE_TYPE_FLOAT); + } + if (a.isInt64() || b.isInt64()) { + auto d = b.toInt64(); + if (d == 0) { + return Value::makeError(); + } + return Value(1.0 * a.toInt64() / d, VALUE_TYPE_DOUBLE); + } + if (b.int32Value == 0) { + return Value::makeError(); + } + return Value(1.0 * a.int32Value / b.int32Value, VALUE_TYPE_DOUBLE); +} +Value op_mod(const Value& a1, const Value& b1) { + if (a1.isError()) { + return a1; + } + if (b1.isError()) { + return b1; + } + auto a = a1.getValue(); + auto b = b1.getValue(); + if (!(a.isDouble() || a.isFloat() || a.isInt64() || a.isInt32OrLess())) { + return Value::makeError(); + } + if (!(b.isDouble() || b.isFloat() || b.isInt64() || b.isInt32OrLess())) { + return Value::makeError(); + } + if (a.isDouble() || b.isDouble()) { + return Value(a.toDouble() - floor(a.toDouble() / b.toDouble()) * b.toDouble(), VALUE_TYPE_DOUBLE); + } + if (a.isFloat() || b.isFloat()) { + return Value(a.toFloat() - floor(a.toFloat() / b.toFloat()) * b.toFloat(), VALUE_TYPE_FLOAT); + } + if (a.isInt64() || b.isInt64()) { + auto d = b.toInt64(); + if (d == 0) { + return Value::makeError(); + } + return Value(a.toInt64() % d, VALUE_TYPE_INT64); + } + if (b.int32Value == 0) { + return Value::makeError(); + } + return Value((int)(a.int32Value % b.int32Value), VALUE_TYPE_INT32); +} +Value op_left_shift(const Value& a1, const Value& b1) { + if (a1.isError()) { + return a1; + } + if (b1.isError()) { + return b1; + } + auto a = a1.getValue(); + auto b = b1.getValue(); + if (!(a.isInt64() || a.isInt32OrLess())) { + return Value::makeError(); + } + if (!(b.isInt64() || b.isInt32OrLess())) { + return Value::makeError(); + } + if (a.isInt64() || b.isInt64()) { + return Value(a.toInt64() << b.toInt64(), VALUE_TYPE_INT64); + } + return Value((int)(a.toInt32() << b.toInt32()), VALUE_TYPE_INT32); +} +Value op_right_shift(const Value& a1, const Value& b1) { + if (a1.isError()) { + return a1; + } + if (b1.isError()) { + return b1; + } + auto a = a1.getValue(); + auto b = b1.getValue(); + if (!(a.isInt64() || a.isInt32OrLess())) { + return Value::makeError(); + } + if (!(b.isInt64() || b.isInt32OrLess())) { + return Value::makeError(); + } + if (a.isInt64() || b.isInt64()) { + return Value(a.toInt64() >> b.toInt64(), VALUE_TYPE_INT64); + } + return Value((int)(a.toInt32() >> b.toInt32()), VALUE_TYPE_INT32); +} +Value op_binary_and(const Value& a1, const Value& b1) { + if (a1.isError()) { + return a1; + } + if (b1.isError()) { + return b1; + } + auto a = a1.getValue(); + auto b = b1.getValue(); + if (!(a.isInt64() || a.isInt32OrLess())) { + return Value::makeError(); + } + if (!(b.isInt64() || b.isInt32OrLess())) { + return Value::makeError(); + } + if (a.isInt64() || b.isInt64()) { + return Value(a.toInt64() & b.toInt64(), VALUE_TYPE_INT64); + } + return Value((int)(a.toInt32() & b.toInt32()), VALUE_TYPE_INT32); +} +Value op_binary_or(const Value& a1, const Value& b1) { + if (a1.isError()) { + return a1; + } + if (b1.isError()) { + return b1; + } + auto a = a1.getValue(); + auto b = b1.getValue(); + if (!(a.isInt64() || a.isInt32OrLess())) { + return Value::makeError(); + } + if (!(b.isInt64() || b.isInt32OrLess())) { + return Value::makeError(); + } + if (a.isInt64() || b.isInt64()) { + return Value(a.toInt64() | b.toInt64(), VALUE_TYPE_INT64); + } + return Value((int)(a.toInt32() | b.toInt32()), VALUE_TYPE_INT32); +} +Value op_binary_xor(const Value& a1, const Value& b1) { + if (a1.isError()) { + return a1; + } + if (b1.isError()) { + return b1; + } + auto a = a1.getValue(); + auto b = b1.getValue(); + if (!(a.isInt64() || a.isInt32OrLess())) { + return Value::makeError(); + } + if (!(b.isInt64() || b.isInt32OrLess())) { + return Value::makeError(); + } + if (a.isInt64() || b.isInt64()) { + return Value(a.toInt64() ^ b.toInt64(), VALUE_TYPE_INT64); + } + return Value((int)(a.toInt32() ^ b.toInt32()), VALUE_TYPE_INT32); +} +static bool is_equal(const Value& a1, const Value& b1) { + auto a = a1.getValue(); + auto b = b1.getValue(); + auto aIsUndefinedOrNull = a.getType() == VALUE_TYPE_UNDEFINED || a.getType() == VALUE_TYPE_NULL; + auto bIsUndefinedOrNull = b.getType() == VALUE_TYPE_UNDEFINED || b.getType() == VALUE_TYPE_NULL; + if (aIsUndefinedOrNull) { + return bIsUndefinedOrNull; + } else if (bIsUndefinedOrNull) { + return false; + } + if (a.isString() && b.isString()) { + const char *aStr = a.getString(); + const char *bStr = b.getString(); + if (!aStr && !bStr) { + return true; + } + if (!aStr || !bStr) { + return false; + } + return strcmp(aStr, bStr) == 0; + } + if (a.isBlob() && b.isBlob()) { + auto aBlobRef = a.getBlob(); + auto bBlobRef = b.getBlob(); + if (!aBlobRef && !bBlobRef) { + return true; + } + if (!aBlobRef || !bBlobRef) { + return false; + } + if (aBlobRef->len != bBlobRef->len) { + return false; + } + return memcmp(aBlobRef->blob, bBlobRef->blob, aBlobRef->len) == 0; + } + if (a.getType() == b.getType()) { + return a == b; + } + if (a.isInt32OrLess() == b.isInt32OrLess()) { + return a.toInt32() == b.toInt32(); + } + return a.toDouble() == b.toDouble(); +} +static bool is_less(const Value& a1, const Value& b1) { + auto a = a1.getValue(); + auto b = b1.getValue(); + if (a.isString() && b.isString()) { + const char *aStr = a.getString(); + const char *bStr = b.getString(); + if (!aStr || !bStr) { + return false; + } + return strcmp(aStr, bStr) < 0; + } + return a.toDouble() < b.toDouble(); +} +static bool is_great(const Value& a1, const Value& b1) { + return !is_less(a1, b1) && !is_equal(a1, b1); +} +Value op_eq(const Value& a1, const Value& b1) { + if (a1.isError()) { + return a1; + } + if (b1.isError()) { + return b1; + } + return Value(is_equal(a1, b1), VALUE_TYPE_BOOLEAN); +} +Value op_neq(const Value& a1, const Value& b1) { + if (a1.isError()) { + return a1; + } + if (b1.isError()) { + return b1; + } + return Value(!is_equal(a1, b1), VALUE_TYPE_BOOLEAN); +} +Value op_less(const Value& a1, const Value& b1) { + if (a1.isError()) { + return a1; + } + if (b1.isError()) { + return b1; + } + return Value(is_less(a1, b1), VALUE_TYPE_BOOLEAN); +} +Value op_great(const Value& a1, const Value& b1) { + if (a1.isError()) { + return a1; + } + if (b1.isError()) { + return b1; + } + return Value(is_great(a1, b1), VALUE_TYPE_BOOLEAN); +} +Value op_less_eq(const Value& a1, const Value& b1) { + if (a1.isError()) { + return a1; + } + if (b1.isError()) { + return b1; + } + return Value(is_less(a1, b1) || is_equal(a1, b1), VALUE_TYPE_BOOLEAN); +} +Value op_great_eq(const Value& a1, const Value& b1) { + if (a1.isError()) { + return a1; + } + if (b1.isError()) { + return b1; + } + return Value(!is_less(a1, b1), VALUE_TYPE_BOOLEAN); +} +static void do_OPERATION_TYPE_ADD(EvalStack &stack) { + auto b = stack.pop(); + auto a = stack.pop(); + auto result = op_add(a, b); + if (result.getType() == VALUE_TYPE_UNDEFINED) { + result = Value::makeError(); + } + stack.push(result); +} +static void do_OPERATION_TYPE_SUB(EvalStack &stack) { + auto b = stack.pop(); + auto a = stack.pop(); + auto result = op_sub(a, b); + if (result.getType() == VALUE_TYPE_UNDEFINED) { + result = Value::makeError(); + } + stack.push(result); +} +static void do_OPERATION_TYPE_MUL(EvalStack &stack) { + auto b = stack.pop(); + auto a = stack.pop(); + auto result = op_mul(a, b); + if (result.getType() == VALUE_TYPE_UNDEFINED) { + result = Value::makeError(); + } + stack.push(result); +} +static void do_OPERATION_TYPE_DIV(EvalStack &stack) { + auto b = stack.pop(); + auto a = stack.pop(); + auto result = op_div(a, b); + if (result.getType() == VALUE_TYPE_UNDEFINED) { + result = Value::makeError(); + } + stack.push(result); +} +static void do_OPERATION_TYPE_MOD(EvalStack &stack) { + auto b = stack.pop(); + auto a = stack.pop(); + auto result = op_mod(a, b); + if (result.getType() == VALUE_TYPE_UNDEFINED) { + result = Value::makeError(); + } + stack.push(result); +} +static void do_OPERATION_TYPE_LEFT_SHIFT(EvalStack &stack) { + auto b = stack.pop(); + auto a = stack.pop(); + auto result = op_left_shift(a, b); + if (result.getType() == VALUE_TYPE_UNDEFINED) { + result = Value::makeError(); + } + stack.push(result); +} +static void do_OPERATION_TYPE_RIGHT_SHIFT(EvalStack &stack) { + auto b = stack.pop(); + auto a = stack.pop(); + auto result = op_right_shift(a, b); + if (result.getType() == VALUE_TYPE_UNDEFINED) { + result = Value::makeError(); + } + stack.push(result); +} +static void do_OPERATION_TYPE_BINARY_AND(EvalStack &stack) { + auto b = stack.pop(); + auto a = stack.pop(); + auto result = op_binary_and(a, b); + if (result.getType() == VALUE_TYPE_UNDEFINED) { + result = Value::makeError(); + } + stack.push(result); +} +static void do_OPERATION_TYPE_BINARY_OR(EvalStack &stack) { + auto b = stack.pop(); + auto a = stack.pop(); + auto result = op_binary_or(a, b); + if (result.getType() == VALUE_TYPE_UNDEFINED) { + result = Value::makeError(); + } + stack.push(result); +} +static void do_OPERATION_TYPE_BINARY_XOR(EvalStack &stack) { + auto b = stack.pop(); + auto a = stack.pop(); + auto result = op_binary_xor(a, b); + if (result.getType() == VALUE_TYPE_UNDEFINED) { + result = Value::makeError(); + } + stack.push(result); +} +static void do_OPERATION_TYPE_EQUAL(EvalStack &stack) { + auto b = stack.pop(); + auto a = stack.pop(); + stack.push(op_eq(a, b)); +} +static void do_OPERATION_TYPE_NOT_EQUAL(EvalStack &stack) { + auto b = stack.pop(); + auto a = stack.pop(); + stack.push(op_neq(a, b)); +} +static void do_OPERATION_TYPE_LESS(EvalStack &stack) { + auto b = stack.pop(); + auto a = stack.pop(); + stack.push(op_less(a, b)); +} +static void do_OPERATION_TYPE_GREATER(EvalStack &stack) { + auto b = stack.pop(); + auto a = stack.pop(); + stack.push(op_great(a, b)); +} +static void do_OPERATION_TYPE_LESS_OR_EQUAL(EvalStack &stack) { + auto b = stack.pop(); + auto a = stack.pop(); + stack.push(op_less_eq(a, b)); +} +static void do_OPERATION_TYPE_GREATER_OR_EQUAL(EvalStack &stack) { + auto b = stack.pop(); + auto a = stack.pop(); + stack.push(op_great_eq(a, b)); +} +static void do_OPERATION_TYPE_LOGICAL_AND(EvalStack &stack) { + auto bValue = stack.pop().getValue(); + auto aValue = stack.pop().getValue(); + if (aValue.isError()) { + stack.push(aValue); + return; + } + if (!aValue.toBool()) { + stack.push(Value(false, VALUE_TYPE_BOOLEAN)); + return; + } + if (bValue.isError()) { + stack.push(bValue); + return; + } + stack.push(Value(bValue.toBool(), VALUE_TYPE_BOOLEAN)); +} +static void do_OPERATION_TYPE_LOGICAL_OR(EvalStack &stack) { + auto bValue = stack.pop().getValue(); + auto aValue = stack.pop().getValue(); + if (aValue.isError()) { + stack.push(aValue); + return; + } + if (aValue.toBool()) { + stack.push(Value(true, VALUE_TYPE_BOOLEAN)); + return; + } + if (bValue.isError()) { + stack.push(bValue); + return; + } + stack.push(Value(bValue.toBool(), VALUE_TYPE_BOOLEAN)); +} +static void do_OPERATION_TYPE_UNARY_PLUS(EvalStack &stack) { + auto a = stack.pop().getValue(); + if (a.isDouble()) { + stack.push(Value(a.getDouble(), VALUE_TYPE_DOUBLE)); + return; + } + if (a.isFloat()) { + stack.push(Value(a.toFloat(), VALUE_TYPE_FLOAT)); + return; + } + if (a.isInt64()) { + stack.push(Value((int64_t)a.getInt64(), VALUE_TYPE_INT64)); + return; + } + if (a.isInt32()) { + stack.push(Value((int)a.getInt32(), VALUE_TYPE_INT32)); + return; + } + if (a.isInt16()) { + stack.push(Value((int16_t)a.getInt16(), VALUE_TYPE_INT16)); + return; + } + if (a.isInt8()) { + stack.push(Value((int8_t)a.getInt8(), VALUE_TYPE_INT8)); + return; + } + stack.push(Value::makeError()); +} +static void do_OPERATION_TYPE_UNARY_MINUS(EvalStack &stack) { + auto a = stack.pop().getValue(); + if (a.isDouble()) { + stack.push(Value(-a.getDouble(), VALUE_TYPE_DOUBLE)); + return; + } + if (a.isFloat()) { + stack.push(Value(-a.toFloat(), VALUE_TYPE_FLOAT)); + return; + } + if (a.isInt64()) { + stack.push(Value((int64_t)-a.getInt64(), VALUE_TYPE_INT64)); + return; + } + if (a.isInt32()) { + stack.push(Value((int)-a.getInt32(), VALUE_TYPE_INT32)); + return; + } + if (a.isInt16()) { + stack.push(Value((int16_t)-a.getInt16(), VALUE_TYPE_INT16)); + return; + } + if (a.isInt8()) { + stack.push(Value((int8_t)-a.getInt8(), VALUE_TYPE_INT8)); + return; + } + stack.push(Value::makeError()); +} +static void do_OPERATION_TYPE_BINARY_ONE_COMPLEMENT(EvalStack &stack) { + auto a = stack.pop().getValue(); + if (a.isInt64()) { + stack.push(Value(~a.uint64Value, VALUE_TYPE_UINT64)); + return; + } + if (a.isInt32()) { + stack.push(Value(~a.uint32Value, VALUE_TYPE_UINT32)); + return; + } + if (a.isInt16()) { + stack.push(Value(~a.uint16Value, VALUE_TYPE_UINT16)); + return; + } + if (a.isInt8()) { + stack.push(Value(~a.uint8Value, VALUE_TYPE_UINT8)); + return; + } + stack.push(Value::makeError()); +} +static void do_OPERATION_TYPE_NOT(EvalStack &stack) { + auto aValue = stack.pop(); + if (aValue.isError()) { + stack.push(aValue); + return; + } + int err; + auto a = aValue.toBool(&err); + if (err != 0) { + stack.push(Value::makeError()); + return; + } + stack.push(Value(!a, VALUE_TYPE_BOOLEAN)); +} +static void do_OPERATION_TYPE_CONDITIONAL(EvalStack &stack) { + auto alternate = stack.pop(); + auto consequent = stack.pop(); + auto conditionValue = stack.pop(); + if (conditionValue.isError()) { + stack.push(conditionValue); + return; + } + int err; + auto condition = conditionValue.toBool(&err); + if (err != 0) { + stack.push(Value::makeError()); + return; + } + stack.push(condition ? consequent : alternate); +} +static void do_OPERATION_TYPE_SYSTEM_GET_TICK(EvalStack &stack) { + stack.push(Value(millis(), VALUE_TYPE_UINT32)); +} +static void do_OPERATION_TYPE_FLOW_INDEX(EvalStack &stack) { + if (!stack.iterators) { + stack.push(Value::makeError()); + return; + } + auto a = stack.pop(); + int err; + auto iteratorIndex = a.toInt32(&err); + if (err != 0) { + stack.push(Value::makeError()); + return; + } + if (iteratorIndex < 0 || iteratorIndex >= (int)MAX_ITERATORS) { + stack.push(Value::makeError()); + return; + } + stack.push(stack.iterators[iteratorIndex]); +} +static void do_OPERATION_TYPE_FLOW_IS_PAGE_ACTIVE(EvalStack &stack) { + auto pageIndex = getPageIndexIncludeParents(stack.flowState); + stack.push(Value(pageIndex == g_currentScreen, VALUE_TYPE_BOOLEAN)); +} +static void do_OPERATION_TYPE_FLOW_PAGE_TIMELINE_POSITION(EvalStack &stack) { + stack.push(Value(stack.flowState->timelinePosition, VALUE_TYPE_FLOAT)); +} +static void do_OPERATION_TYPE_FLOW_MAKE_ARRAY_VALUE(EvalStack &stack) { + auto arrayTypeValue = stack.pop(); + if (arrayTypeValue.isError()) { + stack.push(arrayTypeValue); + return; + } + auto arraySizeValue = stack.pop(); + if (arraySizeValue.isError()) { + stack.push(arraySizeValue); + return; + } + auto numInitElementsValue = stack.pop(); + if (numInitElementsValue.isError()) { + stack.push(numInitElementsValue); + return; + } + int arrayType = arrayTypeValue.getInt(); + int err; + int arraySize = arraySizeValue.toInt32(&err); + if (err) { + stack.push(Value::makeError()); + return; + } + int numInitElements = numInitElementsValue.toInt32(&err); + if (err) { + stack.push(Value::makeError()); + return; + } + auto arrayValue = Value::makeArrayRef(arraySize, arrayType, 0x837260d4); + auto array = arrayValue.getArray(); + for (int i = 0; i < arraySize; i++) { + if (i < numInitElements) { + array->values[i] = stack.pop().getValue(); + } else { + array->values[i] = Value(); + } + } + stack.push(arrayValue); +} +static void do_OPERATION_TYPE_FLOW_LANGUAGES(EvalStack &stack) { + auto &languages = stack.flowState->assets->languages; + auto arrayValue = Value::makeArrayRef(languages.count, VALUE_TYPE_STRING, 0xff4787fc); + auto array = arrayValue.getArray(); + for (uint32_t i = 0; i < languages.count; i++) { + array->values[i] = Value((const char *)(languages[i]->languageID)); + } + stack.push(arrayValue); +} +static void do_OPERATION_TYPE_FLOW_TRANSLATE(EvalStack &stack) { + auto textResourceIndexValue = stack.pop(); + int err; + int textResourceIndex = textResourceIndexValue.toInt32(&err); + if (err) { + stack.push(Value::makeError()); + return; + } + int languageIndex = g_selectedLanguage; + auto &languages = stack.flowState->assets->languages; + if (languageIndex >= 0 && languageIndex < (int)languages.count) { + auto &translations = languages[languageIndex]->translations; + if (textResourceIndex >= 0 && textResourceIndex < (int)translations.count) { + stack.push(translations[textResourceIndex]); + return; + } + } + stack.push(""); +} +static void do_OPERATION_TYPE_FLOW_THEMES(EvalStack &stack) { + auto &themes = stack.flowState->assets->colorsDefinition->themes; + auto arrayValue = Value::makeArrayRef(themes.count, VALUE_TYPE_STRING, 0x03906e8f); + auto array = arrayValue.getArray(); + for (uint32_t i = 0; i < themes.count; i++) { + array->values[i] = Value((const char *)(themes[i]->name)); + } + stack.push(arrayValue); +} +static void do_OPERATION_TYPE_FLOW_GET_THEME_COLOR(EvalStack &stack) { + auto colorIndexValue = stack.pop(); + if (colorIndexValue.isError()) { + stack.push(colorIndexValue); + return; + } + uint32_t colorIndex = colorIndexValue.getUInt32(); + uint32_t color = eez_flow_get_theme_color(colorIndex); + stack.push(Value(color, VALUE_TYPE_UINT32)); +} +static void do_OPERATION_TYPE_FLOW_PARSE_INTEGER(EvalStack &stack) { + auto str = stack.pop(); + if (str.isError()) { + stack.push(str); + return; + } + int err; + auto value = str.toInt32(&err); + if (err) { + stack.push(Value::makeError()); + return; + } + stack.push(Value((int)value, VALUE_TYPE_INT32)); +} +static void do_OPERATION_TYPE_FLOW_PARSE_FLOAT(EvalStack &stack) { + auto str = stack.pop(); + if (str.isError()) { + stack.push(str); + return; + } + int err; + auto value = str.toFloat(&err); + if (err) { + stack.push(Value::makeError()); + return; + } + stack.push(Value(value, VALUE_TYPE_FLOAT)); +} +static void do_OPERATION_TYPE_FLOW_PARSE_DOUBLE(EvalStack &stack) { + auto str = stack.pop(); + if (str.isError()) { + stack.push(str); + return; + } + int err; + auto value = str.toDouble(&err); + if (err) { + stack.push(Value::makeError()); + return; + } + stack.push(Value(value, VALUE_TYPE_DOUBLE)); +} +static void do_OPERATION_TYPE_FLOW_TO_INTEGER(EvalStack &stack) { + auto str = stack.pop(); + if (str.isError()) { + stack.push(str); + return; + } + int err; + int value = str.toInt32(&err); + if (err) { + stack.push(Value::makeError()); + return; + } + stack.push(Value(value, VALUE_TYPE_INT32)); +} +static void do_OPERATION_TYPE_FLOW_GET_BITMAP_INDEX(EvalStack &stack) { + stack.push(Value::makeError()); +} +static void do_OPERATION_TYPE_FLOW_GET_BITMAP_AS_DATA_URL(EvalStack &stack) { + stack.push(Value::makeError()); +} +static void do_OPERATION_TYPE_DATE_NOW(EvalStack &stack) { + stack.push(Value((double)date::now(), VALUE_TYPE_DATE)); +} +static void do_OPERATION_TYPE_DATE_TO_STRING(EvalStack &stack) { +#ifndef ARDUINO + auto a = stack.pop().getValue(); + if (a.isError()) { + stack.push(a); + return; + } + if (a.getType() != VALUE_TYPE_DATE) { + stack.push(Value::makeError()); + return; + } + char str[128]; + date::toString(a.getDouble(), str, sizeof(str)); + stack.push(Value::makeStringRef(str, -1, 0xbe440ec8)); +#else + stack.push(Value::makeError()); +#endif +} +static void do_OPERATION_TYPE_DATE_TO_LOCALE_STRING(EvalStack &stack) { +#ifndef ARDUINO + auto a = stack.pop().getValue(); + if (a.isError()) { + stack.push(a); + return; + } + if (a.getType() != VALUE_TYPE_DATE) { + stack.push(Value::makeError()); + return; + } + char str[128]; + date::toLocaleString(a.getDouble(), str, sizeof(str)); + stack.push(Value::makeStringRef(str, -1, 0xbe440ec8)); +#else + stack.push(Value::makeError()); +#endif +} +static void do_OPERATION_TYPE_DATE_FROM_STRING(EvalStack &stack) { +#ifndef ARDUINO + auto a = stack.pop().getValue(); + if (a.isError()) { + stack.push(a); + return; + } + Value dateStrValue = a.toString(0x99cb1a93); + auto date = (double)date::fromString(dateStrValue.getString()); + stack.push(Value(date, VALUE_TYPE_DATE)); +#else + stack.push(Value::makeError()); +#endif +} +static void do_OPERATION_TYPE_DATE_GET_YEAR(EvalStack &stack) { + auto a = stack.pop().getValue(); + if (a.isError()) { + stack.push(a); + return; + } + if (a.getType() != VALUE_TYPE_DATE) { + stack.push(Value::makeError()); + return; + } + stack.push(date::getYear(a.getDouble())); +} +static void do_OPERATION_TYPE_DATE_GET_MONTH(EvalStack &stack) { + auto a = stack.pop().getValue(); + if (a.isError()) { + stack.push(a); + return; + } + if (a.getType() != VALUE_TYPE_DATE) { + stack.push(Value::makeError()); + return; + } + stack.push(date::getMonth(a.getDouble())); +} +static void do_OPERATION_TYPE_DATE_GET_DAY(EvalStack &stack) { + auto a = stack.pop().getValue(); + if (a.isError()) { + stack.push(a); + return; + } + if (a.getType() != VALUE_TYPE_DATE) { + stack.push(Value::makeError()); + return; + } + stack.push(date::getDay(a.getDouble())); +} +static void do_OPERATION_TYPE_DATE_GET_HOURS(EvalStack &stack) { + auto a = stack.pop().getValue(); + if (a.isError()) { + stack.push(a); + return; + } + if (a.getType() != VALUE_TYPE_DATE) { + stack.push(Value::makeError()); + return; + } + stack.push(date::getHours(a.getDouble())); +} +static void do_OPERATION_TYPE_DATE_GET_MINUTES(EvalStack &stack) { + auto a = stack.pop().getValue(); + if (a.isError()) { + stack.push(a); + return; + } + if (a.getType() != VALUE_TYPE_DATE) { + stack.push(Value::makeError()); + return; + } + stack.push(date::getMinutes(a.getDouble())); +} +static void do_OPERATION_TYPE_DATE_GET_SECONDS(EvalStack &stack) { + auto a = stack.pop().getValue(); + if (a.isError()) { + stack.push(a); + return; + } + if (a.getType() != VALUE_TYPE_DATE) { + stack.push(Value::makeError()); + return; + } + stack.push(date::getSeconds(a.getDouble())); +} +static void do_OPERATION_TYPE_DATE_GET_MILLISECONDS(EvalStack &stack) { + auto a = stack.pop().getValue(); + if (a.isError()) { + stack.push(a); + return; + } + if (a.getType() != VALUE_TYPE_DATE) { + stack.push(Value::makeError()); + return; + } + stack.push(date::getMilliseconds(a.getDouble())); +} +static void do_OPERATION_TYPE_DATE_MAKE(EvalStack &stack) { + int err; + Value value; + value = stack.pop().getValue(); + if (value.isError()) { + stack.push(value); + return; + } + int year = value.toInt32(&err); + if (err) { + stack.push(Value::makeError()); + return; + } + value = stack.pop().getValue(); + if (value.isError()) { + stack.push(value); + return; + } + int month = value.toInt32(&err); + if (err) { + stack.push(Value::makeError()); + return; + } + value = stack.pop().getValue(); + if (value.isError()) { + stack.push(value); + return; + } + int day = value.toInt32(&err); + if (err) { + stack.push(Value::makeError()); + return; + } + value = stack.pop().getValue(); + if (value.isError()) { + stack.push(value); + return; + } + int hours = value.toInt32(&err); + if (err) { + stack.push(Value::makeError()); + return; + } + value = stack.pop().getValue(); + if (value.isError()) { + stack.push(value); + return; + } + int minutes = value.toInt32(&err); + if (err) { + stack.push(Value::makeError()); + return; + } + value = stack.pop().getValue(); + if (value.isError()) { + stack.push(value); + return; + } + int seconds = value.toInt32(&err); + if (err) { + stack.push(Value::makeError()); + return; + } + value = stack.pop().getValue(); + if (value.isError()) { + stack.push(value); + return; + } + int milliseconds = value.toInt32(&err); + if (err) { + stack.push(Value::makeError()); + return; + } + auto date = (double)date::makeDate(year, month, day, hours, minutes, seconds, milliseconds); + stack.push(Value(date, VALUE_TYPE_DATE)); +} +static void do_OPERATION_TYPE_MATH_SIN(EvalStack &stack) { + auto a = stack.pop().getValue(); + if (a.isError()) { + stack.push(a); + return; + } + if (a.isDouble()) { + stack.push(Value(sin(a.getDouble()), VALUE_TYPE_DOUBLE)); + return; + } + if (a.isFloat()) { + stack.push(Value(sinf(a.toFloat()), VALUE_TYPE_FLOAT)); + return; + } + if (a.isInt64()) { + stack.push(Value(sin(a.toInt64()), VALUE_TYPE_FLOAT)); + return; + } + if (a.isInt32OrLess()) { + stack.push(Value(sinf(a.int32Value), VALUE_TYPE_FLOAT)); + return; + } + stack.push(Value::makeError()); +} +static void do_OPERATION_TYPE_MATH_COS(EvalStack &stack) { + auto a = stack.pop().getValue(); + if (a.isError()) { + stack.push(a); + return; + } + if (a.isDouble()) { + stack.push(Value(cos(a.getDouble()), VALUE_TYPE_DOUBLE)); + return; + } + if (a.isFloat()) { + stack.push(Value(cosf(a.toFloat()), VALUE_TYPE_FLOAT)); + return; + } + if (a.isInt64()) { + stack.push(Value(cos(a.toInt64()), VALUE_TYPE_FLOAT)); + return; + } + if (a.isInt32OrLess()) { + stack.push(Value(cosf(a.int32Value), VALUE_TYPE_FLOAT)); + return; + } + stack.push(Value::makeError()); +} +static void do_OPERATION_TYPE_MATH_POW(EvalStack &stack) { + auto baseValue = stack.pop().getValue(); + if (baseValue.isError()) { + stack.push(Value::makeError()); + return; + } + if (!baseValue.isInt32OrLess() && !baseValue.isFloat() && !baseValue.isDouble()) { + stack.push(Value::makeError()); + return; + } + auto exponentValue = stack.pop().getValue(); + if (exponentValue.isError()) { + stack.push(Value::makeError()); + return; + } + if (!exponentValue.isInt32OrLess() && !exponentValue.isFloat() && !exponentValue.isDouble()) { + stack.push(Value::makeError()); + return; + } + if (baseValue.isFloat() && (exponentValue.isFloat() || exponentValue.isInt32OrLess())) { + int err; + float base = baseValue.toFloat(&err); + if (err) { + stack.push(Value::makeError()); + return; + } + float exponent = exponentValue.toFloat(&err); + if (err) { + stack.push(Value::makeError()); + return; + } + float result = powf(base, exponent); + stack.push(Value(result, VALUE_TYPE_FLOAT)); + } else { + int err; + double base = baseValue.toDouble(&err); + if (err) { + stack.push(Value::makeError()); + return; + } + double exponent = exponentValue.toDouble(&err); + if (err) { + stack.push(Value::makeError()); + return; + } + double result = pow(base, exponent); + stack.push(Value(result, VALUE_TYPE_DOUBLE)); + } +} +static void do_OPERATION_TYPE_MATH_LOG(EvalStack &stack) { + auto a = stack.pop().getValue(); + if (a.isError()) { + stack.push(a); + return; + } + if (a.isDouble()) { + stack.push(Value(log(a.getDouble()), VALUE_TYPE_DOUBLE)); + return; + } + if (a.isFloat()) { + stack.push(Value(logf(a.toFloat()), VALUE_TYPE_FLOAT)); + return; + } + if (a.isInt64()) { + stack.push(Value(log(a.toInt64()), VALUE_TYPE_FLOAT)); + return; + } + if (a.isInt32OrLess()) { + stack.push(Value(logf(a.int32Value), VALUE_TYPE_FLOAT)); + return; + } + stack.push(Value::makeError()); +} +static void do_OPERATION_TYPE_MATH_LOG10(EvalStack &stack) { + auto a = stack.pop().getValue(); + if (a.isError()) { + stack.push(a); + return; + } + if (a.isDouble()) { + stack.push(Value(log10(a.getDouble()), VALUE_TYPE_DOUBLE)); + return; + } + if (a.isFloat()) { + stack.push(Value(log10f(a.toFloat()), VALUE_TYPE_FLOAT)); + return; + } + if (a.isInt64()) { + stack.push(Value(log10(a.toInt64()), VALUE_TYPE_FLOAT)); + return; + } + if (a.isInt32OrLess()) { + stack.push(Value(log10f(a.int32Value), VALUE_TYPE_FLOAT)); + return; + } + stack.push(Value::makeError()); +} +static void do_OPERATION_TYPE_MATH_ABS(EvalStack &stack) { + auto a = stack.pop().getValue(); + if (a.isError()) { + stack.push(a); + return; + } + if (a.isDouble()) { + stack.push(Value(abs(a.getDouble()), VALUE_TYPE_DOUBLE)); + return; + } + if (a.isFloat()) { + stack.push(Value(abs(a.toFloat()), VALUE_TYPE_FLOAT)); + return; + } + if (a.isInt64()) { + stack.push(Value((int64_t)abs(a.getInt64()), VALUE_TYPE_INT64)); + return; + } + if (a.isInt32()) { + stack.push(Value((int)abs(a.getInt32()), VALUE_TYPE_INT32)); + return; + } + if (a.isInt16()) { + stack.push(Value(abs(a.getInt16()), VALUE_TYPE_INT16)); + return; + } + if (a.isInt8()) { + stack.push(Value(abs(a.getInt8()), VALUE_TYPE_INT8)); + return; + } + stack.push(Value::makeError()); +} +static void do_OPERATION_TYPE_MATH_FLOOR(EvalStack &stack) { + auto a = stack.pop().getValue(); + if (a.isError()) { + stack.push(a); + return; + } + if (a.isInt32OrLess()) { + stack.push(a); + return; + } + if (a.isDouble()) { + stack.push(Value(floor(a.getDouble()), VALUE_TYPE_DOUBLE)); + return; + } + if (a.isFloat()) { + stack.push(Value(floorf(a.toFloat()), VALUE_TYPE_FLOAT)); + return; + } + stack.push(Value::makeError()); +} +static void do_OPERATION_TYPE_MATH_CEIL(EvalStack &stack) { + auto a = stack.pop().getValue(); + if (a.isError()) { + stack.push(a); + return; + } + if (a.isInt32OrLess()) { + stack.push(a); + return; + } + if (a.isDouble()) { + stack.push(Value(ceil(a.getDouble()), VALUE_TYPE_DOUBLE)); + return; + } + if (a.isFloat()) { + stack.push(Value(ceilf(a.toFloat()), VALUE_TYPE_FLOAT)); + return; + } + stack.push(Value::makeError()); +} +static float roundN(float value, unsigned int numDigits) { + float pow_10 = pow(10.0f, numDigits); + return round(value * pow_10) / pow_10; +} +static double roundN(double value, unsigned int numDigits) { + float pow_10 = pow(10.0f, numDigits); + return round(value * pow_10) / pow_10; +} +static void do_OPERATION_TYPE_MATH_ROUND(EvalStack &stack) { + auto numArgs = stack.pop().getInt(); + auto a = stack.pop().getValue(); + if (a.isError()) { + stack.push(a); + return; + } + unsigned int numDigits; + if (numArgs > 1) { + auto b = stack.pop().getValue(); + numDigits = b.toInt32(); + } else { + numDigits = 0; + } + if (a.isInt32OrLess()) { + stack.push(a); + return; + } + if (a.isDouble()) { + stack.push(Value(roundN(a.getDouble(), numDigits), VALUE_TYPE_DOUBLE)); + return; + } + if (a.isFloat()) { + stack.push(Value(roundN(a.toFloat(), numDigits), VALUE_TYPE_FLOAT)); + return; + } + if (a.isInt32OrLess()) { + stack.push(a); + return; + } + stack.push(Value::makeError()); +} +static void do_OPERATION_TYPE_MATH_MIN(EvalStack &stack) { + auto numArgs = stack.pop().getInt(); + Value minValue; + for (int i = 0; i < numArgs; i++) { + auto value = stack.pop().getValue(); + if (value.isError()) { + stack.push(value); + return; + } + if (minValue.isUndefinedOrNull() || is_less(value, minValue)) { + minValue = value; + } + } + stack.push(minValue); +} +static void do_OPERATION_TYPE_MATH_MAX(EvalStack &stack) { + auto numArgs = stack.pop().getInt(); + Value maxValue; + for (int i = 0; i < numArgs; i++) { + auto value = stack.pop().getValue(); + if (value.isError()) { + stack.push(value); + return; + } + if (maxValue.isUndefinedOrNull() || is_great(value, maxValue)) { + maxValue = value; + } + } + stack.push(maxValue); +} +static void do_OPERATION_TYPE_STRING_LENGTH(EvalStack &stack) { + auto a = stack.pop().getValue(); + if (a.isError()) { + stack.push(a); + return; + } + const char *aStr = a.getString(); + if (!aStr) { + stack.push(Value::makeError()); + return; + } + int aStrLen = strlen(aStr); + stack.push(Value(aStrLen, VALUE_TYPE_INT32)); +} +static void do_OPERATION_TYPE_STRING_SUBSTRING(EvalStack &stack) { + auto numArgs = stack.pop().getInt(); + Value strValue = stack.pop().getValue(); + if (strValue.isError()) { + stack.push(strValue); + return; + } + Value startValue = stack.pop().getValue(); + if (startValue.isError()) { + stack.push(startValue); + return; + } + Value endValue; + if (numArgs == 3) { + endValue = stack.pop().getValue(); + if (endValue.isError()) { + stack.push(endValue); + return; + } + } + const char *str = strValue.getString(); + if (!str) { + stack.push(Value::makeError()); + return; + } + int strLen = (int)strlen(str); + int err = 0; + int start = startValue.toInt32(&err); + if (err != 0) { + stack.push(Value::makeError()); + return; + } + int end; + if (endValue.getType() == VALUE_TYPE_UNDEFINED) { + end = strLen; + } else { + end = endValue.toInt32(&err); + if (err != 0) { + stack.push(Value::makeError()); + return; + } + } + if (start < 0) { + start = 0; + } else if (start > strLen) { + start = strLen; + } + if (end < 0) { + end = 0; + } else if (end > strLen) { + end = strLen; + } + if (start < end) { + Value resultValue = Value::makeStringRef(str + start, end - start, 0x203b08a2); + stack.push(resultValue); + return; + } + stack.push(Value("", VALUE_TYPE_STRING)); +} +static void do_OPERATION_TYPE_STRING_FIND(EvalStack &stack) { + auto a = stack.pop().getValue(); + if (a.isError()) { + stack.push(a); + return; + } + auto b = stack.pop().getValue(); + if (b.isError()) { + stack.push(b); + return; + } + Value aStr = a.toString(0xf616bf4d); + Value bStr = b.toString(0x81229133); + if (!aStr.getString() || !bStr.getString()) { + stack.push(Value(-1, VALUE_TYPE_INT32)); + return; + } + const char *pos = strstr(aStr.getString(), bStr.getString()); + if (pos) { + stack.push(Value((int)(pos - aStr.getString()), VALUE_TYPE_INT32)); + return; + } + stack.push(Value(-1, VALUE_TYPE_INT32)); +} +typedef enum { + type_int, + type_signed_char, + type_short_int, + type_long_int, + type_long_long_int, + type_intmax_t, + type_size_t, + type_unsigned_int, + type_unsigned_char, + type_unsigned_short_int, + type_unsigned_long_int, + type_unsigned_long_long_int, + type_uintmax_t, + type_double, + type_string +} FormatType; +typedef enum { + length_none, + length_hh, + length_h, + length_l, + length_ll, + length_j, + length_z, + length_t, + length_L +} FormatLength; +static size_t do_string_format(FormatType type, const Value& b, char *result, size_t result_size, const char *format) { + if (type == type_int) return snprintf(result, result_size, format, (int)b.getInt()); + if (type == type_signed_char) return snprintf(result, result_size, format, (signed char)b.getInt32()); + if (type == type_short_int) return snprintf(result, result_size, format, (short int)b.getInt32()); + if (type == type_long_int) return snprintf(result, result_size, format, (long int)b.getInt64()); + if (type == type_long_long_int) return snprintf(result, result_size, format, (long long int)b.getInt64()); + if (type == type_intmax_t) return snprintf(result, result_size, format, (intmax_t)b.getInt64()); + if (type == type_size_t) return snprintf(result, result_size, format, (size_t)b.getInt64()); + if (type == type_unsigned_int) return snprintf(result, result_size, format, (unsigned int)b.getUInt32()); + if (type == type_unsigned_char) return snprintf(result, result_size, format, (unsigned char)b.getUInt32()); + if (type == type_unsigned_short_int) return snprintf(result, result_size, format, (unsigned short int)b.getUInt32()); + if (type == type_unsigned_long_int) return snprintf(result, result_size, format, (unsigned long int)b.getUInt64()); + if (type == type_unsigned_long_long_int) return snprintf(result, result_size, format, (unsigned long long int)b.getUInt64()); + if (type == type_uintmax_t) return snprintf(result, result_size, format, (uintmax_t)b.getUInt64()); + if (type == type_double) { + if (b.isDouble()) { + return snprintf(result, result_size, format, b.getDouble()); + } + float f = b.toFloat(); + return snprintf(result, result_size, format, f); + } + return snprintf(result, result_size, format, b.getString()); +} +static void do_OPERATION_TYPE_STRING_FORMAT(EvalStack &stack) { + auto a = stack.pop().getValue(); + if (a.isError()) { + stack.push(a); + return; + } + auto b = stack.pop().getValue(); + if (b.isError()) { + stack.push(b); + return; + } + if (!a.isString()) { + stack.push(Value::makeError()); + return; + } + const char *format = a.getString(); + size_t formatLength = strlen(format); + if (formatLength == 0) { + stack.push(Value::makeError()); + return; + } + char specifier = format[formatLength-1]; + char l1 = formatLength > 1 ? format[formatLength-2] : 0; + char l2 = formatLength > 2 ? format[formatLength-3] : 0; + FormatLength length = length_none; + if (l1 == 'h' && l2 == 'h') length = length_hh; + else if (l1 == 'h') length = length_h; + else if (l1 == 'l') length = length_l; + else if (l1 == 'l' && l2 == 'l') length = length_ll; + else if (l1 == 'j') length = length_j; + else if (l1 == 'z') length = length_z; + else if (l1 == 't') length = length_t; + else if (l1 == 'L') length = length_L; + FormatType type = type_int; + if (specifier == 'd' || specifier == 'i') { + if (length == length_none) { + type = type_int; + } else if (length == length_hh) { + type = type_signed_char; + } else if (length == length_h) { + type = type_short_int; + } else if (length == length_l) { + type = type_long_int; + } else if (length == length_ll) { + type = type_long_long_int; + } else if (length == length_j) { + type = type_intmax_t; + } else if (length == length_z) { + type = type_size_t; + } else { + stack.push(Value::makeError()); + return; + } + } else if (specifier == 'u' || specifier == 'o' || specifier == 'x' || specifier == 'X') { + if (length == length_none) { + type = type_unsigned_int; + } else if (length == length_hh) { + type = type_unsigned_char; + } else if (length == length_h) { + type = type_unsigned_short_int; + } else if (length == length_l) { + type = type_unsigned_long_int; + } else if (length == length_ll) { + type = type_unsigned_long_long_int; + } else if (length == length_j) { + type = type_uintmax_t; + } else if (length == length_z) { + type = type_size_t; + } else { + stack.push(Value::makeError()); + return; + } + } else if (specifier == 'f' || specifier == 'F' || specifier == 'e' || specifier == 'E' || specifier == 'g' || specifier == 'G' || specifier == 'a' || specifier == 'A') { + type = type_double; + } else if (specifier == 'c') { + type = type_int; + } else if (specifier == 's') { + type = type_string; + } else { + stack.push(Value::makeError()); + return; + } + int resultStrLen = do_string_format(type, b, NULL, 0, format); + char *resultStr = (char *)eez::alloc(resultStrLen + 1, 0x987ee4eb); + do_string_format(type, b, resultStr, resultStrLen + 1, format); + stack.push(Value::makeStringRef(resultStr, -1, 0x1e1227fd)); + eez::free(resultStr); +} +static void do_OPERATION_TYPE_STRING_FORMAT_PREFIX(EvalStack &stack) { + auto a = stack.pop().getValue(); + if (a.isError()) { + stack.push(a); + return; + } + auto b = stack.pop().getValue(); + if (b.isError()) { + stack.push(b); + return; + } + auto c = stack.pop().getValue(); + if (c.isError()) { + stack.push(c); + return; + } + if (!a.isString()) { + stack.push(Value::makeError()); + return; + } + stack.push(Value::makeError()); + return; +} +static void do_OPERATION_TYPE_STRING_PAD_START(EvalStack &stack) { + auto a = stack.pop().getValue(); + if (a.isError()) { + stack.push(a); + return; + } + auto b = stack.pop().getValue(); + if (b.isError()) { + stack.push(b); + return; + } + auto c = stack.pop().getValue(); + if (c.isError()) { + stack.push(c); + return; + } + auto str = a.toString(0xcf6aabe6); + if (!str.getString()) { + stack.push(Value::makeError()); + return; + } + int strLen = strlen(str.getString()); + int err; + int targetLength = b.toInt32(&err); + if (err) { + stack.push(Value::makeError()); + return; + } + if (targetLength < strLen) { + targetLength = strLen; + } + auto padStr = c.toString(0x81353bd7); + if (!padStr.getString()) { + stack.push(Value::makeError()); + return; + } + int padStrLen = strlen(padStr.getString()); + Value resultValue = Value::makeStringRef("", targetLength, 0xf43b14dd); + if (resultValue.type == VALUE_TYPE_NULL) { + stack.push(Value::makeError()); + return; + } + char *resultStr = (char *)resultValue.getString(); + auto n = targetLength - strLen; + stringCopy(resultStr + (targetLength - strLen), strLen + 1, str.getString()); + for (int i = 0; i < n; i++) { + resultStr[i] = padStr.getString()[i % padStrLen]; + } + stack.push(resultValue); +} +static void do_OPERATION_TYPE_STRING_SPLIT(EvalStack &stack) { + auto strValue = stack.pop().getValue(); + if (strValue.isError()) { + stack.push(strValue); + return; + } + auto delimValue = stack.pop().getValue(); + if (delimValue.isError()) { + stack.push(delimValue); + return; + } + auto str = strValue.getString(); + if (!str) { + stack.push(Value::makeError()); + return; + } + auto delim = delimValue.getString(); + if (!delim) { + stack.push(Value::makeError()); + return; + } + auto strLen = strlen(str); + char *strCopy = (char *)eez::alloc(strLen + 1, 0xea9d0bc0); + stringCopy(strCopy, strLen + 1, str); + size_t arraySize = 0; + char *token = strtok(strCopy, delim); + while (token != NULL) { + arraySize++; + token = strtok(NULL, delim); + } + eez::free(strCopy); + strCopy = (char *)eez::alloc(strLen + 1, 0xea9d0bc1); + stringCopy(strCopy, strLen + 1, str); + auto arrayValue = Value::makeArrayRef(arraySize, VALUE_TYPE_STRING, 0xe82675d4); + auto array = arrayValue.getArray(); + int i = 0; + token = strtok(strCopy, delim); + while (token != NULL) { + array->values[i++] = Value::makeStringRef(token, -1, 0x45209ec0); + token = strtok(NULL, delim); + } + eez::free(strCopy); + stack.push(arrayValue); +} +static void do_OPERATION_TYPE_STRING_FROM_CODE_POINT(EvalStack &stack) { + Value charCodeValue = stack.pop().getValue(); + if (charCodeValue.isError()) { + stack.push(charCodeValue); + return; + } + int err = 0; + int32_t charCode = charCodeValue.toInt32(&err); + if (err != 0) { + stack.push(Value::makeError()); + return; + } + char str[16] = {0}; + utf8catcodepoint(str, charCode, sizeof(str)); + Value resultValue = Value::makeStringRef(str, strlen(str), 0x02c2e778); + stack.push(resultValue); + return; +} +static void do_OPERATION_TYPE_STRING_CODE_POINT_AT(EvalStack &stack) { + auto strValue = stack.pop().getValue(); + if (strValue.isError()) { + stack.push(strValue); + return; + } + Value indexValue = stack.pop().getValue(); + if (indexValue.isError()) { + stack.push(indexValue); + return; + } + utf8_int32_t codePoint = 0; + const char *str = strValue.getString(); + if (str) { + int index = indexValue.toInt32(); + if (index >= 0) { + do { + str = utf8codepoint(str, &codePoint); + } while (codePoint && --index >= 0); + } + } + stack.push(Value((int)codePoint, VALUE_TYPE_INT32)); + return; +} +static void do_OPERATION_TYPE_ARRAY_LENGTH(EvalStack &stack) { + auto a = stack.pop().getValue(); + if (a.isError()) { + stack.push(a); + return; + } + if (a.isArray()) { + auto array = a.getArray(); + stack.push(Value(array->arraySize, VALUE_TYPE_UINT32)); + return; + } + if (a.isBlob()) { + auto blobRef = a.getBlob(); + stack.push(Value(blobRef->len, VALUE_TYPE_UINT32)); + return; + } + stack.push(Value::makeError()); +} +static void do_OPERATION_TYPE_ARRAY_SLICE(EvalStack &stack) { + auto numArgs = stack.pop().getInt(); + auto arrayValue = stack.pop().getValue(); + if (arrayValue.isError()) { + stack.push(arrayValue); + return; + } + int from = 0; + if (numArgs > 1) { + auto fromValue = stack.pop().getValue(); + if (fromValue.isError()) { + stack.push(fromValue); + return; + } + int err; + from = fromValue.toInt32(&err); + if (err) { + stack.push(Value::makeError()); + return; + } + if (from < 0) { + from = 0; + } + } + int to = -1; + if (numArgs > 2) { + auto toValue = stack.pop().getValue(); + if (toValue.isError()) { + stack.push(toValue); + return; + } + int err; + to = toValue.toInt32(&err); + if (err) { + stack.push(Value::makeError()); + return; + } + if (to < 0) { + to = 0; + } + } + if (!arrayValue.isArray()) { + stack.push(Value::makeError()); + return; + } + auto array = arrayValue.getArray(); + if (to == -1) { + to = array->arraySize; + } + if (from > to) { + stack.push(Value::makeError()); + return; + } + auto size = to - from; + auto resultArrayValue = Value::makeArrayRef(size, array->arrayType, 0xe2d78c65); + auto resultArray = resultArrayValue.getArray(); + for (int elementIndex = from; elementIndex < to && elementIndex < (int)array->arraySize; elementIndex++) { + resultArray->values[elementIndex - from] = array->values[elementIndex]; + } + stack.push(resultArrayValue); +} +static void do_OPERATION_TYPE_ARRAY_ALLOCATE(EvalStack &stack) { + auto sizeValue = stack.pop(); + if (sizeValue.isError()) { + stack.push(sizeValue); + return; + } + int err; + auto size = sizeValue.toInt32(&err); + if (err) { + stack.push(Value::makeError()); + return; + } + auto resultArrayValue = Value::makeArrayRef(size, defs_v3::ARRAY_TYPE_ANY, 0xe2d78c65); + stack.push(resultArrayValue); +} +static void do_OPERATION_TYPE_ARRAY_APPEND(EvalStack &stack) { + auto arrayValue = stack.pop().getValue(); + if (arrayValue.isError()) { + stack.push(arrayValue); + return; + } + auto value = stack.pop().getValue(); + if (value.isError()) { + stack.push(value); + return; + } + if (!arrayValue.isArray()) { + stack.push(Value::makeError()); + return; + } + auto array = arrayValue.getArray(); + auto resultArrayValue = Value::makeArrayRef(array->arraySize + 1, array->arrayType, 0x664c3199); + auto resultArray = resultArrayValue.getArray(); + for (uint32_t elementIndex = 0; elementIndex < array->arraySize; elementIndex++) { + resultArray->values[elementIndex] = array->values[elementIndex]; + } + resultArray->values[array->arraySize] = value; + stack.push(resultArrayValue); +} +static void do_OPERATION_TYPE_ARRAY_INSERT(EvalStack &stack) { + auto arrayValue = stack.pop().getValue(); + if (arrayValue.isError()) { + stack.push(arrayValue); + return; + } + auto positionValue = stack.pop().getValue(); + if (positionValue.isError()) { + stack.push(positionValue); + return; + } + auto value = stack.pop().getValue(); + if (value.isError()) { + stack.push(value); + return; + } + int err; + auto position = positionValue.toInt32(&err); + if (err != 0) { + stack.push(Value::makeError()); + return; + } + if (!arrayValue.isArray()) { + stack.push(Value::makeError()); + return; + } + auto array = arrayValue.getArray(); + auto resultArrayValue = Value::makeArrayRef(array->arraySize + 1, array->arrayType, 0xc4fa9cd9); + auto resultArray = resultArrayValue.getArray(); + if (position < 0) { + position = 0; + } else if ((uint32_t)position > array->arraySize) { + position = array->arraySize; + } + for (uint32_t elementIndex = 0; (int)elementIndex < position; elementIndex++) { + resultArray->values[elementIndex] = array->values[elementIndex]; + } + resultArray->values[position] = value; + for (uint32_t elementIndex = position; elementIndex < array->arraySize; elementIndex++) { + resultArray->values[elementIndex + 1] = array->values[elementIndex]; + } + stack.push(resultArrayValue); +} +static void do_OPERATION_TYPE_ARRAY_REMOVE(EvalStack &stack) { + auto arrayValue = stack.pop().getValue(); + if (arrayValue.isError()) { + stack.push(arrayValue); + return; + } + auto positionValue = stack.pop().getValue(); + if (positionValue.isError()) { + stack.push(positionValue); + return; + } + int err; + auto position = positionValue.toInt32(&err); + if (err != 0) { + stack.push(Value::makeError()); + return; + } + if (!arrayValue.isArray()) { + stack.push(Value::makeError()); + return; + } + auto array = arrayValue.getArray(); + if (position >= 0 && position < (int32_t)array->arraySize) { + auto resultArrayValue = Value::makeArrayRef(array->arraySize - 1, array->arrayType, 0x40e9bb4b); + auto resultArray = resultArrayValue.getArray(); + for (uint32_t elementIndex = 0; (int)elementIndex < position; elementIndex++) { + resultArray->values[elementIndex] = array->values[elementIndex]; + } + for (uint32_t elementIndex = position + 1; elementIndex < array->arraySize; elementIndex++) { + resultArray->values[elementIndex - 1] = array->values[elementIndex]; + } + stack.push(resultArrayValue); + } else { + stack.push(Value::makeError()); + } +} +static void do_OPERATION_TYPE_ARRAY_CLONE(EvalStack &stack) { + auto arrayValue = stack.pop().getValue(); + if (arrayValue.isError()) { + stack.push(arrayValue); + return; + } + auto resultArray = arrayValue.clone(); + stack.push(resultArray); +} +static void do_OPERATION_TYPE_LVGL_METER_TICK_INDEX(EvalStack &stack) { + stack.push(g_eezFlowLvlgMeterTickIndex); +} +static void do_OPERATION_TYPE_CRYPTO_SHA256(EvalStack &stack) { + stack.push(Value::makeError()); +} +static void do_OPERATION_TYPE_BLOB_ALLOCATE(EvalStack &stack) { + auto sizeValue = stack.pop(); + if (sizeValue.isError()) { + stack.push(sizeValue); + return; + } + int err; + auto size = sizeValue.toInt32(&err); + if (err) { + stack.push(Value::makeError()); + return; + } + auto result = Value::makeBlobRef(nullptr, size, 0xd3de43f1); + stack.push(result); +} +static void do_OPERATION_TYPE_BLOB_TO_STRING(EvalStack &stack) { + stack.push(Value::makeError()); +} +static void do_OPERATION_TYPE_JSON_GET(EvalStack &stack) { + stack.push(Value::makeError()); +} +static void do_OPERATION_TYPE_JSON_CLONE(EvalStack &stack) { + stack.push(Value::makeError()); +} +static void do_OPERATION_TYPE_EVENT_GET_CODE(EvalStack &stack) { + auto eventValue = stack.pop().getValue(); + if (eventValue.type != VALUE_TYPE_EVENT) { + stack.push(Value::makeError()); + return; + } + auto event = eventValue.getLVGLEventRef(); + stack.push(Value(event->code, VALUE_TYPE_UINT32)); +} +static void do_OPERATION_TYPE_EVENT_GET_CURRENT_TARGET(EvalStack &stack) { + auto eventValue = stack.pop().getValue(); + if (eventValue.type != VALUE_TYPE_EVENT) { + stack.push(Value::makeError()); + return; + } + auto event = eventValue.getLVGLEventRef(); + stack.push(Value(event->currentTarget, VALUE_TYPE_WIDGET)); +} +static void do_OPERATION_TYPE_EVENT_GET_TARGET(EvalStack &stack) { + auto eventValue = stack.pop().getValue(); + if (eventValue.type != VALUE_TYPE_EVENT) { + stack.push(Value::makeError()); + return; + } + auto event = eventValue.getLVGLEventRef(); + stack.push(Value(event->target, VALUE_TYPE_WIDGET)); +} +static void do_OPERATION_TYPE_EVENT_GET_USER_DATA(EvalStack &stack) { + auto eventValue = stack.pop().getValue(); + if (eventValue.type != VALUE_TYPE_EVENT) { + stack.push(Value::makeError()); + return; + } + auto event = eventValue.getLVGLEventRef(); + stack.push(Value((int)event->userData, VALUE_TYPE_INT32)); +} +static void do_OPERATION_TYPE_EVENT_GET_KEY(EvalStack &stack) { + auto eventValue = stack.pop().getValue(); + if (eventValue.type != VALUE_TYPE_EVENT) { + stack.push(Value::makeError()); + return; + } + auto event = eventValue.getLVGLEventRef(); + stack.push(Value(event->key, VALUE_TYPE_UINT32)); +} +static void do_OPERATION_TYPE_EVENT_GET_GESTURE_DIR(EvalStack &stack) { + auto eventValue = stack.pop().getValue(); + if (eventValue.type != VALUE_TYPE_EVENT) { + stack.push(Value::makeError()); + return; + } + auto event = eventValue.getLVGLEventRef(); + stack.push(Value((int)event->gestureDir, VALUE_TYPE_INT32)); +} +static void do_OPERATION_TYPE_EVENT_GET_ROTARY_DIFF(EvalStack &stack) { + auto eventValue = stack.pop().getValue(); + if (eventValue.type != VALUE_TYPE_EVENT) { + stack.push(Value::makeError()); + return; + } + auto event = eventValue.getLVGLEventRef(); + stack.push(Value((int)event->rotaryDiff, VALUE_TYPE_INT32)); +} +EvalOperation g_evalOperations[] = { + do_OPERATION_TYPE_ADD, + do_OPERATION_TYPE_SUB, + do_OPERATION_TYPE_MUL, + do_OPERATION_TYPE_DIV, + do_OPERATION_TYPE_MOD, + do_OPERATION_TYPE_LEFT_SHIFT, + do_OPERATION_TYPE_RIGHT_SHIFT, + do_OPERATION_TYPE_BINARY_AND, + do_OPERATION_TYPE_BINARY_OR, + do_OPERATION_TYPE_BINARY_XOR, + do_OPERATION_TYPE_EQUAL, + do_OPERATION_TYPE_NOT_EQUAL, + do_OPERATION_TYPE_LESS, + do_OPERATION_TYPE_GREATER, + do_OPERATION_TYPE_LESS_OR_EQUAL, + do_OPERATION_TYPE_GREATER_OR_EQUAL, + do_OPERATION_TYPE_LOGICAL_AND, + do_OPERATION_TYPE_LOGICAL_OR, + do_OPERATION_TYPE_UNARY_PLUS, + do_OPERATION_TYPE_UNARY_MINUS, + do_OPERATION_TYPE_BINARY_ONE_COMPLEMENT, + do_OPERATION_TYPE_NOT, + do_OPERATION_TYPE_CONDITIONAL, + do_OPERATION_TYPE_SYSTEM_GET_TICK, + do_OPERATION_TYPE_FLOW_INDEX, + do_OPERATION_TYPE_FLOW_IS_PAGE_ACTIVE, + do_OPERATION_TYPE_FLOW_PAGE_TIMELINE_POSITION, + do_OPERATION_TYPE_FLOW_MAKE_ARRAY_VALUE, + do_OPERATION_TYPE_FLOW_MAKE_ARRAY_VALUE, + do_OPERATION_TYPE_FLOW_LANGUAGES, + do_OPERATION_TYPE_FLOW_TRANSLATE, + do_OPERATION_TYPE_FLOW_PARSE_INTEGER, + do_OPERATION_TYPE_FLOW_PARSE_FLOAT, + do_OPERATION_TYPE_FLOW_PARSE_DOUBLE, + do_OPERATION_TYPE_DATE_NOW, + do_OPERATION_TYPE_DATE_TO_STRING, + do_OPERATION_TYPE_DATE_FROM_STRING, + do_OPERATION_TYPE_MATH_SIN, + do_OPERATION_TYPE_MATH_COS, + do_OPERATION_TYPE_MATH_LOG, + do_OPERATION_TYPE_MATH_LOG10, + do_OPERATION_TYPE_MATH_ABS, + do_OPERATION_TYPE_MATH_FLOOR, + do_OPERATION_TYPE_MATH_CEIL, + do_OPERATION_TYPE_MATH_ROUND, + do_OPERATION_TYPE_MATH_MIN, + do_OPERATION_TYPE_MATH_MAX, + do_OPERATION_TYPE_STRING_LENGTH, + do_OPERATION_TYPE_STRING_SUBSTRING, + do_OPERATION_TYPE_STRING_FIND, + do_OPERATION_TYPE_STRING_PAD_START, + do_OPERATION_TYPE_STRING_SPLIT, + do_OPERATION_TYPE_ARRAY_LENGTH, + do_OPERATION_TYPE_ARRAY_SLICE, + do_OPERATION_TYPE_ARRAY_ALLOCATE, + do_OPERATION_TYPE_ARRAY_APPEND, + do_OPERATION_TYPE_ARRAY_INSERT, + do_OPERATION_TYPE_ARRAY_REMOVE, + do_OPERATION_TYPE_ARRAY_CLONE, + do_OPERATION_TYPE_DATE_TO_LOCALE_STRING, + do_OPERATION_TYPE_DATE_GET_YEAR, + do_OPERATION_TYPE_DATE_GET_MONTH, + do_OPERATION_TYPE_DATE_GET_DAY, + do_OPERATION_TYPE_DATE_GET_HOURS, + do_OPERATION_TYPE_DATE_GET_MINUTES, + do_OPERATION_TYPE_DATE_GET_SECONDS, + do_OPERATION_TYPE_DATE_GET_MILLISECONDS, + do_OPERATION_TYPE_DATE_MAKE, + do_OPERATION_TYPE_MATH_POW, + do_OPERATION_TYPE_LVGL_METER_TICK_INDEX, + do_OPERATION_TYPE_FLOW_GET_BITMAP_INDEX, + do_OPERATION_TYPE_FLOW_TO_INTEGER, + do_OPERATION_TYPE_STRING_FROM_CODE_POINT, + do_OPERATION_TYPE_STRING_CODE_POINT_AT, + do_OPERATION_TYPE_CRYPTO_SHA256, + do_OPERATION_TYPE_BLOB_ALLOCATE, + do_OPERATION_TYPE_JSON_GET, + do_OPERATION_TYPE_JSON_CLONE, + do_OPERATION_TYPE_FLOW_GET_BITMAP_AS_DATA_URL, + do_OPERATION_TYPE_STRING_FORMAT, + do_OPERATION_TYPE_STRING_FORMAT_PREFIX, + do_OPERATION_TYPE_EVENT_GET_CODE, + do_OPERATION_TYPE_EVENT_GET_CURRENT_TARGET, + do_OPERATION_TYPE_EVENT_GET_TARGET, + do_OPERATION_TYPE_EVENT_GET_USER_DATA, + do_OPERATION_TYPE_EVENT_GET_KEY, + do_OPERATION_TYPE_EVENT_GET_GESTURE_DIR, + do_OPERATION_TYPE_EVENT_GET_ROTARY_DIFF, + do_OPERATION_TYPE_BLOB_TO_STRING, + do_OPERATION_TYPE_FLOW_THEMES, + do_OPERATION_TYPE_FLOW_GET_THEME_COLOR, +}; +} +} +// ----------------------------------------------------------------------------- +// flow/private.cpp +// ----------------------------------------------------------------------------- +#include +#include +namespace eez { +namespace flow { +GlobalVariables *g_globalVariables = nullptr; +static const unsigned NO_COMPONENT_INDEX = 0xFFFFFFFF; +static bool g_enableThrowError = true; +inline bool isInputEmpty(const Value& inputValue) { + return inputValue.type == VALUE_TYPE_UNDEFINED && inputValue.int32Value > 0; +} +inline Value getEmptyInputValue() { + Value emptyInputValue; + emptyInputValue.int32Value = 1; + return emptyInputValue; +} +void initGlobalVariables(Assets *assets) { + if (assets->external || g_mainAssetsAreMutable) { + return; + } + auto flowDefinition = static_cast(assets->flowDefinition); + auto numVars = flowDefinition->globalVariables.count; + g_globalVariables = (GlobalVariables *) alloc( + sizeof(GlobalVariables) + + (numVars > 0 ? numVars - 1 : 0) * sizeof(Value), + 0xcc34ca8e + ); + for (uint32_t i = 0; i < numVars; i++) { + new (g_globalVariables->values + i) Value(); + g_globalVariables->values[i] = flowDefinition->globalVariables[i]->clone(); + } +} +static bool isComponentReadyToRun(FlowState *flowState, unsigned componentIndex) { + auto component = flowState->flow->components[componentIndex]; + if (component->type == defs_v3::COMPONENT_TYPE_CATCH_ERROR_ACTION) { + return false; + } + if (component->type == defs_v3::COMPONENT_TYPE_ON_EVENT_ACTION) { + return false; + } + if (component->type == defs_v3::COMPONENT_TYPE_LABEL_IN_ACTION) { + return false; + } + if (component->type > defs_v3::FIRST_LVGL_WIDGET_COMPONENT_TYPE) { + return false; + } + if ((component->type < defs_v3::COMPONENT_TYPE_START_ACTION && component->type != defs_v3::COMPONENT_TYPE_USER_WIDGET_WIDGET) || component->type >= defs_v3::FIRST_DASHBOARD_WIDGET_COMPONENT_TYPE) { + return hasExecFunc(flowState, componentIndex); + } + if (component->type == defs_v3::COMPONENT_TYPE_START_ACTION) { + if (flowState->parentComponent && flowState->parentComponentIndex != -1) { + auto flowInputIndex = flowState->parentComponent->inputs[0]; + auto value = flowState->parentFlowState->values[flowInputIndex]; + return value.getType() != VALUE_TYPE_UNDEFINED; + } else { + return true; + } + } + int numSeqInputs = 0; + int numDefinedSeqInputs = 0; + for (unsigned inputIndex = 0; inputIndex < component->inputs.count; inputIndex++) { + auto inputValueIndex = component->inputs[inputIndex]; + auto input = flowState->flow->componentInputs[inputValueIndex]; + if (input & COMPONENT_INPUT_FLAG_IS_SEQ_INPUT) { + numSeqInputs++; + auto &value = flowState->values[inputValueIndex]; + if (!isInputEmpty(value)) { + numDefinedSeqInputs++; + } + } else { + if (!(input & COMPONENT_INPUT_FLAG_IS_OPTIONAL)) { + auto &value = flowState->values[inputValueIndex]; + if (isInputEmpty(value)) { + return false; + } + } + } + } + if (numSeqInputs && !numDefinedSeqInputs) { + return false; + } + return true; +} +static bool pingComponent(FlowState *flowState, unsigned componentIndex, int sourceComponentIndex = -1, int sourceOutputIndex = -1, int targetInputIndex = -1) { + if (isComponentReadyToRun(flowState, componentIndex)) { + return addToQueue(flowState, componentIndex, sourceComponentIndex, sourceOutputIndex, targetInputIndex, false); + } + return false; +} +static FlowState *initFlowState(Assets *assets, int flowIndex, FlowState *parentFlowState, int parentComponentIndex, const Value& inputValue) { + auto flowDefinition = static_cast(assets->flowDefinition); + auto flow = flowDefinition->flows[flowIndex]; + auto nValues = flow->componentInputs.count + flow->localVariables.count; + FlowState *flowState = new ( + alloc( + sizeof(FlowState) + + nValues * sizeof(Value) + + flow->components.count * sizeof(ComponenentExecutionState *) + + flow->components.count * sizeof(bool), + 0x4c3b6ef5 + ) + ) FlowState; + flowState->assets = assets; + flowState->flowStateIndex = (int)((uint8_t *)flowState - ALLOC_BUFFER); + flowState->flow = flowDefinition->flows[flowIndex]; + flowState->flowIndex = flowIndex; + flowState->error = false; + flowState->deleteOnNextTick = false; + flowState->refCounter = 0; + flowState->parentFlowState = parentFlowState; + flowState->executingComponentIndex = NO_COMPONENT_INDEX; + flowState->timelinePosition = 0; + flowState->lvglWidgetStartIndex = 0; + if (parentFlowState) { + if (parentFlowState->lastChild) { + parentFlowState->lastChild->nextSibling = flowState; + flowState->previousSibling = parentFlowState->lastChild; + parentFlowState->lastChild = flowState; + } else { + flowState->previousSibling = nullptr; + parentFlowState->firstChild = flowState; + parentFlowState->lastChild = flowState; + } + flowState->parentComponentIndex = parentComponentIndex; + flowState->parentComponent = parentComponentIndex == -1 ? nullptr : parentFlowState->flow->components[parentComponentIndex]; + } else { + if (g_lastFlowState) { + g_lastFlowState->nextSibling = flowState; + flowState->previousSibling = g_lastFlowState; + g_lastFlowState = flowState; + } else { + flowState->previousSibling = nullptr; + g_firstFlowState = flowState; + g_lastFlowState = flowState; + } + flowState->parentComponentIndex = -1; + flowState->parentComponent = nullptr; + } + flowState->inputValue = inputValue; + flowState->firstChild = nullptr; + flowState->lastChild = nullptr; + flowState->nextSibling = nullptr; + flowState->values = (Value *)(flowState + 1); + flowState->componenentExecutionStates = (ComponenentExecutionState **)(flowState->values + nValues); + flowState->componenentAsyncStates = (bool *)(flowState->componenentExecutionStates + flow->components.count); + for (unsigned i = 0; i < nValues; i++) { + new (flowState->values + i) Value(); + } + Value emptyInputValue = getEmptyInputValue(); + for (unsigned i = 0; i < flow->componentInputs.count; i++) { + flowState->values[i] = emptyInputValue; + } + for (unsigned i = 0; i < flow->localVariables.count; i++) { + auto value = flow->localVariables[i]; + flowState->values[flow->componentInputs.count + i] = *value; + } + for (unsigned i = 0; i < flow->components.count; i++) { + flowState->componenentExecutionStates[i] = nullptr; + flowState->componenentAsyncStates[i] = false; + } + onFlowStateCreated(flowState); + for (unsigned componentIndex = 0; componentIndex < flow->components.count; componentIndex++) { + pingComponent(flowState, componentIndex); + } + return flowState; +} +FlowState *initActionFlowState(int flowIndex, FlowState *parentFlowState, int parentComponentIndex, const Value &inputValue) { + auto flowState = initFlowState(parentFlowState->assets, flowIndex, parentFlowState, parentComponentIndex, inputValue); + if (flowState) { + flowState->isAction = true; + } + return flowState; +} +FlowState *initPageFlowState(Assets *assets, int flowIndex, FlowState *parentFlowState, int parentComponentIndex) { + auto flowState = initFlowState(assets, flowIndex, parentFlowState, parentComponentIndex, Value()); + if (flowState) { + flowState->isAction = false; + } + return flowState; +} +void incRefCounterForFlowState(FlowState *flowState) { + if (!flowState) { + return; + } + flowState->refCounter++; + for (auto parent = flowState->parentFlowState; parent; parent = parent->parentFlowState) { + parent->refCounter++; + } +} +void decRefCounterForFlowState(FlowState *flowState) { + if (!flowState) { + return; + } + flowState->refCounter--; + for (auto parent = flowState->parentFlowState; parent; parent = parent->parentFlowState) { + parent->refCounter--; + } +} +bool canFreeFlowState(FlowState *flowState) { + if (!flowState->isAction) { + return false; + } + if (flowState->refCounter > 0) { + return false; + } + return true; +} +void freeFlowState(FlowState *flowState) { + auto parentFlowState = flowState->parentFlowState; + if (parentFlowState) { + if (flowState->parentComponentIndex != -1) { + auto componentExecutionState = parentFlowState->componenentExecutionStates[flowState->parentComponentIndex]; + if (componentExecutionState) { + deallocateComponentExecutionState(parentFlowState, flowState->parentComponentIndex); + return; + } + } + if (parentFlowState->firstChild == flowState) { + parentFlowState->firstChild = flowState->nextSibling; + } + if (parentFlowState->lastChild == flowState) { + parentFlowState->lastChild = flowState->previousSibling; + } + } else { + if (g_firstFlowState == flowState) { + g_firstFlowState = flowState->nextSibling; + } + if (g_lastFlowState == flowState) { + g_lastFlowState = flowState->previousSibling; + } + } + if (flowState->previousSibling) { + flowState->previousSibling->nextSibling = flowState->nextSibling; + } + if (flowState->nextSibling) { + flowState->nextSibling->previousSibling = flowState->previousSibling; + } + auto flow = flowState->flow; + auto valuesCount = flow->componentInputs.count + flow->localVariables.count; + for (unsigned int i = 0; i < valuesCount; i++) { + (flowState->values + i)->~Value(); + } + for (unsigned i = 0; i < flow->components.count; i++) { + deallocateComponentExecutionState(flowState, i); + } + removeTasksFromQueueForFlowState(flowState); + removeWatchesForFlowState(flowState); + freeAllChildrenFlowStates(flowState->firstChild); + onFlowStateDestroyed(flowState); + flowState->~FlowState(); + free(flowState); +} +void freeAllChildrenFlowStates(FlowState *firstChildFlowState) { + auto flowState = firstChildFlowState; + while (flowState != nullptr) { + auto nextFlowState = flowState->nextSibling; + freeAllChildrenFlowStates(flowState->firstChild); + freeFlowState(flowState); + flowState = nextFlowState; + } +} +void deallocateComponentExecutionState(FlowState *flowState, unsigned componentIndex) { + auto executionState = flowState->componenentExecutionStates[componentIndex]; + if (executionState) { + auto component = flowState->flow->components[componentIndex]; + if (TRACK_REF_COUNTER_FOR_COMPONENT_STATE(component)) { + decRefCounterForFlowState(flowState); + } + flowState->componenentExecutionStates[componentIndex] = nullptr; + onComponentExecutionStateChanged(flowState, componentIndex); + ObjectAllocator::deallocate(executionState); + } +} +void resetSequenceInputs(FlowState *flowState) { + if (flowState->executingComponentIndex != NO_COMPONENT_INDEX) { + auto component = flowState->flow->components[flowState->executingComponentIndex]; + flowState->executingComponentIndex = NO_COMPONENT_INDEX; + if (component->type != defs_v3::COMPONENT_TYPE_OUTPUT_ACTION) { + for (uint32_t i = 0; i < component->inputs.count; i++) { + auto inputIndex = component->inputs[i]; + if (flowState->flow->componentInputs[inputIndex] & COMPONENT_INPUT_FLAG_IS_SEQ_INPUT) { + auto pValue = &flowState->values[inputIndex]; + if (!isInputEmpty(*pValue)) { + *pValue = getEmptyInputValue(); + onValueChanged(pValue); + } + } + } + } + } +} +void propagateValue(FlowState *flowState, unsigned componentIndex, unsigned outputIndex, const Value &value) { + if ((int)componentIndex == -1) { + auto flowIndex = outputIndex; + executeCallAction(flowState, -1, flowIndex, value); + return; + } + resetSequenceInputs(flowState); + auto component = flowState->flow->components[componentIndex]; + auto componentOutput = component->outputs[outputIndex]; + auto value2 = value.getValue(); + for (unsigned connectionIndex = 0; connectionIndex < componentOutput->connections.count; connectionIndex++) { + auto connection = componentOutput->connections[connectionIndex]; + auto pValue = &flowState->values[connection->targetInputIndex]; + if (*pValue != value2) { + *pValue = value2; + onValueChanged(pValue); + } + pingComponent(flowState, connection->targetComponentIndex, componentIndex, outputIndex, connection->targetInputIndex); + } +} +void propagateValue(FlowState *flowState, unsigned componentIndex, unsigned outputIndex) { + auto &nullValue = *flowState->assets->flowDefinition->constants[NULL_VALUE_INDEX]; + propagateValue(flowState, componentIndex, outputIndex, nullValue); +} +void propagateValueThroughSeqout(FlowState *flowState, unsigned componentIndex) { + auto component = flowState->flow->components[componentIndex]; + for (uint32_t i = 0; i < component->outputs.count; i++) { + if (component->outputs[i]->isSeqOut) { + propagateValue(flowState, componentIndex, i); + return; + } + } +} +void assignValue(FlowState *flowState, int componentIndex, Value &dstValue, const Value &srcValue) { + if (dstValue.getType() == VALUE_TYPE_FLOW_OUTPUT) { + propagateValue(flowState, componentIndex, dstValue.getUInt16(), srcValue); + } else if (dstValue.getType() == VALUE_TYPE_NATIVE_VARIABLE) { + setVar(dstValue.getInt(), srcValue); + } else { + Value *pDstValue; + uint32_t dstValueType = VALUE_TYPE_UNDEFINED; + if (dstValue.getType() == VALUE_TYPE_ARRAY_ELEMENT_VALUE) { + auto arrayElementValue = (ArrayElementValue *)dstValue.refValue; + if (arrayElementValue->arrayValue.isBlob()) { + auto blobRef = arrayElementValue->arrayValue.getBlob(); + if (arrayElementValue->elementIndex < 0 || arrayElementValue->elementIndex >= (int)blobRef->len) { + throwError(flowState, componentIndex, FlowError::Plain("Can not assign, blob element index out of bounds")); + return; + } + int err; + int32_t elementValue = srcValue.toInt32(&err); + if (err != 0) { + throwError(flowState, componentIndex, FlowError::Plain("Can not non-integer to blob")); + } else if (elementValue < 0 || elementValue > 255) { + char errorMessage[100]; + snprintf(errorMessage, sizeof(errorMessage), "Can not assign %d to blob", (int)elementValue); + throwError(flowState, componentIndex, FlowError::Plain(errorMessage)); + } else { + blobRef->blob[arrayElementValue->elementIndex] = elementValue; + } + return; + } else { + auto array = arrayElementValue->arrayValue.getArray(); + if (arrayElementValue->elementIndex < 0 || arrayElementValue->elementIndex >= (int)array->arraySize) { + throwError(flowState, componentIndex, FlowError::Plain("Can not assign, array element index out of bounds")); + return; + } + pDstValue = &array->values[arrayElementValue->elementIndex]; + } + } + else { + pDstValue = dstValue.pValueValue; + dstValueType = dstValue.dstValueType; + } + while (true) { + if (pDstValue->type == VALUE_TYPE_ARRAY_ELEMENT_VALUE) { + assignValue(flowState, componentIndex, *pDstValue, srcValue); + return; + } + if (pDstValue->type == VALUE_TYPE_PROPERTY_REF) { + auto propertyRef = pDstValue->getPropertyRef(); + Value dstValue; + if (evalAssignableProperty(propertyRef->flowState, propertyRef->componentIndex, propertyRef->propertyIndex, dstValue, FlowError::Plain("Failed to evaluate an assignable user property in UserWidget"), nullptr, nullptr)) { + if (dstValue.getType() == VALUE_TYPE_FLOW_OUTPUT) { + propagateValue(propertyRef->flowState, propertyRef->componentIndex, dstValue.getUInt16(), srcValue); + } else { + assignValue(flowState, componentIndex, dstValue, srcValue); + onValueChanged(pDstValue); + } + } + return; + } + if (pDstValue->type == VALUE_TYPE_VALUE_PTR) { + onValueChanged(pDstValue); + pDstValue = pDstValue->pValueValue; + } else { + break; + } + } + if (assignValue(*pDstValue, srcValue, dstValueType)) { + onValueChanged(pDstValue); + } else { + char errorMessage[100]; + snprintf(errorMessage, sizeof(errorMessage), "Can not assign %s to %s\n", + g_valueTypeNames[pDstValue->type](srcValue), g_valueTypeNames[srcValue.type](*pDstValue) + ); + throwError(flowState, componentIndex, FlowError::Plain(errorMessage)); + } + } +} +void clearInputValue(FlowState *flowState, int inputIndex) { + flowState->values[inputIndex] = Value(); + onValueChanged(flowState->values + inputIndex); +} +void startAsyncExecution(FlowState *flowState, int componentIndex) { + if (!flowState->componenentAsyncStates[componentIndex]) { + flowState->componenentAsyncStates[componentIndex] = true; + onComponentAsyncStateChanged(flowState, componentIndex); + incRefCounterForFlowState(flowState); + } +} +void endAsyncExecution(FlowState *flowState, int componentIndex) { + if (!g_firstFlowState) { + return; + } + if (flowState->componenentAsyncStates[componentIndex]) { + flowState->componenentAsyncStates[componentIndex] = false; + onComponentAsyncStateChanged(flowState, componentIndex); + decRefCounterForFlowState(flowState); + do { + if (!canFreeFlowState(flowState)) { + break; + } + auto temp = flowState->parentFlowState; + freeFlowState(flowState); + flowState = temp; + } while (flowState); + } +} +void onEvent(FlowState *flowState, FlowEvent flowEvent, Value eventValue) { + for (unsigned componentIndex = 0; componentIndex < flowState->flow->components.count; componentIndex++) { + auto component = flowState->flow->components[componentIndex]; + if (component->type == defs_v3::COMPONENT_TYPE_ON_EVENT_ACTION) { + auto onEventComponent = (OnEventComponent *)component; + if (onEventComponent->event == flowEvent) { + flowState->eventValue = eventValue; + if (!isInQueue(flowState, componentIndex)) { + if (!addToQueue(flowState, componentIndex, -1, -1, -1, false)) { + return; + } + } + } + } + } + if (flowEvent == FLOW_EVENT_KEYDOWN) { + for (auto childFlowState = flowState->firstChild; childFlowState != nullptr; childFlowState = childFlowState->nextSibling) { + onEvent(childFlowState, flowEvent, eventValue); + } + } +} +static bool findCatchErrorComponent(FlowState *flowState, FlowState *&catchErrorFlowState, int &catchErrorComponentIndex) { + if (!flowState) { + return false; + } + for (unsigned componentIndex = 0; componentIndex < flowState->flow->components.count; componentIndex++) { + auto component = flowState->flow->components[componentIndex]; + if (component->type == defs_v3::COMPONENT_TYPE_CATCH_ERROR_ACTION) { + catchErrorFlowState = flowState; + catchErrorComponentIndex = componentIndex; + return true; + } + } + if (flowState->parentFlowState && flowState->parentComponent && flowState->parentComponent->errorCatchOutput != -1) { + catchErrorFlowState = flowState->parentFlowState; + catchErrorComponentIndex = flowState->parentComponentIndex; + return true; + } + return findCatchErrorComponent(flowState->parentFlowState, catchErrorFlowState, catchErrorComponentIndex); +} +void throwError(FlowState *flowState, int componentIndex, const char *errorMessage) { + auto component = flowState->flow->components[componentIndex]; + if (!g_enableThrowError) { + return; + } + LV_LOG_ERROR("EEZ-FLOW error: %s", errorMessage); + if (component->errorCatchOutput != -1) { + propagateValue( + flowState, + componentIndex, + component->errorCatchOutput, + Value::makeStringRef(errorMessage, strlen(errorMessage), 0xef6f8414) + ); + } else { + FlowState *catchErrorFlowState; + int catchErrorComponentIndex; + if ( + findCatchErrorComponent( + component->type == defs_v3::COMPONENT_TYPE_ERROR_ACTION ? flowState->parentFlowState : flowState, + catchErrorFlowState, + catchErrorComponentIndex + ) + ) { + for (FlowState *fs = flowState; fs != catchErrorFlowState; fs = fs->parentFlowState) { + if (fs->isAction) { + fs->error = true; + } + } + auto component = catchErrorFlowState->flow->components[catchErrorComponentIndex]; + if (component->type == defs_v3::COMPONENT_TYPE_CATCH_ERROR_ACTION) { + auto catchErrorComponentExecutionState = allocateComponentExecutionState(catchErrorFlowState, catchErrorComponentIndex); + catchErrorComponentExecutionState->message = Value::makeStringRef(errorMessage, strlen(errorMessage), 0x9473eef2); + if (!addToQueue(catchErrorFlowState, catchErrorComponentIndex, -1, -1, -1, false)) { + onFlowError(flowState, componentIndex, errorMessage); + stopScriptHook(); + } + } else { + propagateValue( + catchErrorFlowState, + catchErrorComponentIndex, + component->errorCatchOutput, + Value::makeStringRef(errorMessage, strlen(errorMessage), 0x9473eef3) + ); + } + } else { + onFlowError(flowState, componentIndex, errorMessage); + stopScriptHook(); + } + } +} +const char *FlowError::getMessage(char *messageStr, size_t messageStrLength, int flowIndex, int componentIndex) const { + #define GET_MESSAGE(FMT, ...) \ + if (file) snprintf(messageStr, messageStrLength, FMT " | %d.%d | %s:%d", __VA_ARGS__, flowIndex, componentIndex, file, line); \ + else snprintf(messageStr, messageStrLength, FMT " | %d.%d", __VA_ARGS__, flowIndex, componentIndex); + if (type == FLOW_ERROR_PLAIN) { + if (description) { + GET_MESSAGE("%s: %s", messagePart1, description); + } else { + GET_MESSAGE("%s", messagePart1); + } + } else if (type == FLOW_ERROR_PROPERTY) { + if (!description) { + GET_MESSAGE("Failed to evaluate '%s' in '%s'", messagePart2, messagePart1); + } else { + GET_MESSAGE("Failed to evaluate '%s' in '%s': %s", messagePart2, messagePart1, description); + } + } else if (type == FLOW_ERROR_PROPERTY_INVALID) { + if (!description) { + GET_MESSAGE("Invalid '%s' value in '%s'", messagePart2, messagePart1); + } else { + GET_MESSAGE("Invalid '%s' value in '%s': %s", messagePart2, messagePart1, description); + } + } else if (type == FLOW_ERROR_PROPERTY_CONVERT) { + if (!description) { + GET_MESSAGE("Failed to convert '%s' to '%s' in '%s'", messagePart2, messagePart3, messagePart1); + } else { + GET_MESSAGE("Failed to convert '%s' to '%s' in '%s': %s", messagePart2, messagePart3, messagePart1, description); + } + } else if (type == FLOW_ERROR_PROPERTY_IN_ARRAY) { + if (!description) { + GET_MESSAGE("Failed to evaluate '%s' no. %d in '%s'", messagePart2, messagePartInt + 1, messagePart1); + } else { + GET_MESSAGE("Failed to evaluate '%s' no. %d in '%s': %s", messagePart2, messagePartInt + 1, messagePart1, description); + } + } else if (type == FLOW_ERROR_PROPERTY_IN_ARRAY_CONVERT) { + if (!description) { + GET_MESSAGE("Failed to convert '%s' no. %d to '%s' in '%s'", messagePart2, messagePartInt + 1, messagePart3, messagePart1); + } else { + GET_MESSAGE("Failed to evaluate '%s' no. %d to '%s' in '%s': %s", messagePart2, messagePartInt + 1, messagePart3, messagePart1, description); + } + } else if (type == FLOW_ERROR_PROPERTY_NUM) { + if (!description) { + GET_MESSAGE("Failed to evaluate property #%d in '%s'", messagePartInt + 1, messagePart1); + } else { + GET_MESSAGE("Failed to evaluate property #%d in '%s': %s", messagePartInt + 1, messagePart1, description); + } + } else if (type == FLOW_ERROR_PROPERTY_IN_ACTION) { + if (!description) { + GET_MESSAGE("Failed to evaluate '%s' in '%s' action #%d", messagePart2, messagePart1, messagePartInt + 1); + } else { + GET_MESSAGE("Failed to evaluate '%s' in '%s' action #%d: %s", messagePart2, messagePart1, messagePartInt + 1, description); + } + } else if (type == FLOW_ERROR_PROPERTY_ASSIGN_IN_ACTION) { + if (!description) { + GET_MESSAGE("Failed to assign '%s' in '%s' action #%d", messagePart2, messagePart1, messagePartInt + 1); + } else { + GET_MESSAGE("Failed to assign '%s' in '%s' action #%d: %s", messagePart2, messagePart1, messagePartInt + 1, description); + } + } else if (type == FLOW_ERROR_PROPERTY_IN_ACTION_CONVERT) { + if (!description) { + GET_MESSAGE("Failed to convert '%s' to '%s' in '%s' action #%d", messagePart2, messagePart3, messagePart1, messagePartInt + 1); + } else { + GET_MESSAGE("Failed to convert '%s' to '%s' in '%s' action #%d: %s", messagePart2, messagePart3, messagePart1, messagePartInt + 1, description); + } + } else if (type == FLOW_ERROR_PROPERTY_NOT_FOUND_IN_ACTION) { + if (!description) { + GET_MESSAGE("%s '%s' not found in '%s' action #%d", messagePart1, messagePart2, messagePart3, messagePartInt + 1); + } else { + GET_MESSAGE("%s '%s' not found in '%s' action #%d: %s", messagePart1, messagePart2, messagePart3, messagePartInt + 1, description); + } + } else if (type == FLOW_ERROR_PROPERTY_IS_NULL_IN_ACTION) { + if (!description) { + GET_MESSAGE("%s is NULL in '%s' action #%d", messagePart1, messagePart2, messagePartInt + 1); + } else { + GET_MESSAGE("%s is NULL in '%s' action #%d: %s", messagePart1, messagePart2, messagePartInt + 1, description); + } + } else if (type == FLOW_ERROR_USER_PROPERTY) { + if (!description) { + GET_MESSAGE("Failed to evaluate property #%d in '%s'", messagePartInt + 1, messagePart1); + } else { + GET_MESSAGE("Failed to evaluate property #%d in '%s': %s", messagePartInt + 1, messagePart1, description); + } + } else if (type == FLOW_ERROR_USER_ASSIGNABLE_PROPERTY) { + if (!description) { + GET_MESSAGE("Failed to evaluate assignable property #%d in '%s'", messagePartInt + 1, messagePart1); + } else { + GET_MESSAGE("Failed to evaluate assignable property #%d in '%s': %s", messagePartInt + 1, messagePart1, description); + } + } else { + GET_MESSAGE("%s", "UNKNOWN ERROR"); + } + return messageStr; +} +void throwError(FlowState *flowState, int componentIndex, const FlowError &error) { + char errorMessageStr[512]; + const char *errorMessage = error.getMessage(errorMessageStr, sizeof(errorMessageStr), flowState->flowIndex, componentIndex); + throwError(flowState, componentIndex, errorMessage); +} +void enableThrowError(bool enable) { + g_enableThrowError = enable; +} +} +} +// ----------------------------------------------------------------------------- +// flow/queue.cpp +// ----------------------------------------------------------------------------- +namespace eez { +namespace flow { +#if !defined(EEZ_FLOW_QUEUE_SIZE) +#define EEZ_FLOW_QUEUE_SIZE 1000 +#endif +static const unsigned QUEUE_SIZE = EEZ_FLOW_QUEUE_SIZE; +static struct { + FlowState *flowState; + unsigned componentIndex; + bool continuousTask; +} g_queue[QUEUE_SIZE]; +static unsigned g_queueHead; +static unsigned g_queueTail; +static unsigned g_queueMax; +static bool g_queueIsFull = false; +unsigned g_numNonContinuousTaskInQueue; +void queueReset() { + g_queueHead = 0; + g_queueTail = 0; + g_queueMax = 0; + g_queueIsFull = false; + g_numNonContinuousTaskInQueue = 0; +} +size_t getQueueSize() { + if (g_queueHead == g_queueTail) { + if (g_queueIsFull) { + return QUEUE_SIZE; + } + return 0; + } + if (g_queueHead < g_queueTail) { + return g_queueTail - g_queueHead; + } + return QUEUE_SIZE - g_queueHead + g_queueTail; +} +size_t getMaxQueueSize() { + return g_queueMax; +} +bool addToQueue(FlowState *flowState, unsigned componentIndex, int sourceComponentIndex, int sourceOutputIndex, int targetInputIndex, bool continuousTask) { + if (g_queueIsFull) { + throwError(flowState, componentIndex, "Execution queue is full\n"); + return false; + } + g_queue[g_queueTail].flowState = flowState; + g_queue[g_queueTail].componentIndex = componentIndex; + g_queue[g_queueTail].continuousTask = continuousTask; + g_queueTail = (g_queueTail + 1) % QUEUE_SIZE; + if (g_queueHead == g_queueTail) { + g_queueIsFull = true; + } + size_t queueSize = getQueueSize(); + g_queueMax = g_queueMax < queueSize ? queueSize : g_queueMax; + if (!continuousTask) { + ++g_numNonContinuousTaskInQueue; + onAddToQueue(flowState, sourceComponentIndex, sourceOutputIndex, componentIndex, targetInputIndex); + } + incRefCounterForFlowState(flowState); + return true; +} +bool peekNextTaskFromQueue(FlowState *&flowState, unsigned &componentIndex, bool &continuousTask) { + if (g_queueHead == g_queueTail && !g_queueIsFull) { + return false; + } + flowState = g_queue[g_queueHead].flowState; + componentIndex = g_queue[g_queueHead].componentIndex; + continuousTask = g_queue[g_queueHead].continuousTask; + return true; +} +void removeNextTaskFromQueue() { + auto flowState = g_queue[g_queueHead].flowState; + decRefCounterForFlowState(flowState); + auto continuousTask = g_queue[g_queueHead].continuousTask; + g_queueHead = (g_queueHead + 1) % QUEUE_SIZE; + g_queueIsFull = false; + if (!continuousTask) { + --g_numNonContinuousTaskInQueue; + onRemoveFromQueue(); + } +} +bool isInQueue(FlowState *flowState, unsigned componentIndex) { + if (g_queueHead == g_queueTail && !g_queueIsFull) { + return false; + } + unsigned int it = g_queueHead; + while (true) { + if (g_queue[it].flowState == flowState && g_queue[it].componentIndex == componentIndex) { + return true; + } + it = (it + 1) % QUEUE_SIZE; + if (it == g_queueTail) { + break; + } + } + return false; +} +void removeTasksFromQueueForFlowState(FlowState *flowState) { + if (g_queueHead == g_queueTail && !g_queueIsFull) { + return; + } + unsigned int it = g_queueHead; + while (true) { + if (g_queue[it].flowState == flowState) { + g_queue[it].flowState = 0; + } + it = (it + 1) % QUEUE_SIZE; + if (it == g_queueTail) { + break; + } + } +} +} +} +// ----------------------------------------------------------------------------- +// flow/watch_list.cpp +// ----------------------------------------------------------------------------- +namespace eez { +namespace flow { +void executeWatchVariableComponent(FlowState *flowState, unsigned componentIndex); +struct WatchListNode { + FlowState *flowState; + unsigned componentIndex; + WatchListNode *prev; + WatchListNode *next; +}; +struct WatchList { + WatchListNode *first; + WatchListNode *last; + unsigned size; +}; +static WatchList g_watchList; +WatchListNode *watchListAdd(FlowState *flowState, unsigned componentIndex) { + auto node = (WatchListNode *)alloc(sizeof(WatchListNode), 0x00864d67); + node->prev = g_watchList.last; + if (g_watchList.last != 0) { + g_watchList.last->next = node; + } + g_watchList.last = node; + if (g_watchList.first == 0) { + g_watchList.first = node; + } + node->next = 0; + node->flowState = flowState; + node->componentIndex = componentIndex; + incRefCounterForFlowState(flowState); + (g_watchList.size)++; + return node; +} +void watchListRemove(WatchListNode *node) { + if (node->prev) { + node->prev->next = node->next; + } else { + g_watchList.first = node->next; + } + if (node->next) { + node->next->prev = node->prev; + } else { + g_watchList.last = node->prev; + } + free(node); + g_watchList.size > 0 ? (g_watchList.size)-- : 0; +} +void visitWatchList() { + for (auto node = g_watchList.first; node; ) { + auto nextNode = node->next; + if (canExecuteStep(node->flowState, node->componentIndex)) { + executeWatchVariableComponent(node->flowState, node->componentIndex); + } + decRefCounterForFlowState(node->flowState); + if (canFreeFlowState(node->flowState)) { + freeFlowState(node->flowState); + } else { + incRefCounterForFlowState(node->flowState); + } + node = nextNode; + } +} +void watchListReset() { + for (auto node = g_watchList.first; node;) { + auto nextNode = node->next; + watchListRemove(node); + node = nextNode; + } +} +void removeWatchesForFlowState(FlowState *flowState) { + for (auto node = g_watchList.first; node;) { + auto nextNode = node->next; + if (node->flowState == flowState) { + watchListRemove(node); + } + node = nextNode; + } +} +unsigned getWatchListSize() { + return g_watchList.size; +} +} +} \ No newline at end of file diff --git a/components/ui/eez-flow.h b/components/ui/eez-flow.h new file mode 100644 index 0000000..65f3cf7 --- /dev/null +++ b/components/ui/eez-flow.h @@ -0,0 +1,4388 @@ +/* Autogenerated on February 9, 2026 10:19:04 AM from eez-framework commit 123e5b8ddf542fe522cd07c6f6d09fcb044ea1db */ +/* + * eez-framework + * + * MIT License + * Copyright 2026 Envox d.o.o. + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + * THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ +#pragma once + +#define EEZ_FOR_LVGL 1 +#define EEZ_FOR_LVGL_LZ4_OPTION 0 +#define EEZ_FOR_LVGL_SHA256_OPTION 0 +#define EEZ_FLOW_QUEUE_SIZE 1000 +#define EEZ_FLOW_EVAL_STACK_SIZE 20 + +#include +#if LVGL_VERSION_MAJOR > 9 || (LVGL_VERSION_MAJOR == 9 && LVGL_VERSION_MINOR > 1) + #ifdef __has_include + #if __has_include("lvgl_private.h") + #include "lvgl_private.h" + #elif __has_include("src/lvgl_private.h") + #include "src/lvgl_private.h" + #elif __has_include("lvgl/src/lvgl_private.h") + #include "lvgl/src/lvgl_private.h" + #endif + #endif +#endif + +// ----------------------------------------------------------------------------- +// conf-internal.h +// ----------------------------------------------------------------------------- +#ifdef __cplusplus + #ifdef __has_include + #if __has_include("eez-framework-conf.h") + #include "eez-framework-conf.h" + #endif + #endif +#endif +#if ARDUINO + #define EEZ_FOR_LVGL 1 + #ifndef LV_LVGL_H_INCLUDE_SIMPLE + #define LV_LVGL_H_INCLUDE_SIMPLE + #endif + #include +#endif + #define EEZ_OPTION_GUI 0 +#ifndef EEZ_OPTION_THREADS + #define EEZ_OPTION_THREADS 1 +#endif +#ifndef EEZ_OPTION_FS + #define EEZ_OPTION_FS 1 +#endif +#ifndef OPTION_KEYBOARD + #define OPTION_KEYBOARD 0 +#endif +#ifndef OPTION_MOUSE + #define OPTION_MOUSE 0 +#endif +#ifndef OPTION_KEYPAD + #define OPTION_KEYPAD 0 +#endif +#ifndef CUSTOM_VALUE_TYPES + #define CUSTOM_VALUE_TYPES +#endif +#define EEZ_UNUSED(x) (void)(x) +#if defined(__clang__) + #define DIAG_PRAGMA(x) _Pragma(#x) + #define DIAG_PUSH DIAG_PRAGMA(clang diagnostic push) + #define DIAG_POP DIAG_PRAGMA(clang diagnostic pop) + #define DIAG_IGNORE(w) DIAG_PRAGMA(clang diagnostic ignored w) +#elif defined(__GNUC__) + #define DIAG_PRAGMA(x) _Pragma(#x) + #define DIAG_PUSH DIAG_PRAGMA(GCC diagnostic push) + #define DIAG_POP DIAG_PRAGMA(GCC diagnostic pop) + #define DIAG_IGNORE(w) DIAG_PRAGMA(GCC diagnostic ignored w) +#elif defined(_MSC_VER) + #define DIAG_PRAGMA(x) __pragma(x) + #define DIAG_PUSH DIAG_PRAGMA(warning(push)) + #define DIAG_POP DIAG_PRAGMA(warning(pop)) + #define DIAG_IGNORE(w) +#else + #define DIAG_PUSH + #define DIAG_POP + #define DIAG_IGNORE(w) +#endif +#ifdef __cplusplus + +// ----------------------------------------------------------------------------- +// core/unit.h +// ----------------------------------------------------------------------------- +#define INFINITY_SYMBOL "\x91" +#define DEGREE_SYMBOL "\x8a" +namespace eez { +enum Unit { + UNIT_UNKNOWN = 255, + UNIT_NONE = 0, + UNIT_VOLT, + UNIT_MILLI_VOLT, + UNIT_AMPER, + UNIT_MILLI_AMPER, + UNIT_MICRO_AMPER, + UNIT_WATT, + UNIT_MILLI_WATT, + UNIT_SECOND, + UNIT_MILLI_SECOND, + UNIT_CELSIUS, + UNIT_RPM, + UNIT_OHM, + UNIT_KOHM, + UNIT_MOHM, + UNIT_PERCENT, + UNIT_HERTZ, + UNIT_MILLI_HERTZ, + UNIT_KHERTZ, + UNIT_MHERTZ, + UNIT_JOULE, + UNIT_FARAD, + UNIT_MILLI_FARAD, + UNIT_MICRO_FARAD, + UNIT_NANO_FARAD, + UNIT_PICO_FARAD, + UNIT_MINUTE, + UNIT_VOLT_AMPERE, + UNIT_VOLT_AMPERE_REACTIVE, + UNIT_DEGREE, + UNIT_VOLT_PP, + UNIT_MILLI_VOLT_PP, + UNIT_AMPER_PP, + UNIT_MILLI_AMPER_PP, + UNIT_MICRO_AMPER_PP, +}; +extern const char *g_unitNames[]; +inline const char *getUnitName(Unit unit) { + if (unit == UNIT_UNKNOWN) { + return ""; + } + return g_unitNames[unit]; +} +Unit getUnitFromName(const char *unitName); +Unit getBaseUnit(Unit unit); +float getUnitFactor(Unit unit); +Unit findDerivedUnit(float value, Unit unit); +Unit getSmallerUnit(Unit unit, float min, float precision); +Unit getBiggestUnit(Unit unit, float max); +Unit getSmallestUnit(Unit unit, float min, float precision); +} +// ----------------------------------------------------------------------------- +// core/value_types.h +// ----------------------------------------------------------------------------- +#define VALUE_TYPES \ + VALUE_TYPE(UNDEFINED) \ + VALUE_TYPE(NULL) \ + VALUE_TYPE(BOOLEAN) \ + VALUE_TYPE(INT8) \ + VALUE_TYPE(UINT8) \ + VALUE_TYPE(INT16) \ + VALUE_TYPE(UINT16) \ + VALUE_TYPE(INT32) \ + VALUE_TYPE(UINT32) \ + VALUE_TYPE(INT64) \ + VALUE_TYPE(UINT64) \ + VALUE_TYPE(FLOAT) \ + VALUE_TYPE(DOUBLE) \ + VALUE_TYPE(STRING) \ + VALUE_TYPE(STRING_ASSET) \ + VALUE_TYPE(ARRAY) \ + VALUE_TYPE(ARRAY_ASSET) \ + VALUE_TYPE(STRING_REF) \ + VALUE_TYPE(ARRAY_REF) \ + VALUE_TYPE(BLOB_REF) \ + VALUE_TYPE(STREAM) \ + VALUE_TYPE(DATE) \ + VALUE_TYPE(VERSIONED_STRING) \ + VALUE_TYPE(VALUE_PTR) \ + VALUE_TYPE(ARRAY_ELEMENT_VALUE) \ + VALUE_TYPE(FLOW_OUTPUT) \ + VALUE_TYPE(NATIVE_VARIABLE) \ + VALUE_TYPE(ERROR) \ + VALUE_TYPE(RANGE) \ + VALUE_TYPE(POINTER) \ + VALUE_TYPE(ENUM) \ + VALUE_TYPE(IP_ADDRESS) \ + VALUE_TYPE(TIME_ZONE) \ + VALUE_TYPE(YT_DATA_GET_VALUE_FUNCTION_POINTER) \ + VALUE_TYPE(WIDGET) \ + VALUE_TYPE(JSON) \ + VALUE_TYPE(JSON_MEMBER_VALUE) \ + VALUE_TYPE(EVENT) \ + VALUE_TYPE(PROPERTY_REF) \ + CUSTOM_VALUE_TYPES +namespace eez { +#define VALUE_TYPE(NAME) VALUE_TYPE_##NAME, +enum ValueType { + VALUE_TYPES +}; +#undef VALUE_TYPE +} +// ----------------------------------------------------------------------------- +// core/alloc.h +// ----------------------------------------------------------------------------- +#include +#include +#include +namespace eez { +void initAllocHeap(uint8_t *heap, size_t heapSize); +void *alloc(size_t size, uint32_t id); +void free(void *ptr); +template struct ObjectAllocator { + static T *allocate(uint32_t id) { + auto ptr = alloc(sizeof(T), id); + return new (ptr) T; + } + static void deallocate(T* ptr) { + ptr->~T(); + free(ptr); + } +}; +void getAllocInfo(uint32_t &free, uint32_t &alloc); +} +// ----------------------------------------------------------------------------- +// flow/flow_defs_v3.h +// ----------------------------------------------------------------------------- +namespace eez { +namespace flow { +namespace defs_v3 { +enum ComponentTypes { + COMPONENT_TYPE_NONE = 0, + COMPONENT_TYPE_CONTAINER_WIDGET = 1, + COMPONENT_TYPE_LIST_WIDGET = 2, + COMPONENT_TYPE_GRID_WIDGET = 3, + COMPONENT_TYPE_SELECT_WIDGET = 4, + COMPONENT_TYPE_DISPLAY_DATA_WIDGET = 5, + COMPONENT_TYPE_TEXT_WIDGET = 6, + COMPONENT_TYPE_MULTILINE_TEXT_WIDGET = 7, + COMPONENT_TYPE_RECTANGLE_WIDGET = 8, + COMPONENT_TYPE_BITMAP_WIDGET = 9, + COMPONENT_TYPE_BUTTON_WIDGET = 10, + COMPONENT_TYPE_TOGGLE_BUTTON_WIDGET = 11, + COMPONENT_TYPE_BUTTON_GROUP_WIDGET = 12, + COMPONENT_TYPE_BAR_GRAPH_WIDGET = 14, + COMPONENT_TYPE_USER_WIDGET_WIDGET = 15, + COMPONENT_TYPE_YT_GRAPH_WIDGET = 16, + COMPONENT_TYPE_UP_DOWN_WIDGET = 17, + COMPONENT_TYPE_LIST_GRAPH_WIDGET = 18, + COMPONENT_TYPE_APP_VIEW_WIDGET = 19, + COMPONENT_TYPE_SCROLL_BAR_WIDGET = 20, + COMPONENT_TYPE_PROGRESS_WIDGET = 21, + COMPONENT_TYPE_CANVAS_WIDGET = 22, + COMPONENT_TYPE_GAUGE_EMBEDDED_WIDGET = 23, + COMPONENT_TYPE_INPUT_EMBEDDED_WIDGET = 24, + COMPONENT_TYPE_ROLLER_WIDGET = 25, + COMPONENT_TYPE_SWITCH_WIDGET = 26, + COMPONENT_TYPE_SLIDER_WIDGET = 27, + COMPONENT_TYPE_DROP_DOWN_LIST_WIDGET = 28, + COMPONENT_TYPE_LINE_CHART_EMBEDDED_WIDGET = 29, + COMPONENT_TYPE_QR_CODE_WIDGET = 30, + COMPONENT_TYPE_START_ACTION = 1001, + COMPONENT_TYPE_END_ACTION = 1002, + COMPONENT_TYPE_INPUT_ACTION = 1003, + COMPONENT_TYPE_OUTPUT_ACTION = 1004, + COMPONENT_TYPE_WATCH_VARIABLE_ACTION = 1005, + COMPONENT_TYPE_EVAL_EXPR_ACTION = 1006, + COMPONENT_TYPE_SET_VARIABLE_ACTION = 1007, + COMPONENT_TYPE_SWITCH_ACTION = 1008, + COMPONENT_TYPE_COMPARE_ACTION = 1009, + COMPONENT_TYPE_IS_TRUE_ACTION = 1010, + COMPONENT_TYPE_CONSTANT_ACTION = 1011, + COMPONENT_TYPE_LOG_ACTION = 1012, + COMPONENT_TYPE_CALL_ACTION_ACTION = 1013, + COMPONENT_TYPE_DELAY_ACTION = 1014, + COMPONENT_TYPE_ERROR_ACTION = 1015, + COMPONENT_TYPE_CATCH_ERROR_ACTION = 1016, + COMPONENT_TYPE_COUNTER_ACTION = 1017, + COMPONENT_TYPE_LOOP_ACTION = 1018, + COMPONENT_TYPE_SHOW_PAGE_ACTION = 1019, + COMPONENT_TYPE_SCPI_ACTION = 1020, + COMPONENT_TYPE_SHOW_MESSAGE_BOX_ACTION = 1021, + COMPONENT_TYPE_SHOW_KEYBOARD_ACTION = 1022, + COMPONENT_TYPE_SHOW_KEYPAD_ACTION = 1023, + COMPONENT_TYPE_NOOP_ACTION = 1024, + COMPONENT_TYPE_COMMENT_ACTION = 1025, + COMPONENT_TYPE_SELECT_LANGUAGE_ACTION = 1026, + COMPONENT_TYPE_SET_PAGE_DIRECTION_ACTION = 1027, + COMPONENT_TYPE_ANIMATE_ACTION = 1028, + COMPONENT_TYPE_ON_EVENT_ACTION = 1029, + COMPONENT_TYPE_OVERRIDE_STYLE_ACTION = 1031, + COMPONENT_TYPE_SORT_ARRAY_ACTION = 1032, + COMPONENT_TYPE_LVGL_USER_WIDGET_WIDGET = 1033, + COMPONENT_TYPE_TEST_AND_SET_ACTION = 1034, + COMPONENT_TYPE_MQTT_INIT_ACTION = 1035, + COMPONENT_TYPE_MQTT_CONNECT_ACTION = 1036, + COMPONENT_TYPE_MQTT_DISCONNECT_ACTION = 1037, + COMPONENT_TYPE_MQTT_EVENT_ACTION = 1038, + COMPONENT_TYPE_MQTT_SUBSCRIBE_ACTION = 1039, + COMPONENT_TYPE_MQTT_UNSUBSCRIBE_ACTION = 1040, + COMPONENT_TYPE_MQTT_PUBLISH_ACTION = 1041, + COMPONENT_TYPE_LABEL_IN_ACTION = 1042, + COMPONENT_TYPE_LABEL_OUT_ACTION = 1043, + COMPONENT_TYPE_LVGL_ACTION = 1044, + COMPONENT_TYPE_SET_COLOR_THEME_ACTION = 1045, + FIRST_DASHBOARD_ACTION_COMPONENT_TYPE = 10000, + FIRST_DASHBOARD_WIDGET_COMPONENT_TYPE = 20000, + FIRST_LVGL_WIDGET_COMPONENT_TYPE = 30000 +}; +enum Component_CONTAINER_WIDGET_Properties { + CONTAINER_WIDGET_PROPERTY_DATA = 0, + CONTAINER_WIDGET_PROPERTY_VISIBLE = 1, + CONTAINER_WIDGET_PROPERTY_TAB_TITLE = 2, + CONTAINER_WIDGET_PROPERTY_OVERLAY = 3 +}; +enum Component_LIST_WIDGET_Properties { + LIST_WIDGET_PROPERTY_DATA = 0, + LIST_WIDGET_PROPERTY_VISIBLE = 1, + LIST_WIDGET_PROPERTY_TAB_TITLE = 2 +}; +enum Component_GRID_WIDGET_Properties { + GRID_WIDGET_PROPERTY_DATA = 0, + GRID_WIDGET_PROPERTY_VISIBLE = 1, + GRID_WIDGET_PROPERTY_TAB_TITLE = 2 +}; +enum Component_SELECT_WIDGET_Properties { + SELECT_WIDGET_PROPERTY_DATA = 0, + SELECT_WIDGET_PROPERTY_VISIBLE = 1, + SELECT_WIDGET_PROPERTY_TAB_TITLE = 2 +}; +enum Component_DISPLAY_DATA_WIDGET_Properties { + DISPLAY_DATA_WIDGET_PROPERTY_DATA = 0, + DISPLAY_DATA_WIDGET_PROPERTY_VISIBLE = 1, + DISPLAY_DATA_WIDGET_PROPERTY_TAB_TITLE = 2, + DISPLAY_DATA_WIDGET_PROPERTY_REFRESH_RATE = 3 +}; +enum Component_TEXT_WIDGET_Properties { + TEXT_WIDGET_PROPERTY_DATA = 0, + TEXT_WIDGET_PROPERTY_VISIBLE = 1, + TEXT_WIDGET_PROPERTY_TAB_TITLE = 2 +}; +enum Component_MULTILINE_TEXT_WIDGET_Properties { + MULTILINE_TEXT_WIDGET_PROPERTY_DATA = 0, + MULTILINE_TEXT_WIDGET_PROPERTY_VISIBLE = 1, + MULTILINE_TEXT_WIDGET_PROPERTY_TAB_TITLE = 2 +}; +enum Component_RECTANGLE_WIDGET_Properties { + RECTANGLE_WIDGET_PROPERTY_DATA = 0, + RECTANGLE_WIDGET_PROPERTY_VISIBLE = 1, + RECTANGLE_WIDGET_PROPERTY_TAB_TITLE = 2 +}; +enum Component_BITMAP_WIDGET_Properties { + BITMAP_WIDGET_PROPERTY_DATA = 0, + BITMAP_WIDGET_PROPERTY_VISIBLE = 1, + BITMAP_WIDGET_PROPERTY_TAB_TITLE = 2 +}; +enum Component_BUTTON_WIDGET_Properties { + BUTTON_WIDGET_PROPERTY_DATA = 0, + BUTTON_WIDGET_PROPERTY_VISIBLE = 1, + BUTTON_WIDGET_PROPERTY_TAB_TITLE = 2, + BUTTON_WIDGET_PROPERTY_ENABLED = 3 +}; +enum Component_TOGGLE_BUTTON_WIDGET_Properties { + TOGGLE_BUTTON_WIDGET_PROPERTY_DATA = 0, + TOGGLE_BUTTON_WIDGET_PROPERTY_VISIBLE = 1, + TOGGLE_BUTTON_WIDGET_PROPERTY_TAB_TITLE = 2 +}; +enum Component_BUTTON_GROUP_WIDGET_Properties { + BUTTON_GROUP_WIDGET_PROPERTY_DATA = 0, + BUTTON_GROUP_WIDGET_PROPERTY_VISIBLE = 1, + BUTTON_GROUP_WIDGET_PROPERTY_TAB_TITLE = 2, + BUTTON_GROUP_WIDGET_PROPERTY_SELECTED_BUTTON = 3 +}; +enum Component_BAR_GRAPH_WIDGET_Properties { + BAR_GRAPH_WIDGET_PROPERTY_DATA = 0, + BAR_GRAPH_WIDGET_PROPERTY_VISIBLE = 1, + BAR_GRAPH_WIDGET_PROPERTY_TAB_TITLE = 2, + BAR_GRAPH_WIDGET_PROPERTY_LINE1_DATA = 3, + BAR_GRAPH_WIDGET_PROPERTY_LINE2_DATA = 4, + BAR_GRAPH_WIDGET_PROPERTY_MIN = 5, + BAR_GRAPH_WIDGET_PROPERTY_MAX = 6, + BAR_GRAPH_WIDGET_PROPERTY_REFRESH_RATE = 7 +}; +enum Component_USER_WIDGET_WIDGET_Properties { + USER_WIDGET_WIDGET_PROPERTY_DATA = 0, + USER_WIDGET_WIDGET_PROPERTY_VISIBLE = 1, + USER_WIDGET_WIDGET_PROPERTY_TAB_TITLE = 2, + USER_WIDGET_WIDGET_PROPERTY_CONTEXT = 3, + USER_WIDGET_WIDGET_USER_PROPERTIES_START = 4 +}; +enum Component_YT_GRAPH_WIDGET_Properties { + YT_GRAPH_WIDGET_PROPERTY_DATA = 0, + YT_GRAPH_WIDGET_PROPERTY_VISIBLE = 1, + YT_GRAPH_WIDGET_PROPERTY_TAB_TITLE = 2, + YT_GRAPH_WIDGET_PROPERTY_Y2_DATA = 3 +}; +enum Component_UP_DOWN_WIDGET_Properties { + UP_DOWN_WIDGET_PROPERTY_DATA = 0, + UP_DOWN_WIDGET_PROPERTY_VISIBLE = 1, + UP_DOWN_WIDGET_PROPERTY_TAB_TITLE = 2, + UP_DOWN_WIDGET_PROPERTY_MIN = 3, + UP_DOWN_WIDGET_PROPERTY_MAX = 4 +}; +enum Component_LIST_GRAPH_WIDGET_Properties { + LIST_GRAPH_WIDGET_PROPERTY_DATA = 0, + LIST_GRAPH_WIDGET_PROPERTY_VISIBLE = 1, + LIST_GRAPH_WIDGET_PROPERTY_TAB_TITLE = 2, + LIST_GRAPH_WIDGET_PROPERTY_DWELL_DATA = 3, + LIST_GRAPH_WIDGET_PROPERTY_Y1_DATA = 4, + LIST_GRAPH_WIDGET_PROPERTY_Y2_DATA = 5, + LIST_GRAPH_WIDGET_PROPERTY_CURSOR_DATA = 6 +}; +enum Component_APP_VIEW_WIDGET_Properties { + APP_VIEW_WIDGET_PROPERTY_DATA = 0, + APP_VIEW_WIDGET_PROPERTY_VISIBLE = 1, + APP_VIEW_WIDGET_PROPERTY_TAB_TITLE = 2 +}; +enum Component_SCROLL_BAR_WIDGET_Properties { + SCROLL_BAR_WIDGET_PROPERTY_DATA = 0, + SCROLL_BAR_WIDGET_PROPERTY_VISIBLE = 1, + SCROLL_BAR_WIDGET_PROPERTY_TAB_TITLE = 2 +}; +enum Component_PROGRESS_WIDGET_Properties { + PROGRESS_WIDGET_PROPERTY_DATA = 0, + PROGRESS_WIDGET_PROPERTY_VISIBLE = 1, + PROGRESS_WIDGET_PROPERTY_TAB_TITLE = 2, + PROGRESS_WIDGET_PROPERTY_MIN = 3, + PROGRESS_WIDGET_PROPERTY_MAX = 4 +}; +enum Component_CANVAS_WIDGET_Properties { + CANVAS_WIDGET_PROPERTY_DATA = 0, + CANVAS_WIDGET_PROPERTY_VISIBLE = 1, + CANVAS_WIDGET_PROPERTY_TAB_TITLE = 2 +}; +enum Component_GAUGE_EMBEDDED_WIDGET_Properties { + GAUGE_EMBEDDED_WIDGET_PROPERTY_DATA = 0, + GAUGE_EMBEDDED_WIDGET_PROPERTY_VISIBLE = 1, + GAUGE_EMBEDDED_WIDGET_PROPERTY_TAB_TITLE = 2, + GAUGE_EMBEDDED_WIDGET_PROPERTY_MIN = 3, + GAUGE_EMBEDDED_WIDGET_PROPERTY_MAX = 4, + GAUGE_EMBEDDED_WIDGET_PROPERTY_THRESHOLD = 5, + GAUGE_EMBEDDED_WIDGET_PROPERTY_UNIT = 6 +}; +enum Component_INPUT_EMBEDDED_WIDGET_Properties { + INPUT_EMBEDDED_WIDGET_PROPERTY_DATA = 0, + INPUT_EMBEDDED_WIDGET_PROPERTY_VISIBLE = 1, + INPUT_EMBEDDED_WIDGET_PROPERTY_TAB_TITLE = 2, + INPUT_EMBEDDED_WIDGET_PROPERTY_MIN = 3, + INPUT_EMBEDDED_WIDGET_PROPERTY_MAX = 4, + INPUT_EMBEDDED_WIDGET_PROPERTY_PRECISION = 5, + INPUT_EMBEDDED_WIDGET_PROPERTY_UNIT = 6 +}; +enum Component_ROLLER_WIDGET_Properties { + ROLLER_WIDGET_PROPERTY_DATA = 0, + ROLLER_WIDGET_PROPERTY_VISIBLE = 1, + ROLLER_WIDGET_PROPERTY_TAB_TITLE = 2, + ROLLER_WIDGET_PROPERTY_MIN = 3, + ROLLER_WIDGET_PROPERTY_MAX = 4, + ROLLER_WIDGET_PROPERTY_TEXT = 5 +}; +enum Component_SWITCH_WIDGET_Properties { + SWITCH_WIDGET_PROPERTY_DATA = 0, + SWITCH_WIDGET_PROPERTY_VISIBLE = 1, + SWITCH_WIDGET_PROPERTY_TAB_TITLE = 2 +}; +enum Component_SLIDER_WIDGET_Properties { + SLIDER_WIDGET_PROPERTY_DATA = 0, + SLIDER_WIDGET_PROPERTY_VISIBLE = 1, + SLIDER_WIDGET_PROPERTY_TAB_TITLE = 2, + SLIDER_WIDGET_PROPERTY_MIN = 3, + SLIDER_WIDGET_PROPERTY_MAX = 4 +}; +enum Component_DROP_DOWN_LIST_WIDGET_Properties { + DROP_DOWN_LIST_WIDGET_PROPERTY_DATA = 0, + DROP_DOWN_LIST_WIDGET_PROPERTY_VISIBLE = 1, + DROP_DOWN_LIST_WIDGET_PROPERTY_TAB_TITLE = 2, + DROP_DOWN_LIST_WIDGET_PROPERTY_OPTIONS = 3 +}; +enum Component_LINE_CHART_EMBEDDED_WIDGET_Properties { + LINE_CHART_EMBEDDED_WIDGET_PROPERTY_DATA = 0, + LINE_CHART_EMBEDDED_WIDGET_PROPERTY_VISIBLE = 1, + LINE_CHART_EMBEDDED_WIDGET_PROPERTY_TAB_TITLE = 2, + LINE_CHART_EMBEDDED_WIDGET_PROPERTY_X_VALUE = 3, + LINE_CHART_EMBEDDED_WIDGET_PROPERTY_SHOW_TITLE = 4, + LINE_CHART_EMBEDDED_WIDGET_PROPERTY_SHOW_LEGEND = 5, + LINE_CHART_EMBEDDED_WIDGET_PROPERTY_SHOW_XAXIS = 6, + LINE_CHART_EMBEDDED_WIDGET_PROPERTY_SHOW_YAXIS = 7, + LINE_CHART_EMBEDDED_WIDGET_PROPERTY_SHOW_GRID = 8, + LINE_CHART_EMBEDDED_WIDGET_PROPERTY_TITLE = 9, + LINE_CHART_EMBEDDED_WIDGET_PROPERTY_Y_AXIS_RANGE_FROM = 10, + LINE_CHART_EMBEDDED_WIDGET_PROPERTY_Y_AXIS_RANGE_TO = 11, + LINE_CHART_EMBEDDED_WIDGET_PROPERTY_MARKER = 12 +}; +enum Component_QR_CODE_WIDGET_Properties { + QR_CODE_WIDGET_PROPERTY_DATA = 0, + QR_CODE_WIDGET_PROPERTY_VISIBLE = 1, + QR_CODE_WIDGET_PROPERTY_TAB_TITLE = 2 +}; +enum Component_WATCH_VARIABLE_ACTION_COMPONENT_Properties { + WATCH_VARIABLE_ACTION_COMPONENT_PROPERTY_VARIABLE = 0 +}; +enum Component_EVAL_EXPR_ACTION_COMPONENT_Properties { + EVAL_EXPR_ACTION_COMPONENT_PROPERTY_EXPRESSION = 0 +}; +enum Component_COMPARE_ACTION_COMPONENT_Properties { + COMPARE_ACTION_COMPONENT_PROPERTY_A = 0, + COMPARE_ACTION_COMPONENT_PROPERTY_B = 1, + COMPARE_ACTION_COMPONENT_PROPERTY_C = 2 +}; +enum Component_IS_TRUE_ACTION_COMPONENT_Properties { + IS_TRUE_ACTION_COMPONENT_PROPERTY_VALUE = 0 +}; +enum Component_CONSTANT_ACTION_COMPONENT_Properties { + CONSTANT_ACTION_COMPONENT_PROPERTY_VALUE = 0 +}; +enum Component_LOG_ACTION_COMPONENT_Properties { + LOG_ACTION_COMPONENT_PROPERTY_VALUE = 0 +}; +enum Component_DELAY_ACTION_COMPONENT_Properties { + DELAY_ACTION_COMPONENT_PROPERTY_MILLISECONDS = 0 +}; +enum Component_ERROR_ACTION_COMPONENT_Properties { + ERROR_ACTION_COMPONENT_PROPERTY_MESSAGE = 0 +}; +enum Component_COUNTER_ACTION_COMPONENT_Properties { + COUNTER_ACTION_COMPONENT_PROPERTY_COUNT_VALUE = 0 +}; +enum Component_LOOP_ACTION_COMPONENT_Properties { + LOOP_ACTION_COMPONENT_PROPERTY_VARIABLE = 0, + LOOP_ACTION_COMPONENT_PROPERTY_FROM = 1, + LOOP_ACTION_COMPONENT_PROPERTY_TO = 2, + LOOP_ACTION_COMPONENT_PROPERTY_STEP = 3 +}; +enum Component_SCPI_ACTION_COMPONENT_Properties { + SCPI_ACTION_COMPONENT_PROPERTY_INSTRUMENT = 0, + SCPI_ACTION_COMPONENT_PROPERTY_TIMEOUT = 1, + SCPI_ACTION_COMPONENT_PROPERTY_DELAY = 2 +}; +enum Component_SHOW_MESSAGE_BOX_ACTION_COMPONENT_Properties { + SHOW_MESSAGE_BOX_ACTION_COMPONENT_PROPERTY_MESSAGE = 0, + SHOW_MESSAGE_BOX_ACTION_COMPONENT_PROPERTY_BUTTONS = 1 +}; +enum Component_SHOW_KEYBOARD_ACTION_COMPONENT_Properties { + SHOW_KEYBOARD_ACTION_COMPONENT_PROPERTY_LABEL = 0, + SHOW_KEYBOARD_ACTION_COMPONENT_PROPERTY_INITAL_TEXT = 1, + SHOW_KEYBOARD_ACTION_COMPONENT_PROPERTY_MIN_CHARS = 2, + SHOW_KEYBOARD_ACTION_COMPONENT_PROPERTY_MAX_CHARS = 3 +}; +enum Component_SHOW_KEYPAD_ACTION_COMPONENT_Properties { + SHOW_KEYPAD_ACTION_COMPONENT_PROPERTY_LABEL = 0, + SHOW_KEYPAD_ACTION_COMPONENT_PROPERTY_INITAL_VALUE = 1, + SHOW_KEYPAD_ACTION_COMPONENT_PROPERTY_MIN = 2, + SHOW_KEYPAD_ACTION_COMPONENT_PROPERTY_MAX = 3, + SHOW_KEYPAD_ACTION_COMPONENT_PROPERTY_PRECISION = 4, + SHOW_KEYPAD_ACTION_COMPONENT_PROPERTY_UNIT = 5 +}; +enum Component_SELECT_LANGUAGE_ACTION_COMPONENT_Properties { + SELECT_LANGUAGE_ACTION_COMPONENT_PROPERTY_LANGUAGE = 0 +}; +enum Component_ANIMATE_ACTION_COMPONENT_Properties { + ANIMATE_ACTION_COMPONENT_PROPERTY_FROM = 0, + ANIMATE_ACTION_COMPONENT_PROPERTY_TO = 1, + ANIMATE_ACTION_COMPONENT_PROPERTY_SPEED = 2 +}; +enum Component_SORT_ARRAY_ACTION_COMPONENT_Properties { + SORT_ARRAY_ACTION_COMPONENT_PROPERTY_ARRAY = 0 +}; +enum Component_LVGL_USER_WIDGET_WIDGET_Properties { + LVGL_USER_WIDGET_WIDGET_PROPERTY_DATA = 0, + LVGL_USER_WIDGET_WIDGET_PROPERTY_VISIBLE = 1, + LVGL_USER_WIDGET_WIDGET_PROPERTY_TAB_TITLE = 2, + LVGL_USER_WIDGET_WIDGET_PROPERTY_HIDDEN_FLAG = 3, + LVGL_USER_WIDGET_WIDGET_PROPERTY_CLICKABLE_FLAG = 4, + LVGL_USER_WIDGET_WIDGET_PROPERTY_CHECKED_STATE = 5, + LVGL_USER_WIDGET_WIDGET_PROPERTY_DISABLED_STATE = 6, + LVGL_USER_WIDGET_WIDGET_USER_PROPERTIES_START = 7 +}; +enum Component_TEST_AND_SET_ACTION_COMPONENT_Properties { + TEST_AND_SET_ACTION_COMPONENT_PROPERTY_VARIABLE = 0 +}; +enum Component_MQTT_INIT_ACTION_COMPONENT_Properties { + MQTT_INIT_ACTION_COMPONENT_PROPERTY_CONNECTION = 0, + MQTT_INIT_ACTION_COMPONENT_PROPERTY_PROTOCOL = 1, + MQTT_INIT_ACTION_COMPONENT_PROPERTY_HOST = 2, + MQTT_INIT_ACTION_COMPONENT_PROPERTY_PORT = 3, + MQTT_INIT_ACTION_COMPONENT_PROPERTY_USER_NAME = 4, + MQTT_INIT_ACTION_COMPONENT_PROPERTY_PASSWORD = 5 +}; +enum Component_MQTT_CONNECT_ACTION_COMPONENT_Properties { + MQTT_CONNECT_ACTION_COMPONENT_PROPERTY_CONNECTION = 0 +}; +enum Component_MQTT_DISCONNECT_ACTION_COMPONENT_Properties { + MQTT_DISCONNECT_ACTION_COMPONENT_PROPERTY_CONNECTION = 0 +}; +enum Component_MQTT_EVENT_ACTION_COMPONENT_Properties { + MQTT_EVENT_ACTION_COMPONENT_PROPERTY_CONNECTION = 0 +}; +enum Component_MQTT_SUBSCRIBE_ACTION_COMPONENT_Properties { + MQTT_SUBSCRIBE_ACTION_COMPONENT_PROPERTY_CONNECTION = 0, + MQTT_SUBSCRIBE_ACTION_COMPONENT_PROPERTY_TOPIC = 1 +}; +enum Component_MQTT_UNSUBSCRIBE_ACTION_COMPONENT_Properties { + MQTT_UNSUBSCRIBE_ACTION_COMPONENT_PROPERTY_CONNECTION = 0, + MQTT_UNSUBSCRIBE_ACTION_COMPONENT_PROPERTY_TOPIC = 1 +}; +enum Component_MQTT_PUBLISH_ACTION_COMPONENT_Properties { + MQTT_PUBLISH_ACTION_COMPONENT_PROPERTY_CONNECTION = 0, + MQTT_PUBLISH_ACTION_COMPONENT_PROPERTY_TOPIC = 1, + MQTT_PUBLISH_ACTION_COMPONENT_PROPERTY_PAYLOAD = 2 +}; +enum Component_SET_COLOR_THEME_ACTION_COMPONENT_Properties { + SET_COLOR_THEME_ACTION_COMPONENT_PROPERTY_THEME = 0 +}; +enum OperationTypes { + OPERATION_TYPE_ADD = 0, + OPERATION_TYPE_SUB = 1, + OPERATION_TYPE_MUL = 2, + OPERATION_TYPE_DIV = 3, + OPERATION_TYPE_MOD = 4, + OPERATION_TYPE_LEFT_SHIFT = 5, + OPERATION_TYPE_RIGHT_SHIFT = 6, + OPERATION_TYPE_BINARY_AND = 7, + OPERATION_TYPE_BINARY_OR = 8, + OPERATION_TYPE_BINARY_XOR = 9, + OPERATION_TYPE_EQUAL = 10, + OPERATION_TYPE_NOT_EQUAL = 11, + OPERATION_TYPE_LESS = 12, + OPERATION_TYPE_GREATER = 13, + OPERATION_TYPE_LESS_OR_EQUAL = 14, + OPERATION_TYPE_GREATER_OR_EQUAL = 15, + OPERATION_TYPE_LOGICAL_AND = 16, + OPERATION_TYPE_LOGICAL_OR = 17, + OPERATION_TYPE_UNARY_PLUS = 18, + OPERATION_TYPE_UNARY_MINUS = 19, + OPERATION_TYPE_BINARY_ONE_COMPLEMENT = 20, + OPERATION_TYPE_NOT = 21, + OPERATION_TYPE_CONDITIONAL = 22, + OPERATION_TYPE_SYSTEM_GET_TICK = 23, + OPERATION_TYPE_FLOW_INDEX = 24, + OPERATION_TYPE_FLOW_IS_PAGE_ACTIVE = 25, + OPERATION_TYPE_FLOW_PAGE_TIMELINE_POSITION = 26, + OPERATION_TYPE_FLOW_MAKE_VALUE = 27, + OPERATION_TYPE_FLOW_MAKE_ARRAY_VALUE = 28, + OPERATION_TYPE_FLOW_LANGUAGES = 29, + OPERATION_TYPE_FLOW_TRANSLATE = 30, + OPERATION_TYPE_FLOW_THEMES = 89, + OPERATION_TYPE_FLOW_PARSE_INTEGER = 31, + OPERATION_TYPE_FLOW_PARSE_FLOAT = 32, + OPERATION_TYPE_FLOW_PARSE_DOUBLE = 33, + OPERATION_TYPE_FLOW_TO_INTEGER = 71, + OPERATION_TYPE_FLOW_GET_BITMAP_INDEX = 70, + OPERATION_TYPE_FLOW_GET_BITMAP_AS_DATA_URL = 78, + OPERATION_TYPE_CRYPTO_SHA256 = 74, + OPERATION_TYPE_DATE_NOW = 34, + OPERATION_TYPE_DATE_TO_STRING = 35, + OPERATION_TYPE_DATE_TO_LOCALE_STRING = 59, + OPERATION_TYPE_DATE_FROM_STRING = 36, + OPERATION_TYPE_DATE_GET_YEAR = 60, + OPERATION_TYPE_DATE_GET_MONTH = 61, + OPERATION_TYPE_DATE_GET_DAY = 62, + OPERATION_TYPE_DATE_GET_HOURS = 63, + OPERATION_TYPE_DATE_GET_MINUTES = 64, + OPERATION_TYPE_DATE_GET_SECONDS = 65, + OPERATION_TYPE_DATE_GET_MILLISECONDS = 66, + OPERATION_TYPE_DATE_MAKE = 67, + OPERATION_TYPE_MATH_SIN = 37, + OPERATION_TYPE_MATH_COS = 38, + OPERATION_TYPE_MATH_POW = 68, + OPERATION_TYPE_MATH_LOG = 39, + OPERATION_TYPE_MATH_LOG10 = 40, + OPERATION_TYPE_MATH_ABS = 41, + OPERATION_TYPE_MATH_FLOOR = 42, + OPERATION_TYPE_MATH_CEIL = 43, + OPERATION_TYPE_MATH_ROUND = 44, + OPERATION_TYPE_MATH_MIN = 45, + OPERATION_TYPE_MATH_MAX = 46, + OPERATION_TYPE_STRING_LENGTH = 47, + OPERATION_TYPE_STRING_SUBSTRING = 48, + OPERATION_TYPE_STRING_FIND = 49, + OPERATION_TYPE_STRING_FORMAT = 79, + OPERATION_TYPE_STRING_FORMAT_PREFIX = 80, + OPERATION_TYPE_STRING_PAD_START = 50, + OPERATION_TYPE_STRING_SPLIT = 51, + OPERATION_TYPE_STRING_FROM_CODE_POINT = 72, + OPERATION_TYPE_STRING_CODE_POINT_AT = 73, + OPERATION_TYPE_ARRAY_LENGTH = 52, + OPERATION_TYPE_ARRAY_SLICE = 53, + OPERATION_TYPE_ARRAY_ALLOCATE = 54, + OPERATION_TYPE_ARRAY_APPEND = 55, + OPERATION_TYPE_ARRAY_INSERT = 56, + OPERATION_TYPE_ARRAY_REMOVE = 57, + OPERATION_TYPE_ARRAY_CLONE = 58, + OPERATION_TYPE_BLOB_ALLOCATE = 75, + OPERATION_TYPE_BLOB_TO_STRING = 88, + OPERATION_TYPE_JSON_GET = 76, + OPERATION_TYPE_JSON_CLONE = 77, + OPERATION_TYPE_EVENT_GET_CODE = 81, + OPERATION_TYPE_EVENT_GET_CURRENT_TARGET = 82, + OPERATION_TYPE_EVENT_GET_TARGET = 83, + OPERATION_TYPE_EVENT_GET_USER_DATA = 84, + OPERATION_TYPE_EVENT_GET_KEY = 85, + OPERATION_TYPE_EVENT_GET_GESTURE_DIR = 86, + OPERATION_TYPE_EVENT_GET_ROTARY_DIFF = 87, + OPERATION_TYPE_LVGL_METER_TICK_INDEX = 69 +}; +enum SystemStructures { + SYSTEM_STRUCTURE_CLICK_EVENT = 8192, + SYSTEM_STRUCTURE_CHECKBOX_CHANGE_EVENT = 8193, + SYSTEM_STRUCTURE_TEXT_INPUT_CHANGE_EVENT = 8194, + SYSTEM_STRUCTURE_DROP_DOWN_LIST_CHANGE_EVENT = 8195, + SYSTEM_STRUCTURE_SLIDER_CHANGE_EVENT = 8196, + SYSTEM_STRUCTURE_SWITCH_CHANGE_EVENT = 8197, + SYSTEM_STRUCTURE_SCROLLBAR_STATE = 8198, + SYSTEM_STRUCTURE_OBJECT_VARIABLE_STATUS = 8199, + SYSTEM_STRUCTURE_RADIO_CHANGE_EVENT = 8200, + SYSTEM_STRUCTURE_REG_EXP_RESULT = 8201, + SYSTEM_STRUCTURE_SERIAL_PORT = 8202, + SYSTEM_STRUCTURE_MQTT_MESSAGE = 8203, + SYSTEM_STRUCTURE_TERMINAL_WIDGET_ON_DATA_PARAMS = 8204, + SYSTEM_STRUCTURE_UDP_MESSAGE = 8205 +}; +enum ClickEventSystemStructureFields { + SYSTEM_STRUCTURE_CLICK_EVENT_FIELD_INDEX = 0, + SYSTEM_STRUCTURE_CLICK_EVENT_FIELD_INDEXES = 1, + SYSTEM_STRUCTURE_CLICK_EVENT_NUM_FIELDS +}; +enum CheckboxChangeEventSystemStructureFields { + SYSTEM_STRUCTURE_CHECKBOX_CHANGE_EVENT_FIELD_INDEX = 0, + SYSTEM_STRUCTURE_CHECKBOX_CHANGE_EVENT_FIELD_INDEXES = 1, + SYSTEM_STRUCTURE_CHECKBOX_CHANGE_EVENT_FIELD_VALUE = 2, + SYSTEM_STRUCTURE_CHECKBOX_CHANGE_EVENT_NUM_FIELDS +}; +enum TextInputChangeEventSystemStructureFields { + SYSTEM_STRUCTURE_TEXT_INPUT_CHANGE_EVENT_FIELD_INDEX = 0, + SYSTEM_STRUCTURE_TEXT_INPUT_CHANGE_EVENT_FIELD_INDEXES = 1, + SYSTEM_STRUCTURE_TEXT_INPUT_CHANGE_EVENT_FIELD_VALUE = 2, + SYSTEM_STRUCTURE_TEXT_INPUT_CHANGE_EVENT_NUM_FIELDS +}; +enum DropDownListChangeEventSystemStructureFields { + SYSTEM_STRUCTURE_DROP_DOWN_LIST_CHANGE_EVENT_FIELD_INDEX = 0, + SYSTEM_STRUCTURE_DROP_DOWN_LIST_CHANGE_EVENT_FIELD_INDEXES = 1, + SYSTEM_STRUCTURE_DROP_DOWN_LIST_CHANGE_EVENT_FIELD_SELECTED_INDEX = 2, + SYSTEM_STRUCTURE_DROP_DOWN_LIST_CHANGE_EVENT_NUM_FIELDS +}; +enum SliderChangeEventSystemStructureFields { + SYSTEM_STRUCTURE_SLIDER_CHANGE_EVENT_FIELD_INDEX = 0, + SYSTEM_STRUCTURE_SLIDER_CHANGE_EVENT_FIELD_INDEXES = 1, + SYSTEM_STRUCTURE_SLIDER_CHANGE_EVENT_FIELD_VALUE = 2, + SYSTEM_STRUCTURE_SLIDER_CHANGE_EVENT_NUM_FIELDS +}; +enum SwitchChangeEventSystemStructureFields { + SYSTEM_STRUCTURE_SWITCH_CHANGE_EVENT_FIELD_INDEX = 0, + SYSTEM_STRUCTURE_SWITCH_CHANGE_EVENT_FIELD_INDEXES = 1, + SYSTEM_STRUCTURE_SWITCH_CHANGE_EVENT_FIELD_VALUE = 2, + SYSTEM_STRUCTURE_SWITCH_CHANGE_EVENT_NUM_FIELDS +}; +enum ScrollbarStateSystemStructureFields { + SYSTEM_STRUCTURE_SCROLLBAR_STATE_FIELD_NUM_ITEMS = 0, + SYSTEM_STRUCTURE_SCROLLBAR_STATE_FIELD_ITEMS_PER_PAGE = 1, + SYSTEM_STRUCTURE_SCROLLBAR_STATE_FIELD_POSITION_INCREMENT = 2, + SYSTEM_STRUCTURE_SCROLLBAR_STATE_FIELD_POSITION = 3, + SYSTEM_STRUCTURE_SCROLLBAR_STATE_NUM_FIELDS +}; +enum ObjectVariableStatusSystemStructureFields { + SYSTEM_STRUCTURE_OBJECT_VARIABLE_STATUS_FIELD_LABEL = 0, + SYSTEM_STRUCTURE_OBJECT_VARIABLE_STATUS_FIELD_IMAGE = 1, + SYSTEM_STRUCTURE_OBJECT_VARIABLE_STATUS_FIELD_COLOR = 2, + SYSTEM_STRUCTURE_OBJECT_VARIABLE_STATUS_FIELD_ERROR = 3, + SYSTEM_STRUCTURE_OBJECT_VARIABLE_STATUS_NUM_FIELDS +}; +enum RadioChangeEventSystemStructureFields { + SYSTEM_STRUCTURE_RADIO_CHANGE_EVENT_FIELD_INDEX = 0, + SYSTEM_STRUCTURE_RADIO_CHANGE_EVENT_FIELD_INDEXES = 1, + SYSTEM_STRUCTURE_RADIO_CHANGE_EVENT_FIELD_CHECKED = 2, + SYSTEM_STRUCTURE_RADIO_CHANGE_EVENT_NUM_FIELDS +}; +enum RegExpResultSystemStructureFields { + SYSTEM_STRUCTURE_REG_EXP_RESULT_FIELD_INDEX = 0, + SYSTEM_STRUCTURE_REG_EXP_RESULT_FIELD_TEXTS = 1, + SYSTEM_STRUCTURE_REG_EXP_RESULT_FIELD_INDICES = 2, + SYSTEM_STRUCTURE_REG_EXP_RESULT_NUM_FIELDS +}; +enum SerialPortSystemStructureFields { + SYSTEM_STRUCTURE_SERIAL_PORT_FIELD_MANUFACTURER = 0, + SYSTEM_STRUCTURE_SERIAL_PORT_FIELD_SERIAL_NUMBER = 1, + SYSTEM_STRUCTURE_SERIAL_PORT_FIELD_PATH = 2, + SYSTEM_STRUCTURE_SERIAL_PORT_NUM_FIELDS +}; +enum MQTTMessageSystemStructureFields { + SYSTEM_STRUCTURE_MQTT_MESSAGE_FIELD_TOPIC = 0, + SYSTEM_STRUCTURE_MQTT_MESSAGE_FIELD_PAYLOAD = 1, + SYSTEM_STRUCTURE_MQTT_MESSAGE_NUM_FIELDS +}; +enum TerminalWidgetOnDataParamsSystemStructureFields { + SYSTEM_STRUCTURE_TERMINAL_WIDGET_ON_DATA_PARAMS_FIELD_INDEX = 0, + SYSTEM_STRUCTURE_TERMINAL_WIDGET_ON_DATA_PARAMS_FIELD_INDEXES = 1, + SYSTEM_STRUCTURE_TERMINAL_WIDGET_ON_DATA_PARAMS_FIELD_DATA = 2, + SYSTEM_STRUCTURE_TERMINAL_WIDGET_ON_DATA_PARAMS_NUM_FIELDS +}; +enum UDPMessageSystemStructureFields { + SYSTEM_STRUCTURE_UDP_MESSAGE_FIELD_PAYLOAD = 0, + SYSTEM_STRUCTURE_UDP_MESSAGE_FIELD_ADDRESS = 1, + SYSTEM_STRUCTURE_UDP_MESSAGE_FIELD_PORT = 2, + SYSTEM_STRUCTURE_UDP_MESSAGE_NUM_FIELDS +}; +enum ObjectTypes { + FIRST_OBJECT_TYPE = 40960, + OBJECT_TYPE_INSTRUMENT = 40960, + OBJECT_TYPE_SERIAL_CONNECTION = 40961, + OBJECT_TYPE_MQTT_CONNECTION = 40962, + OBJECT_TYPE_TCP_SOCKET = 40963, + LAST_OBJECT_TYPE = 40963 +}; +enum InstrumentObjectTypeFields { + OBJECT_TYPE_INSTRUMENT_FIELD_ID = 0, + OBJECT_TYPE_INSTRUMENT_FIELD_IS_CONNECTED = 1, + OBJECT_TYPE_INSTRUMENT_FIELD_STATUS = 2, + OBJECT_TYPE_INSTRUMENT_NUM_FIELDS +}; +enum SerialConnectionObjectTypeFields { + OBJECT_TYPE_SERIAL_CONNECTION_FIELD_PORT = 0, + OBJECT_TYPE_SERIAL_CONNECTION_FIELD_BAUD_RATE = 1, + OBJECT_TYPE_SERIAL_CONNECTION_FIELD_DATA_BITS = 2, + OBJECT_TYPE_SERIAL_CONNECTION_FIELD_STOP_BITS = 3, + OBJECT_TYPE_SERIAL_CONNECTION_FIELD_PARITY = 4, + OBJECT_TYPE_SERIAL_CONNECTION_FIELD_IS_CONNECTED = 5, + OBJECT_TYPE_SERIAL_CONNECTION_FIELD_ID = 6, + OBJECT_TYPE_SERIAL_CONNECTION_FIELD_STATUS = 7, + OBJECT_TYPE_SERIAL_CONNECTION_NUM_FIELDS +}; +enum MQTTConnectionObjectTypeFields { + OBJECT_TYPE_MQTT_CONNECTION_FIELD_PROTOCOL = 0, + OBJECT_TYPE_MQTT_CONNECTION_FIELD_HOST = 1, + OBJECT_TYPE_MQTT_CONNECTION_FIELD_PORT = 2, + OBJECT_TYPE_MQTT_CONNECTION_FIELD_USER_NAME = 3, + OBJECT_TYPE_MQTT_CONNECTION_FIELD_PASSWORD = 4, + OBJECT_TYPE_MQTT_CONNECTION_FIELD_IS_CONNECTED = 5, + OBJECT_TYPE_MQTT_CONNECTION_FIELD_ID = 6, + OBJECT_TYPE_MQTT_CONNECTION_FIELD_STATUS = 7, + OBJECT_TYPE_MQTT_CONNECTION_NUM_FIELDS +}; +enum TCPSocketObjectTypeFields { + OBJECT_TYPE_TCP_SOCKET_FIELD_IP_ADDRESS = 0, + OBJECT_TYPE_TCP_SOCKET_FIELD_PORT = 1, + OBJECT_TYPE_TCP_SOCKET_FIELD_IS_CONNECTED = 2, + OBJECT_TYPE_TCP_SOCKET_FIELD_ID = 3, + OBJECT_TYPE_TCP_SOCKET_FIELD_STATUS = 4, + OBJECT_TYPE_TCP_SOCKET_NUM_FIELDS +}; +enum ArrayTypes { + ARRAY_TYPE_INTEGER = 65543, + ARRAY_TYPE_FLOAT = 65547, + ARRAY_TYPE_DOUBLE = 65548, + ARRAY_TYPE_BOOLEAN = 65538, + ARRAY_TYPE_STRING = 65549, + ARRAY_TYPE_DATE = 65557, + ARRAY_TYPE_BLOB = 65555, + ARRAY_TYPE_STREAM = 65556, + ARRAY_TYPE_WIDGET = 65570, + ARRAY_TYPE_JSON = 65571, + ARRAY_TYPE_EVENT = 65573, + ARRAY_TYPE_ANY = 15 +}; +} +} +} +// ----------------------------------------------------------------------------- +// core/value.h +// ----------------------------------------------------------------------------- +#include +namespace eez { +namespace flow { + struct FlowState; +} +static const size_t MAX_ITERATORS = 4; +namespace gui { + struct Style; +} +struct EnumValue { + uint16_t enumValue; + uint16_t enumDefinition; +}; +#define VALUE_OPTIONS_REF (1 << 0) +#define STRING_OPTIONS_FILE_ELLIPSIS (1 << 1) +#define FLOAT_OPTIONS_LESS_THEN (1 << 1) +#define FLOAT_OPTIONS_FIXED_DECIMALS (1 << 2) +#define FLOAT_OPTIONS_GET_NUM_FIXED_DECIMALS(options) (((options) >> 3) & 0b111) +#define FLOAT_OPTIONS_SET_NUM_FIXED_DECIMALS(n) (FLOAT_OPTIONS_FIXED_DECIMALS | ((n & 0b111) << 3)) +struct Value; +typedef bool (*CompareValueFunction)(const Value &a, const Value &b); +typedef void (*ValueToTextFunction)(const Value &value, char *text, int count); +typedef const char * (*ValueTypeNameFunction)(const Value &value); +typedef void (*CopyValueFunction)(Value &a, const Value &b); +extern CompareValueFunction g_valueTypeCompareFunctions[]; +extern ValueToTextFunction g_valueTypeToTextFunctions[]; +extern ValueTypeNameFunction g_valueTypeNames[]; +struct PairOfUint8Value { + uint8_t first; + uint8_t second; +}; +struct PairOfUint16Value { + uint16_t first; + uint16_t second; +}; +struct PairOfInt16Value { + int16_t first; + int16_t second; +}; +struct Ref { + uint32_t refCounter; + virtual ~Ref() {} +}; +struct ArrayValue; +struct ArrayElementValue; +struct BlobRef; +struct PropertyRef; +struct LVGLEventRef; +struct Value { + public: + Value() + : type(VALUE_TYPE_UNDEFINED), unit(UNIT_UNKNOWN), options(0), dstValueType(VALUE_TYPE_UNDEFINED), uint64Value(0) + { + } + Value(int value) + : type(VALUE_TYPE_INT32), unit(UNIT_UNKNOWN), options(0), dstValueType(VALUE_TYPE_UNDEFINED), int32Value(value) + { + } + Value(const char *str) + : type(VALUE_TYPE_STRING), unit(UNIT_UNKNOWN), options(0), dstValueType(VALUE_TYPE_UNDEFINED), strValue(str) + { + } + Value(uint8_t version, const char *str) + : type(VALUE_TYPE_VERSIONED_STRING), unit(version), options(0), dstValueType(VALUE_TYPE_UNDEFINED), strValue(str) + { + } + Value(Value *pValue) + : type(VALUE_TYPE_VALUE_PTR), unit(UNIT_UNKNOWN), options(0), dstValueType(VALUE_TYPE_UNDEFINED), pValueValue(pValue) + { + } + Value(const char *str, ValueType type_) + : type(type_), unit(UNIT_UNKNOWN), options(0), dstValueType(VALUE_TYPE_UNDEFINED), strValue(str) + { + } + Value(int value, ValueType type_) + : type(type_), unit(UNIT_UNKNOWN), options(0), dstValueType(VALUE_TYPE_UNDEFINED), int32Value(value) + { + } + Value(int value, ValueType type_, uint16_t options_) + : type(type_), unit(UNIT_UNKNOWN), options(options_), dstValueType(VALUE_TYPE_UNDEFINED), int32Value(value) + { + } + Value(int8_t value, ValueType type_) + : type(type_), unit(UNIT_UNKNOWN), options(0), dstValueType(VALUE_TYPE_UNDEFINED), int8Value(value) + { + } + Value(uint8_t value, ValueType type_) + : type(type_), unit(UNIT_UNKNOWN), options(0), dstValueType(VALUE_TYPE_UNDEFINED), uint8Value(value) + { + } + Value(int16_t value, ValueType type_) + : type(type_), unit(UNIT_UNKNOWN), options(0), dstValueType(VALUE_TYPE_UNDEFINED), int16Value(value) + { + } + Value(uint16_t value, ValueType type_) + : type(type_), unit(UNIT_UNKNOWN), options(0), dstValueType(VALUE_TYPE_UNDEFINED), uint16Value(value) + { + } + Value(uint32_t value, ValueType type_) + : type(type_), unit(UNIT_UNKNOWN), options(0), dstValueType(VALUE_TYPE_UNDEFINED), uint32Value(value) + { + } + Value(int64_t value, ValueType type_) + : type(type_), unit(UNIT_UNKNOWN), options(0), dstValueType(VALUE_TYPE_UNDEFINED), int64Value(value) + { + } + Value(uint64_t value, ValueType type_) + : type(type_), unit(UNIT_UNKNOWN), options(0), dstValueType(VALUE_TYPE_UNDEFINED), uint64Value(value) + { + } + Value(float value, Unit unit_) + : type(VALUE_TYPE_FLOAT), unit(unit_), options(0), dstValueType(VALUE_TYPE_UNDEFINED), floatValue(value) + { + } + Value(float value, Unit unit_, uint16_t options_) + : type(VALUE_TYPE_FLOAT), unit(unit_), options(options_), dstValueType(VALUE_TYPE_UNDEFINED), floatValue(value) + { + } + Value(float value, ValueType type_) + : type(type_), unit(UNIT_UNKNOWN), options(0), dstValueType(VALUE_TYPE_UNDEFINED), floatValue(value) + { + } + Value(double value, ValueType type_) + : type(type_), unit(UNIT_UNKNOWN), options(0), dstValueType(VALUE_TYPE_UNDEFINED), doubleValue(value) { + } + Value(const char *value, ValueType type_, uint16_t options_) + : type(type_), unit(UNIT_UNKNOWN), options(options_), dstValueType(VALUE_TYPE_UNDEFINED), strValue(value) + { + } + Value(void *value, ValueType type_) + : type(type_), unit(UNIT_UNKNOWN), options(0), dstValueType(VALUE_TYPE_UNDEFINED), pVoidValue(value) + { + } + typedef float (*YtDataGetValueFunctionPointer)(uint32_t rowIndex, uint8_t columnIndex, float *max); + Value(YtDataGetValueFunctionPointer ytDataGetValueFunctionPointer) + : type(VALUE_TYPE_YT_DATA_GET_VALUE_FUNCTION_POINTER), unit(UNIT_UNKNOWN), options(0), dstValueType(VALUE_TYPE_UNDEFINED), pVoidValue((void *)ytDataGetValueFunctionPointer) + { + } + Value(const Value& value) + : type(VALUE_TYPE_UNDEFINED), unit(UNIT_UNKNOWN), options(0), dstValueType(VALUE_TYPE_UNDEFINED), uint64Value(0) + { + *this = value; + } + ~Value() { + freeRef(); + } + void freeRef() { + if (options & VALUE_OPTIONS_REF) { + if (--refValue->refCounter == 0) { + ObjectAllocator::deallocate(refValue); + } + } + } + Value& operator = (const Value &value) { + freeRef(); + if (value.type == VALUE_TYPE_STRING_ASSET) { + type = VALUE_TYPE_STRING; + unit = 0; + options = 0; + DIAG_PUSH + DIAG_IGNORE("-Wdangling-pointer") + strValue = (const char *)((uint8_t *)&value.int32Value + value.int32Value); + DIAG_POP + } else if (value.type == VALUE_TYPE_ARRAY_ASSET) { + type = VALUE_TYPE_ARRAY; + unit = 0; + options = 0; + DIAG_PUSH + DIAG_IGNORE("-Wdangling-pointer") + arrayValue = (ArrayValue *)((uint8_t *)&value.int32Value + value.int32Value); + DIAG_POP + } else { + type = value.type; + unit = value.unit; + options = value.options; + dstValueType = value.dstValueType; + memcpy((void *)&int64Value, (const void *)&value.int64Value, sizeof(int64_t)); + if (options & VALUE_OPTIONS_REF) { + refValue->refCounter++; + } + } + return *this; + } + bool operator==(const Value &other) const { + return g_valueTypeCompareFunctions[type](*this, other); + } + bool operator!=(const Value &other) const { + return !(*this == other); + } + ValueType getType() const { + return (ValueType)type; + } + bool isIndirectValueType() const { + return type == VALUE_TYPE_VALUE_PTR || type == VALUE_TYPE_NATIVE_VARIABLE || type == VALUE_TYPE_ARRAY_ELEMENT_VALUE || type == VALUE_TYPE_JSON_MEMBER_VALUE || type == VALUE_TYPE_PROPERTY_REF; + } + Value getValue() const; + bool isUndefinedOrNull() { + return type == VALUE_TYPE_UNDEFINED || type == VALUE_TYPE_NULL; + } + static bool isInt32OrLess(int type) { + return (type >= VALUE_TYPE_INT8 && type <= VALUE_TYPE_UINT32) || type == VALUE_TYPE_BOOLEAN; + } + bool isInt32OrLess() const { + return (type >= VALUE_TYPE_INT8 && type <= VALUE_TYPE_UINT32) || type == VALUE_TYPE_BOOLEAN; + } + bool isInt64() const { + return type == VALUE_TYPE_INT64 || type == VALUE_TYPE_UINT64; + } + bool isInt32() const { + return type == VALUE_TYPE_INT32 || type == VALUE_TYPE_UINT32; + } + bool isInt16() const { + return type == VALUE_TYPE_INT16 || type == VALUE_TYPE_UINT16; + } + bool isInt8() const { + return type == VALUE_TYPE_INT8 || type == VALUE_TYPE_UINT8; + } + bool isFloat() const { + return type == VALUE_TYPE_FLOAT; + } + bool isDouble() const { + return type == VALUE_TYPE_DOUBLE || type == VALUE_TYPE_DATE; + } + bool isBoolean() const { + return type == VALUE_TYPE_BOOLEAN; + } + bool isString() const { + return type == VALUE_TYPE_STRING || type == VALUE_TYPE_STRING_ASSET || type == VALUE_TYPE_STRING_REF; + } + bool isArray() const { + return type == VALUE_TYPE_ARRAY || type == VALUE_TYPE_ARRAY_ASSET || type == VALUE_TYPE_ARRAY_REF; + } + bool isBlob() const { + return type == VALUE_TYPE_BLOB_REF; + } + bool isJson() const { + return type == VALUE_TYPE_JSON; + } + bool isWidget() const { + return type == VALUE_TYPE_WIDGET; + } + bool isError() const { + return type == VALUE_TYPE_ERROR; + } + Unit getUnit() const { + return (Unit)unit; + } + bool getBoolean() const { + return int32Value; + } + int8_t getInt8() const { + return int8Value; + } + uint8_t getUInt8() const { + return uint8Value; + } + int16_t getInt16() const { + return int16Value; + } + uint16_t getUInt16() const { + return uint16Value; + } + int32_t getInt32() const { + return int32Value; + } + uint32_t getUInt32() const { + return uint32Value; + } + int64_t getInt64() const { + return int64Value; + } + uint64_t getUInt64() const { + return uint64Value; + } + float getFloat() const { + return floatValue; + } + double getDouble() const { + return doubleValue; + } + const char *getString() const; + const ArrayValue *getArray() const; + ArrayValue *getArray(); + int getInt() const { + if (type == VALUE_TYPE_ENUM) { + return enumValue.enumValue; + } + return int32Value; + } + const EnumValue &getEnum() const { + return enumValue; + } + int16_t getScpiError() const { + return int16Value; + } + uint8_t *getPUint8() const { + return puint8Value; + } + float *getFloatList() const { + return pFloatValue; + } + void *getVoidPointer() const { + return pVoidValue; + } + YtDataGetValueFunctionPointer getYtDataGetValueFunctionPointer() const { + return (YtDataGetValueFunctionPointer)pVoidValue; + } + uint8_t getFirstUInt8() const { + return pairOfUint8Value.first; + } + uint8_t getSecondUInt8() const { + return pairOfUint8Value.second; + } + uint16_t getFirstUInt16() const { + return pairOfUint16Value.first; + } + uint16_t getSecondUInt16() const { + return pairOfUint16Value.second; + } + int16_t getFirstInt16() const { + return pairOfInt16Value.first; + } + int16_t getSecondInt16() const { + return pairOfInt16Value.second; + } + BlobRef *getBlob() const { + return (BlobRef *)refValue; + } + void *getWidget() { + return pVoidValue; + } + LVGLEventRef *getLVGLEventRef() const { + return (LVGLEventRef *)refValue; + } + void toText(char *text, int count) const { + *text = 0; + g_valueTypeToTextFunctions[type](*this, text, count); + } + uint16_t getOptions() const { + return options; + } + uint16_t getRangeFrom() { + return pairOfUint16Value.first; + } + uint16_t getRangeTo() { + return pairOfUint16Value.second; + } + double toDouble(int *err = nullptr) const; + float toFloat(int *err = nullptr) const; + int32_t toInt32(int *err = nullptr) const; + int64_t toInt64(int *err = nullptr) const; + bool toBool(int *err = nullptr) const; + Value toString(uint32_t id) const; + static Value makeStringRef(const char *str, int len, uint32_t id); + static Value concatenateString(const Value &str1, const Value &str2); + static Value makeArrayRef(int arraySize, int arrayType, uint32_t id); + static Value makeArrayElementRef(Value arrayValue, int elementIndex, uint32_t id); + static Value makeJsonMemberRef(Value jsonValue, Value propertyName, uint32_t id); + static Value makeBlobRef(const uint8_t *blob, uint32_t len, uint32_t id); + static Value makeBlobRef(const uint8_t *blob1, uint32_t len1, const uint8_t *blob2, uint32_t len2, uint32_t id); + static Value makeLVGLEventRef(uint32_t code, void *currentTarget, void *target, int32_t userData, uint32_t key, int32_t gestureDir, int32_t rotaryDiff, uint32_t id); + static Value makeError() { return Value(0, VALUE_TYPE_ERROR); } + static Value makePropertyRef(flow::FlowState *flowState, int componentIndex, int propertyIndex, uint32_t id); + PropertyRef *getPropertyRef() const { + return (PropertyRef *)refValue; + } + Value evalProperty() const; + Value clone(); + public: + uint8_t type; + uint8_t unit; + uint16_t options; + uint32_t dstValueType; + union { + int8_t int8Value; + uint8_t uint8Value; + int16_t int16Value; + uint16_t uint16Value; + int32_t int32Value; + uint32_t uint32Value; + int64_t int64Value; + uint64_t uint64Value; + float floatValue; + double doubleValue; + const char *strValue; + ArrayValue *arrayValue; + Ref *refValue; + uint8_t *puint8Value; + float *pFloatValue; + void *pVoidValue; + Value *pValueValue; + EnumValue enumValue; + PairOfUint8Value pairOfUint8Value; + PairOfUint16Value pairOfUint16Value; + PairOfInt16Value pairOfInt16Value; + }; +}; +struct StringRef : public Ref { + ~StringRef() { + if (str) { + eez::free(str); + } + } + char *str; +}; +struct ArrayValue { + uint32_t arraySize; + uint32_t arrayType; + Value values[1]; +}; +struct ArrayValueRef : public Ref { + ~ArrayValueRef(); + ArrayValue arrayValue; +}; +struct BlobRef : public Ref { + ~BlobRef() { + if (blob) { + eez::free(blob); + } + } + uint8_t *blob; + uint32_t len; +}; +struct LVGLEventRef : public Ref { + uint32_t code; + void *currentTarget; + void *target; + int32_t userData; + uint32_t key; + int32_t gestureDir; + int32_t rotaryDiff; +}; +struct PropertyRef : public Ref { + flow::FlowState *flowState; + int componentIndex; + int propertyIndex; +}; +struct ArrayElementValue : public Ref { + Value arrayValue; + int elementIndex; + uint32_t dstValueType; +}; +struct JsonMemberValue : public Ref { + Value jsonValue; + Value propertyName; +}; +Value getVar(int16_t id); +void setVar(int16_t id, const Value& value); +inline Value Value::getValue() const { + if (type == VALUE_TYPE_VALUE_PTR) { + return pValueValue->getValue(); + } + if (type == VALUE_TYPE_NATIVE_VARIABLE) { + return getVar(int32Value); + } + if (type == VALUE_TYPE_ARRAY_ELEMENT_VALUE) { + auto arrayElementValue = (ArrayElementValue *)refValue; + if (arrayElementValue->arrayValue.isBlob()) { + auto blobRef = arrayElementValue->arrayValue.getBlob(); + if (arrayElementValue->elementIndex < 0 || arrayElementValue->elementIndex >= (int)blobRef->len) { + return Value(); + } + return Value((uint32_t)blobRef->blob[arrayElementValue->elementIndex], VALUE_TYPE_UINT32); + } else { + auto array = arrayElementValue->arrayValue.getArray(); + if (arrayElementValue->elementIndex < 0 || arrayElementValue->elementIndex >= (int)array->arraySize) { + return Value(); + } + return array->values[arrayElementValue->elementIndex]; + } + } + else if (type == VALUE_TYPE_PROPERTY_REF) { + return evalProperty(); + } + return *this; +} +bool assignValue(Value &dstValue, const Value &srcValue, uint32_t dstValueType = VALUE_TYPE_UNDEFINED); +uint16_t getPageIndexFromValue(const Value &value); +uint16_t getNumPagesFromValue(const Value &value); +Value MakeRangeValue(uint16_t from, uint16_t to); +Value MakeEnumDefinitionValue(uint8_t enumValue, uint8_t enumDefinition); +inline Value IntegerValue(int32_t value) { return Value((int)value, VALUE_TYPE_INT32); } +inline Value FloatValue(float value) { return Value(value, VALUE_TYPE_FLOAT); } +inline Value DoubleValue(double value) { return Value(value, VALUE_TYPE_DOUBLE); } +inline Value BooleanValue(bool value) { return Value(value, VALUE_TYPE_BOOLEAN); } +inline Value StringValue(const char *value) { return Value::makeStringRef(value, -1, 0); } +template +struct ArrayOf { + Value value; + ArrayOf(size_t size) { + value = Value::makeArrayRef((uint32_t)size, ARRAY_TYPE, 0); + } + ArrayOf(Value value_) : value(value_) {} + operator Value() const { return value; } + operator bool() const { return value.isArray(); } + size_t size() { + return (size_t)value.getArray()->arraySize; + } + T at(int position) { + return value.getArray()->values[position]; + } + void at(int position, const T &point) { + value.getArray()->values[position] = point.value; + } +}; +struct ArrayOfInteger { + Value value; + ArrayOfInteger(size_t size) { + value = Value::makeArrayRef((uint32_t)size, flow::defs_v3::ARRAY_TYPE_INTEGER, 0); + } + ArrayOfInteger(Value value_) : value(value_) {} + operator Value() const { return value; } + operator bool() const { return value.isArray(); } + size_t size() { + return (size_t)value.getArray()->arraySize; + } + int at(int position) { + return value.getArray()->values[position].getInt(); + } + void at(int position, int intValue) { + value.getArray()->values[position] = Value(intValue, VALUE_TYPE_INT32); + } +}; +struct ArrayOfFloat { + Value value; + ArrayOfFloat(size_t size) { + value = Value::makeArrayRef((uint32_t)size, flow::defs_v3::ARRAY_TYPE_INTEGER, 0); + } + ArrayOfFloat(Value value_) : value(value_) {} + operator Value() const { return value; } + operator bool() const { return value.isArray(); } + size_t size() { + return (size_t)value.getArray()->arraySize; + } + float at(int position) { + return value.getArray()->values[position].getFloat(); + } + void at(int position, float floatValue) { + value.getArray()->values[position] = Value(floatValue, VALUE_TYPE_FLOAT); + } +}; +struct ArrayOfDouble { + Value value; + ArrayOfDouble(size_t size) { + value = Value::makeArrayRef((uint32_t)size, flow::defs_v3::ARRAY_TYPE_INTEGER, 0); + } + ArrayOfDouble(Value value_) : value(value_) {} + operator Value() const { return value; } + operator bool() const { return value.isArray(); } + size_t size() { + return (size_t)value.getArray()->arraySize; + } + double at(int position) { + return value.getArray()->values[position].getDouble(); + } + void at(int position, double doubleValue) { + value.getArray()->values[position] = Value(doubleValue, VALUE_TYPE_DOUBLE); + } +}; +struct ArrayOfBoolean { + Value value; + ArrayOfBoolean(size_t size) { + value = Value::makeArrayRef((uint32_t)size, flow::defs_v3::ARRAY_TYPE_INTEGER, 0); + } + ArrayOfBoolean(Value value_) : value(value_) {} + operator Value() const { return value; } + operator bool() const { return value.isArray(); } + size_t size() { + return (size_t)value.getArray()->arraySize; + } + bool at(int position) { + return value.getArray()->values[position].getBoolean(); + } + void at(int position, bool boolValue) { + value.getArray()->values[position] = Value(boolValue, VALUE_TYPE_BOOLEAN); + } +}; +struct ArrayOfString { + Value value; + ArrayOfString(size_t size) { + value = Value::makeArrayRef((uint32_t)size, flow::defs_v3::ARRAY_TYPE_INTEGER, 0); + } + ArrayOfString(Value value_) : value(value_) {} + operator Value() const { return value; } + operator bool() const { return value.isArray(); } + size_t size() { + return (size_t)value.getArray()->arraySize; + } + const char *at(int position) { + return value.getArray()->values[position].getString(); + } + void at(int position, const char *stringValue) { + value.getArray()->values[position] = Value(stringValue, VALUE_TYPE_STRING); + } +}; +} +// ----------------------------------------------------------------------------- +// core/action.h +// ----------------------------------------------------------------------------- +namespace eez { +void executeActionFunction(int actionId); +} +// ----------------------------------------------------------------------------- +// core/assets.h +// ----------------------------------------------------------------------------- +#include +namespace eez { +static const uint32_t HEADER_TAG = 0x5A45457E; +static const uint32_t HEADER_TAG_COMPRESSED = 0x7A65657E; +static const uint8_t PROJECT_VERSION_V2 = 2; +static const uint8_t PROJECT_VERSION_V3 = 3; +static const uint8_t ASSETS_TYPE_FIRMWARE = 1; +static const uint8_t ASSETS_TYPE_FIRMWARE_MODULE = 2; +static const uint8_t ASSETS_TYPE_RESOURCE = 3; +static const uint8_t ASSETS_TYPE_APPLET = 4; +static const uint8_t ASSETS_TYPE_DASHBOARD = 5; +struct Header { + uint32_t tag; + uint8_t projectMajorVersion; + uint8_t projectMinorVersion; + uint8_t assetsType; + uint8_t reserved; + uint32_t decompressedSize; +}; +struct Assets; +extern Assets *g_mainAssets; +extern bool g_mainAssetsAreMutable; +template +struct AssetsPtr { + AssetsPtr() : offset(0) {} + AssetsPtr(const AssetsPtr &rhs) = delete; + void operator=(T* ptr) { + if (ptr != nullptr) { + offset = (uint8_t *)ptr - (uint8_t *)&offset; + } else { + offset = 0; + } + } + operator T*() { return ptr(); } + operator const T*() const { return ptr(); } + T* operator->() { return ptr(); } + const T* operator->() const { return ptr(); } +private: + int32_t offset; + T* ptr() { + return offset ? (T *)((uint8_t *)&offset + offset) : nullptr; + } + const T* ptr() const { + return offset ? (const T *)((uint8_t *)&offset + offset) : nullptr; + } +}; +template +struct ListOfAssetsPtr { + uint32_t count = 0; + T* operator[](uint32_t i) { return item(i); } + const T* operator[](uint32_t i) const { return item(i); } +private: + AssetsPtr> items; + T* item(int i) { + return static_cast(static_cast *>(items)[i]); + } + const T* item(int i) const { + return static_cast(static_cast *>(items)[i]); + } +}; +template +struct ListOfFundamentalType { + uint32_t count; + AssetsPtr items; + T& operator[](uint32_t i) { return ptr()[i]; } + const T& operator[](uint32_t i) const { return ptr()[i]; } +private: + T *ptr() { + return static_cast(items); + } + const T *ptr() const { + return static_cast(items); + } +}; +struct Settings { + uint16_t displayWidth; + uint16_t displayHeight; +}; +struct Theme { + AssetsPtr name; + ListOfFundamentalType colors; +}; +struct Colors { + ListOfAssetsPtr themes; + ListOfFundamentalType colors; +}; +static const uint16_t EXPR_EVAL_INSTRUCTION_TYPE_MASK = 0x0007 << 13; +static const uint16_t EXPR_EVAL_INSTRUCTION_PARAM_MASK = 0xFFFF >> 3; +static const uint16_t EXPR_EVAL_INSTRUCTION_TYPE_PUSH_CONSTANT = (0 << 13); +static const uint16_t EXPR_EVAL_INSTRUCTION_TYPE_PUSH_INPUT = (1 << 13); +static const uint16_t EXPR_EVAL_INSTRUCTION_TYPE_PUSH_LOCAL_VAR = (2 << 13); +static const uint16_t EXPR_EVAL_INSTRUCTION_TYPE_PUSH_GLOBAL_VAR = (3 << 13); +static const uint16_t EXPR_EVAL_INSTRUCTION_TYPE_PUSH_OUTPUT = (4 << 13); +static const uint16_t EXPR_EVAL_INSTRUCTION_ARRAY_ELEMENT = (5 << 13); +static const uint16_t EXPR_EVAL_INSTRUCTION_TYPE_OPERATION = (6 << 13); +static const uint16_t EXPR_EVAL_INSTRUCTION_TYPE_END = (7 << 13); +static const uint16_t EXPR_EVAL_INSTRUCTION_TYPE_END_WITH_DST_VALUE_TYPE = (7 << 13) | (1 << 12); +struct Property { + uint8_t evalInstructions[1]; +}; +struct Connection { + uint16_t targetComponentIndex; + uint16_t targetInputIndex; +}; +struct ComponentOutput { + ListOfAssetsPtr connections; + uint32_t isSeqOut; +}; +static const uint16_t BREAKPOINT_ENABLED = 1; +static const uint16_t BREAKPOINT_DISABLED = 2; +struct Component { + uint16_t type; + uint16_t breakpoint; + ListOfFundamentalType inputs; + ListOfAssetsPtr properties; + ListOfAssetsPtr outputs; + int16_t errorCatchOutput; + uint16_t reserved; +}; +struct WidgetDataItem { + int16_t componentIndex; + int16_t propertyValueIndex; +}; +struct WidgetActionItem { + int16_t componentIndex; + int16_t componentOutputIndex; +}; +#define COMPONENT_INPUT_FLAG_IS_SEQ_INPUT (1 << 0) +#define COMPONENT_INPUT_FLAG_IS_OPTIONAL (1 << 1) +typedef uint8_t ComponentInput; +struct Flow { + ListOfAssetsPtr components; + ListOfAssetsPtr localVariables; + ListOfFundamentalType componentInputs; + ListOfAssetsPtr widgetDataItems; + ListOfAssetsPtr widgetActions; + ListOfFundamentalType userPropertiesAssignable; +}; +struct FlowDefinition { + ListOfAssetsPtr flows; + ListOfAssetsPtr constants; + ListOfAssetsPtr globalVariables; +}; +struct Language { + AssetsPtr languageID; + ListOfAssetsPtr translations; +}; +struct Assets { + uint8_t projectMajorVersion; + uint8_t projectMinorVersion; + uint8_t assetsType; + uint8_t external; + uint32_t reserved; + AssetsPtr settings; + AssetsPtr colorsDefinition; + ListOfAssetsPtr actionNames; + ListOfAssetsPtr variableNames; + AssetsPtr flowDefinition; + ListOfAssetsPtr languages; +}; +bool decompressAssetsData(const uint8_t *assetsData, uint32_t assetsDataSize, Assets *decompressedAssets, uint32_t maxDecompressedAssetsSize, int *err); +void loadMainAssets(const uint8_t *assets, uint32_t assetsSize); +int getThemesCount(); +const char *getThemeName(int i); +uint32_t getThemeColorsCount(int themeIndex); +const uint16_t *getThemeColors(int themeIndex); +const uint16_t *getColors(); +} +// ----------------------------------------------------------------------------- +// core/debug.h +// ----------------------------------------------------------------------------- +#ifdef DEBUG +#include +#include +namespace eez { +namespace debug { +void pushDebugTraceHook(const char *message, size_t messageLength); +void pushInfoTraceHook(const char *message, size_t messageLength); +void pushErrorTraceHook(const char *message, size_t messageLength); +enum TraceType { + TRACE_TYPE_DEBUG, + TRACE_TYPE_INFO, + TRACE_TYPE_ERROR +}; +void Trace(TraceType traceType, const char *format, ...); +} +} +#define InfoTrace(...) ::eez::debug::Trace(::eez::debug::TRACE_TYPE_INFO, __VA_ARGS__) +#define ErrorTrace(...) ::eez::debug::Trace(::eez::debug::TRACE_TYPE_ERROR, __VA_ARGS__) +#define DebugTrace(...) ::eez::debug::Trace(::eez::debug::TRACE_TYPE_DEBUG, __VA_ARGS__) +#else +#define InfoTrace(...) (void)0 +#define ErrorTrace(...) (void)0 +#define DebugTrace(...) (void)0 +#endif +// ----------------------------------------------------------------------------- +// core/os.h +// ----------------------------------------------------------------------------- +#include +uint32_t osKernelGetTickCount(void); +#if defined(__EMSCRIPTEN__) + #ifndef EM_PORT_API + #if defined(__EMSCRIPTEN__) + #include + #if defined(__cplusplus) + #define EM_PORT_API(rettype) extern "C" rettype EMSCRIPTEN_KEEPALIVE + #else + #define EM_PORT_API(rettype) rettype EMSCRIPTEN_KEEPALIVE + #endif + #else + #if defined(__cplusplus) + #define EM_PORT_API(rettype) extern "C" rettype + #else + #define EM_PORT_API(rettype) rettype + #endif + #endif + #endif +#else + #define EM_PORT_API(rettype) rettype + uint32_t osKernelGetTickCount(); +#endif +namespace eez { +enum TestResult { + TEST_NONE, + TEST_FAILED, + TEST_OK, + TEST_CONNECTING, + TEST_SKIPPED, + TEST_WARNING +}; +uint32_t millis(); +#if EEZ_OPTION_THREADS +extern bool g_shutdown; +#endif +void shutdown(); +} +// ----------------------------------------------------------------------------- +// core/memory.h +// ----------------------------------------------------------------------------- +#include +namespace eez { +#ifdef CONF_MEMORY_BEGIN + static uint8_t * const MEMORY_BEGIN = (uint8_t *)CONF_MEMORY_BEGIN; +#else + static uint8_t * const MEMORY_BEGIN = 0; +#endif +#ifdef CONF_MEMORY_SIZE + static const uint32_t MEMORY_SIZE = CONF_MEMORY_SIZE; +#else +#endif +extern uint8_t *ALLOC_BUFFER; +extern uint32_t ALLOC_BUFFER_SIZE; +void initMemory(); +void initAssetsMemory(); +void initOtherMemory(); +uint8_t *allocBuffer(uint32_t size); +} +// ----------------------------------------------------------------------------- +// core/utf8.h +// ----------------------------------------------------------------------------- +#ifndef UTF8_SUPPORT +#define UTF8_SUPPORT 1 +#endif +#if UTF8_SUPPORT +#else +#include +typedef char utf8_int8_t; +typedef int32_t utf8_int32_t; +inline const utf8_int8_t* utf8codepoint(const utf8_int8_t *str, utf8_int32_t *out_codepoint) { + *out_codepoint = *((uint8_t *)str); + return str + 1; +} +inline utf8_int8_t *utf8catcodepoint(utf8_int8_t *str, utf8_int32_t chr, size_t n) { + if (n < 1) return nullptr; + str[0] = (char)chr; + return str + 1; +} +#define utf8len strlen +#define utf8cmp strcmp +#ifdef _MSC_VER +#define utf8casecmp _stricmp +#else +#define utf8casecmp strcasecmp +#endif +#endif +// ----------------------------------------------------------------------------- +// core/util.h +// ----------------------------------------------------------------------------- +#include +#include +#define clear_bit(reg, bitmask) *reg &= ~bitmask +#define set_bit(reg, bitmask) *reg |= bitmask +#define util_swap(type, i, j) \ + { \ + type t = i; \ + i = j; \ + j = t; \ + } +#ifndef MIN +#define MIN(a, b) ((a) < (b) ? (a) : (b)) +#endif +#ifndef MAX +#define MAX(a, b) ((a) > (b) ? (a) : (b)) +#endif +#define PATH_SEPARATOR "/" +namespace eez { +float remap(float x, float x1, float y1, float x2, float y2); +float remapQuad(float x, float x1, float y1, float x2, float y2); +float remapOutQuad(float x, float x1, float y1, float x2, float y2); +float remapInOutQuad(float x, float x1, float y1, float x2, float y2); +float remapCubic(float x, float x1, float y1, float x2, float y2); +float remapOutCubic(float x, float x1, float y1, float x2, float y2); +float remapExp(float x, float x1, float y1, float x2, float y2); +float remapOutExp(float x, float x1, float y1, float x2, float y2); +float clamp(float x, float min, float max); +void stringCopy(char *dst, size_t maxStrLength, const char *src); +void stringCopyLength(char *dst, size_t maxStrLength, const char *src, size_t length); +void stringAppendString(char *str, size_t maxStrLength, const char *value); +void stringAppendStringLength(char *str, size_t maxStrLength, const char *value, size_t length); +void stringAppendInt(char *str, size_t maxStrLength, int value); +void stringAppendUInt32(char *str, size_t maxStrLength, uint32_t value); +void stringAppendInt64(char *str, size_t maxStrLength, int64_t value); +void stringAppendUInt64(char *str, size_t maxStrLength, uint64_t value); +void stringAppendFloat(char *str, size_t maxStrLength, float value); +void stringAppendFloat(char *str, size_t maxStrLength, float value, int numDecimalPlaces); +void stringAppendDouble(char *str, size_t maxStrLength, double value); +void stringAppendDouble(char *str, size_t maxStrLength, double value, int numDecimalPlaces); +void stringAppendVoltage(char *str, size_t maxStrLength, float value); +void stringAppendCurrent(char *str, size_t maxStrLength, float value); +void stringAppendPower(char *str, size_t maxStrLength, float value); +void stringAppendDuration(char *str, size_t maxStrLength, float value); +void stringAppendLoad(char *str, size_t maxStrLength, float value); +uint32_t crc32(const uint8_t *message, size_t size); +uint8_t toBCD(uint8_t bin); +uint8_t fromBCD(uint8_t bcd); +float roundPrec(float a, float prec); +float floorPrec(float a, float prec); +float ceilPrec(float a, float prec); +bool isNaN(float x); +bool isNaN(double x); +bool isDigit(char ch); +bool isHexDigit(char ch); +bool isUperCaseLetter(char ch); +char toHexDigit(int num); +int fromHexDigit(char ch); +bool pointInsideRect(int xPoint, int yPoint, int xRect, int yRect, int wRect, int hRect); +void getParentDir(const char *path, char *parentDirPath); +bool parseMacAddress(const char *macAddressStr, size_t macAddressStrLength, uint8_t *macAddress); +int getIpAddressPartA(uint32_t ipAddress); +void setIpAddressPartA(uint32_t *ipAddress, uint8_t value); +int getIpAddressPartB(uint32_t ipAddress); +void setIpAddressPartB(uint32_t *ipAddress, uint8_t value); +int getIpAddressPartC(uint32_t ipAddress); +void setIpAddressPartC(uint32_t *ipAddress, uint8_t value); +int getIpAddressPartD(uint32_t ipAddress); +void setIpAddressPartD(uint32_t *ipAddress, uint8_t value); +void ipAddressToArray(uint32_t ipAddress, uint8_t *ipAddressArray); +uint32_t arrayToIpAddress(uint8_t *ipAddressArray); +uint32_t getIpAddress(uint8_t a, uint8_t b, uint8_t c, uint8_t d); +bool parseIpAddress(const char *ipAddressStr, size_t ipAddressStrLength, uint32_t &ipAddress); +void ipAddressToString(uint32_t ipAddress, char *ipAddressStr, size_t maxIpAddressStrLength); +void macAddressToString(const uint8_t *macAddress, char *macAddressStr); +void formatTimeZone(int16_t timeZone, char *text, int count); +bool parseTimeZone(const char *timeZoneStr, size_t timeZoneLength, int16_t &timeZone); +void replaceCharacter(char *str, char ch, char repl); +int strcicmp(char const *a, char const *b); +int strncicmp(char const *a, char const *b, int n); +bool isStringEmpty(char const *a); +bool startsWith(const char *str, const char *prefix); +bool startsWithNoCase(const char *str, const char *prefix); +bool endsWith(const char *str, const char *suffix); +bool endsWithNoCase(const char *str, const char *suffix); +void formatBytes(uint64_t bytes, char *text, int count); +void getFileName(const char *path, char *fileName, unsigned fileNameSize); +void getBaseFileName(const char *path, char *baseName, unsigned baseNameSize); +typedef float (*EasingFuncType)(float x); +extern EasingFuncType g_easingFuncs[]; +uint32_t millis(); +class Interval { +public: + bool test(uint32_t interval) { + auto time = millis(); + if (lastTime == 0) { + lastTime = time == 0 ? 1 : time; + return true; + } + if (time >= lastTime + interval) { + lastTime += ((uint32_t)(time - lastTime) / interval) * interval; + return true; + } + return false; + } +private: + uint32_t lastTime = 0; +}; +template +class MovingAverage { +public: + void operator()(T sample) { + if (m_numSamples < N) { + m_samples[m_numSamples++] = sample; + m_total += sample; + } else { + T& oldest = m_samples[m_numSamples++ % N]; + m_total += sample - oldest; + oldest = sample; + } + } + operator T() const { + if (m_numSamples < N) { + return m_total / m_numSamples; + } else { + return m_total / N; + } + } + void reset() { + m_numSamples = 0; + m_total = 0; + } +private: + T m_samples[N]; + uint64_t m_numSamples{0}; + Total m_total{0}; +}; +} +// ----------------------------------------------------------------------------- +// flow/private.h +// ----------------------------------------------------------------------------- +namespace eez { +namespace flow { +struct GlobalVariables { + uint32_t count; + Value values[1]; +}; +extern struct GlobalVariables *g_globalVariables; +void initGlobalVariables(Assets *assets); +static const int UNDEFINED_VALUE_INDEX = 0; +static const int NULL_VALUE_INDEX = 1; +#define TRACK_REF_COUNTER_FOR_COMPONENT_STATE(component) \ + !( \ + component->type == defs_v3::COMPONENT_TYPE_INPUT_ACTION || \ + component->type == defs_v3::COMPONENT_TYPE_LOOP_ACTION || \ + component->type == defs_v3::COMPONENT_TYPE_COUNTER_ACTION || \ + component->type == defs_v3::COMPONENT_TYPE_WATCH_VARIABLE_ACTION \ + ) +struct ComponenentExecutionState { + virtual ~ComponenentExecutionState() {} +}; +struct CatchErrorComponenentExecutionState : public ComponenentExecutionState { + Value message; +}; +struct FlowState { + Assets *assets; + uint32_t flowStateIndex; + Flow *flow; + uint16_t flowIndex; + bool isAction; + bool error; + bool deleteOnNextTick; + uint32_t refCounter; + FlowState *parentFlowState; + Component *parentComponent; + int parentComponentIndex; + Value inputValue; + Value *values; + ComponenentExecutionState **componenentExecutionStates; + bool *componenentAsyncStates; + unsigned executingComponentIndex; + float timelinePosition; + int32_t lvglWidgetStartIndex; + Value eventValue; + FlowState *firstChild; + FlowState *lastChild; + FlowState *previousSibling; + FlowState *nextSibling; +}; +extern int g_selectedLanguage; +extern FlowState *g_firstFlowState; +extern FlowState *g_lastFlowState; +FlowState *initActionFlowState(int flowIndex, FlowState *parentFlowState, int parentComponentIndex, const Value &value); +FlowState *initPageFlowState(Assets *assets, int flowIndex, FlowState *parentFlowState, int parentComponentIndex); +void incRefCounterForFlowState(FlowState *flowState); +void decRefCounterForFlowState(FlowState *flowState); +bool canFreeFlowState(FlowState *flowState); +void freeFlowState(FlowState *flowState); +void freeAllChildrenFlowStates(FlowState *flowState); +void deallocateComponentExecutionState(FlowState *flowState, unsigned componentIndex); +extern void onComponentExecutionStateChanged(FlowState *flowState, int componentIndex); +template +T *allocateComponentExecutionState(FlowState *flowState, unsigned componentIndex) { + if (flowState->componenentExecutionStates[componentIndex]) { + deallocateComponentExecutionState(flowState, componentIndex); + } + auto executionState = ObjectAllocator::allocate(0x72dc3bf4); + flowState->componenentExecutionStates[componentIndex] = executionState; + auto component = flowState->flow->components[componentIndex]; + if (TRACK_REF_COUNTER_FOR_COMPONENT_STATE(component)) { + incRefCounterForFlowState(flowState); + } + onComponentExecutionStateChanged(flowState, componentIndex); + return executionState; +} +void resetSequenceInputs(FlowState *flowState); +void propagateValue(FlowState *flowState, unsigned componentIndex, unsigned outputIndex, const Value &value); +void propagateValue(FlowState *flowState, unsigned componentIndex, unsigned outputIndex); +void propagateValueThroughSeqout(FlowState *flowState, unsigned componentIndex); +void assignValue(FlowState *flowState, int componentIndex, Value &dstValue, const Value &srcValue); +void clearInputValue(FlowState *flowState, int inputIndex); +void startAsyncExecution(FlowState *flowState, int componentIndex); +void endAsyncExecution(FlowState *flowState, int componentIndex); +void executeCallAction(FlowState *flowState, unsigned componentIndex, int flowIndex, const Value& value); +extern FlowState *g_executeActionFlowState; +extern unsigned g_executeActionComponentIndex; +enum FlowEvent { + FLOW_EVENT_OPEN_PAGE, + FLOW_EVENT_CLOSE_PAGE, + FLOW_EVENT_KEYDOWN +}; +void onEvent(FlowState *flowState, FlowEvent flowEvent, Value eventValue); +enum FlowErrorType { + FLOW_ERROR_PLAIN, + FLOW_ERROR_PROPERTY, + FLOW_ERROR_PROPERTY_INVALID, + FLOW_ERROR_PROPERTY_CONVERT, + FLOW_ERROR_PROPERTY_IN_ARRAY, + FLOW_ERROR_PROPERTY_IN_ARRAY_CONVERT, + FLOW_ERROR_PROPERTY_NUM, + FLOW_ERROR_PROPERTY_IN_ACTION, + FLOW_ERROR_PROPERTY_ASSIGN_IN_ACTION, + FLOW_ERROR_PROPERTY_IN_ACTION_CONVERT, + FLOW_ERROR_PROPERTY_NOT_FOUND_IN_ACTION, + FLOW_ERROR_PROPERTY_IS_NULL_IN_ACTION, + FLOW_ERROR_USER_PROPERTY, + FLOW_ERROR_USER_ASSIGNABLE_PROPERTY +}; +struct FlowError { + static FlowError Plain(const char *message, const char *file = 0, int line = -1) { + return FlowError(FLOW_ERROR_PLAIN, message, file, line); + } + static FlowError Property(const char *componentName, const char *propertyName, const char *file = 0, int line = -1) { + return FlowError(FLOW_ERROR_PROPERTY, componentName, propertyName, file, line); + } + static FlowError PropertyInvalid(const char *componentName, const char *propertyName, const char *file = 0, int line = -1) { + return FlowError(FLOW_ERROR_PROPERTY_INVALID, componentName, propertyName, file, line); + } + static FlowError PropertyConvert(const char *componentName, const char *propertyName, const char *typeName, const char *file = 0, int line = -1) { + return FlowError(FLOW_ERROR_PROPERTY_CONVERT, componentName, propertyName, typeName, file, line); + } + static FlowError PropertyInArray(const char *componentName, const char *propertyName, int index, const char *file = 0, int line = -1) { + return FlowError(FLOW_ERROR_PROPERTY_IN_ARRAY, componentName, propertyName, index, file, line); + } + static FlowError PropertyInArrayConvert(const char *componentName, const char *propertyName, const char *typeName, int index, const char *file = 0, int line = -1) { + return FlowError(FLOW_ERROR_PROPERTY_IN_ARRAY_CONVERT, componentName, propertyName, typeName, index, file, line); + } + static FlowError PropertyNum(const char *componentName, int index, const char *file = 0, int line = -1) { + return FlowError(FLOW_ERROR_PROPERTY_NUM, componentName, index, file, line); + } + static FlowError PropertyInAction(const char *componentName, const char *propertyName, int actionIndex, const char *file = 0, int line = -1) { + return FlowError(FLOW_ERROR_PROPERTY_IN_ACTION, componentName, propertyName, actionIndex, file, line); + } + static FlowError PropertyAssignInAction(const char *componentName, const char *propertyName, int actionIndex, const char *file = 0, int line = -1) { + return FlowError(FLOW_ERROR_PROPERTY_ASSIGN_IN_ACTION, componentName, propertyName, actionIndex, file, line); + } + static FlowError PropertyInActionConvert(const char *componentName, const char *propertyName, const char *typeName, int actionIndex, const char *file = 0, int line = -1) { + return FlowError(FLOW_ERROR_PROPERTY_IN_ACTION_CONVERT, componentName, propertyName, typeName, actionIndex, file, line); + } + static FlowError NotFoundInAction(const char *resourceType, const char *resourceName, const char *actionName, int actionIndex, const char *file = 0, int line = -1) { + return FlowError(FLOW_ERROR_PROPERTY_NOT_FOUND_IN_ACTION, resourceType, resourceName, actionName, actionIndex, file, line); + } + static FlowError NullInAction(const char *resourceType, const char *actionName, int actionIndex, const char *file = 0, int line = -1) { + return FlowError(FLOW_ERROR_PROPERTY_IS_NULL_IN_ACTION, resourceType, actionName, actionIndex, file, line); + } + static FlowError UserProperty(const char *componentName, int userPropertyIndex, const char *file = 0, int line = -1) { + return FlowError(FLOW_ERROR_USER_PROPERTY, componentName, userPropertyIndex, file, line); + } + static FlowError UserAssignableProperty(const char *componentName, int userPropertyIndex, const char *file = 0, int line = -1) { + return FlowError(FLOW_ERROR_USER_ASSIGNABLE_PROPERTY, componentName, userPropertyIndex, file, line); + } + FlowError setDescription(const char *description_) const { + return FlowError(type, messagePart1, messagePart2, messagePart3, messagePartInt, description_, file, line); + } + const char *getMessage(char *messageStr, size_t messageStrLength, int flowIndex, int componentIndex) const; +private: + FlowErrorType type; + const char *messagePart1; + const char *messagePart2; + const char *messagePart3; + const char *description; + int messagePartInt; + const char *file; + int line; + FlowError(FlowErrorType _type, const char *_messagePart1, const char *_file, int _line) + : type(_type), messagePart1(_messagePart1), messagePart2(0), messagePart3(0), description(0), messagePartInt(0), file(_file), line(_line) {} + FlowError(FlowErrorType _type, const char *_messagePart1, const char *_messagePart2, const char *_file, int _line) + : type(_type), messagePart1(_messagePart1), messagePart2(_messagePart2), messagePart3(0), description(0), messagePartInt(0), file(_file), line(_line) {} + FlowError(FlowErrorType _type, const char *_messagePart1, const char *_messagePart2, const char *_messagePart3, const char *_file, int _line) + : type(_type), messagePart1(_messagePart1), messagePart2(_messagePart2), messagePart3(_messagePart3), description(0), messagePartInt(0), file(_file), line(_line) {} + FlowError(FlowErrorType _type, const char *_messagePart1, int _messagePartInt, const char *_file, int _line) + : type(_type), messagePart1(_messagePart1), messagePart2(0), messagePart3(0), description(0), messagePartInt(_messagePartInt), file(_file), line(_line) {} + FlowError(FlowErrorType _type, const char *_messagePart1, const char *_messagePart2, int _messagePartInt, const char *_file, int _line) + : type(_type), messagePart1(_messagePart1), messagePart2(_messagePart2), messagePart3(0), description(0), messagePartInt(_messagePartInt), file(_file), line(_line) {} + FlowError(FlowErrorType _type, const char *_messagePart1, const char *_messagePart2, const char *_messagePart3, int _messagePartInt, const char *_file, int _line) + : type(_type), messagePart1(_messagePart1), messagePart2(_messagePart2), messagePart3(_messagePart3), description(0), messagePartInt(_messagePartInt), file(_file), line(_line) {} + FlowError(FlowErrorType _type, const char *_messagePart1, const char *_messagePart2, const char *_messagePart3, int _messagePartInt, const char *_description, const char *_file, int _line) + : type(_type), messagePart1(_messagePart1), messagePart2(_messagePart2), messagePart3(_messagePart3), description(_description), messagePartInt(_messagePartInt), file(_file), line(_line) {} +}; +void throwError(FlowState *flowState, int componentIndex, const char *errorMessage); +void throwError(FlowState *flowState, int componentIndex, const FlowError &error); +void enableThrowError(bool enable); +} +} +// ----------------------------------------------------------------------------- +// flow/components.h +// ----------------------------------------------------------------------------- +namespace eez { +namespace flow { +using defs_v3::ComponentTypes; +typedef void (*ExecuteComponentFunctionType)(FlowState *flowState, unsigned componentIndex); +void registerComponent(ComponentTypes componentType, ExecuteComponentFunctionType executeComponentFunction); +void executeComponent(FlowState *flowState, unsigned componentIndex); +bool hasExecFunc(FlowState *flowState, unsigned componentIndex); +} +} +// ----------------------------------------------------------------------------- +// flow/date.h +// ----------------------------------------------------------------------------- +#include +namespace eez { +namespace flow { +namespace date { +enum DstRule { DST_RULE_OFF, DST_RULE_EUROPE, DST_RULE_USA, DST_RULE_AUSTRALIA }; +enum Format { FORMAT_DMY_24, FORMAT_MDY_24, FORMAT_DMY_12, FORMAT_MDY_12 }; +typedef uint64_t Date; +extern Format g_localeFormat; +extern int g_timeZone; +extern DstRule g_dstRule; +Date now(); +void toString(Date time, char *str, uint32_t strLen); +void toLocaleString(Date time, char *str, uint32_t strLen); +Date fromString(const char *str); +Date makeDate(int year, int month, int day, int hours, int minutes, int seconds, int milliseconds); +void breakDate(Date time, int &year, int &month, int &day, int &hours, int &minutes, int &seconds, int &milliseconds); +int getYear(Date time); +int getMonth(Date time); +int getDay(Date time); +int getHours(Date time); +int getMinutes(Date time); +int getSeconds(Date time); +int getMilliseconds(Date time); +Date utcToLocal(Date utc); +Date localToUtc(Date local); +} +} +} +// ----------------------------------------------------------------------------- +// flow/debugger.h +// ----------------------------------------------------------------------------- +namespace eez { +namespace flow { +extern bool g_debuggerIsConnected; +enum { + DEBUGGER_MODE_RUN, + DEBUGGER_MODE_DEBUG, +}; +extern int g_debuggerMode; +bool canExecuteStep(FlowState *&flowState, unsigned &componentIndex); +void onStarted(Assets *assets); +void onStopped(); +void onAddToQueue(FlowState *flowState, int sourceComponentIndex, int sourceOutputIndex, unsigned targetComponentIndex, int targetInputIndex); +void onRemoveFromQueue(); +void onValueChanged(const Value *pValue); +void onFlowStateCreated(FlowState *flowState); +void onFlowStateDestroyed(FlowState *flowState); +void onFlowStateTimelineChanged(FlowState *flowState); +void onFlowError(FlowState *flowState, int componentIndex, const char *errorMessage); +void onComponentExecutionStateChanged(FlowState *flowState, int componentIndex); +void onComponentAsyncStateChanged(FlowState *flowState, int componentIndex); +void logInfo(FlowState *flowState, unsigned componentIndex, const char *message); +void logScpiCommand(FlowState *flowState, unsigned componentIndex, const char *cmd); +void logScpiQuery(FlowState *flowState, unsigned componentIndex, const char *query); +void logScpiQueryResult(FlowState *flowState, unsigned componentIndex, const char *resultText, size_t resultTextLen); +void onPageChanged(int previousPageId, int activePageId, bool activePageIsFromStack = false, bool previousPageIsStillOnStack = false); +void processDebuggerInput(char *buffer, uint32_t length); +} +} +// ----------------------------------------------------------------------------- +// flow/expression.h +// ----------------------------------------------------------------------------- +namespace eez { +namespace flow { +#if !defined(EEZ_FLOW_EVAL_STACK_SIZE) +#define EEZ_FLOW_EVAL_STACK_SIZE 20 +#endif +static const size_t STACK_SIZE = EEZ_FLOW_EVAL_STACK_SIZE; +struct EvalStack { + FlowState *flowState; + int componentIndex; + const int32_t *iterators; + Value stack[STACK_SIZE]; + size_t sp = 0; + const char *errorMessage; + bool push(const Value &value) { + if (sp >= STACK_SIZE) { + throwError(flowState, componentIndex, "Evaluation stack is full\n"); + return false; + } + stack[sp++] = value; + return true; + } + bool push(Value *pValue) { + if (sp >= STACK_SIZE) { + return false; + } + stack[sp++] = Value(pValue, VALUE_TYPE_VALUE_PTR); + return true; + } + Value pop() { + if (sp == 0) { + return Value::makeError(); + } + return stack[--sp]; + } + void setErrorMessage(const char *str) { + errorMessage = str; + } +}; +bool evalExpression(FlowState *flowState, int componentIndex, const uint8_t *instructions, Value &result, const FlowError &errorMessage, int *numInstructionBytes = nullptr, const int32_t *iterators = nullptr); +bool evalAssignableExpression(FlowState *flowState, int componentIndex, const uint8_t *instructions, Value &result, const FlowError &errorMessage, int *numInstructionBytes = nullptr, const int32_t *iterators = nullptr); +bool evalProperty(FlowState *flowState, int componentIndex, int propertyIndex, Value &result, const FlowError &errorMessage, int *numInstructionBytes = nullptr, const int32_t *iterators = nullptr); +bool evalAssignableProperty(FlowState *flowState, int componentIndex, int propertyIndex, Value &result, const FlowError &errorMessage, int *numInstructionBytes = nullptr, const int32_t *iterators = nullptr); +} +} +// ----------------------------------------------------------------------------- +// flow/flow.h +// ----------------------------------------------------------------------------- +namespace eez { +namespace flow { +#if defined(__EMSCRIPTEN__) +extern uint32_t g_wasmModuleId; +#endif +struct FlowState; +unsigned start(Assets *assets); +void tick(); +void stop(Assets* assets = nullptr); +bool isFlowStopped(); +unsigned getTickMaxDurationCounter(); +FlowState *getPageFlowState(Assets *assets, int16_t pageIndex); +int getPageIndex(FlowState *flowState); +int getPageIndexIncludeParents(FlowState *flowState); +void deletePageFlowState(Assets *assets, int16_t pageIndex); +Value getGlobalVariable(uint32_t globalVariableIndex); +Value getGlobalVariable(Assets *assets, uint32_t globalVariableIndex); +void setGlobalVariable(uint32_t globalVariableIndex, const Value &value); +void setGlobalVariable(Assets *assets, uint32_t globalVariableIndex, const Value &value); +Value getUserProperty(unsigned propertyIndex); +void setUserProperty(unsigned propertyIndex, const Value &value); +struct AsyncAction { + eez::flow::FlowState *flowState; + unsigned componentIndex; +}; +AsyncAction *beginAsyncExecution(); +void endAsyncExecution(AsyncAction *asyncAction); +Value getUserPropertyAsync(AsyncAction *asyncAction, unsigned propertyIndex); +void setUserPropertyAsync(AsyncAction *asyncAction, unsigned propertyIndex, const Value &value); +void setDebuggerMessageSubsciptionFilter(uint32_t filter); +void onDebuggerClientConnected(); +void onDebuggerClientDisconnected(); +void onArrayValueFree(ArrayValue *arrayValue); +void onFreeMQTTConnection(ArrayValue *mqttConnectionValue); +void executeScpi(); +void flushToDebuggerMessage(); +} +} +// ----------------------------------------------------------------------------- +// flow/hooks.h +// ----------------------------------------------------------------------------- +#include +#include +namespace eez { +namespace flow { +extern void (*replacePageHook)(int16_t pageId, uint32_t animType, uint32_t speed, uint32_t delay); +extern void (*showKeyboardHook)(Value label, Value initialText, Value minChars, Value maxChars, bool isPassword, void(*onOk)(char *), void(*onCancel)()); +extern void (*showKeypadHook)(Value label, Value initialValue, Value min, Value max, Unit unit, void(*onOk)(float), void(*onCancel)()); +extern void (*stopScriptHook)(); +extern void (*scpiComponentInitHook)(); +extern void (*startToDebuggerMessageHook)(); +extern void (*writeDebuggerBufferHook)(const char *buffer, uint32_t length); +extern void (*finishToDebuggerMessageHook)(); +extern void (*onDebuggerInputAvailableHook)(); +extern lv_obj_t *(*getLvglObjectFromIndexHook)(int32_t index); +extern lv_group_t *(*getLvglGroupFromIndexHook)(int32_t index); +extern int32_t (*getLvglScreenByNameHook)(const char *name); +extern int32_t (*getLvglObjectByNameHook)(const char *name); +extern int32_t (*getLvglGroupByNameHook)(const char *name); +extern int32_t (*getLvglStyleByNameHook)(const char *name); +extern const void *(*getLvglImageByNameHook)(const char *name); +extern const void *(*getLvglFontByNameHook)(const char *name); +extern const char *(*getLvglObjectNameFromIndexHook)(int32_t index); +extern void (*executeLvglActionHook)(int actionIndex); +extern void (*lvglObjAddStyleHook)(lv_obj_t *object, int32_t styleIndex); +extern void (*lvglObjRemoveStyleHook)(lv_obj_t *object, int32_t styleIndex); +extern void (*lvglSetColorThemeHook)(const char *themeName); +extern double (*getDateNowHook)(); +extern void (*onFlowErrorHook)(FlowState *flowState, int componentIndex, const char *errorMessage); +} +} +// ----------------------------------------------------------------------------- +// flow/operations.h +// ----------------------------------------------------------------------------- +namespace eez { +namespace flow { +typedef void (*EvalOperation)(EvalStack &); +extern EvalOperation g_evalOperations[]; +Value op_add(const Value& a1, const Value& b1); +Value op_sub(const Value& a1, const Value& b1); +Value op_mul(const Value& a1, const Value& b1); +Value op_div(const Value& a1, const Value& b1); +Value op_mod(const Value& a1, const Value& b1); +Value op_left_shift(const Value& a1, const Value& b1); +Value op_right_shift(const Value& a1, const Value& b1); +Value op_binary_and(const Value& a1, const Value& b1); +Value op_binary_or(const Value& a1, const Value& b1); +Value op_binary_xor(const Value& a1, const Value& b1); +Value op_eq(const Value& a1, const Value& b1); +Value op_neq(const Value& a1, const Value& b1); +Value op_less(const Value& a1, const Value& b1); +Value op_great(const Value& a1, const Value& b1); +Value op_less_eq(const Value& a1, const Value& b1); +Value op_great_eq(const Value& a1, const Value& b1); +} +} +// ----------------------------------------------------------------------------- +// flow/queue.h +// ----------------------------------------------------------------------------- +namespace eez { +namespace flow { +void queueReset(); +size_t getQueueSize(); +size_t getMaxQueueSize(); +extern unsigned g_numNonContinuousTaskInQueue; +bool addToQueue(FlowState *flowState, unsigned componentIndex, + int sourceComponentIndex, int sourceOutputIndex, int targetInputIndex, + bool continuousTask); +bool peekNextTaskFromQueue(FlowState *&flowState, unsigned &componentIndex, bool &continuousTask); +void removeNextTaskFromQueue(); +bool isInQueue(FlowState *flowState, unsigned componentIndex); +void removeTasksFromQueueForFlowState(FlowState *flowState); +} +} +// ----------------------------------------------------------------------------- +// flow/watch_list.h +// ----------------------------------------------------------------------------- +namespace eez { +namespace flow { +struct WatchListNode; +WatchListNode *watchListAdd(FlowState *flowState, unsigned componentIndex); +void watchListRemove(WatchListNode *node); +void visitWatchList(); +void watchListReset(); +void removeWatchesForFlowState(FlowState *flowState); +unsigned getWatchListSize(); +} +} +// ----------------------------------------------------------------------------- +// flow/components/call_action.h +// ----------------------------------------------------------------------------- +namespace eez { +namespace flow { +struct CallActionActionComponent : public Component { + int16_t flowIndex; + uint8_t inputsStartIndex; + uint8_t outputsStartIndex; +}; +} +} +// ----------------------------------------------------------------------------- +// flow/components/input.h +// ----------------------------------------------------------------------------- +namespace eez { +namespace flow { +struct InputActionComponent : public Component { + uint8_t inputIndex; +}; +struct InputActionComponentExecutionState : public ComponenentExecutionState { + Value value; +}; +bool getCallActionValue(FlowState *flowState, unsigned componentIndex, Value &value); +} +} +// ----------------------------------------------------------------------------- +// flow/components/lvgl.h +// ----------------------------------------------------------------------------- +namespace eez { +namespace flow { +enum LVGL_ACTIONS { + CHANGE_SCREEN, + PLAY_ANIMATION, + SET_PROPERTY, + ADD_STYLE, + REMOVE_STYLE, + ADD_FLAG, + CLEAR_FLAG, + GROUP, + ADD_STATE, + CLEAR_STATE, +}; +struct LVGLComponent_ActionType { + uint32_t action; +}; +struct LVGLComponent_ChangeScreen_ActionType : public LVGLComponent_ActionType { + int32_t screen; + uint32_t fadeMode; + uint32_t speed; + uint32_t delay; +}; +#define ANIMATION_PROPERTY_POSITION_X 0 +#define ANIMATION_PROPERTY_POSITION_Y 1 +#define ANIMATION_PROPERTY_WIDTH 2 +#define ANIMATION_PROPERTY_HEIGHT 3 +#define ANIMATION_PROPERTY_OPACITY 4 +#define ANIMATION_PROPERTY_IMAGE_ANGLE 5 +#define ANIMATION_PROPERTY_IMAGE_ZOOM +#define ANIMATION_ITEM_FLAG_RELATIVE (1 << 0) +#define ANIMATION_ITEM_FLAG_INSTANT (1 << 1) +#define ANIMATION_PATH_LINEAR 0 +#define ANIMATION_PATH_EASE_IN 1 +#define ANIMATION_PATH_EASE_OUT 2 +#define ANIMATION_PATH_EASE_IN_OUT 3 +#define ANIMATION_PATH_OVERSHOOT 4 +#define ANIMATION_PATH_BOUNCE 5 +struct LVGLComponent_PlayAnimation_ActionType : public LVGLComponent_ActionType { + int32_t target; + uint32_t property; + int32_t start; + int32_t end; + uint32_t delay; + uint32_t time; + uint32_t flags; + uint32_t path; +}; +struct LVGLComponent_SetProperty_ActionType : public LVGLComponent_ActionType { + int32_t target; + uint32_t property; + AssetsPtr value; + int32_t textarea; + uint32_t animated; +}; +struct LVGLComponent_AddStyle_ActionType : public LVGLComponent_ActionType { + int32_t target; + int32_t style; +}; +struct LVGLComponent_RemoveStyle_ActionType : public LVGLComponent_ActionType { + int32_t target; + int32_t style; +}; +struct LVGLComponent_AddFlag_ActionType : public LVGLComponent_ActionType { + int32_t target; + uint32_t flag; +}; +struct LVGLComponent_ClearFlag_ActionType : public LVGLComponent_ActionType { + int32_t target; + uint32_t flag; +}; +struct LVGLComponent_Group_ActionType : public LVGLComponent_ActionType { + uint32_t groupAction; + int32_t target; + uint32_t enable; +}; +struct LVGLComponent_AddState_ActionType : public LVGLComponent_ActionType { + int32_t target; + uint32_t state; +}; +struct LVGLComponent_ClearState_ActionType : public LVGLComponent_ActionType { + int32_t target; + uint32_t state; +}; +struct LVGLComponent : public Component { + ListOfAssetsPtr actions; +}; +struct LVGLApiComponent_ActionType { + uint32_t action; + ListOfAssetsPtr properties; +}; +struct LVGLApiComponent : public Component { + ListOfAssetsPtr actions; +}; +} +} +// ----------------------------------------------------------------------------- +// flow/components/lvgl_user_widget.h +// ----------------------------------------------------------------------------- +namespace eez { +namespace flow { +struct LVGLUserWidgetExecutionState : public ComponenentExecutionState { + FlowState *flowState; + ~LVGLUserWidgetExecutionState() { + freeFlowState(flowState); + } +}; +LVGLUserWidgetExecutionState *createUserWidgetFlowState(FlowState *flowState, unsigned userWidgetWidgetComponentIndex); +} +} +// ----------------------------------------------------------------------------- +// flow/components/mqtt.h +// ----------------------------------------------------------------------------- +#ifdef __cplusplus +extern "C" { +#endif +#define MQTT_ERROR_OK 0 +#define MQTT_ERROR_OTHER 1 +#define MQTT_ERROR_NOT_IMPLEMENTED 2 +int eez_mqtt_init(const char *protocol, const char *host, int port, const char *username, const char *password, void **handle); +int eez_mqtt_deinit(void *handle); +int eez_mqtt_connect(void *handle); +int eez_mqtt_disconnect(void *handle); +int eez_mqtt_subscribe(void *handle, const char *topic); +int eez_mqtt_unsubscribe(void *handle, const char *topic); +int eez_mqtt_publish(void *handle, const char *topic, const char *payload); +typedef enum { + EEZ_MQTT_EVENT_CONNECT = 0, + EEZ_MQTT_EVENT_RECONNECT = 1, + EEZ_MQTT_EVENT_CLOSE = 2, + EEZ_MQTT_EVENT_DISCONNECT = 3, + EEZ_MQTT_EVENT_OFFLINE = 4, + EEZ_MQTT_EVENT_END = 5, + EEZ_MQTT_EVENT_ERROR = 6, + EEZ_MQTT_EVENT_MESSAGE = 7 +} EEZ_MQTT_Event; +typedef struct { + const char *topic; + const char *payload; +} EEZ_MQTT_MessageEvent; +#ifdef __cplusplus +} +#endif +// ----------------------------------------------------------------------------- +// flow/components/on_event.h +// ----------------------------------------------------------------------------- +namespace eez { +namespace flow { +struct OnEventComponent : public Component { + uint8_t event; +}; +} +} +// ----------------------------------------------------------------------------- +// flow/components/set_variable.h +// ----------------------------------------------------------------------------- +namespace eez { +namespace flow { +struct SetVariableEntry { + AssetsPtr variable; + AssetsPtr value; +}; +struct SetVariableActionComponent : public Component { + ListOfAssetsPtr entries; +}; +} +} +// ----------------------------------------------------------------------------- +// flow/components/sort_array.h +// ----------------------------------------------------------------------------- +namespace eez { +namespace flow { +#define SORT_ARRAY_FLAG_ASCENDING (1 << 0) +#define SORT_ARRAY_FLAG_IGNORE_CASE (1 << 1) +struct SortArrayActionComponent : public Component { + int32_t arrayType; + int32_t structFieldIndex; + uint32_t flags; +}; +void sortArray(SortArrayActionComponent *component, ArrayValue *array); +} +} +// ----------------------------------------------------------------------------- +// flow/components/switch.h +// ----------------------------------------------------------------------------- +namespace eez { +namespace flow { +struct SwitchTest { + uint32_t outputIndex; + AssetsPtr condition; + AssetsPtr outputValue; +}; +struct SwitchActionComponent : public Component { + ListOfAssetsPtr tests; +}; +} +} +#endif + +// ----------------------------------------------------------------------------- +// core/vars.h +// ----------------------------------------------------------------------------- +#ifndef EEZ_FRAMEWORK_CORE_VARS_H +#define EEZ_FRAMEWORK_CORE_VARS_H +typedef enum { + NATIVE_VAR_TYPE_NONE, + NATIVE_VAR_TYPE_INTEGER, + NATIVE_VAR_TYPE_BOOLEAN, + NATIVE_VAR_TYPE_FLOAT, + NATIVE_VAR_TYPE_DOUBLE, + NATIVE_VAR_TYPE_STRING, +} NativeVarType; +typedef struct _native_var_t { + NativeVarType type; + void *get; + void *set; +} native_var_t; +#ifdef __cplusplus +extern "C" { +#endif +extern native_var_t native_vars[]; +#ifdef __cplusplus +} +#endif +#endif +// ----------------------------------------------------------------------------- +// flow/lvgl_api.h +// ----------------------------------------------------------------------------- +#include +#include +#if LVGL_VERSION_MAJOR >= 9 +#define lv_scr_load_anim_t lv_screen_load_anim_t +#define lv_scr_load_anim lv_screen_load_anim +#endif +#ifdef __cplusplus +extern "C" { +#endif +#ifndef EXT_IMG_DESC_T +#define EXT_IMG_DESC_T +typedef struct _ext_img_desc_t { + const char *name; + const lv_img_dsc_t *img_dsc; +} ext_img_desc_t; +#endif +#ifndef EXT_FONT_DESC_T +#define EXT_FONT_DESC_T +typedef struct _ext_font_desc_t { + const char *name; + const void *font_ptr; +} ext_font_desc_t; +#endif +typedef void (*ActionExecFunc)(lv_event_t * e); +void eez_flow_init(const uint8_t *assets, uint32_t assetsSize, lv_obj_t **objects, size_t numObjects, const ext_img_desc_t *images, size_t numImages, ActionExecFunc *actions); +void eez_flow_init_styles( + void (*add_style)(lv_obj_t *obj, int32_t styleIndex), + void (*remove_style)(lv_obj_t *obj, int32_t styleIndex) +); +void eez_flow_init_groups(lv_group_t **groups, size_t numGroups); +void eez_flow_init_screen_names(const char **screenNames, size_t numScreens); +void eez_flow_init_object_names(const char **objectNames, size_t numObjects); +void eez_flow_init_group_names(const char **groupNames, size_t numGroups); +void eez_flow_init_style_names(const char **styleNames, size_t numStyles); +void eez_flow_init_themes(const char **themeNames, size_t numThemes, void (*changeColorTheme)(uint32_t themeIndex), uint32_t *themeColors, size_t numColorsPerTheme); +void eez_flow_init_fonts(const ext_font_desc_t *fonts, size_t numFonts); +void eez_flow_set_create_screen_func(void (*createScreenFunc)(int screenIndex)); +void eez_flow_set_delete_screen_func(void (*deleteScreenFunc)(int screenIndex)); +void eez_flow_tick(); +bool eez_flow_is_stopped(); +extern int16_t g_currentScreen; +int16_t eez_flow_get_current_screen(); +void eez_flow_set_screen(int16_t screenId, lv_scr_load_anim_t animType, uint32_t speed, uint32_t delay); +void eez_flow_push_screen(int16_t screenId, lv_scr_load_anim_t animType, uint32_t speed, uint32_t delay); +void eez_flow_pop_screen(lv_scr_load_anim_t animType, uint32_t speed, uint32_t delay); +void eez_flow_create_screen(int16_t screenId); +void eez_flow_delete_screen(int16_t screenId); +bool eez_flow_is_screen_created(int16_t screenId); +void eez_flow_delete_screen_on_unload(int screenIndex); +void flowOnPageLoaded(unsigned pageIndex); +void *getFlowState(void *flowState, unsigned userWidgetComponentIndexOrPageIndex); +void deletePageFlowState(unsigned pageIndex); +void flowPropagateValue(void *flowState, unsigned componentIndex, unsigned outputIndex); +void flowPropagateValueInt32(void *flowState, unsigned componentIndex, unsigned outputIndex, int32_t value); +void flowPropagateValueUint32(void *flowState, unsigned componentIndex, unsigned outputIndex, uint32_t value); +void flowPropagateValueLVGLEvent(void *flowState, unsigned componentIndex, unsigned outputIndex, lv_event_t *event); +#define evalTextProperty(flowState, componentIndex, propertyIndex, errorMessage) _evalTextProperty(flowState, componentIndex, propertyIndex, errorMessage, __FILE__, __LINE__) +#define evalIntegerProperty(flowState, componentIndex, propertyIndex, errorMessage) _evalIntegerProperty(flowState, componentIndex, propertyIndex, errorMessage, __FILE__, __LINE__) +#define evalUnsignedIntegerProperty(flowState, componentIndex, propertyIndex, errorMessage) _evalUnsignedIntegerProperty(flowState, componentIndex, propertyIndex, errorMessage, __FILE__, __LINE__) +#define evalBooleanProperty(flowState, componentIndex, propertyIndex, errorMessage) _evalBooleanProperty(flowState, componentIndex, propertyIndex, errorMessage, __FILE__, __LINE__) +#define evalStringArrayPropertyAndJoin(flowState, componentIndex, propertyIndex, errorMessage, separator) _evalStringArrayPropertyAndJoin(flowState, componentIndex, propertyIndex, errorMessage, separator, __FILE__, __LINE__) +#define assignStringProperty(flowState, componentIndex, propertyIndex, value, errorMessage) _assignStringProperty(flowState, componentIndex, propertyIndex, value, errorMessage, __FILE__, __LINE__) +#define assignIntegerProperty(flowState, componentIndex, propertyIndex, value, errorMessage) _assignIntegerProperty(flowState, componentIndex, propertyIndex, value, errorMessage, __FILE__, __LINE__) +#define assignBooleanProperty(flowState, componentIndex, propertyIndex, value, errorMessage) _assignBooleanProperty(flowState, componentIndex, propertyIndex, value, errorMessage, __FILE__, __LINE__) +const char *_evalTextProperty(void *flowState, unsigned componentIndex, unsigned propertyIndex, const char *errorMessage, const char *file, int line); +int32_t _evalIntegerProperty(void *flowState, unsigned componentIndex, unsigned propertyIndex, const char *errorMessage, const char *file, int line); +uint32_t _evalUnsignedIntegerProperty(void *flowState, unsigned componentIndex, unsigned propertyIndex, const char *errorMessage, const char *file, int line); +bool _evalBooleanProperty(void *flowState, unsigned componentIndex, unsigned propertyIndex, const char *errorMessage, const char *file, int line); +const char *_evalStringArrayPropertyAndJoin(void *flowState, unsigned componentIndex, unsigned propertyIndex, const char *errorMessage, const char *separator, const char *file, int line); +void _assignStringProperty(void *flowState, unsigned componentIndex, unsigned propertyIndex, const char *value, const char *errorMessage, const char *file, int line); +void _assignIntegerProperty(void *flowState, unsigned componentIndex, unsigned propertyIndex, int32_t value, const char *errorMessage, const char *file, int line); +void _assignBooleanProperty(void *flowState, unsigned componentIndex, unsigned propertyIndex, bool value, const char *errorMessage, const char *file, int line); +float eez_linear(float x); +float eez_easeInQuad(float x); +float eez_easeOutQuad(float x); +float eez_easeInOutQuad(float x); +float eez_easeInCubic(float x); +float eez_easeOutCubic(float x); +float eez_easeInOutCubic(float x); +float eez_easeInQuart(float x); +float eez_easeOutQuart(float x); +float eez_easeInOutQuart(float x); +float eez_easeInQuint(float x); +float eez_easeOutQuint(float x); +float eez_easeInOutQuint(float x); +float eez_easeInSine(float x); +float eez_easeOutSine(float x); +float eez_easeInOutSine(float x); +float eez_easeInExpo(float x); +float eez_easeOutExpo(float x); +float eez_easeInOutExpo(float x); +float eez_easeInCirc(float x); +float eez_easeOutCirc(float x); +float eez_easeInOutCirc(float x); +float eez_easeInBack(float x); +float eez_easeOutBack(float x); +float eez_easeInOutBack(float x); +float eez_easeInElastic(float x); +float eez_easeOutElastic(float x); +float eez_easeInOutElastic(float x); +float eez_easeOutBounce(float x); +float eez_easeInBounce(float x); +float eez_easeOutBounce(float x); +float eez_easeInOutBounce(float x); +float getTimelinePosition(void *flowState); +extern int g_eezFlowLvlgMeterTickIndex; +int compareRollerOptions(lv_roller_t *roller, const char *new_val, const char *cur_val, lv_roller_mode_t mode); +void eez_flow_set_theme(const char *themeName); +uint32_t eez_flow_get_selected_theme_index(); +uint32_t eez_flow_get_theme_color(uint32_t colorIndex); +#ifdef __cplusplus +} +#endif + +/* The latest version of this library is available on GitHub; + * https://github.com/sheredom/utf8.h */ + +/* This is free and unencumbered software released into the public domain. + * + * Anyone is free to copy, modify, publish, use, compile, sell, or + * distribute this software, either in source code form or as a compiled + * binary, for any purpose, commercial or non-commercial, and by any + * means. + * + * In jurisdictions that recognize copyright laws, the author or authors + * of this software dedicate any and all copyright interest in the + * software to the public domain. We make this dedication for the benefit + * of the public at large and to the detriment of our heirs and + * successors. We intend this dedication to be an overt act of + * relinquishment in perpetuity of all present and future rights to this + * software under copyright law. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR + * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, + * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + * OTHER DEALINGS IN THE SOFTWARE. + * + * For more information, please refer to */ + +#ifndef SHEREDOM_UTF8_H_INCLUDED +#define SHEREDOM_UTF8_H_INCLUDED + +#if defined(_MSC_VER) +#pragma warning(push) + +/* disable warning: no function prototype given: converting '()' to '(void)' */ +#pragma warning(disable : 4255) + +/* disable warning: '__cplusplus' is not defined as a preprocessor macro, + * replacing with '0' for '#if/#elif' */ +#pragma warning(disable : 4668) + +/* disable warning: bytes padding added after construct */ +#pragma warning(disable : 4820) +#endif + +#include +#include + +#if defined(_MSC_VER) +#pragma warning(pop) +#endif + +#if defined(_MSC_VER) && (_MSC_VER < 1920) +typedef __int32 utf8_int32_t; +#else +#include +typedef int32_t utf8_int32_t; +#endif + +#if defined(__clang__) +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wold-style-cast" +#pragma clang diagnostic ignored "-Wcast-qual" +#endif + +#ifdef __cplusplus +extern "C" { +#endif + +#if defined(_MSC_VER) +#define utf8_nonnull +#define utf8_pure +#define utf8_restrict __restrict +#define utf8_weak __inline +#elif defined(__clang__) || defined(__GNUC__) +#define utf8_nonnull __attribute__((nonnull)) +#define utf8_pure __attribute__((pure)) +#define utf8_restrict __restrict__ +#define utf8_weak __attribute__((weak)) +#else +#error Non clang, non gcc, non MSVC compiler found! +#endif + +#ifdef __cplusplus +#define utf8_null NULL +#else +#define utf8_null 0 +#endif + +#if !defined(RENESAS) && !defined(ESP32) && !defined(ESP_PLATFORM) && (defined(__cplusplus) && __cplusplus >= 201402L) +#define utf8_constexpr14 constexpr +#define utf8_constexpr14_impl constexpr +#else +/* constexpr and weak are incompatible. so only enable one of them */ +#define utf8_constexpr14 utf8_weak +#define utf8_constexpr14_impl +#endif + +#if !defined(RENESAS) && !defined(ESP32) && !defined(ESP_PLATFORM) && defined(__cplusplus) && __cplusplus >= 202002L +using utf8_int8_t = char8_t; /* Introduced in C++20 */ +#else +typedef char utf8_int8_t; +#endif + +/* Return less than 0, 0, greater than 0 if src1 < src2, src1 == src2, src1 > + * src2 respectively, case insensitive. */ +utf8_constexpr14 utf8_nonnull utf8_pure int +utf8casecmp(const utf8_int8_t *src1, const utf8_int8_t *src2); + +/* Append the utf8 string src onto the utf8 string dst. */ +utf8_nonnull utf8_weak utf8_int8_t * +utf8cat(utf8_int8_t *utf8_restrict dst, const utf8_int8_t *utf8_restrict src); + +/* Find the first match of the utf8 codepoint chr in the utf8 string src. */ +utf8_constexpr14 utf8_nonnull utf8_pure utf8_int8_t * +utf8chr(const utf8_int8_t *src, utf8_int32_t chr); + +/* Return less than 0, 0, greater than 0 if src1 < src2, + * src1 == src2, src1 > src2 respectively. */ +utf8_constexpr14 utf8_nonnull utf8_pure int utf8cmp(const utf8_int8_t *src1, + const utf8_int8_t *src2); + +/* Copy the utf8 string src onto the memory allocated in dst. */ +utf8_nonnull utf8_weak utf8_int8_t * +utf8cpy(utf8_int8_t *utf8_restrict dst, const utf8_int8_t *utf8_restrict src); + +/* Number of utf8 codepoints in the utf8 string src that consists entirely + * of utf8 codepoints not from the utf8 string reject. */ +utf8_constexpr14 utf8_nonnull utf8_pure size_t +utf8cspn(const utf8_int8_t *src, const utf8_int8_t *reject); + +/* Duplicate the utf8 string src by getting its size, malloc'ing a new buffer + * copying over the data, and returning that. Or 0 if malloc failed. */ +utf8_weak utf8_int8_t *utf8dup(const utf8_int8_t *src); + +/* Number of utf8 codepoints in the utf8 string str, + * excluding the null terminating byte. */ +utf8_constexpr14 utf8_nonnull utf8_pure size_t utf8len(const utf8_int8_t *str); + +/* Similar to utf8len, except that only at most n bytes of src are looked. */ +utf8_constexpr14 utf8_nonnull utf8_pure size_t utf8nlen(const utf8_int8_t *str, + size_t n); + +/* Return less than 0, 0, greater than 0 if src1 < src2, src1 == src2, src1 > + * src2 respectively, case insensitive. Checking at most n bytes of each utf8 + * string. */ +utf8_constexpr14 utf8_nonnull utf8_pure int +utf8ncasecmp(const utf8_int8_t *src1, const utf8_int8_t *src2, size_t n); + +/* Append the utf8 string src onto the utf8 string dst, + * writing at most n+1 bytes. Can produce an invalid utf8 + * string if n falls partway through a utf8 codepoint. */ +utf8_nonnull utf8_weak utf8_int8_t * +utf8ncat(utf8_int8_t *utf8_restrict dst, const utf8_int8_t *utf8_restrict src, + size_t n); + +/* Return less than 0, 0, greater than 0 if src1 < src2, + * src1 == src2, src1 > src2 respectively. Checking at most n + * bytes of each utf8 string. */ +utf8_constexpr14 utf8_nonnull utf8_pure int +utf8ncmp(const utf8_int8_t *src1, const utf8_int8_t *src2, size_t n); + +/* Copy the utf8 string src onto the memory allocated in dst. + * Copies at most n bytes. If n falls partway through a utf8 + * codepoint, or if dst doesn't have enough room for a null + * terminator, the final string will be cut short to preserve + * utf8 validity. */ + +utf8_nonnull utf8_weak utf8_int8_t * +utf8ncpy(utf8_int8_t *utf8_restrict dst, const utf8_int8_t *utf8_restrict src, + size_t n); + +/* Similar to utf8dup, except that at most n bytes of src are copied. If src is + * longer than n, only n bytes are copied and a null byte is added. + * + * Returns a new string if successful, 0 otherwise */ +utf8_weak utf8_int8_t *utf8ndup(const utf8_int8_t *src, size_t n); + +/* Locates the first occurrence in the utf8 string str of any byte in the + * utf8 string accept, or 0 if no match was found. */ +utf8_constexpr14 utf8_nonnull utf8_pure utf8_int8_t * +utf8pbrk(const utf8_int8_t *str, const utf8_int8_t *accept); + +/* Find the last match of the utf8 codepoint chr in the utf8 string src. */ +utf8_constexpr14 utf8_nonnull utf8_pure utf8_int8_t * +utf8rchr(const utf8_int8_t *src, int chr); + +/* Number of bytes in the utf8 string str, + * including the null terminating byte. */ +utf8_constexpr14 utf8_nonnull utf8_pure size_t utf8size(const utf8_int8_t *str); + +/* Similar to utf8size, except that the null terminating byte is excluded. */ +utf8_constexpr14 utf8_nonnull utf8_pure size_t +utf8size_lazy(const utf8_int8_t *str); + +/* Similar to utf8size, except that only at most n bytes of src are looked and + * the null terminating byte is excluded. */ +utf8_constexpr14 utf8_nonnull utf8_pure size_t +utf8nsize_lazy(const utf8_int8_t *str, size_t n); + +/* Number of utf8 codepoints in the utf8 string src that consists entirely + * of utf8 codepoints from the utf8 string accept. */ +utf8_constexpr14 utf8_nonnull utf8_pure size_t +utf8spn(const utf8_int8_t *src, const utf8_int8_t *accept); + +/* The position of the utf8 string needle in the utf8 string haystack. */ +utf8_constexpr14 utf8_nonnull utf8_pure utf8_int8_t * +utf8str(const utf8_int8_t *haystack, const utf8_int8_t *needle); + +/* The position of the utf8 string needle in the utf8 string haystack, case + * insensitive. */ +utf8_constexpr14 utf8_nonnull utf8_pure utf8_int8_t * +utf8casestr(const utf8_int8_t *haystack, const utf8_int8_t *needle); + +/* Return 0 on success, or the position of the invalid + * utf8 codepoint on failure. */ +utf8_constexpr14 utf8_nonnull utf8_pure utf8_int8_t * +utf8valid(const utf8_int8_t *str); + +/* Similar to utf8valid, except that only at most n bytes of src are looked. */ +utf8_constexpr14 utf8_nonnull utf8_pure utf8_int8_t * +utf8nvalid(const utf8_int8_t *str, size_t n); + +/* Given a null-terminated string, makes the string valid by replacing invalid + * codepoints with a 1-byte replacement. Returns 0 on success. */ +utf8_nonnull utf8_weak int utf8makevalid(utf8_int8_t *str, + const utf8_int32_t replacement); + +/* Sets out_codepoint to the current utf8 codepoint in str, and returns the + * address of the next utf8 codepoint after the current one in str. */ +utf8_constexpr14 utf8_nonnull utf8_int8_t * +utf8codepoint(const utf8_int8_t *utf8_restrict str, + utf8_int32_t *utf8_restrict out_codepoint); + +/* Calculates the size of the next utf8 codepoint in str. */ +utf8_constexpr14 utf8_nonnull size_t +utf8codepointcalcsize(const utf8_int8_t *str); + +/* Returns the size of the given codepoint in bytes. */ +utf8_constexpr14 size_t utf8codepointsize(utf8_int32_t chr); + +/* Write a codepoint to the given string, and return the address to the next + * place after the written codepoint. Pass how many bytes left in the buffer to + * n. If there is not enough space for the codepoint, this function returns + * null. */ +utf8_nonnull utf8_weak utf8_int8_t * +utf8catcodepoint(utf8_int8_t *str, utf8_int32_t chr, size_t n); + +/* Returns 1 if the given character is lowercase, or 0 if it is not. */ +utf8_constexpr14 int utf8islower(utf8_int32_t chr); + +/* Returns 1 if the given character is uppercase, or 0 if it is not. */ +utf8_constexpr14 int utf8isupper(utf8_int32_t chr); + +/* Transform the given string into all lowercase codepoints. */ +utf8_nonnull utf8_weak void utf8lwr(utf8_int8_t *utf8_restrict str); + +/* Transform the given string into all uppercase codepoints. */ +utf8_nonnull utf8_weak void utf8upr(utf8_int8_t *utf8_restrict str); + +/* Make a codepoint lower case if possible. */ +utf8_constexpr14 utf8_int32_t utf8lwrcodepoint(utf8_int32_t cp); + +/* Make a codepoint upper case if possible. */ +utf8_constexpr14 utf8_int32_t utf8uprcodepoint(utf8_int32_t cp); + +/* Sets out_codepoint to the current utf8 codepoint in str, and returns the + * address of the previous utf8 codepoint before the current one in str. */ +utf8_constexpr14 utf8_nonnull utf8_int8_t * +utf8rcodepoint(const utf8_int8_t *utf8_restrict str, + utf8_int32_t *utf8_restrict out_codepoint); + +/* Duplicate the utf8 string src by getting its size, calling alloc_func_ptr to + * copy over data to a new buffer, and returning that. Or 0 if alloc_func_ptr + * returned null. */ +utf8_weak utf8_int8_t *utf8dup_ex(const utf8_int8_t *src, + utf8_int8_t *(*alloc_func_ptr)(utf8_int8_t *, + size_t), + utf8_int8_t *user_data); + +/* Similar to utf8dup, except that at most n bytes of src are copied. If src is + * longer than n, only n bytes are copied and a null byte is added. + * + * Returns a new string if successful, 0 otherwise. */ +utf8_weak utf8_int8_t *utf8ndup_ex(const utf8_int8_t *src, size_t n, + utf8_int8_t *(*alloc_func_ptr)(utf8_int8_t *, + size_t), + utf8_int8_t *user_data); + +#undef utf8_weak +#undef utf8_pure +#undef utf8_nonnull + +utf8_constexpr14_impl int utf8casecmp(const utf8_int8_t *src1, + const utf8_int8_t *src2) { + utf8_int32_t src1_lwr_cp = 0, src2_lwr_cp = 0, src1_upr_cp = 0, + src2_upr_cp = 0, src1_orig_cp = 0, src2_orig_cp = 0; + + for (;;) { + src1 = utf8codepoint(src1, &src1_orig_cp); + src2 = utf8codepoint(src2, &src2_orig_cp); + + /* lower the srcs if required */ + src1_lwr_cp = utf8lwrcodepoint(src1_orig_cp); + src2_lwr_cp = utf8lwrcodepoint(src2_orig_cp); + + /* lower the srcs if required */ + src1_upr_cp = utf8uprcodepoint(src1_orig_cp); + src2_upr_cp = utf8uprcodepoint(src2_orig_cp); + + /* check if the lowered codepoints match */ + if ((0 == src1_orig_cp) && (0 == src2_orig_cp)) { + return 0; + } else if ((src1_lwr_cp == src2_lwr_cp) || (src1_upr_cp == src2_upr_cp)) { + continue; + } + + /* if they don't match, then we return the difference between the characters + */ + return src1_lwr_cp - src2_lwr_cp; + } +} + +utf8_int8_t *utf8cat(utf8_int8_t *utf8_restrict dst, + const utf8_int8_t *utf8_restrict src) { + utf8_int8_t *d = dst; + /* find the null terminating byte in dst */ + while ('\0' != *d) { + d++; + } + + /* overwriting the null terminating byte in dst, append src byte-by-byte */ + while ('\0' != *src) { + *d++ = *src++; + } + + /* write out a new null terminating byte into dst */ + *d = '\0'; + + return dst; +} + +utf8_constexpr14_impl utf8_int8_t *utf8chr(const utf8_int8_t *src, + utf8_int32_t chr) { + utf8_int8_t c[5] = {'\0', '\0', '\0', '\0', '\0'}; + + if (0 == chr) { + /* being asked to return position of null terminating byte, so + * just run s to the end, and return! */ + while ('\0' != *src) { + src++; + } + return (utf8_int8_t *)src; + } else if (0 == ((utf8_int32_t)0xffffff80 & chr)) { + /* 1-byte/7-bit ascii + * (0b0xxxxxxx) */ + c[0] = (utf8_int8_t)chr; + } else if (0 == ((utf8_int32_t)0xfffff800 & chr)) { + /* 2-byte/11-bit utf8 code point + * (0b110xxxxx 0b10xxxxxx) */ + c[0] = (utf8_int8_t)(0xc0 | (utf8_int8_t)(chr >> 6)); + c[1] = (utf8_int8_t)(0x80 | (utf8_int8_t)(chr & 0x3f)); + } else if (0 == ((utf8_int32_t)0xffff0000 & chr)) { + /* 3-byte/16-bit utf8 code point + * (0b1110xxxx 0b10xxxxxx 0b10xxxxxx) */ + c[0] = (utf8_int8_t)(0xe0 | (utf8_int8_t)(chr >> 12)); + c[1] = (utf8_int8_t)(0x80 | (utf8_int8_t)((chr >> 6) & 0x3f)); + c[2] = (utf8_int8_t)(0x80 | (utf8_int8_t)(chr & 0x3f)); + } else { /* if (0 == ((int)0xffe00000 & chr)) { */ + /* 4-byte/21-bit utf8 code point + * (0b11110xxx 0b10xxxxxx 0b10xxxxxx 0b10xxxxxx) */ + c[0] = (utf8_int8_t)(0xf0 | (utf8_int8_t)(chr >> 18)); + c[1] = (utf8_int8_t)(0x80 | (utf8_int8_t)((chr >> 12) & 0x3f)); + c[2] = (utf8_int8_t)(0x80 | (utf8_int8_t)((chr >> 6) & 0x3f)); + c[3] = (utf8_int8_t)(0x80 | (utf8_int8_t)(chr & 0x3f)); + } + + /* we've made c into a 2 utf8 codepoint string, one for the chr we are + * seeking, another for the null terminating byte. Now use utf8str to + * search */ + return utf8str(src, c); +} + +utf8_constexpr14_impl int utf8cmp(const utf8_int8_t *src1, + const utf8_int8_t *src2) { + while (('\0' != *src1) || ('\0' != *src2)) { + if (*src1 < *src2) { + return -1; + } else if (*src1 > *src2) { + return 1; + } + + src1++; + src2++; + } + + /* both utf8 strings matched */ + return 0; +} + +utf8_constexpr14_impl int utf8coll(const utf8_int8_t *src1, + const utf8_int8_t *src2); + +utf8_int8_t *utf8cpy(utf8_int8_t *utf8_restrict dst, + const utf8_int8_t *utf8_restrict src) { + utf8_int8_t *d = dst; + + /* overwriting anything previously in dst, write byte-by-byte + * from src */ + while ('\0' != *src) { + *d++ = *src++; + } + + /* append null terminating byte */ + *d = '\0'; + + return dst; +} + +utf8_constexpr14_impl size_t utf8cspn(const utf8_int8_t *src, + const utf8_int8_t *reject) { + size_t chars = 0; + + while ('\0' != *src) { + const utf8_int8_t *r = reject; + size_t offset = 0; + + while ('\0' != *r) { + /* checking that if *r is the start of a utf8 codepoint + * (it is not 0b10xxxxxx) and we have successfully matched + * a previous character (0 < offset) - we found a match */ + if ((0x80 != (0xc0 & *r)) && (0 < offset)) { + return chars; + } else { + if (*r == src[offset]) { + /* part of a utf8 codepoint matched, so move our checking + * onwards to the next byte */ + offset++; + r++; + } else { + /* r could be in the middle of an unmatching utf8 code point, + * so we need to march it on to the next character beginning, */ + + do { + r++; + } while (0x80 == (0xc0 & *r)); + + /* reset offset too as we found a mismatch */ + offset = 0; + } + } + } + + /* found a match at the end of *r, so didn't get a chance to test it */ + if (0 < offset) { + return chars; + } + + /* the current utf8 codepoint in src did not match reject, but src + * could have been partway through a utf8 codepoint, so we need to + * march it onto the next utf8 codepoint starting byte */ + do { + src++; + } while ((0x80 == (0xc0 & *src))); + chars++; + } + + return chars; +} + +utf8_int8_t *utf8dup(const utf8_int8_t *src) { + return utf8dup_ex(src, utf8_null, utf8_null); +} + +utf8_int8_t *utf8dup_ex(const utf8_int8_t *src, + utf8_int8_t *(*alloc_func_ptr)(utf8_int8_t *, size_t), + utf8_int8_t *user_data) { + utf8_int8_t *n = utf8_null; + + /* figure out how many bytes (including the terminator) we need to copy first + */ + size_t bytes = utf8size(src); + + if (alloc_func_ptr) { + n = alloc_func_ptr(user_data, bytes); + } else { + n = (utf8_int8_t *)malloc(bytes); + } + + if (utf8_null == n) { + /* out of memory so we bail */ + return utf8_null; + } else { + bytes = 0; + + /* copy src byte-by-byte into our new utf8 string */ + while ('\0' != src[bytes]) { + n[bytes] = src[bytes]; + bytes++; + } + + /* append null terminating byte */ + n[bytes] = '\0'; + return n; + } +} + +utf8_constexpr14_impl utf8_int8_t *utf8fry(const utf8_int8_t *str); + +utf8_constexpr14_impl size_t utf8len(const utf8_int8_t *str) { + return utf8nlen(str, SIZE_MAX); +} + +utf8_constexpr14_impl size_t utf8nlen(const utf8_int8_t *str, size_t n) { + const utf8_int8_t *t = str; + size_t length = 0; + + while ((size_t)(str - t) < n && '\0' != *str) { + if (0xf0 == (0xf8 & *str)) { + /* 4-byte utf8 code point (began with 0b11110xxx) */ + str += 4; + } else if (0xe0 == (0xf0 & *str)) { + /* 3-byte utf8 code point (began with 0b1110xxxx) */ + str += 3; + } else if (0xc0 == (0xe0 & *str)) { + /* 2-byte utf8 code point (began with 0b110xxxxx) */ + str += 2; + } else { /* if (0x00 == (0x80 & *s)) { */ + /* 1-byte ascii (began with 0b0xxxxxxx) */ + str += 1; + } + + /* no matter the bytes we marched s forward by, it was + * only 1 utf8 codepoint */ + length++; + } + + if ((size_t)(str - t) > n) { + length--; + } + return length; +} + +utf8_constexpr14_impl int utf8ncasecmp(const utf8_int8_t *src1, + const utf8_int8_t *src2, size_t n) { + utf8_int32_t src1_lwr_cp = 0, src2_lwr_cp = 0, src1_upr_cp = 0, + src2_upr_cp = 0, src1_orig_cp = 0, src2_orig_cp = 0; + + do { + const utf8_int8_t *const s1 = src1; + const utf8_int8_t *const s2 = src2; + + /* first check that we have enough bytes left in n to contain an entire + * codepoint */ + if (0 == n) { + return 0; + } + + if ((1 == n) && ((0xc0 == (0xe0 & *s1)) || (0xc0 == (0xe0 & *s2)))) { + const utf8_int32_t c1 = (0xe0 & *s1); + const utf8_int32_t c2 = (0xe0 & *s2); + + if (c1 < c2) { + return c1 - c2; + } else { + return 0; + } + } + + if ((2 >= n) && ((0xe0 == (0xf0 & *s1)) || (0xe0 == (0xf0 & *s2)))) { + const utf8_int32_t c1 = (0xf0 & *s1); + const utf8_int32_t c2 = (0xf0 & *s2); + + if (c1 < c2) { + return c1 - c2; + } else { + return 0; + } + } + + if ((3 >= n) && ((0xf0 == (0xf8 & *s1)) || (0xf0 == (0xf8 & *s2)))) { + const utf8_int32_t c1 = (0xf8 & *s1); + const utf8_int32_t c2 = (0xf8 & *s2); + + if (c1 < c2) { + return c1 - c2; + } else { + return 0; + } + } + + src1 = utf8codepoint(src1, &src1_orig_cp); + src2 = utf8codepoint(src2, &src2_orig_cp); + n -= utf8codepointsize(src1_orig_cp); + + src1_lwr_cp = utf8lwrcodepoint(src1_orig_cp); + src2_lwr_cp = utf8lwrcodepoint(src2_orig_cp); + + src1_upr_cp = utf8uprcodepoint(src1_orig_cp); + src2_upr_cp = utf8uprcodepoint(src2_orig_cp); + + /* check if the lowered codepoints match */ + if ((0 == src1_orig_cp) && (0 == src2_orig_cp)) { + return 0; + } else if ((src1_lwr_cp == src2_lwr_cp) || (src1_upr_cp == src2_upr_cp)) { + continue; + } + + /* if they don't match, then we return the difference between the characters + */ + return src1_lwr_cp - src2_lwr_cp; + } while (0 < n); + + /* both utf8 strings matched */ + return 0; +} + +utf8_int8_t *utf8ncat(utf8_int8_t *utf8_restrict dst, + const utf8_int8_t *utf8_restrict src, size_t n) { + utf8_int8_t *d = dst; + + /* find the null terminating byte in dst */ + while ('\0' != *d) { + d++; + } + + /* overwriting the null terminating byte in dst, append src byte-by-byte + * stopping if we run out of space */ + while (('\0' != *src) && (0 != n--)) { + *d++ = *src++; + } + + /* write out a new null terminating byte into dst */ + *d = '\0'; + + return dst; +} + +utf8_constexpr14_impl int utf8ncmp(const utf8_int8_t *src1, + const utf8_int8_t *src2, size_t n) { + while ((0 != n--) && (('\0' != *src1) || ('\0' != *src2))) { + if (*src1 < *src2) { + return -1; + } else if (*src1 > *src2) { + return 1; + } + + src1++; + src2++; + } + + /* both utf8 strings matched */ + return 0; +} + +utf8_int8_t *utf8ncpy(utf8_int8_t *utf8_restrict dst, + const utf8_int8_t *utf8_restrict src, size_t n) { + utf8_int8_t *d = dst; + size_t index = 0, check_index = 0; + + if (n == 0) { + return dst; + } + + /* overwriting anything previously in dst, write byte-by-byte + * from src */ + for (index = 0; index < n; index++) { + d[index] = src[index]; + if ('\0' == src[index]) { + break; + } + } + + for (check_index = index - 1; + check_index > 0 && 0x80 == (0xc0 & d[check_index]); check_index--) { + /* just moving the index */ + } + + if (check_index < index && + (index - check_index) < utf8codepointsize(d[check_index])) { + index = check_index; + } + + /* append null terminating byte */ + for (; index < n; index++) { + d[index] = 0; + } + + return dst; +} + +utf8_int8_t *utf8ndup(const utf8_int8_t *src, size_t n) { + return utf8ndup_ex(src, n, utf8_null, utf8_null); +} + +utf8_int8_t *utf8ndup_ex(const utf8_int8_t *src, size_t n, + utf8_int8_t *(*alloc_func_ptr)(utf8_int8_t *, size_t), + utf8_int8_t *user_data) { + utf8_int8_t *c = utf8_null; + size_t bytes = 0; + + /* Find the end of the string or stop when n is reached */ + while ('\0' != src[bytes] && bytes < n) { + bytes++; + } + + /* In case bytes is actually less than n, we need to set it + * to be used later in the copy byte by byte. */ + n = bytes; + + if (alloc_func_ptr) { + c = alloc_func_ptr(user_data, bytes + 1); + } else { + c = (utf8_int8_t *)malloc(bytes + 1); + } + + if (utf8_null == c) { + /* out of memory so we bail */ + return utf8_null; + } + + bytes = 0; + + /* copy src byte-by-byte into our new utf8 string */ + while ('\0' != src[bytes] && bytes < n) { + c[bytes] = src[bytes]; + bytes++; + } + + /* append null terminating byte */ + c[bytes] = '\0'; + return c; +} + +utf8_constexpr14_impl utf8_int8_t *utf8rchr(const utf8_int8_t *src, int chr) { + + utf8_int8_t *match = utf8_null; + utf8_int8_t c[5] = {'\0', '\0', '\0', '\0', '\0'}; + + if (0 == chr) { + /* being asked to return position of null terminating byte, so + * just run s to the end, and return! */ + while ('\0' != *src) { + src++; + } + return (utf8_int8_t *)src; + } else if (0 == ((int)0xffffff80 & chr)) { + /* 1-byte/7-bit ascii + * (0b0xxxxxxx) */ + c[0] = (utf8_int8_t)chr; + } else if (0 == ((int)0xfffff800 & chr)) { + /* 2-byte/11-bit utf8 code point + * (0b110xxxxx 0b10xxxxxx) */ + c[0] = (utf8_int8_t)(0xc0 | (utf8_int8_t)(chr >> 6)); + c[1] = (utf8_int8_t)(0x80 | (utf8_int8_t)(chr & 0x3f)); + } else if (0 == ((int)0xffff0000 & chr)) { + /* 3-byte/16-bit utf8 code point + * (0b1110xxxx 0b10xxxxxx 0b10xxxxxx) */ + c[0] = (utf8_int8_t)(0xe0 | (utf8_int8_t)(chr >> 12)); + c[1] = (utf8_int8_t)(0x80 | (utf8_int8_t)((chr >> 6) & 0x3f)); + c[2] = (utf8_int8_t)(0x80 | (utf8_int8_t)(chr & 0x3f)); + } else { /* if (0 == ((int)0xffe00000 & chr)) { */ + /* 4-byte/21-bit utf8 code point + * (0b11110xxx 0b10xxxxxx 0b10xxxxxx 0b10xxxxxx) */ + c[0] = (utf8_int8_t)(0xf0 | (utf8_int8_t)(chr >> 18)); + c[1] = (utf8_int8_t)(0x80 | (utf8_int8_t)((chr >> 12) & 0x3f)); + c[2] = (utf8_int8_t)(0x80 | (utf8_int8_t)((chr >> 6) & 0x3f)); + c[3] = (utf8_int8_t)(0x80 | (utf8_int8_t)(chr & 0x3f)); + } + + /* we've created a 2 utf8 codepoint string in c that is + * the utf8 character asked for by chr, and a null + * terminating byte */ + + while ('\0' != *src) { + size_t offset = 0; + + while (src[offset] == c[offset]) { + offset++; + } + + if ('\0' == c[offset]) { + /* we found a matching utf8 code point */ + match = (utf8_int8_t *)src; + src += offset; + } else { + src += offset; + + /* need to march s along to next utf8 codepoint start + * (the next byte that doesn't match 0b10xxxxxx) */ + if ('\0' != *src) { + do { + src++; + } while (0x80 == (0xc0 & *src)); + } + } + } + + /* return the last match we found (or 0 if no match was found) */ + return match; +} + +utf8_constexpr14_impl utf8_int8_t *utf8pbrk(const utf8_int8_t *str, + const utf8_int8_t *accept) { + while ('\0' != *str) { + const utf8_int8_t *a = accept; + size_t offset = 0; + + while ('\0' != *a) { + /* checking that if *a is the start of a utf8 codepoint + * (it is not 0b10xxxxxx) and we have successfully matched + * a previous character (0 < offset) - we found a match */ + if ((0x80 != (0xc0 & *a)) && (0 < offset)) { + return (utf8_int8_t *)str; + } else { + if (*a == str[offset]) { + /* part of a utf8 codepoint matched, so move our checking + * onwards to the next byte */ + offset++; + a++; + } else { + /* r could be in the middle of an unmatching utf8 code point, + * so we need to march it on to the next character beginning, */ + + do { + a++; + } while (0x80 == (0xc0 & *a)); + + /* reset offset too as we found a mismatch */ + offset = 0; + } + } + } + + /* we found a match on the last utf8 codepoint */ + if (0 < offset) { + return (utf8_int8_t *)str; + } + + /* the current utf8 codepoint in src did not match accept, but src + * could have been partway through a utf8 codepoint, so we need to + * march it onto the next utf8 codepoint starting byte */ + do { + str++; + } while ((0x80 == (0xc0 & *str))); + } + + return utf8_null; +} + +utf8_constexpr14_impl size_t utf8size(const utf8_int8_t *str) { + return utf8size_lazy(str) + 1; +} + +utf8_constexpr14_impl size_t utf8size_lazy(const utf8_int8_t *str) { + return utf8nsize_lazy(str, SIZE_MAX); +} + +utf8_constexpr14_impl size_t utf8nsize_lazy(const utf8_int8_t *str, size_t n) { + size_t size = 0; + while (size < n && '\0' != str[size]) { + size++; + } + return size; +} + +utf8_constexpr14_impl size_t utf8spn(const utf8_int8_t *src, + const utf8_int8_t *accept) { + size_t chars = 0; + + while ('\0' != *src) { + const utf8_int8_t *a = accept; + size_t offset = 0; + + while ('\0' != *a) { + /* checking that if *r is the start of a utf8 codepoint + * (it is not 0b10xxxxxx) and we have successfully matched + * a previous character (0 < offset) - we found a match */ + if ((0x80 != (0xc0 & *a)) && (0 < offset)) { + /* found a match, so increment the number of utf8 codepoints + * that have matched and stop checking whether any other utf8 + * codepoints in a match */ + chars++; + src += offset; + offset = 0; + break; + } else { + if (*a == src[offset]) { + offset++; + a++; + } else { + /* a could be in the middle of an unmatching utf8 codepoint, + * so we need to march it on to the next character beginning, */ + do { + a++; + } while (0x80 == (0xc0 & *a)); + + /* reset offset too as we found a mismatch */ + offset = 0; + } + } + } + + /* found a match at the end of *a, so didn't get a chance to test it */ + if (0 < offset) { + chars++; + src += offset; + continue; + } + + /* if a got to its terminating null byte, then we didn't find a match. + * Return the current number of matched utf8 codepoints */ + if ('\0' == *a) { + return chars; + } + } + + return chars; +} + +utf8_constexpr14_impl utf8_int8_t *utf8str(const utf8_int8_t *haystack, + const utf8_int8_t *needle) { + utf8_int32_t throwaway_codepoint = 0; + + /* if needle has no utf8 codepoints before the null terminating + * byte then return haystack */ + if ('\0' == *needle) { + return (utf8_int8_t *)haystack; + } + + while ('\0' != *haystack) { + const utf8_int8_t *maybeMatch = haystack; + const utf8_int8_t *n = needle; + + while (*haystack == *n && (*haystack != '\0' && *n != '\0')) { + n++; + haystack++; + } + + if ('\0' == *n) { + /* we found the whole utf8 string for needle in haystack at + * maybeMatch, so return it */ + return (utf8_int8_t *)maybeMatch; + } else { + /* h could be in the middle of an unmatching utf8 codepoint, + * so we need to march it on to the next character beginning + * starting from the current character */ + haystack = utf8codepoint(maybeMatch, &throwaway_codepoint); + } + } + + /* no match */ + return utf8_null; +} + +utf8_constexpr14_impl utf8_int8_t *utf8casestr(const utf8_int8_t *haystack, + const utf8_int8_t *needle) { + /* if needle has no utf8 codepoints before the null terminating + * byte then return haystack */ + if ('\0' == *needle) { + return (utf8_int8_t *)haystack; + } + + for (;;) { + const utf8_int8_t *maybeMatch = haystack; + const utf8_int8_t *n = needle; + utf8_int32_t h_cp = 0, n_cp = 0; + + /* Get the next code point and track it */ + const utf8_int8_t *nextH = haystack = utf8codepoint(haystack, &h_cp); + n = utf8codepoint(n, &n_cp); + + while ((0 != h_cp) && (0 != n_cp)) { + h_cp = utf8lwrcodepoint(h_cp); + n_cp = utf8lwrcodepoint(n_cp); + + /* if we find a mismatch, bail out! */ + if (h_cp != n_cp) { + break; + } + + haystack = utf8codepoint(haystack, &h_cp); + n = utf8codepoint(n, &n_cp); + } + + if (0 == n_cp) { + /* we found the whole utf8 string for needle in haystack at + * maybeMatch, so return it */ + return (utf8_int8_t *)maybeMatch; + } + + if (0 == h_cp) { + /* no match */ + return utf8_null; + } + + /* Roll back to the next code point in the haystack to test */ + haystack = nextH; + } +} + +utf8_constexpr14_impl utf8_int8_t *utf8valid(const utf8_int8_t *str) { + return utf8nvalid(str, SIZE_MAX); +} + +utf8_constexpr14_impl utf8_int8_t *utf8nvalid(const utf8_int8_t *str, + size_t n) { + const utf8_int8_t *t = str; + size_t consumed = 0, remained = 0; + + while ((void)(consumed = (size_t)(str - t)), consumed < n && '\0' != *str) { + remained = n - consumed; + + if (0xf0 == (0xf8 & *str)) { + /* ensure that there's 4 bytes or more remained */ + if (remained < 4) { + return (utf8_int8_t *)str; + } + + /* ensure each of the 3 following bytes in this 4-byte + * utf8 codepoint began with 0b10xxxxxx */ + if ((0x80 != (0xc0 & str[1])) || (0x80 != (0xc0 & str[2])) || + (0x80 != (0xc0 & str[3]))) { + return (utf8_int8_t *)str; + } + + /* ensure that our utf8 codepoint ended after 4 bytes */ + if (0x80 == (0xc0 & str[4])) { + return (utf8_int8_t *)str; + } + + /* ensure that the top 5 bits of this 4-byte utf8 + * codepoint were not 0, as then we could have used + * one of the smaller encodings */ + if ((0 == (0x07 & str[0])) && (0 == (0x30 & str[1]))) { + return (utf8_int8_t *)str; + } + + /* 4-byte utf8 code point (began with 0b11110xxx) */ + str += 4; + } else if (0xe0 == (0xf0 & *str)) { + /* ensure that there's 3 bytes or more remained */ + if (remained < 3) { + return (utf8_int8_t *)str; + } + + /* ensure each of the 2 following bytes in this 3-byte + * utf8 codepoint began with 0b10xxxxxx */ + if ((0x80 != (0xc0 & str[1])) || (0x80 != (0xc0 & str[2]))) { + return (utf8_int8_t *)str; + } + + /* ensure that our utf8 codepoint ended after 3 bytes */ + if (0x80 == (0xc0 & str[3])) { + return (utf8_int8_t *)str; + } + + /* ensure that the top 5 bits of this 3-byte utf8 + * codepoint were not 0, as then we could have used + * one of the smaller encodings */ + if ((0 == (0x0f & str[0])) && (0 == (0x20 & str[1]))) { + return (utf8_int8_t *)str; + } + + /* 3-byte utf8 code point (began with 0b1110xxxx) */ + str += 3; + } else if (0xc0 == (0xe0 & *str)) { + /* ensure that there's 2 bytes or more remained */ + if (remained < 2) { + return (utf8_int8_t *)str; + } + + /* ensure the 1 following byte in this 2-byte + * utf8 codepoint began with 0b10xxxxxx */ + if (0x80 != (0xc0 & str[1])) { + return (utf8_int8_t *)str; + } + + /* ensure that our utf8 codepoint ended after 2 bytes */ + if (0x80 == (0xc0 & str[2])) { + return (utf8_int8_t *)str; + } + + /* ensure that the top 4 bits of this 2-byte utf8 + * codepoint were not 0, as then we could have used + * one of the smaller encodings */ + if (0 == (0x1e & str[0])) { + return (utf8_int8_t *)str; + } + + /* 2-byte utf8 code point (began with 0b110xxxxx) */ + str += 2; + } else if (0x00 == (0x80 & *str)) { + /* 1-byte ascii (began with 0b0xxxxxxx) */ + str += 1; + } else { + /* we have an invalid 0b1xxxxxxx utf8 code point entry */ + return (utf8_int8_t *)str; + } + } + + return utf8_null; +} + +int utf8makevalid(utf8_int8_t *str, const utf8_int32_t replacement) { + utf8_int8_t *read = str; + utf8_int8_t *write = read; + const utf8_int8_t r = (utf8_int8_t)replacement; + utf8_int32_t codepoint = 0; + + if (replacement > 0x7f) { + return -1; + } + + while ('\0' != *read) { + if (0xf0 == (0xf8 & *read)) { + /* ensure each of the 3 following bytes in this 4-byte + * utf8 codepoint began with 0b10xxxxxx */ + if ((0x80 != (0xc0 & read[1])) || (0x80 != (0xc0 & read[2])) || + (0x80 != (0xc0 & read[3]))) { + *write++ = r; + read++; + continue; + } + + /* 4-byte utf8 code point (began with 0b11110xxx) */ + read = utf8codepoint(read, &codepoint); + write = utf8catcodepoint(write, codepoint, 4); + } else if (0xe0 == (0xf0 & *read)) { + /* ensure each of the 2 following bytes in this 3-byte + * utf8 codepoint began with 0b10xxxxxx */ + if ((0x80 != (0xc0 & read[1])) || (0x80 != (0xc0 & read[2]))) { + *write++ = r; + read++; + continue; + } + + /* 3-byte utf8 code point (began with 0b1110xxxx) */ + read = utf8codepoint(read, &codepoint); + write = utf8catcodepoint(write, codepoint, 3); + } else if (0xc0 == (0xe0 & *read)) { + /* ensure the 1 following byte in this 2-byte + * utf8 codepoint began with 0b10xxxxxx */ + if (0x80 != (0xc0 & read[1])) { + *write++ = r; + read++; + continue; + } + + /* 2-byte utf8 code point (began with 0b110xxxxx) */ + read = utf8codepoint(read, &codepoint); + write = utf8catcodepoint(write, codepoint, 2); + } else if (0x00 == (0x80 & *read)) { + /* 1-byte ascii (began with 0b0xxxxxxx) */ + read = utf8codepoint(read, &codepoint); + write = utf8catcodepoint(write, codepoint, 1); + } else { + /* if we got here then we've got a dangling continuation (0b10xxxxxx) */ + *write++ = r; + read++; + continue; + } + } + + *write = '\0'; + + return 0; +} + +utf8_constexpr14_impl utf8_int8_t * +utf8codepoint(const utf8_int8_t *utf8_restrict str, + utf8_int32_t *utf8_restrict out_codepoint) { + if (0xf0 == (0xf8 & str[0])) { + /* 4 byte utf8 codepoint */ + *out_codepoint = ((0x07 & str[0]) << 18) | ((0x3f & str[1]) << 12) | + ((0x3f & str[2]) << 6) | (0x3f & str[3]); + str += 4; + } else if (0xe0 == (0xf0 & str[0])) { + /* 3 byte utf8 codepoint */ + *out_codepoint = + ((0x0f & str[0]) << 12) | ((0x3f & str[1]) << 6) | (0x3f & str[2]); + str += 3; + } else if (0xc0 == (0xe0 & str[0])) { + /* 2 byte utf8 codepoint */ + *out_codepoint = ((0x1f & str[0]) << 6) | (0x3f & str[1]); + str += 2; + } else { + /* 1 byte utf8 codepoint otherwise */ + *out_codepoint = str[0]; + str += 1; + } + + return (utf8_int8_t *)str; +} + +utf8_constexpr14_impl size_t utf8codepointcalcsize(const utf8_int8_t *str) { + if (0xf0 == (0xf8 & str[0])) { + /* 4 byte utf8 codepoint */ + return 4; + } else if (0xe0 == (0xf0 & str[0])) { + /* 3 byte utf8 codepoint */ + return 3; + } else if (0xc0 == (0xe0 & str[0])) { + /* 2 byte utf8 codepoint */ + return 2; + } + + /* 1 byte utf8 codepoint otherwise */ + return 1; +} + +utf8_constexpr14_impl size_t utf8codepointsize(utf8_int32_t chr) { + if (0 == ((utf8_int32_t)0xffffff80 & chr)) { + return 1; + } else if (0 == ((utf8_int32_t)0xfffff800 & chr)) { + return 2; + } else if (0 == ((utf8_int32_t)0xffff0000 & chr)) { + return 3; + } else { /* if (0 == ((int)0xffe00000 & chr)) { */ + return 4; + } +} + +utf8_int8_t *utf8catcodepoint(utf8_int8_t *str, utf8_int32_t chr, size_t n) { + if (0 == ((utf8_int32_t)0xffffff80 & chr)) { + /* 1-byte/7-bit ascii + * (0b0xxxxxxx) */ + if (n < 1) { + return utf8_null; + } + str[0] = (utf8_int8_t)chr; + str += 1; + } else if (0 == ((utf8_int32_t)0xfffff800 & chr)) { + /* 2-byte/11-bit utf8 code point + * (0b110xxxxx 0b10xxxxxx) */ + if (n < 2) { + return utf8_null; + } + str[0] = (utf8_int8_t)(0xc0 | (utf8_int8_t)((chr >> 6) & 0x1f)); + str[1] = (utf8_int8_t)(0x80 | (utf8_int8_t)(chr & 0x3f)); + str += 2; + } else if (0 == ((utf8_int32_t)0xffff0000 & chr)) { + /* 3-byte/16-bit utf8 code point + * (0b1110xxxx 0b10xxxxxx 0b10xxxxxx) */ + if (n < 3) { + return utf8_null; + } + str[0] = (utf8_int8_t)(0xe0 | (utf8_int8_t)((chr >> 12) & 0x0f)); + str[1] = (utf8_int8_t)(0x80 | (utf8_int8_t)((chr >> 6) & 0x3f)); + str[2] = (utf8_int8_t)(0x80 | (utf8_int8_t)(chr & 0x3f)); + str += 3; + } else { /* if (0 == ((int)0xffe00000 & chr)) { */ + /* 4-byte/21-bit utf8 code point + * (0b11110xxx 0b10xxxxxx 0b10xxxxxx 0b10xxxxxx) */ + if (n < 4) { + return utf8_null; + } + str[0] = (utf8_int8_t)(0xf0 | (utf8_int8_t)((chr >> 18) & 0x07)); + str[1] = (utf8_int8_t)(0x80 | (utf8_int8_t)((chr >> 12) & 0x3f)); + str[2] = (utf8_int8_t)(0x80 | (utf8_int8_t)((chr >> 6) & 0x3f)); + str[3] = (utf8_int8_t)(0x80 | (utf8_int8_t)(chr & 0x3f)); + str += 4; + } + + return str; +} + +utf8_constexpr14_impl int utf8islower(utf8_int32_t chr) { + return chr != utf8uprcodepoint(chr); +} + +utf8_constexpr14_impl int utf8isupper(utf8_int32_t chr) { + return chr != utf8lwrcodepoint(chr); +} + +void utf8lwr(utf8_int8_t *utf8_restrict str) { + utf8_int32_t cp = 0; + utf8_int8_t *pn = utf8codepoint(str, &cp); + + while (cp != 0) { + const utf8_int32_t lwr_cp = utf8lwrcodepoint(cp); + const size_t size = utf8codepointsize(lwr_cp); + + if (lwr_cp != cp) { + utf8catcodepoint(str, lwr_cp, size); + } + + str = pn; + pn = utf8codepoint(str, &cp); + } +} + +void utf8upr(utf8_int8_t *utf8_restrict str) { + utf8_int32_t cp = 0; + utf8_int8_t *pn = utf8codepoint(str, &cp); + + while (cp != 0) { + const utf8_int32_t lwr_cp = utf8uprcodepoint(cp); + const size_t size = utf8codepointsize(lwr_cp); + + if (lwr_cp != cp) { + utf8catcodepoint(str, lwr_cp, size); + } + + str = pn; + pn = utf8codepoint(str, &cp); + } +} + +utf8_constexpr14_impl utf8_int32_t utf8lwrcodepoint(utf8_int32_t cp) { + if (((0x0041 <= cp) && (0x005a >= cp)) || + ((0x00c0 <= cp) && (0x00d6 >= cp)) || + ((0x00d8 <= cp) && (0x00de >= cp)) || + ((0x0391 <= cp) && (0x03a1 >= cp)) || + ((0x03a3 <= cp) && (0x03ab >= cp)) || + ((0x0410 <= cp) && (0x042f >= cp))) { + cp += 32; + } else if ((0x0400 <= cp) && (0x040f >= cp)) { + cp += 80; + } else if (((0x0100 <= cp) && (0x012f >= cp)) || + ((0x0132 <= cp) && (0x0137 >= cp)) || + ((0x014a <= cp) && (0x0177 >= cp)) || + ((0x0182 <= cp) && (0x0185 >= cp)) || + ((0x01a0 <= cp) && (0x01a5 >= cp)) || + ((0x01de <= cp) && (0x01ef >= cp)) || + ((0x01f8 <= cp) && (0x021f >= cp)) || + ((0x0222 <= cp) && (0x0233 >= cp)) || + ((0x0246 <= cp) && (0x024f >= cp)) || + ((0x03d8 <= cp) && (0x03ef >= cp)) || + ((0x0460 <= cp) && (0x0481 >= cp)) || + ((0x048a <= cp) && (0x04ff >= cp))) { + cp |= 0x1; + } else if (((0x0139 <= cp) && (0x0148 >= cp)) || + ((0x0179 <= cp) && (0x017e >= cp)) || + ((0x01af <= cp) && (0x01b0 >= cp)) || + ((0x01b3 <= cp) && (0x01b6 >= cp)) || + ((0x01cd <= cp) && (0x01dc >= cp))) { + cp += 1; + cp &= ~0x1; + } else { + switch (cp) { + default: + break; + case 0x0178: + cp = 0x00ff; + break; + case 0x0243: + cp = 0x0180; + break; + case 0x018e: + cp = 0x01dd; + break; + case 0x023d: + cp = 0x019a; + break; + case 0x0220: + cp = 0x019e; + break; + case 0x01b7: + cp = 0x0292; + break; + case 0x01c4: + cp = 0x01c6; + break; + case 0x01c7: + cp = 0x01c9; + break; + case 0x01ca: + cp = 0x01cc; + break; + case 0x01f1: + cp = 0x01f3; + break; + case 0x01f7: + cp = 0x01bf; + break; + case 0x0187: + cp = 0x0188; + break; + case 0x018b: + cp = 0x018c; + break; + case 0x0191: + cp = 0x0192; + break; + case 0x0198: + cp = 0x0199; + break; + case 0x01a7: + cp = 0x01a8; + break; + case 0x01ac: + cp = 0x01ad; + break; + case 0x01af: + cp = 0x01b0; + break; + case 0x01b8: + cp = 0x01b9; + break; + case 0x01bc: + cp = 0x01bd; + break; + case 0x01f4: + cp = 0x01f5; + break; + case 0x023b: + cp = 0x023c; + break; + case 0x0241: + cp = 0x0242; + break; + case 0x03fd: + cp = 0x037b; + break; + case 0x03fe: + cp = 0x037c; + break; + case 0x03ff: + cp = 0x037d; + break; + case 0x037f: + cp = 0x03f3; + break; + case 0x0386: + cp = 0x03ac; + break; + case 0x0388: + cp = 0x03ad; + break; + case 0x0389: + cp = 0x03ae; + break; + case 0x038a: + cp = 0x03af; + break; + case 0x038c: + cp = 0x03cc; + break; + case 0x038e: + cp = 0x03cd; + break; + case 0x038f: + cp = 0x03ce; + break; + case 0x0370: + cp = 0x0371; + break; + case 0x0372: + cp = 0x0373; + break; + case 0x0376: + cp = 0x0377; + break; + case 0x03f4: + cp = 0x03b8; + break; + case 0x03cf: + cp = 0x03d7; + break; + case 0x03f9: + cp = 0x03f2; + break; + case 0x03f7: + cp = 0x03f8; + break; + case 0x03fa: + cp = 0x03fb; + break; + } + } + + return cp; +} + +utf8_constexpr14_impl utf8_int32_t utf8uprcodepoint(utf8_int32_t cp) { + if (((0x0061 <= cp) && (0x007a >= cp)) || + ((0x00e0 <= cp) && (0x00f6 >= cp)) || + ((0x00f8 <= cp) && (0x00fe >= cp)) || + ((0x03b1 <= cp) && (0x03c1 >= cp)) || + ((0x03c3 <= cp) && (0x03cb >= cp)) || + ((0x0430 <= cp) && (0x044f >= cp))) { + cp -= 32; + } else if ((0x0450 <= cp) && (0x045f >= cp)) { + cp -= 80; + } else if (((0x0100 <= cp) && (0x012f >= cp)) || + ((0x0132 <= cp) && (0x0137 >= cp)) || + ((0x014a <= cp) && (0x0177 >= cp)) || + ((0x0182 <= cp) && (0x0185 >= cp)) || + ((0x01a0 <= cp) && (0x01a5 >= cp)) || + ((0x01de <= cp) && (0x01ef >= cp)) || + ((0x01f8 <= cp) && (0x021f >= cp)) || + ((0x0222 <= cp) && (0x0233 >= cp)) || + ((0x0246 <= cp) && (0x024f >= cp)) || + ((0x03d8 <= cp) && (0x03ef >= cp)) || + ((0x0460 <= cp) && (0x0481 >= cp)) || + ((0x048a <= cp) && (0x04ff >= cp))) { + cp &= ~0x1; + } else if (((0x0139 <= cp) && (0x0148 >= cp)) || + ((0x0179 <= cp) && (0x017e >= cp)) || + ((0x01af <= cp) && (0x01b0 >= cp)) || + ((0x01b3 <= cp) && (0x01b6 >= cp)) || + ((0x01cd <= cp) && (0x01dc >= cp))) { + cp -= 1; + cp |= 0x1; + } else { + switch (cp) { + default: + break; + case 0x00ff: + cp = 0x0178; + break; + case 0x0180: + cp = 0x0243; + break; + case 0x01dd: + cp = 0x018e; + break; + case 0x019a: + cp = 0x023d; + break; + case 0x019e: + cp = 0x0220; + break; + case 0x0292: + cp = 0x01b7; + break; + case 0x01c6: + cp = 0x01c4; + break; + case 0x01c9: + cp = 0x01c7; + break; + case 0x01cc: + cp = 0x01ca; + break; + case 0x01f3: + cp = 0x01f1; + break; + case 0x01bf: + cp = 0x01f7; + break; + case 0x0188: + cp = 0x0187; + break; + case 0x018c: + cp = 0x018b; + break; + case 0x0192: + cp = 0x0191; + break; + case 0x0199: + cp = 0x0198; + break; + case 0x01a8: + cp = 0x01a7; + break; + case 0x01ad: + cp = 0x01ac; + break; + case 0x01b0: + cp = 0x01af; + break; + case 0x01b9: + cp = 0x01b8; + break; + case 0x01bd: + cp = 0x01bc; + break; + case 0x01f5: + cp = 0x01f4; + break; + case 0x023c: + cp = 0x023b; + break; + case 0x0242: + cp = 0x0241; + break; + case 0x037b: + cp = 0x03fd; + break; + case 0x037c: + cp = 0x03fe; + break; + case 0x037d: + cp = 0x03ff; + break; + case 0x03f3: + cp = 0x037f; + break; + case 0x03ac: + cp = 0x0386; + break; + case 0x03ad: + cp = 0x0388; + break; + case 0x03ae: + cp = 0x0389; + break; + case 0x03af: + cp = 0x038a; + break; + case 0x03cc: + cp = 0x038c; + break; + case 0x03cd: + cp = 0x038e; + break; + case 0x03ce: + cp = 0x038f; + break; + case 0x0371: + cp = 0x0370; + break; + case 0x0373: + cp = 0x0372; + break; + case 0x0377: + cp = 0x0376; + break; + case 0x03d1: + cp = 0x0398; + break; + case 0x03d7: + cp = 0x03cf; + break; + case 0x03f2: + cp = 0x03f9; + break; + case 0x03f8: + cp = 0x03f7; + break; + case 0x03fb: + cp = 0x03fa; + break; + } + } + + return cp; +} + +utf8_constexpr14_impl utf8_int8_t * +utf8rcodepoint(const utf8_int8_t *utf8_restrict str, + utf8_int32_t *utf8_restrict out_codepoint) { + const utf8_int8_t *s = (const utf8_int8_t *)str; + + if (0xf0 == (0xf8 & s[0])) { + /* 4 byte utf8 codepoint */ + *out_codepoint = ((0x07 & s[0]) << 18) | ((0x3f & s[1]) << 12) | + ((0x3f & s[2]) << 6) | (0x3f & s[3]); + } else if (0xe0 == (0xf0 & s[0])) { + /* 3 byte utf8 codepoint */ + *out_codepoint = + ((0x0f & s[0]) << 12) | ((0x3f & s[1]) << 6) | (0x3f & s[2]); + } else if (0xc0 == (0xe0 & s[0])) { + /* 2 byte utf8 codepoint */ + *out_codepoint = ((0x1f & s[0]) << 6) | (0x3f & s[1]); + } else { + /* 1 byte utf8 codepoint otherwise */ + *out_codepoint = s[0]; + } + + do { + s--; + } while ((0 != (0x80 & s[0])) && (0x80 == (0xc0 & s[0]))); + + return (utf8_int8_t *)s; +} + +#undef utf8_restrict +#undef utf8_constexpr14 +#undef utf8_null + +#ifdef __cplusplus +} /* extern "C" */ +#endif + +#if defined(__clang__) +#pragma clang diagnostic pop +#endif + +#endif /* SHEREDOM_UTF8_H_INCLUDED */ \ No newline at end of file diff --git a/components/ui/fonts.h b/components/ui/fonts.h new file mode 100644 index 0000000..8f96d72 --- /dev/null +++ b/components/ui/fonts.h @@ -0,0 +1,24 @@ +#ifndef EEZ_LVGL_UI_FONTS_H +#define EEZ_LVGL_UI_FONTS_H + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +#ifndef EXT_FONT_DESC_T +#define EXT_FONT_DESC_T +typedef struct _ext_font_desc_t { + const char *name; + const void *font_ptr; +} ext_font_desc_t; +#endif + +extern ext_font_desc_t fonts[]; + +#ifdef __cplusplus +} +#endif + +#endif /*EEZ_LVGL_UI_FONTS_H*/ \ No newline at end of file diff --git a/components/ui/images.c b/components/ui/images.c new file mode 100644 index 0000000..38d810c --- /dev/null +++ b/components/ui/images.c @@ -0,0 +1,5 @@ +#include "images.h" + +const ext_img_desc_t images[1] = { + 0 +}; \ No newline at end of file diff --git a/components/ui/images.h b/components/ui/images.h new file mode 100644 index 0000000..3aa52ad --- /dev/null +++ b/components/ui/images.h @@ -0,0 +1,24 @@ +#ifndef EEZ_LVGL_UI_IMAGES_H +#define EEZ_LVGL_UI_IMAGES_H + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +#ifndef EXT_IMG_DESC_T +#define EXT_IMG_DESC_T +typedef struct _ext_img_desc_t { + const char *name; + const lv_img_dsc_t *img_dsc; +} ext_img_desc_t; +#endif + +extern const ext_img_desc_t images[1]; + +#ifdef __cplusplus +} +#endif + +#endif /*EEZ_LVGL_UI_IMAGES_H*/ \ No newline at end of file diff --git a/components/ui/screens.c b/components/ui/screens.c new file mode 100644 index 0000000..afb466b --- /dev/null +++ b/components/ui/screens.c @@ -0,0 +1,154 @@ +#include + +#include "screens.h" +#include "images.h" +#include "fonts.h" +#include "actions.h" +#include "vars.h" +#include "styles.h" +#include "ui.h" + +#include + +objects_t objects; + +static const char *screen_names[] = { "Main" }; +static const char *object_names[] = { "main" }; + +// +// Event handlers +// + +lv_obj_t *tick_value_change_obj; + +// +// Screens +// + +void create_screen_main() { + void *flowState = getFlowState(0, 0); + (void)flowState; + lv_obj_t *obj = lv_obj_create(0); + objects.main = obj; + lv_obj_set_pos(obj, 0, 0); + lv_obj_set_size(obj, 240, 240); + lv_obj_set_style_bg_color(obj, lv_color_hex(0xff075d00), LV_PART_MAIN | LV_STATE_DEFAULT); + { + lv_obj_t *parent_obj = obj; + { + lv_obj_t *obj = lv_label_create(parent_obj); + lv_obj_set_pos(obj, 75, 103); + lv_obj_set_size(obj, LV_SIZE_CONTENT, LV_SIZE_CONTENT); + lv_label_set_text(obj, "Hello, world!"); + } + } + + tick_screen_main(); +} + +void tick_screen_main() { + void *flowState = getFlowState(0, 0); + (void)flowState; +} + +typedef void (*tick_screen_func_t)(); +tick_screen_func_t tick_screen_funcs[] = { + tick_screen_main, +}; +void tick_screen(int screen_index) { + tick_screen_funcs[screen_index](); +} +void tick_screen_by_id(enum ScreensEnum screenId) { + tick_screen_funcs[screenId - 1](); +} + +// +// Fonts +// + +ext_font_desc_t fonts[] = { +#if LV_FONT_MONTSERRAT_8 + { "MONTSERRAT_8", &lv_font_montserrat_8 }, +#endif +#if LV_FONT_MONTSERRAT_10 + { "MONTSERRAT_10", &lv_font_montserrat_10 }, +#endif +#if LV_FONT_MONTSERRAT_12 + { "MONTSERRAT_12", &lv_font_montserrat_12 }, +#endif +#if LV_FONT_MONTSERRAT_14 + { "MONTSERRAT_14", &lv_font_montserrat_14 }, +#endif +#if LV_FONT_MONTSERRAT_16 + { "MONTSERRAT_16", &lv_font_montserrat_16 }, +#endif +#if LV_FONT_MONTSERRAT_18 + { "MONTSERRAT_18", &lv_font_montserrat_18 }, +#endif +#if LV_FONT_MONTSERRAT_20 + { "MONTSERRAT_20", &lv_font_montserrat_20 }, +#endif +#if LV_FONT_MONTSERRAT_22 + { "MONTSERRAT_22", &lv_font_montserrat_22 }, +#endif +#if LV_FONT_MONTSERRAT_24 + { "MONTSERRAT_24", &lv_font_montserrat_24 }, +#endif +#if LV_FONT_MONTSERRAT_26 + { "MONTSERRAT_26", &lv_font_montserrat_26 }, +#endif +#if LV_FONT_MONTSERRAT_28 + { "MONTSERRAT_28", &lv_font_montserrat_28 }, +#endif +#if LV_FONT_MONTSERRAT_30 + { "MONTSERRAT_30", &lv_font_montserrat_30 }, +#endif +#if LV_FONT_MONTSERRAT_32 + { "MONTSERRAT_32", &lv_font_montserrat_32 }, +#endif +#if LV_FONT_MONTSERRAT_34 + { "MONTSERRAT_34", &lv_font_montserrat_34 }, +#endif +#if LV_FONT_MONTSERRAT_36 + { "MONTSERRAT_36", &lv_font_montserrat_36 }, +#endif +#if LV_FONT_MONTSERRAT_38 + { "MONTSERRAT_38", &lv_font_montserrat_38 }, +#endif +#if LV_FONT_MONTSERRAT_40 + { "MONTSERRAT_40", &lv_font_montserrat_40 }, +#endif +#if LV_FONT_MONTSERRAT_42 + { "MONTSERRAT_42", &lv_font_montserrat_42 }, +#endif +#if LV_FONT_MONTSERRAT_44 + { "MONTSERRAT_44", &lv_font_montserrat_44 }, +#endif +#if LV_FONT_MONTSERRAT_46 + { "MONTSERRAT_46", &lv_font_montserrat_46 }, +#endif +#if LV_FONT_MONTSERRAT_48 + { "MONTSERRAT_48", &lv_font_montserrat_48 }, +#endif +}; + +// +// +// + +void create_screens() { + + eez_flow_init_fonts(fonts, sizeof(fonts) / sizeof(ext_font_desc_t)); + +// Set default LVGL theme + lv_display_t *dispp = lv_display_get_default(); + lv_theme_t *theme = lv_theme_default_init(dispp, lv_palette_main(LV_PALETTE_BLUE), lv_palette_main(LV_PALETTE_RED), false, LV_FONT_DEFAULT); + lv_display_set_theme(dispp, theme); + + // Initialize screens + eez_flow_init_screen_names(screen_names, sizeof(screen_names) / sizeof(const char *)); + eez_flow_init_object_names(object_names, sizeof(object_names) / sizeof(const char *)); + + // Create screens + create_screen_main(); +} \ No newline at end of file diff --git a/components/ui/screens.h b/components/ui/screens.h new file mode 100644 index 0000000..dc8ff8d --- /dev/null +++ b/components/ui/screens.h @@ -0,0 +1,36 @@ +#ifndef EEZ_LVGL_UI_SCREENS_H +#define EEZ_LVGL_UI_SCREENS_H + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +// Screens + +enum ScreensEnum { + _SCREEN_ID_FIRST = 1, + SCREEN_ID_MAIN = 1, + _SCREEN_ID_LAST = 1 +}; + +typedef struct _objects_t { + lv_obj_t *main; +} objects_t; + +extern objects_t objects; + +void create_screen_main(); +void tick_screen_main(); + +void tick_screen_by_id(enum ScreensEnum screenId); +void tick_screen(int screen_index); + +void create_screens(); + +#ifdef __cplusplus +} +#endif + +#endif /*EEZ_LVGL_UI_SCREENS_H*/ \ No newline at end of file diff --git a/components/ui/structs.h b/components/ui/structs.h new file mode 100644 index 0000000..bf3a76d --- /dev/null +++ b/components/ui/structs.h @@ -0,0 +1,13 @@ +#ifndef EEZ_LVGL_UI_STRUCTS_H +#define EEZ_LVGL_UI_STRUCTS_H + +#include "eez-flow.h" + +#include +#include + +#include "vars.h" + +using namespace eez; + +#endif /*EEZ_LVGL_UI_STRUCTS_H*/ \ No newline at end of file diff --git a/components/ui/styles.c b/components/ui/styles.c new file mode 100644 index 0000000..78cf152 --- /dev/null +++ b/components/ui/styles.c @@ -0,0 +1,6 @@ +#include "styles.h" +#include "images.h" +#include "fonts.h" + +#include "ui.h" +#include "screens.h" \ No newline at end of file diff --git a/components/ui/styles.h b/components/ui/styles.h new file mode 100644 index 0000000..f4d548d --- /dev/null +++ b/components/ui/styles.h @@ -0,0 +1,14 @@ +#ifndef EEZ_LVGL_UI_STYLES_H +#define EEZ_LVGL_UI_STYLES_H + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +#ifdef __cplusplus +} +#endif + +#endif /*EEZ_LVGL_UI_STYLES_H*/ \ No newline at end of file diff --git a/components/ui/ui.c b/components/ui/ui.c new file mode 100644 index 0000000..80fda2c --- /dev/null +++ b/components/ui/ui.c @@ -0,0 +1,47 @@ +#include "ui.h" +#include "screens.h" +#include "images.h" +#include "actions.h" +#include "vars.h" + +// ASSETS DEFINITION +const uint8_t assets[332] = { + 0x7E, 0x45, 0x45, 0x5A, 0x03, 0x00, 0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0x24, 0x00, 0x00, 0x00, + 0x24, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0xF0, 0x00, 0xF0, 0x00, 0x01, 0x00, 0x00, 0x00, 0x24, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, + 0x20, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x1C, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, + 0xD4, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0C, 0x00, 0x00, 0x00, + 0x00, 0x00, 0xFF, 0xFF, 0x10, 0x00, 0x00, 0x00, 0x3C, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x34, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x44, 0x65, 0x66, 0x61, 0x75, 0x6C, 0x74, 0x00, 0x08, 0x00, 0x00, 0x00, + 0x24, 0x00, 0x00, 0x00, 0x30, 0x75, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x03, 0x00, 0x00, 0x00, 0x30, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0xFF, 0xFF, 0x00, 0x00, 0x31, 0x75, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x03, 0x00, 0x00, 0x00, 0x1C, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0xFF, 0xFF, 0x00, 0x00, 0x18, 0x00, 0x00, 0x00, 0x18, 0x00, 0x00, 0x00, 0x18, 0x00, 0x00, 0x00, + 0x18, 0x00, 0x00, 0x00, 0x18, 0x00, 0x00, 0x00, 0x18, 0x00, 0x00, 0x00, 0x00, 0xE0, 0x00, 0x00, + 0x00, 0xE0, 0x00, 0x00, 0x00, 0xE0, 0x00, 0x00, 0x00, 0xE0, 0x00, 0x00, 0x00, 0xE0, 0x00, 0x00, + 0x00, 0xE0, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x14, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 +}; + +native_var_t native_vars[] = { + { NATIVE_VAR_TYPE_NONE, 0, 0 }, +}; + +ActionExecFunc actions[] = { + 0 +}; + +void ui_init() { + eez_flow_init(assets, sizeof(assets), (lv_obj_t **)&objects, sizeof(objects), images, sizeof(images), actions); +} + +void ui_tick() { + eez_flow_tick(); + tick_screen(g_currentScreen); +} \ No newline at end of file diff --git a/components/ui/ui.h b/components/ui/ui.h new file mode 100644 index 0000000..a712694 --- /dev/null +++ b/components/ui/ui.h @@ -0,0 +1,21 @@ +#ifndef EEZ_LVGL_UI_GUI_H +#define EEZ_LVGL_UI_GUI_H + +#include + +#include "eez-flow.h" + +#ifdef __cplusplus +extern "C" { +#endif + +extern const uint8_t assets[332]; + +void ui_init(); +void ui_tick(); + +#ifdef __cplusplus +} +#endif + +#endif // EEZ_LVGL_UI_GUI_H \ No newline at end of file diff --git a/components/ui/vars.c b/components/ui/vars.c new file mode 100644 index 0000000..80032e0 --- /dev/null +++ b/components/ui/vars.c @@ -0,0 +1,2 @@ +#include +#include diff --git a/components/ui/vars.h b/components/ui/vars.h new file mode 100644 index 0000000..4a7c185 --- /dev/null +++ b/components/ui/vars.h @@ -0,0 +1,25 @@ +#ifndef EEZ_LVGL_UI_VARS_H +#define EEZ_LVGL_UI_VARS_H + +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +// enum declarations + +// Flow global variables + +enum FlowGlobalVariables { + FLOW_GLOBAL_VARIABLE_NONE +}; + +// Native global variables + +#ifdef __cplusplus +} +#endif + +#endif /*EEZ_LVGL_UI_VARS_H*/ \ No newline at end of file diff --git a/components/ws2812/include/ws2812.h b/components/ws2812/include/ws2812.h index 6f9b646..756ffce 100644 --- a/components/ws2812/include/ws2812.h +++ b/components/ws2812/include/ws2812.h @@ -1 +1,9 @@ +#ifdef __cplusplus +extern "C" { +#endif + void ws2812_start_task(void); + +#ifdef __cplusplus +} +#endif diff --git a/components/ws2812/ws2812.c b/components/ws2812/ws2812.c index caa1a41..7462b81 100644 --- a/components/ws2812/ws2812.c +++ b/components/ws2812/ws2812.c @@ -1,3 +1,7 @@ +#ifdef __cplusplus +extern "C" { +#endif + #include #include #include "freertos/FreeRTOS.h" @@ -106,4 +110,8 @@ void ws2812_start_task(void) if (ret != pdPASS) { ESP_LOGE(TAG, "Failed to create ws2812 blink task"); } -} \ No newline at end of file +} + +#ifdef __cplusplus +} +#endif \ No newline at end of file diff --git a/dependencies.lock b/dependencies.lock index ec7e58e..5d39d6a 100644 --- a/dependencies.lock +++ b/dependencies.lock @@ -1,4 +1,84 @@ dependencies: + esp-idf-lib/esp_idf_lib_helpers: + component_hash: 689853bb8993434f9556af0f2816e808bf77b5d22100144b21f3519993daf237 + dependencies: [] + source: + registry_url: https://components.espressif.com + type: service + targets: + - esp32 + - esp32c2 + - esp32c3 + - esp32c5 + - esp32c6 + - esp32c61 + - esp32h2 + - esp32p4 + - esp32s2 + - esp32s3 + version: 1.4.0 + esp-idf-lib/i2cdev: + component_hash: 9e22a91420695242ceac2c00788820ae45826224d38ef003a1a894367c55ede4 + dependencies: + - name: esp-idf-lib/esp_idf_lib_helpers + registry_url: https://components.espressif.com + require: private + version: '*' + source: + registry_url: https://components.espressif.com + type: service + targets: + - esp32 + - esp32c2 + - esp32c3 + - esp32c5 + - esp32c6 + - esp32c61 + - esp32h2 + - esp32p4 + - esp32s2 + - esp32s3 + version: 2.1.1 + esp-idf-lib/sgm58031: + component_hash: d15fdb3bb3ae4ef362d2df854e8ad0a849d6a8aa38f21d19f90a15c1532b7368 + dependencies: + - name: esp-idf-lib/esp_idf_lib_helpers + registry_url: https://components.espressif.com + require: private + version: '*' + - name: esp-idf-lib/i2cdev + registry_url: https://components.espressif.com + require: private + version: '*' + source: + registry_url: https://components.espressif.com/ + type: service + targets: + - esp32 + - esp32c2 + - esp32c3 + - esp32c5 + - esp32c6 + - esp32c61 + - esp32h2 + - esp32p4 + - esp32s2 + - esp32s3 + version: 1.0.7 + espressif/esp_lvgl_port: + component_hash: b6360960f47b6776462e7092861b3ea66477ffb762a01baa0aecbb3d74cd50f4 + dependencies: + - name: idf + require: private + version: '>=5.1' + - name: lvgl/lvgl + registry_url: https://components.espressif.com + require: public + version: '>=8,<10' + source: + registry_url: https://components.espressif.com/ + type: service + version: 2.7.2 espressif/led_strip: component_hash: 28621486f77229aaf81c71f5e15d6fbf36c2949cf11094e07090593e659e7639 dependencies: @@ -13,9 +93,18 @@ dependencies: source: type: idf version: 5.5.2 + lvgl/lvgl: + component_hash: 184e532558c1c45fefed631f3e235423d22582aafb4630f3e8885c35281a49ae + dependencies: [] + source: + registry_url: https://components.espressif.com + type: service + version: 9.5.0 direct_dependencies: +- esp-idf-lib/sgm58031 +- espressif/esp_lvgl_port - espressif/led_strip - idf -manifest_hash: f9f27a7bfd490a8f252ea50084db6f87c986509746a1f4fe61b5ce5bb0e44fcb +manifest_hash: 14278fd31e9ff4511f755b1131ffdfd07d9a4e2621c691e92ed4bd78b79ee84f target: esp32c3 version: 2.0.0 diff --git a/main/CMakeLists.txt b/main/CMakeLists.txt index bed4e72..c3fe673 100755 --- a/main/CMakeLists.txt +++ b/main/CMakeLists.txt @@ -1,3 +1,3 @@ -idf_component_register(SRCS "main.c" +idf_component_register(SRCS "main.cpp" INCLUDE_DIRS "." - REQUIRES ws2812 wifi-connect) + REQUIRES ws2812 wifi-connect esp_lvgl_port lvgl_st7789_use ui) diff --git a/main/idf_component.yml b/main/idf_component.yml index 88e3292..7d481b7 100644 --- a/main/idf_component.yml +++ b/main/idf_component.yml @@ -15,3 +15,5 @@ dependencies: # # All dependencies of `main` are public by default. # public: true espressif/led_strip: ^3.0.3 + espressif/esp_lvgl_port: ^2.7.2 + esp-idf-lib/sgm58031: ^1.0.7 diff --git a/main/main.c b/main/main.c deleted file mode 100755 index b70c5e9..0000000 --- a/main/main.c +++ /dev/null @@ -1,14 +0,0 @@ -#include "freertos/FreeRTOS.h" -#include "freertos/task.h" -#include "wifi-connect.h" -#include "ws2812.h" - -void app_main(void) -{ - wifi_connect_init(); // 初始化 Wi-Fi 配网模块 - ws2812_start_task(); // 启动 WS2812 LED 灯控制任务 - for(;;) - { - vTaskDelay(100000); - } -} diff --git a/main/main.cpp b/main/main.cpp new file mode 100755 index 0000000..245eb5a --- /dev/null +++ b/main/main.cpp @@ -0,0 +1,50 @@ +#include "freertos/FreeRTOS.h" +#include "freertos/task.h" +#include "wifi-connect.h" +#include "ws2812.h" +#include "esp_lvgl_port.h" // 包含 LVGL 端口头文件,提供 LVGL 相关的类型定义和函数声明 +#include "lvgl_st7789_use.h" // 使用EEZStudio提供的LVGL和ST7789驱动,便于后续扩展 +#include "ui.h" // 使用EEZStudio提供的ui组件,便于后续扩展 +#include "screens.h" // 包含屏幕ID定义 + + +static void ui_task(void *arg); // 声明UI更新任务函数 + +extern "C" void app_main(void) +{ + wifi_connect_init(); // 初始化 Wi-Fi 配网模块 + + start_lvgl_demo(); // 初始化 LVGL 和 LCD 显示 + // 初始化 UI 组件(需在 LVGL 锁内进行对象创建) + lvgl_port_lock(0); + ui_init(); + lvgl_port_unlock(); + // 创建一个 FreeRTOS 任务来更新 UI 显示(字符串拼接需要更多栈空间) + xTaskCreate(ui_task, "ui_task", 4096, NULL, 10, NULL); + ws2812_start_task(); // 启动 WS2812 LED 灯控制任务,大小为 4096 字节,优先级为 5 + for (;;) + { + vTaskDelay(100000); + } +} + +/** + * @brief UI 任务函数 + * + * 负责定期驱动 UI 刷新,并实现屏幕自动轮播。 + * + * @param arg 任务参数(未使用) + */ +static void ui_task(void *arg) +{ + (void)arg; + + for (;;) + { + + lvgl_port_lock(0); + ui_tick(); + lvgl_port_unlock(); + vTaskDelay(pdMS_TO_TICKS(20)); + } +} \ No newline at end of file