add event read and shell
authorkyz <kongyuzhong@google.com>
Tue, 27 Oct 2026 11:18:54 +0000 (19:18 +0800)
committerkyz <kongyuzhong@google.com>
Tue, 27 Oct 2026 11:18:54 +0000 (19:18 +0800)
22 files changed:
APP/BSP/dev_can.c
APP/BSP/dev_uart.c
APP/BSP/dev_uart.h
APP/mb/event.c [new file with mode: 0644]
APP/mb/event.h [new file with mode: 0644]
APP/mb/reg_cache.c
APP/shell/cherryrl/chry_readline.c [new file with mode: 0644]
APP/shell/cherryrl/chry_readline.h [new file with mode: 0644]
APP/shell/cherryrl/chry_readline_config.h [new file with mode: 0644]
APP/shell/cherryrl/chry_readline_keycode.h [new file with mode: 0644]
APP/shell/chry_shell.c [new file with mode: 0644]
APP/shell/chry_shell.h [new file with mode: 0644]
APP/shell/csh.h [new file with mode: 0644]
APP/shell/csh_config.h [new file with mode: 0644]
APP/shell/shell.c [new file with mode: 0644]
APP/shell/shell.h [new file with mode: 0644]
APP/user_app.c
APP/user_mb.c
APP/user_mb.h [new file with mode: 0644]
Linker_Scatter_File/SWM34S_Link_SPI_Flash.sct
Linker_Scatter_File/SWM34S_NoLink_SPI_Flash.sct
dispboard_app.uvprojx

index 033b6af3afcc67840c56d8cbbb4756631080619c..f55caf2319fc7749ee6d0a6c40ace3f050f3d136 100644 (file)
@@ -23,7 +23,7 @@
 #define CAN_MAX_DATA        8
 
 /* CAN 原始收发数据 log 开关: 1=开启打印, 0=关闭 */
-#define CAN_DATA_LOG_EN     1
+#define CAN_DATA_LOG_EN     0
 
 static volatile can_rx_callback_t s_rx_cb = NULL;
 
index 7e5e4556aac4767020e92781fb7668a128fad69e..4331fa04cc518b7f1d5042e503d799e243e7b3a6 100644 (file)
@@ -87,6 +87,28 @@ static void uart_port_switch(void)
 }
 #endif
 
+/* UART1 Shell 接收字节回调 (BSP 不依赖 Shell, 通过函数指针注册) */
+static uart_rx_byte_cb_t s_rx_byte_cb = NULL;
+
+void uart_set_rx_byte_cb(uart_rx_byte_cb_t cb)
+{
+    s_rx_byte_cb = cb;
+}
+
+/* UART1 中断: 读空 FIFO, 逐字节调用 Shell 回调 */
+void UART1_Handler(void)
+{
+    uint8_t byte;
+
+    UART_INTClr(UART1, UART_IT_RX_THR | UART_IT_RX_TOUT);
+    while (!UART_IsRXFIFOEmpty(UART1)) {
+        UART_ReadByte(UART1, &byte);
+        if (s_rx_byte_cb) {
+            s_rx_byte_cb(byte);
+        }
+    }
+}
+
 void UART3_Handler(void)
 {
     uint8_t byte; 
@@ -173,15 +195,27 @@ void uart_debug_init(void)
     UART_initStruct.Parity = UART_PARITY_NONE;
     UART_initStruct.StopBits = UART_STOP_1BIT;
 
-    UART_initStruct.RXThreshold = 3;
-    UART_initStruct.RXThresholdIEn = 0;
     UART_initStruct.TXThreshold = 3;
     UART_initStruct.TXThresholdIEn = 0;
     UART_initStruct.TimeoutTime = 10;
+
+#if SHELL_ENABLE
+    /* Shell 模式: 打开 UART1 接收, 供中断逐字节回调 */
+    UART_initStruct.RXThreshold = 1;
+    UART_initStruct.RXThresholdIEn = 1;
+    UART_initStruct.TimeoutIEn = 1;
+#else
+    UART_initStruct.RXThreshold = 3;
+    UART_initStruct.RXThresholdIEn = 0;
     UART_initStruct.TimeoutIEn = 0;
+#endif
 
     UART_Init(DEBUG_UART_X, &UART_initStruct);
     UART_Open(DEBUG_UART_X);
+
+#if SHELL_ENABLE
+    UART_INTEn(DEBUG_UART_X, UART_IT_RX_THR | UART_IT_RX_TOUT);
+#endif
 }
 
 /**
@@ -241,10 +275,17 @@ FILE __stdout;
 
 PUTCHAR_PROTOTYPE /* 实现串口发送一个字节数据的函数 */
 {
+#if SHELL_ENABLE
+    /* 启用 Shell 后关闭 printf 调试串口输出 */
+    (void)f;
+    (void)ch;
+    return ch;
+#else
     UART_WriteByte(DEBUG_UART_X, ch);
 
     while (UART_IsTXBusy(DEBUG_UART_X))
         ;
 
     return ch;
-}
+#endif
+}
\ No newline at end of file
index b2a0ac0c1a71c66ba229c72eea95523955391071..04627e490a93dfaec9c927af52d38c15571f578c 100644 (file)
 
 #include "SWM341.h"
 
+#define SHELL_ENABLE 0
+
+/* ============================ Shell 总开关 ============================
+ * 启用 Shell(SHELL_ENABLE=1) 后, UART1 作为 Shell 交互串口:
+ *   1. 关闭 printf 的调试串口输出 (见 dev_uart.c 中 fputc/_ttywrch);
+ *   2. 打开 UART1 接收中断, 每收一字节回调 shell.c 注册的字节回调。
+ * 若需在编译命令行覆盖, 请在该文件包含之前定义。 */
+#ifndef SHELL_ENABLE
+#define SHELL_ENABLE 1
+#endif
+
+/* UART 接收中断的字节回调类型: 每收到一字节调用一次 */
+typedef void (*uart_rx_byte_cb_t)(uint8_t byte);
+
+/**
+ * @brief   注册/注销 UART1 接收字节回调
+ * @param   cb  : 回调函数指针, 传 NULL 表示注销
+ * @note    仅在 SHELL_ENABLE 下生效
+ */
+void uart_set_rx_byte_cb(uart_rx_byte_cb_t cb);
+
 /**
  * @brief   配置串口打印调试日志的端口
  */
@@ -45,4 +66,4 @@ void uart_debug_init(void);
  */
 void uart_send_msg(UART_TypeDef *uart_x, const uint8_t *src_buf, const uint32_t num_bytes);
 
-#endif //__DEV_UART_H__
+#endif //__DEV_UART_H__
\ No newline at end of file
diff --git a/APP/mb/event.c b/APP/mb/event.c
new file mode 100644 (file)
index 0000000..40d92dc
--- /dev/null
@@ -0,0 +1,243 @@
+/*
+ * event.c - 事件报告读取 (变位/启动动作报告, MCU/FreeRTOS 移植版)
+ *
+ * 通过 event_zone_t 参数化事件区属性, 用同一套增量同步引擎读取:
+ *   - 变位报告       10000~14095, 最多 512 条, 每条 8  寄存器
+ *   - 启动/动作报告  20000~24095, 最多 128 条, 每条 32 寄存器
+ *
+ * 滚动存储规则:
+ *   最新记录首地址 = base + (最新指针 - 1) * regs; 指针为 0 时换到区末。
+ *   数量(总数)与指针从实时区寄存器读取, 不同事件区地址不同。
+ *
+ * TDDO: 本阶段仅读取原始寄存器到内部缓冲区, 不解析。
+ *
+ * 受 CAN 分片限制, mb_read_regs 单次最多读约 92 个寄存器, 故逐条读取。
+ */
+
+#include "event.h"
+
+#include <string.h>
+#include "reg_cache.h"
+#include "mb_api.h"
+#include "user_mb.h"
+#include "mem_sdram.h"
+
+/* 单次 Modbus 读取超时(ms), 与 user_mb 轮询超时保持一致 */
+#define EVENT_RW_TIMEOUT_MS  500*4
+
+/* 设备协议指针 → 物理槽位换算宏:
+ * 协议中 ptr 为 1..max (0 表示 max), 对应物理槽 0..max-1。
+ * 转换后得到的值与 event_read_one 的 slot 一致, 且即"最新一条记录"所在槽,
+ * 之后整体代码统一用该槽位索引, 不再按协议做其它换算。 */
+#define PTR_TO_SLOT(p, max) \
+    (((uint16_t)(p)) == 0 ? (uint16_t)((max) - 1) : (uint16_t)((p) - 1))
+
+/* ---- 事件区通用上下文 (一个事件区一套状态与缓冲), tag 与 event.h 前向声明一致 ---- */
+struct event_ctx {
+    const event_zone_t *zone;   /* 事件区属性 */
+    uint16_t *buf;              /* 环形缓冲(SDRAM), 容量 max*regs, 镜像设备槽位 */
+    uint16_t  total;            /* 缓冲内当前条数 */
+    uint16_t  last_ptr;         /* 上次同步时设备端指针(槽位) */
+    uint8_t   inited;           /* 是否已完成首次全量同步 */
+};
+
+/* 变位报告区上下文 (buffer 在 SDRAM 动态分配) */
+static uint16_t s_chg_buf[EVENT_CHG_MAX * EVENT_CHG_REG_PER] __attribute__((section(".SDRAM1"))); //512x8
+static uint16_t s_act_buf[EVENT_ACT_MAX * EVENT_ACT_REG_PER] __attribute__((section(".SDRAM1"))); //128x32
+
+static const  event_zone_t chg_zone = {
+        EVENT_CHG_BASE, EVENT_CHG_MAX, EVENT_CHG_REG_PER,
+        EVENT_REG_CHG_TOTAL, EVENT_REG_CHG_PTR
+};
+
+static const  event_zone_t act_zone = {
+        EVENT_ACT_BASE, EVENT_ACT_MAX, EVENT_ACT_REG_PER,
+        EVENT_REG_ACT_TOTAL, EVENT_REG_ACT_PTR
+};
+
+static event_ctx_t s_chg_ctx = { 
+    &chg_zone,
+    s_chg_buf,
+    0,
+    0,
+    0
+};
+
+static event_ctx_t s_act_ctx = { 
+    &act_zone,
+    s_act_buf,
+    0,
+    0,
+    0
+};
+
+/* 两个事件报告区属性定义 (见 event.h) */
+const event_zone_t EVENT_ZONE_CHG = {
+    EVENT_CHG_BASE, EVENT_CHG_MAX, EVENT_CHG_REG_PER,
+    EVENT_REG_CHG_TOTAL, EVENT_REG_CHG_PTR
+};
+const event_zone_t EVENT_ZONE_ACT = {
+    EVENT_ACT_BASE, EVENT_ACT_MAX, EVENT_ACT_REG_PER,
+    EVENT_REG_ACT_TOTAL, EVENT_REG_ACT_PTR
+};
+
+/* 单条读取助手: 按物理槽位读取 1 条事件到 ctx 缓冲。
+ * slot = 物理槽位 (0..max-1), 即设备端滚动存储的槽, 同时用作
+ *         Modbus 读取地址与 buf 索引 (buf 为物理镜像, 与设备槽一一对应)。 */
+static int event_read_one(event_ctx_t *ctx, uint16_t slot)
+{
+    uint16_t temp[EVENT_MAX_REG_PER];
+
+    if (!ctx || slot >= ctx->zone->max)
+        return -1;
+
+    if (mb_read_regs(USER_MB_TARGET_SLAVE,
+                     (uint16_t)(ctx->zone->base + (uint32_t)slot * ctx->zone->regs),
+                     ctx->zone->regs, temp, EVENT_RW_TIMEOUT_MS) < 0)
+        return EVENT_ERR_READ;
+
+    /* 缓冲按逻辑序号紧凑排列: 直接写入 buf[slot] */
+    memcpy(ctx->buf + (uint32_t)slot * ctx->zone->regs,
+           temp, ctx->zone->regs * sizeof(uint16_t));
+    return EVENT_OK;
+}
+
+/* ======================== 增量同步读取引擎 ========================
+ * 本地 buf 为设备滚动物理槽的镜像 (buf[物理槽] 与设备槽一一对应)。
+ * 协议指针经 PTR_TO_SLOT 转换为"最新记录所在物理槽" ptr (0..max-1)。
+ * 每次同步只读取【新增】槽位:
+ *   - 首次同步(inited=0): 从最旧槽 (ptr+1-total) 起全量读 total 条;
+ *   - 增量同步: 仅读 (last_ptr, ptr] 之间新增槽位;
+ *   - total==0 (设备被清除): 清空本地并重置基准。
+ */
+int event_sync_read(event_ctx_t *ctx)
+{
+    if (!ctx || !ctx->zone)
+        return EVENT_ERR_PARAM;
+
+    const event_zone_t *zone = ctx->zone;
+
+    uint16_t total = reg_get_value(zone->total_reg);
+
+    /* 协议指针 → 物理槽位 (0..max-1, 即最新记录所在槽) */
+    uint16_t ptr = PTR_TO_SLOT(reg_get_value(zone->ptr_reg), zone->max);
+
+    if (total > zone->max || ptr >= zone->max) {
+        /* 无效参数: total 或 ptr 超出范围 */
+        printf("event_sync_read: total %d, ptr %d\n", total, ptr);
+        return EVENT_ERR_PARAM;
+    }
+
+    /* 状态未变化: 无新增 */
+    if (ctx->inited && total == ctx->total && ptr == ctx->last_ptr)
+        return (int)ctx->total;
+
+    if (total == 0) {
+        /* 设备端事件已清空: 清空本地, 丢弃基准 */
+        ctx->total    = 0;
+        ctx->last_ptr = 0;
+        ctx->inited   = 0;
+        return 0;
+    }
+
+    if (!ctx->inited ) {
+        /* 首次同步, 全部读出。 */
+        for (uint16_t slot = 0; slot < total; slot++) {
+            if (event_read_one(ctx, slot) != EVENT_OK) {
+                printf("event_sync_read: slot %d, err %d\n", slot, EVENT_ERR_READ);
+                return EVENT_ERR_READ;
+            }
+            vTaskDelay(1);
+        }
+    } else {
+        /* 增量同步: 仅读取 (last_ptr, ptr] 之间的新增槽位 */
+        uint16_t n = (uint16_t)((ptr + zone->max - ctx->last_ptr) % zone->max);
+        for (uint16_t i = 0; i < n; i++) {
+            uint16_t slot = (uint16_t)((ctx->last_ptr + 1 + i) % zone->max);
+            if (event_read_one(ctx, slot) != EVENT_OK) {
+                printf("event_sync_read: slot %d, err %d\n", slot, EVENT_ERR_READ);
+                return EVENT_ERR_READ;
+            }
+            vTaskDelay(1);
+        }
+    }
+
+    ctx->total    = total;
+    ctx->last_ptr = ptr;
+    ctx->inited   = 1;
+    return (int)ctx->total;
+}
+
+/* ======================== 通用访问接口 ======================== */
+uint16_t event_sync_total(const event_zone_t *zone)
+{
+    if (!zone)
+        return 0;
+    event_ctx_t *ctx = (zone == &EVENT_ZONE_CHG) ? &s_chg_ctx : &s_act_ctx;
+    return ctx->total;
+}
+
+int event_sync_get(const event_zone_t *zone, uint16_t idx, uint16_t count,
+                   uint16_t *out)
+{
+    if (!zone || !out)
+        return EVENT_ERR_PARAM;
+    event_ctx_t *ctx = (zone == &EVENT_ZONE_CHG) ? &s_chg_ctx : &s_act_ctx;
+
+    if (idx >= ctx->total || count == 0)
+        return 0;
+    if (count > ctx->total - idx)
+        count = (uint16_t)(ctx->total - idx);
+
+    const uint16_t max  = zone->max;
+    const uint16_t regs = zone->regs;
+
+    /* 物理镜像: 第 idx 条(0=最早)所在物理槽 = oldest + idx */
+    uint16_t oldest = (uint16_t)((ctx->last_ptr + max + 1 - ctx->total) % max);
+    uint16_t slot   = (uint16_t)((oldest + idx) % max);
+
+    /* 环内到槽尾的条数, 不足则跨环分两段拷贝 */
+    uint16_t first = (uint16_t)(max - slot);
+    if (first > count)
+        first = count;
+
+    memcpy(out, ctx->buf + (uint32_t)slot * regs,
+           (size_t)first * regs * sizeof(uint16_t));
+    if (first < count) {
+        memcpy(out + (size_t)first * regs, ctx->buf,
+               (size_t)(count - first) * regs * sizeof(uint16_t));
+    }
+    return (int)count;
+}
+
+/* ======================== 变位报告便捷封装 ======================== */
+int event_read_change(void)
+{
+    return event_sync_read(&s_chg_ctx);
+}
+
+uint16_t event_get_change_total(void)
+{
+    return event_sync_total(&EVENT_ZONE_CHG);
+}
+
+int event_get_change(uint16_t idx, uint16_t count, uint16_t (*out)[EVENT_CHG_REG_PER])
+{
+    return event_sync_get(&EVENT_ZONE_CHG, idx, count, (uint16_t *)out);
+}
+
+/* ======================== 启动/动作报告便捷封装 ======================== */
+int event_read_action(void)
+{
+    return event_sync_read(&s_act_ctx);
+}
+
+uint16_t event_get_action_total(void)
+{
+    return event_sync_total(&EVENT_ZONE_ACT);
+}
+
+int event_get_action(uint16_t idx, uint16_t count, uint16_t (*out)[EVENT_ACT_REG_PER])
+{
+    return event_sync_get(&EVENT_ZONE_ACT, idx, count, (uint16_t *)out);
+}
\ No newline at end of file
diff --git a/APP/mb/event.h b/APP/mb/event.h
new file mode 100644 (file)
index 0000000..4c57139
--- /dev/null
@@ -0,0 +1,99 @@
+/*
+ * event.h - 事件报告读取接口 (变位报告, MCU/FreeRTOS 移植版)
+ *
+ * 变位报告存储在事件数据区 10000~14095 (滚动存储, 最多 512 条, 每条 8 个寄存器):
+ *   ver, year, month_day, hour, minute_second, microsecond, type, state
+ *
+ * 滚动存储规则 (参照 BDM120):
+ *   最新记录首地址 = 10000 + (最新变位报告指针 - 1) * 8; 指针为 0 时首地址 = 14088
+ *   其中 最新变位报告指针 从实时区寄存器 28(chg_report_ptr) 获取,
+ *        最新变位报告总数 从实时区寄存器 27(chg_report_total) 获取。
+ *
+ * 第一步: 仅读取原始寄存器数据到内部缓冲区 (不解析)。
+ */
+
+#ifndef MB_EVENT_H
+#define MB_EVENT_H
+
+#include <stdint.h>
+#include <stdbool.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/* ---- 变位报告区参数 ---- */
+#define EVENT_CHG_BASE       10000   /* 变位报告区基址 */
+#define EVENT_CHG_MAX        512     /* 最多 512 条 */
+#define EVENT_CHG_REG_PER    8       /* 每条 8 寄存器 */
+#define EVENT_REG_CHG_TOTAL  27      /* 变位报告总数 (实时区) */
+#define EVENT_REG_CHG_PTR    28      /* 变位报告指针 (实时区) */
+
+/* ---- 启动/动作报告区参数 ---- */
+#define EVENT_ACT_BASE       20000   /* 启动和动作报告区基址 */
+#define EVENT_ACT_MAX        128     /* 最多 128 条 */
+#define EVENT_ACT_REG_PER    32      /* 每条 32 寄存器 */
+#define EVENT_REG_ACT_TOTAL  25      /* 动作报告总数 (实时区) */
+#define EVENT_REG_ACT_PTR    26      /* 动作报告指针 (实时区) */
+
+/* 单区内最大每条寄存器数 (取动作报告 32 上限) */
+#define EVENT_MAX_REG_PER    EVENT_ACT_REG_PER
+
+/* 返回值: EVENT_OK 成功, 其它负数为错误码 */
+#define EVENT_OK        (0)
+#define EVENT_ERR_PARAM (-1)
+#define EVENT_ERR_READ  (-2)
+
+/* ---- 事件报告区通用描述 (参数化, 变位/启动报告共用同一读取引擎) ---- */
+typedef struct {
+    uint16_t base;      /* 事件数据区基址寄存器 */
+    uint16_t max;       /* 最多条数 */
+    uint16_t regs;      /* 每条寄存器数 */
+    uint16_t total_reg; /* 实时区: 报告总数寄存器地址 */
+    uint16_t ptr_reg;   /* 实时区: 报告指针寄存器地址 */
+} event_zone_t;
+
+/* 两个具体事件报告区 */
+extern const event_zone_t EVENT_ZONE_CHG;   /* 变位报告 10000/512/8  */
+extern const event_zone_t EVENT_ZONE_ACT;   /* 启动动作报告 20000/128/32 */
+
+/* 事件区上下文 (结构体在 event.c 内定义, 此处仅前向声明) */
+typedef struct event_ctx event_ctx_t;
+
+/* ======================== 内部通用接口 ========================
+ * 以下函数是通用事件读取引擎, 由 ctx 描述事件区上下文(含 zone 属性与缓冲),
+ * 变位/启动报告共用。缓冲按逻辑序号紧凑排布, 最早记录在 [0]。
+ */
+
+/** 通用读取: 同步 ctx 事件区事件到内部缓冲, 返回条数(0=无, 负数=错误)。 */
+int event_sync_read(event_ctx_t *ctx);
+
+/** 通用总数: 最近一次同步到的条数。 */
+uint16_t event_sync_total(const event_zone_t *zone);
+
+/**
+ * 通用获取: 取 zone 区原始数据片段 (out[0] 为最早)。
+ * @param idx    起始条序号 (0 为最早)
+ * @param count  欲获取的条数
+ * @param out    输出缓冲, 容量 >= count * regs 个 uint16
+ * @return 实际拷贝的条数; 参数非法返回负数错误码
+ */
+int event_sync_get(const event_zone_t *zone, uint16_t idx, uint16_t count,
+                   uint16_t *out);
+
+/* ======================== 变位报告 (512 x 8) 便捷封装 ======================== */
+int      event_read_change(void);                 /* = sync_read(Chg) */
+uint16_t event_get_change_total(void);            /* = sync_total(Chg) */
+int      event_get_change(uint16_t idx, uint16_t count,
+                          uint16_t (*out)[EVENT_CHG_REG_PER]);   /* = sync_get */
+
+/* ======================== 启动/动作报告 (128 x 32) 便捷封装 ======================== */
+int      event_read_action(void);                 /* = sync_read(Act) */
+uint16_t event_get_action_total(void);            /* = sync_total(Act) */
+int      event_get_action(uint16_t idx, uint16_t count,
+                          uint16_t (*out)[EVENT_ACT_REG_PER]);   /* = sync_get */
+
+#ifdef __cplusplus
+}
+#endif
+#endif /* MB_EVENT_H */
\ No newline at end of file
index 928f7536639239fedb5d0f2f9898524d0bc9c9e9..97f9ea79492587d717eeaecc1732990013d92bff 100644 (file)
@@ -63,6 +63,12 @@ static const reg_area_def_t POLL_AREAS[] = {
     {"增强板网络IP",     5000,    4},      /* 5000-5003 */
 };
 
+/* 事件数据区
+ * 变位报告10000~14095
+ * 启动和动作报告20000~24095
+ * 录波数据 0~1999 私有协议功能码67
+ */
+
 #define NUM_POLL_AREAS (sizeof(POLL_AREAS) / sizeof(POLL_AREAS[0]))
 
 /* ======================== 运行时缓存结构 ======================== */
diff --git a/APP/shell/cherryrl/chry_readline.c b/APP/shell/cherryrl/chry_readline.c
new file mode 100644 (file)
index 0000000..31683e8
--- /dev/null
@@ -0,0 +1,2355 @@
+/*
+ * Copyright (c) 2022, Egahp
+ *
+ * SPDX-License-Identifier: Apache-2.0
+ */
+
+#include <stdio.h>
+#include <stdarg.h>
+#include <stdlib.h>
+#include <string.h>
+#include <stdbool.h>
+#include "csh.h"
+
+#if defined(__CC_ARM) || defined(__CLANG_ARM) || defined(__GNUC__) || defined(__ADSPBLACKFIN__)
+#ifndef __unused
+#define __unused __attribute__((unused))
+#endif
+#else
+#ifndef __unused
+#define __unused
+#endif
+#endif
+
+#define chry_readline_waitkey(__rl, __c)            \
+    do {                                            \
+        while (0 == (__rl)->sget((__rl), (__c), 1)) \
+            ;                                       \
+    } while (0)
+
+#if defined(CONFIG_READLINE_NOBLOCK) && CONFIG_READLINE_NOBLOCK
+
+#define chry_readline_getkey(__rl, __c)                        \
+    do {                                                       \
+        (__rl)->noblock = 0 == (__rl)->sget((__rl), (__c), 1); \
+    } while (0)
+
+#else
+
+#define chry_readline_getkey chry_readline_waitkey
+
+#endif
+
+#if defined(CONFIG_READLINE_DEBUG) && CONFIG_READLINE_DEBUG
+
+#define CHRY_READLINE_PARAM_CHECK(__expr, __ret) \
+    do {                                         \
+        if (!(__expr)) {                         \
+            return __ret;                        \
+        }                                        \
+    } while (0)
+
+#define chry_readline_put(__rl, __pbuf, __size, __ret)          \
+    do {                                                        \
+        uint16_t _size_ = (__size);                             \
+        if (_size_ != (__rl)->sput((__rl), (__pbuf), _size_)) { \
+            return __ret;                                       \
+        }                                                       \
+    } while (0)
+
+#else
+
+#define CHRY_READLINE_PARAM_CHECK(__expr, __ret) ((void)0)
+
+#define chry_readline_put(__rl, __pbuf, __size, __ret) \
+    do {                                               \
+        (__rl)->sput((__rl), (__pbuf), (__size));      \
+    } while (0)
+
+#endif
+
+#define chry_readline_seqgen_ris chry_readline_seqgen_reset
+#define chry_readline_seqgen_cuu chry_readline_seqgen_cursor_up
+#define chry_readline_seqgen_cud chry_readline_seqgen_cursor_down
+#define chry_readline_seqgen_cuf chry_readline_seqgen_cursor_forward
+#define chry_readline_seqgen_cub chry_readline_seqgen_cursor_backward
+#define chry_readline_seqgen_cnl chry_readline_seqgen_cursor_nextline
+#define chry_readline_seqgen_cpl chry_readline_seqgen_cursor_prevline
+#define chry_readline_seqgen_cha chry_readline_seqgen_cursor_absolute
+#define chry_readline_seqgen_cup chry_readline_seqgen_cursor_position
+#define chry_readline_seqgen_ed  chry_readline_seqgen_erase_display
+#define chry_readline_seqgen_el  chry_readline_seqgen_erase_line
+#define chry_readline_seqgen_il  chry_readline_seqgen_insert_line
+#define chry_readline_seqgen_dl  chry_readline_seqgen_delete_line
+#define chry_readline_seqgen_dch chry_readline_seqgen_delete_char
+#define chry_readline_seqgen_ech chry_readline_seqgen_erase_char
+#define chry_readline_seqgen_su  chry_readline_seqgen_scroll_up
+#define chry_readline_seqgen_sd  chry_readline_seqgen_scroll_down
+#define chry_readline_seqgen_scp chry_readline_seqgen_save_cursor_position
+#define chry_readline_seqgen_rcp chry_readline_seqgen_restore_cursor_position
+#define chry_readline_seqgen_nsb chry_readline_seqgen_normal_screen
+#define chry_readline_seqgen_asb chry_readline_seqgen_alternate_screen
+#define chry_readline_seqgen_rss chry_readline_seqgen_report_screen_size
+
+static const uint8_t vtmap[25] = {
+    CHRY_READLINE_EXEC_NUL,  /*!< 0           */
+    CHRY_READLINE_EXEC_MVHM, /*!< 1  home     */
+    CHRY_READLINE_EXEC_NUL,  /*!< 2  insert   */
+    CHRY_READLINE_EXEC_DEL,  /*!< 3  delete   */
+    CHRY_READLINE_EXEC_MVED, /*!< 4  end      */
+    CHRY_READLINE_EXEC_NUL,  /*!< 5  page up  */
+    CHRY_READLINE_EXEC_NUL,  /*!< 6  page dn  */
+    CHRY_READLINE_EXEC_MVHM, /*!< 7  home     */
+    CHRY_READLINE_EXEC_MVED, /*!< 8  end      */
+    CHRY_READLINE_EXEC_NUL,  /*!< 9           */
+    CHRY_READLINE_EXEC_NUL,  /*!< 10          */
+    CHRY_READLINE_EXEC_F1,   /*!< 11 F1       */
+    CHRY_READLINE_EXEC_F2,   /*!< 12 F2       */
+    CHRY_READLINE_EXEC_F3,   /*!< 13 F3       */
+    CHRY_READLINE_EXEC_F4,   /*!< 14 F4       */
+    CHRY_READLINE_EXEC_F5,   /*!< 15 F5       */
+    CHRY_READLINE_EXEC_NUL,  /*!< 16          */
+    CHRY_READLINE_EXEC_F6,   /*!< 17 F6       */
+    CHRY_READLINE_EXEC_F7,   /*!< 18 F7       */
+    CHRY_READLINE_EXEC_F8,   /*!< 19 F8       */
+    CHRY_READLINE_EXEC_F9,   /*!< 20 F9       */
+    CHRY_READLINE_EXEC_F10,  /*!< 21 F10      */
+    CHRY_READLINE_EXEC_NUL,  /*!< 22          */
+    CHRY_READLINE_EXEC_F11,  /*!< 23 F11      */
+    CHRY_READLINE_EXEC_F12,  /*!< 24 F12      */
+};
+
+static const uint8_t xmap[20] = {
+    CHRY_READLINE_EXEC_NUL,  /*!<             */
+    CHRY_READLINE_EXEC_PRVH, /*!< A up        */
+    CHRY_READLINE_EXEC_NXTH, /*!< B down      */
+    CHRY_READLINE_EXEC_MVRT, /*!< C right     */
+    CHRY_READLINE_EXEC_MVLT, /*!< D left      */
+    CHRY_READLINE_EXEC_NUL,  /*!< E           */
+    CHRY_READLINE_EXEC_MVED, /*!< F end       */
+    CHRY_READLINE_EXEC_NUL,  /*!< G           */
+    CHRY_READLINE_EXEC_MVHM, /*!< H home      */
+    CHRY_READLINE_EXEC_NUL,  /*!< I           */
+    CHRY_READLINE_EXEC_NUL,  /*!< J           */
+    CHRY_READLINE_EXEC_NUL,  /*!< K           */
+    CHRY_READLINE_EXEC_NUL,  /*!< L           */
+    CHRY_READLINE_EXEC_NUL,  /*!< M           */
+    CHRY_READLINE_EXEC_NUL,  /*!< N           */
+    CHRY_READLINE_EXEC_NUL,  /*!< O           */
+    CHRY_READLINE_EXEC_F1,   /*!< P F1        */
+    CHRY_READLINE_EXEC_F2,   /*!< Q F2        */
+    CHRY_READLINE_EXEC_F3,   /*!< R F3        */
+    CHRY_READLINE_EXEC_F4    /*!< S F4        */
+};
+
+#if defined(CONFIG_READLINE_CTRLMAP) && CONFIG_READLINE_CTRLMAP
+static const uint8_t ctrlmap[32] = {
+#else
+static uint8_t ctrlmap[32] = {
+#endif
+    CHRY_READLINE_EXEC_NUL,     /*!< @ NUL */
+    CHRY_READLINE_EXEC_MVHM,    /*!< A SOH */
+    CHRY_READLINE_EXEC_MVLT,    /*!< B STX */
+    CHRY_READLINE_EXEC_SIGINT_, /*!< C ETX */
+    CHRY_READLINE_EXEC_EOF_,    /*!< D EOT */
+    CHRY_READLINE_EXEC_MVED,    /*!< E ENQ */
+    CHRY_READLINE_EXEC_MVRT,    /*!< F ACK */
+    CHRY_READLINE_EXEC_NUL,     /*!< G BEL */
+    CHRY_READLINE_EXEC_BS,      /*!< H BS  */
+    CHRY_READLINE_EXEC_CPLT,    /*!< I HT  */
+    CHRY_READLINE_EXEC_NLN,     /*!< J LF  */
+    CHRY_READLINE_EXEC_DELN,    /*!< K VT  */
+    CHRY_READLINE_EXEC_CLR,     /*!< L FF  */
+    CHRY_READLINE_EXEC_NLN,     /*!< M CR  */
+    CHRY_READLINE_EXEC_NXTH,    /*!< N SO  */
+    CHRY_READLINE_EXEC_NLN,     /*!< O SI  */
+    CHRY_READLINE_EXEC_PRVH,    /*!< P DLE */
+    CHRY_READLINE_EXEC_SIGCONT, /*!< Q DC1 */
+    CHRY_READLINE_EXEC_NUL,     /*!< R DC2 */
+    CHRY_READLINE_EXEC_SIGSTOP, /*!< S DC3 */
+    CHRY_READLINE_EXEC_NUL,     /*!< T DC4 */
+    CHRY_READLINE_EXEC_DHLN,    /*!< U NAK */
+    CHRY_READLINE_EXEC_NUL,     /*!< V SYN */
+    CHRY_READLINE_EXEC_DLWD,    /*!< W ETB */
+    CHRY_READLINE_EXEC_NUL,     /*!< X CAN */
+    CHRY_READLINE_EXEC_NUL,     /*!< Y EM  */
+    CHRY_READLINE_EXEC_SIGTSTP, /*!< Z SUB */
+    CHRY_READLINE_EXEC_NUL,     /*!< [ ESC */
+    CHRY_READLINE_EXEC_SIGQUIT, /*!< \ FS  */
+    CHRY_READLINE_EXEC_NUL,     /*!< ] GS  */
+    CHRY_READLINE_EXEC_SWNM,    /*!< ^ RS  */
+    CHRY_READLINE_EXEC_HELP,    /*!< - US  */
+};
+
+#if defined(CONFIG_READLINE_ALTMAP) && CONFIG_READLINE_ALTMAP
+static const uint8_t altmap[26] = {
+#else
+static uint8_t altmap[26] = {
+#endif
+    CHRY_READLINE_EXEC_NUL, /*!< A */
+    CHRY_READLINE_EXEC_NUL, /*!< B */
+    CHRY_READLINE_EXEC_NUL, /*!< C */
+    CHRY_READLINE_EXEC_NUL, /*!< D */
+    CHRY_READLINE_EXEC_NUL, /*!< E */
+    CHRY_READLINE_EXEC_NUL, /*!< F */
+    CHRY_READLINE_EXEC_NUL, /*!< G */
+    CHRY_READLINE_EXEC_NUL, /*!< H */
+    CHRY_READLINE_EXEC_NUL, /*!< I */
+    CHRY_READLINE_EXEC_NUL, /*!< J */
+    CHRY_READLINE_EXEC_NUL, /*!< K */
+    CHRY_READLINE_EXEC_NUL, /*!< L */
+    CHRY_READLINE_EXEC_NUL, /*!< M */
+    CHRY_READLINE_EXEC_NUL, /*!< N */
+    CHRY_READLINE_EXEC_NUL, /*!< O */
+    CHRY_READLINE_EXEC_NUL, /*!< P */
+    CHRY_READLINE_EXEC_NUL, /*!< Q */
+    CHRY_READLINE_EXEC_NUL, /*!< R */
+    CHRY_READLINE_EXEC_NUL, /*!< S */
+    CHRY_READLINE_EXEC_NUL, /*!< T */
+    CHRY_READLINE_EXEC_NUL, /*!< U */
+    CHRY_READLINE_EXEC_NUL, /*!< V */
+    CHRY_READLINE_EXEC_NUL, /*!< W */
+    CHRY_READLINE_EXEC_NUL, /*!< X */
+    CHRY_READLINE_EXEC_NUL, /*!< Y */
+    CHRY_READLINE_EXEC_NUL, /*!< Z */
+};
+
+/*****************************************************************************
+* @brief        print decimal integer (0 - 65535)
+*
+* @param[in]    buf         print buf
+* @param[in]    idx         print idx
+* @param[in]    value       16bit unsigned integer
+*
+*****************************************************************************/
+static void chry_readline_print_integer(uint8_t *buf, size_t *idx, uint16_t value)
+{
+    uint8_t *intbuf = (uint8_t[5]){};
+    uint8_t *outbuf = buf + *idx;
+    size_t count = 0;
+
+    do {
+        const uint8_t digit = (uint8_t)(value % 10);
+        *intbuf++ = (uint8_t)('0' + digit);
+        value /= 10;
+        count++;
+    } while (value);
+
+    do {
+        *outbuf++ = *--intbuf;
+        (*idx)++;
+    } while (--count);
+}
+
+/*****************************************************************************
+* @brief        parse decimal integer (0 - 65535)
+*
+* @param[in]    buf         parse buf
+* @param[out]   value       16bit unsigned integer pointer
+*
+*****************************************************************************/
+static void chry_readline_parse_integer(uint8_t *buf, uint16_t *value)
+{
+    *value = 0;
+
+    while (('0' <= *buf) && (*buf <= '9')) {
+        *value *= 10;
+        *value += *buf - '0';
+        buf++;
+    }
+}
+
+/*****************************************************************************
+* @brief        Reset to Initial State
+*****************************************************************************/
+__unused static void chry_readline_seqgen_reset(uint8_t *buf, size_t *idx)
+{
+    buf[*idx + 0] = '\e';
+    buf[*idx + 1] = 'c';
+    *idx += 2;
+}
+
+/*****************************************************************************
+* @brief        output csi prefix
+*****************************************************************************/
+__unused static void chry_readline_seqgen_csi(uint8_t *buf, size_t *idx)
+{
+    buf[*idx + 0] = '\e';
+    buf[*idx + 1] = '[';
+    *idx += 2;
+}
+
+/*****************************************************************************
+* @brief        output csi 0 pn
+*****************************************************************************/
+__unused static void chry_readline_seqgen_csi0(uint8_t *buf, size_t *idx, char c)
+{
+    chry_readline_seqgen_csi(buf, idx);
+    buf[(*idx)++] = c;
+}
+
+/*****************************************************************************
+* @brief        output csi 1 pn
+*****************************************************************************/
+__unused static void chry_readline_seqgen_csi1(uint8_t *buf, size_t *idx, char c, uint16_t pn)
+{
+    chry_readline_seqgen_csi(buf, idx);
+    chry_readline_print_integer(buf, idx, pn);
+    buf[(*idx)++] = c;
+}
+
+/*****************************************************************************
+* @brief        output csi 2 pn
+*****************************************************************************/
+__unused static void chry_readline_seqgen_csi2(uint8_t *buf, size_t *idx, char c, uint16_t pn, uint16_t pn2)
+{
+    chry_readline_seqgen_csi(buf, idx);
+    chry_readline_print_integer(buf, idx, pn);
+    buf[(*idx)++] = ';';
+    chry_readline_print_integer(buf, idx, pn2);
+    buf[(*idx)++] = c;
+}
+
+/*****************************************************************************
+* @brief        output csi 3 pn
+*****************************************************************************/
+__unused static void chry_readline_seqgen_csi3(uint8_t *buf, size_t *idx, char c, uint16_t pn, uint16_t pn2, uint16_t pn3)
+{
+    chry_readline_seqgen_csi(buf, idx);
+    chry_readline_print_integer(buf, idx, pn);
+    buf[(*idx)++] = ';';
+    chry_readline_print_integer(buf, idx, pn2);
+    buf[(*idx)++] = ';';
+    chry_readline_print_integer(buf, idx, pn3);
+    buf[(*idx)++] = c;
+}
+
+/*****************************************************************************
+* @brief        Cursor Up Pn Times (default = 1)
+*****************************************************************************/
+__unused static void chry_readline_seqgen_cursor_up(uint8_t *buf, size_t *idx, uint16_t pn)
+{
+    chry_readline_seqgen_csi1(buf, idx, 'A', pn);
+}
+
+/*****************************************************************************
+* @brief        Cursor Down Pn Times (default = 1)
+*****************************************************************************/
+__unused static void chry_readline_seqgen_cursor_down(uint8_t *buf, size_t *idx, uint16_t pn)
+{
+    chry_readline_seqgen_csi1(buf, idx, 'B', pn);
+}
+
+/*****************************************************************************
+* @brief        Cursor Forward Pn Times (default = 1)
+*****************************************************************************/
+__unused static void chry_readline_seqgen_cursor_forward(uint8_t *buf, size_t *idx, uint16_t pn)
+{
+    chry_readline_seqgen_csi1(buf, idx, 'C', pn);
+}
+
+/*****************************************************************************
+* @brief        Cursor Backward Pn Times (default = 1)
+*****************************************************************************/
+__unused static void chry_readline_seqgen_cursor_backward(uint8_t *buf, size_t *idx, uint16_t pn)
+{
+    chry_readline_seqgen_csi1(buf, idx, 'D', pn);
+}
+
+/*****************************************************************************
+* @brief        Cursor Next Line Pn Times (default = 1)
+*****************************************************************************/
+__unused static void chry_readline_seqgen_cursor_nextline(uint8_t *buf, size_t *idx, uint16_t pn)
+{
+    chry_readline_seqgen_csi1(buf, idx, 'E', pn);
+}
+
+/*****************************************************************************
+* @brief        Cursor Preceding Line Pn Times (default = 1)
+*****************************************************************************/
+__unused static void chry_readline_seqgen_cursor_prevline(uint8_t *buf, size_t *idx, uint16_t pn)
+{
+    chry_readline_seqgen_csi1(buf, idx, 'F', pn);
+}
+
+/*****************************************************************************
+* @brief        Cursor Character Absolute [column] (default = [row,1])
+*****************************************************************************/
+__unused static void chry_readline_seqgen_cursor_absolute(uint8_t *buf, size_t *idx, uint16_t pn)
+{
+    chry_readline_seqgen_csi1(buf, idx, 'G', pn);
+}
+
+/*****************************************************************************
+* @brief        Cursor Position [row;column] (default = [1,1])
+*****************************************************************************/
+__unused static void chry_readline_seqgen_cursor_position(uint8_t *buf, size_t *idx, uint16_t pn1, uint16_t pn2)
+{
+    chry_readline_seqgen_csi2(buf, idx, 'H', pn1, pn2);
+}
+
+/*****************************************************************************
+* @brief        Erase in Display
+*                   Pn = 0 → Erase Below (default)
+*                   Pn = 1 → Erase Above
+*                   Pn = 2 → Erase All
+*                   Pn = 3 → Erase Saved Lines (xterm)
+*****************************************************************************/
+__unused static void chry_readline_seqgen_erase_display(uint8_t *buf, size_t *idx, uint16_t pn)
+{
+    chry_readline_seqgen_csi1(buf, idx, 'J', pn);
+}
+
+/*****************************************************************************
+* @brief        Erase in Line
+*                   Pn = 0 → Erase to Right (default)
+*                   Pn = 1 → Erase to Left
+*                   Pn = 2 → Erase All
+*****************************************************************************/
+__unused static void chry_readline_seqgen_erase_line(uint8_t *buf, size_t *idx, uint16_t pn)
+{
+    chry_readline_seqgen_csi1(buf, idx, 'K', pn);
+}
+
+/*****************************************************************************
+* @brief        Insert Pn Line(s) (default = 1)
+*****************************************************************************/
+__unused static void chry_readline_seqgen_insert_line(uint8_t *buf, size_t *idx, uint16_t pn)
+{
+    chry_readline_seqgen_csi1(buf, idx, 'L', pn);
+}
+
+/*****************************************************************************
+* @brief        Delete Pn Line(s) (default = 1)
+*****************************************************************************/
+__unused static void chry_readline_seqgen_delete_line(uint8_t *buf, size_t *idx, uint16_t pn)
+{
+    chry_readline_seqgen_csi1(buf, idx, 'M', pn);
+}
+
+/*****************************************************************************
+* @brief        Delete Pn Character(s) (default = 1)
+*****************************************************************************/
+__unused static void chry_readline_seqgen_delete_char(uint8_t *buf, size_t *idx, uint16_t pn)
+{
+    chry_readline_seqgen_csi1(buf, idx, 'P', pn);
+}
+
+/*****************************************************************************
+* @brief        Erase Pn Character(s) (default = 1)
+*****************************************************************************/
+__unused static void chry_readline_seqgen_erase_char(uint8_t *buf, size_t *idx, uint16_t pn)
+{
+    chry_readline_seqgen_csi1(buf, idx, 'X', pn);
+}
+
+/*****************************************************************************
+* @brief        Scroll up Pn lines (default = 1)
+*****************************************************************************/
+__unused static void chry_readline_seqgen_scroll_up(uint8_t *buf, size_t *idx, uint16_t pn)
+{
+    chry_readline_seqgen_csi1(buf, idx, 'S', pn);
+}
+
+/*****************************************************************************
+* @brief        Scroll down Pn lines (default = 1)
+*****************************************************************************/
+__unused static void chry_readline_seqgen_scroll_down(uint8_t *buf, size_t *idx, uint16_t pn)
+{
+    chry_readline_seqgen_csi1(buf, idx, 'T', pn);
+}
+
+/*****************************************************************************
+* @brief        Save Current Cursor Position
+*****************************************************************************/
+__unused static void chry_readline_seqgen_save_cursor_position(uint8_t *buf, size_t *idx)
+{
+    chry_readline_seqgen_csi0(buf, idx, 's');
+}
+
+/*****************************************************************************
+* @brief        Restore Saved Cursor Position
+*****************************************************************************/
+__unused static void chry_readline_seqgen_restore_cursor_position(uint8_t *buf, size_t *idx)
+{
+    chry_readline_seqgen_csi0(buf, idx, 'u');
+}
+
+/*****************************************************************************
+* @brief        DEC Private Mode Reset use alternate screen buffer
+*****************************************************************************/
+__unused static void chry_readline_seqgen_alternate_screen(uint8_t *buf, size_t *idx)
+{
+    chry_readline_seqgen_csi(buf, idx);
+    buf[(*idx) + 0] = '?';
+    buf[(*idx) + 1] = '4';
+    buf[(*idx) + 2] = '7';
+    buf[(*idx) + 3] = 'h';
+    (*idx) += 4;
+}
+
+/*****************************************************************************
+* @brief        DEC Private Mode Set use normal screen buffer
+*****************************************************************************/
+__unused static void chry_readline_seqgen_normal_screen(uint8_t *buf, size_t *idx)
+{
+    chry_readline_seqgen_csi(buf, idx);
+    buf[(*idx) + 0] = '?';
+    buf[(*idx) + 1] = '4';
+    buf[(*idx) + 2] = '7';
+    buf[(*idx) + 3] = 'l';
+    (*idx) += 4;
+}
+
+/*****************************************************************************
+* @brief        Report the size of the text area in characters
+*               as CSI 8;row;column t
+*****************************************************************************/
+__unused static void chry_readline_seqgen_report_screen_size(uint8_t *buf, size_t *idx)
+{
+    chry_readline_seqgen_csi(buf, idx);
+    buf[(*idx) + 0] = '1';
+    buf[(*idx) + 1] = '8';
+    buf[(*idx) + 2] = 't';
+    (*idx) += 3;
+}
+
+/*****************************************************************************
+* @brief        refresh line
+* @retval int               0:Success -1:Error
+*****************************************************************************/
+int chry_readline_edit_refresh(chry_readline_t *rl)
+{
+    size_t idx;
+    uint8_t seq[16];
+
+    uint16_t curoff;
+    uint16_t pptoff;
+    uint16_t diff;
+
+    char *linebuff;
+    uint16_t linesize;
+
+    linebuff = rl->ln.buff->pbuf;
+
+    if (rl->ln.buff == NULL) {
+        linesize = 0;
+        curoff = 0;
+        pptoff = 0;
+    } else {
+        linesize = rl->ln.buff->size;
+        curoff = rl->ln.curoff;
+        pptoff = rl->ln.pptoff;
+    }
+
+    if ((pptoff + curoff) >= rl->term.col) {
+        diff = pptoff + curoff - rl->term.col + 1;
+        linebuff += diff;
+        linesize -= diff;
+        curoff -= diff;
+    }
+
+    if ((pptoff + linesize) > rl->term.col) {
+        linesize -= (pptoff + linesize) - rl->term.col;
+    }
+
+    linebuff[linesize] = '\0';
+
+    idx = 0;
+
+#if defined(CONFIG_READLINE_REFRESH_PROMPT) && CONFIG_READLINE_REFRESH_PROMPT
+    /*!< move to line start */
+    chry_readline_seqgen_cursor_absolute(seq, &idx, 0);
+    chry_readline_put(rl, seq, idx, -1);
+    /*!< output prompt */
+    chry_readline_put(rl, rl->prompt, rl->ln.pptlen, -1);
+#else
+    /*!< move to prompt end */
+    chry_readline_seqgen_cursor_absolute(seq, &idx, pptoff + 1);
+    chry_readline_put(rl, seq, idx, -1);
+#endif
+
+    if (!rl->ln.mask) {
+        /*!< output linebuff */
+        chry_readline_put(rl, linebuff, linesize, -1);
+    }
+
+    /*!< erase to end of display and restore cursor */
+    idx = 0;
+    chry_readline_seqgen_erase_display(seq, &idx, 0);
+    chry_readline_seqgen_cursor_absolute(seq, &idx, pptoff + curoff + 1);
+    chry_readline_put(rl, seq, idx, -1);
+
+    return 0;
+}
+
+/*****************************************************************************
+* @brief        erase to end of line
+*****************************************************************************/
+void chry_readline_erase_line(chry_readline_t *rl)
+{
+    size_t idx;
+    uint8_t seq[16];
+
+    idx = 0;
+
+    /*!< move to line start */
+    chry_readline_seqgen_cursor_absolute(seq, &idx, 0);
+    chry_readline_put(rl, seq, idx, );
+
+    /*!< erase to end of display and restore cursor */
+    idx = 0;
+    chry_readline_seqgen_erase_display(seq, &idx, 0);
+    chry_readline_seqgen_cursor_absolute(seq, &idx, 0);
+    chry_readline_put(rl, seq, idx, );
+}
+
+/*****************************************************************************
+* @brief        clear screen and refresh line
+* @retval int               0:Success -1:Error
+*****************************************************************************/
+int chry_readline_edit_clear(chry_readline_t *rl)
+{
+    chry_readline_put(rl, "\e[2J\e[1;1H", 10, -1);
+
+#if defined(CONFIG_READLINE_REFRESH_PROMPT) && CONFIG_READLINE_REFRESH_PROMPT
+    return chry_readline_edit_refresh(rl);
+#else
+    /*!< output prompt */
+    chry_readline_put(rl, rl->prompt, rl->ln.pptlen, -1);
+    return chry_readline_edit_refresh(rl);
+#endif
+}
+
+/*****************************************************************************
+* @brief        insert a character, (only support 0x20-0x7e)
+* @retval int               0:Success -1:Error
+*****************************************************************************/
+int chry_readline_edit_insert(chry_readline_t *rl, char c)
+{
+    if (rl->ln.buff->size < rl->ln.lnmax) {
+        if (rl->ln.buff->size != rl->ln.curoff) {
+            memmove(rl->ln.buff->pbuf + rl->ln.curoff + 1,
+                    rl->ln.buff->pbuf + rl->ln.curoff,
+                    rl->ln.buff->size - rl->ln.curoff);
+        }
+
+        rl->ln.buff->pbuf[rl->ln.curoff++] = c;
+        rl->ln.buff->size++;
+
+        return chry_readline_edit_refresh(rl);
+    }
+    return 0;
+}
+
+/*****************************************************************************
+* @brief        delete cursor left character
+* @retval int               0:Success -1:Error
+*****************************************************************************/
+int chry_readline_edit_backspace(chry_readline_t *rl)
+{
+    if ((rl->ln.curoff > 0) && (rl->ln.buff->size > 0)) {
+        memmove(rl->ln.buff->pbuf + rl->ln.curoff - 1,
+                rl->ln.buff->pbuf + rl->ln.curoff,
+                rl->ln.buff->size - rl->ln.curoff);
+        rl->ln.buff->size--;
+        rl->ln.curoff--;
+        return chry_readline_edit_refresh(rl);
+    }
+    return 0;
+}
+
+/*****************************************************************************
+* @brief        delete cursor right character
+* @retval int               0:Success -1:Error
+*****************************************************************************/
+int chry_readline_edit_delete(chry_readline_t *rl)
+{
+    if ((rl->ln.curoff < rl->ln.buff->size) && (rl->ln.buff->size > 0)) {
+        memmove(rl->ln.buff->pbuf + rl->ln.curoff,
+                rl->ln.buff->pbuf + rl->ln.curoff + 1,
+                rl->ln.buff->size - rl->ln.curoff - 1);
+        rl->ln.buff->size--;
+        return chry_readline_edit_refresh(rl);
+    }
+
+    return 0;
+}
+
+/*****************************************************************************
+* @brief        move cursor to left
+* @retval int               0:Success -1:Error
+*****************************************************************************/
+int chry_readline_edit_moveleft(chry_readline_t *rl)
+{
+    if (rl->ln.curoff > 0) {
+        rl->ln.curoff--;
+        return chry_readline_edit_refresh(rl);
+    }
+
+    return 0;
+}
+
+/*****************************************************************************
+* @brief        move cursor to right
+* @retval int               0:Success -1:Error
+*****************************************************************************/
+int chry_readline_edit_moveright(chry_readline_t *rl)
+{
+    if (rl->ln.curoff < rl->ln.buff->size) {
+        rl->ln.curoff++;
+        return chry_readline_edit_refresh(rl);
+    }
+
+    return 0;
+}
+
+/*****************************************************************************
+* @brief        move cursor to start of line
+* @retval int               0:Success -1:Error
+*****************************************************************************/
+int chry_readline_edit_movehome(chry_readline_t *rl)
+{
+    rl->ln.curoff = 0;
+    return chry_readline_edit_refresh(rl);
+}
+
+/*****************************************************************************
+* @brief        move cursor to end of line
+* @retval int               0:Success -1:Error
+*****************************************************************************/
+int chry_readline_edit_moveend(chry_readline_t *rl)
+{
+    rl->ln.curoff = rl->ln.buff->size;
+    return chry_readline_edit_refresh(rl);
+}
+
+/*****************************************************************************
+* @brief        delete the whole line
+* @retval int               0:Success -1:Error
+*****************************************************************************/
+int chry_readline_edit_delline(chry_readline_t *rl)
+{
+    rl->ln.buff->size = 0;
+    rl->ln.curoff = 0;
+    return chry_readline_edit_refresh(rl);
+}
+
+/*****************************************************************************
+* @brief        delete from cursor to end of line
+* @retval int               0:Success -1:Error
+*****************************************************************************/
+int chry_readline_edit_delend(chry_readline_t *rl)
+{
+    rl->ln.buff->size = rl->ln.curoff;
+    return chry_readline_edit_refresh(rl);
+}
+
+/*****************************************************************************
+* @brief        delete previosu word
+* @retval int               0:Success -1:Error
+*****************************************************************************/
+int chry_readline_edit_delword(chry_readline_t *rl)
+{
+    uint16_t curoff = rl->ln.curoff;
+
+    while ((curoff > 0) && (rl->ln.buff->pbuf[curoff - 1] == ' ')) {
+        curoff--;
+    }
+
+    while ((curoff > 0) && (rl->ln.buff->pbuf[curoff - 1] != ' ')) {
+        curoff--;
+    }
+
+    memmove(rl->ln.buff->pbuf + curoff,
+            rl->ln.buff->pbuf + rl->ln.curoff,
+            rl->ln.buff->size - rl->ln.curoff + 1);
+    rl->ln.buff->size -= rl->ln.curoff - curoff;
+    rl->ln.curoff = curoff;
+
+    return chry_readline_edit_refresh(rl);
+}
+
+/*****************************************************************************
+* @brief        get now word
+*****************************************************************************/
+__unused static void chry_readline_edit_getword(chry_readline_t *rl, char **pword, uint16_t *size)
+{
+    uint16_t curoff = rl->ln.curoff;
+
+    if ((curoff == 0) || (rl->ln.buff->pbuf[curoff - 1] == ' ')) {
+        goto end;
+    }
+
+    while (curoff > 0) {
+        curoff--;
+        if (rl->ln.buff->pbuf[curoff] == ' ') {
+            curoff++;
+            break;
+        }
+    }
+
+end:
+
+    *pword = &(rl->ln.buff->pbuf[curoff]);
+    *size = rl->ln.curoff - curoff;
+
+    return;
+}
+
+/*****************************************************************************
+* @brief        show help
+* @retval int               0:Success -1:Error
+*****************************************************************************/
+static int chry_readline_help(chry_readline_t *rl)
+{
+    if (sizeof(CONFIG_READLINE_HELP) - 1) {
+        chry_readline_put(rl, CONFIG_READLINE_HELP, sizeof(CONFIG_READLINE_HELP) - 1, -1);
+    }
+    return 0;
+}
+
+/*****************************************************************************
+* @brief        dispatch csi sequences
+*
+* @param[in]    rl          readline instance
+* @param[inout] c           character for dispatch
+* @param[in]    pns         params for dispatch
+*
+* @retval int               0:Success -1:Error
+*****************************************************************************/
+static int chry_readline_dispatch_csi(chry_readline_t *rl, uint8_t *c, uint16_t *pns)
+{
+    uint8_t idx;
+
+    if (*c == '~') {
+        if (pns[0] >= sizeof(vtmap)) {
+            pns[0] = 0;
+        }
+
+        *c = vtmap[pns[0]];
+    } else if (*c == 't') {
+        if (pns[0] == 8) {
+            rl->term.nsupt = 0;
+            rl->term.row = pns[1];
+            rl->term.col = pns[2];
+#if defined(CONFIG_READLINE_XTERM) && CONFIG_READLINE_XTERM
+            /*!< 1.enter alternate screen buffer <esc>[?47h */
+            /*!< 2.clear screen buffer           <esc>[2J   */
+            /*!< 3.move cursor to (1,1)          <esc>[1;1H */
+            /*!< 4.enter normal screen buffer    <esc>[?47l */
+            chry_readline_put(rl, "\e[?47h\e[2J\e[1;1H", 16, -1);
+            chry_readline_help(rl);
+            chry_readline_put(rl, "\e[?47l", 6, -1);
+#endif
+        }
+
+        *c = CHRY_READLINE_EXEC_NUL;
+    } else {
+        idx = *c - 0x40;
+
+        if (idx >= sizeof(xmap)) {
+            idx = 0;
+        }
+
+        *c = xmap[idx];
+    }
+
+    return 0;
+}
+
+/*****************************************************************************
+* @brief        dispatch o sequences
+*
+* @param[in]    rl          readline instance
+* @param[inout] c           character for dispatch
+* @param[in]    pns         params for dispatch
+*
+* @retval int               0:Success -1:Error
+*****************************************************************************/
+static int chry_readline_dispatch_o(chry_readline_t *rl, uint8_t *c, uint16_t *pns)
+{
+    (void)rl;
+    (void)pns;
+
+    switch (*c) {
+        case 'P':
+            *c = CHRY_READLINE_EXEC_F1;
+            break;
+        case 'Q':
+            *c = CHRY_READLINE_EXEC_F2;
+            break;
+        case 'R':
+            *c = CHRY_READLINE_EXEC_F3;
+            break;
+        case 'S':
+            *c = CHRY_READLINE_EXEC_F4;
+            break;
+        default:
+            *c = CHRY_READLINE_EXEC_NUL;
+            break;
+    }
+
+    return 0;
+}
+
+/*****************************************************************************
+* @brief        dispatch alt sequences
+*
+* @param[in]    rl          readline instance
+* @param[inout] c           character for dispatch
+* @param[in]    pns         params for dispatch
+*
+* @retval int               0:Success -1:Error
+*****************************************************************************/
+static int chry_readline_dispatch_alt(chry_readline_t *rl, uint8_t *c, uint16_t *pns)
+{
+    (void)rl;
+    (void)pns;
+
+    if ((*c < 'a') || ('z' < *c)) {
+        *c = CHRY_READLINE_EXEC_NUL;
+        return 0;
+    }
+
+#if defined(CONFIG_READLINE_ALTMAP) && CONFIG_READLINE_ALTMAP
+    *c = rl->altmap[*c - 'a'];
+#else
+    *c = altmap[*c - 'a'];
+#endif
+
+    return 0;
+}
+
+/*****************************************************************************
+* @brief        dispatch ctrl sequences
+*
+* @param[in]    rl          readline instance
+* @param[inout] c           character for dispatch
+* @param[in]    pns         params for dispatch
+*
+* @retval int               0:Success -1:Error
+*****************************************************************************/
+static int chry_readline_dispatch_ctrl(chry_readline_t *rl, uint8_t *c, uint16_t *pns)
+{
+    (void)rl;
+    (void)pns;
+
+#if defined(CONFIG_READLINE_CTRLMAP) && CONFIG_READLINE_CTRLMAP
+    *c = rl->ctrlmap[*c];
+#else
+    *c = ctrlmap[*c];
+#endif
+
+    return 0;
+}
+
+/*****************************************************************************
+* @brief        parse csi sequences
+*
+* @param[in]    rl          readline instance
+* @param[out]   csiend      final csi seq character
+* @param[out]   expre       extend prefix character
+* @param[out]   pns         array of number param
+*
+* @retval int               0:Success -1:Error
+*****************************************************************************/
+static int chry_readline_seqexec_pcsi(chry_readline_t *rl, uint8_t *csiend, uint8_t *expre, uint16_t *pns)
+{
+    uint8_t csibuf[8];
+    uint8_t *pbuf = csibuf;
+
+    /*!< should have buffered key or it will be blocked */
+    chry_readline_waitkey(rl, pbuf);
+
+    if (('0' <= *pbuf) && (*pbuf <= '9')) {
+        pbuf++;
+    } else if ('?' == *pbuf) {
+        *expre = *pbuf;
+    } else if ((('a' <= *pbuf) && (*pbuf <= 'z')) ||
+               (('A' <= *pbuf) && (*pbuf <= 'Z'))) {
+        *csiend = *pbuf;
+        return 0;
+    }
+
+    for (;;) {
+        /*!< should have buffered key or it will be blocked */
+        chry_readline_waitkey(rl, pbuf);
+
+        if (('0' <= *pbuf) && (*pbuf <= '9')) {
+            pbuf++;
+        } else if (*pbuf == ';') {
+            pbuf = csibuf;
+            chry_readline_parse_integer(csibuf, pns++);
+        } else if ((*pbuf == '~') ||
+                   (('a' <= *pbuf) && (*pbuf <= 'z')) ||
+                   (('A' <= *pbuf) && (*pbuf <= 'Z'))) {
+            *csiend = *pbuf;
+            chry_readline_parse_integer(csibuf, pns++);
+            return 0;
+        } else {
+            return -1;
+        }
+    }
+}
+
+/*****************************************************************************
+* @brief        execute CSI sequences
+*
+* @param[in]    rl          readline instance
+* @param[out]   c           character for dispatch
+* @param[out]   pns         array of number param
+*
+* @retval int               0:Success -1:Error
+*****************************************************************************/
+static int chry_readline_seqexec_csi(chry_readline_t *rl, uint8_t *c, uint16_t *pns)
+{
+    uint8_t expre = 0;
+
+    if (chry_readline_seqexec_pcsi(rl, c, &expre, pns)) {
+        return -1;
+    }
+
+    if (expre) {
+        *c = CHRY_READLINE_C0_NUL;
+    }
+
+    return chry_readline_dispatch_csi(rl, c, pns);
+}
+
+/*****************************************************************************
+* @brief        execute ALT sequences
+*
+* @param[in]    rl          readline instance
+* @param[inout]   c         character for dispatch
+* @param[out]   pns         array of number param
+*
+* @retval int               0:Success -1:Error
+*****************************************************************************/
+static int chry_readline_seqexec_alt(chry_readline_t *rl, uint8_t *c, uint16_t *pns)
+{
+    return chry_readline_dispatch_alt(rl, c, pns);
+}
+
+/*****************************************************************************
+* @brief        execute O sequences
+*
+* @param[in]    rl          readline instance
+* @param[out]   c           character for dispatch
+* @param[out]   pns         array of number param
+*
+* @retval int               0:Success -1:Error
+*****************************************************************************/
+static int chry_readline_seqexec_o(chry_readline_t *rl, uint8_t *c, uint16_t *pns)
+{
+    /*!< should have buffered key or it will be blocked */
+    chry_readline_waitkey(rl, c);
+
+    return chry_readline_dispatch_o(rl, c, pns);
+}
+
+/*****************************************************************************
+* @brief        execute sequences
+*
+* @param[in]    rl          readline instance
+* @param[inout] c           character for dispatch
+* @param[out]   pns         array of number param
+*
+* @retval int               0:Success -1:Error
+*****************************************************************************/
+static int chry_readline_seqexec(chry_readline_t *rl, uint8_t *c, uint16_t *pns)
+{
+    /*!< should have buffered key or it will be blocked */
+    chry_readline_waitkey(rl, c);
+
+    switch (*c) {
+        case 'O':
+            return chry_readline_seqexec_o(rl, c, pns);
+        case '[':
+            return chry_readline_seqexec_csi(rl, c, pns);
+        default:
+            return chry_readline_seqexec_alt(rl, c, pns);
+    }
+}
+
+#if defined(CONFIG_READLINE_HISTORY) && CONFIG_READLINE_HISTORY
+
+/*****************************************************************************
+* @brief        reverse memcpy 2byte align
+*
+* @param[in]    dst
+* @param[in]    src
+* @param[in]    n           byte
+*
+*****************************************************************************/
+static void chry_readline_rvsememcpy2(void *dst, const void *src, size_t n)
+{
+    uint16_t *pout = dst;
+    uint16_t *pin = (uint16_t *)src - 1;
+
+    for (; n > 0; n -= 2) {
+        *pout++ = *pin--;
+    }
+}
+
+/*****************************************************************************
+* @brief        align 2 up
+*
+* @param[in]    size        size
+*
+* @retval                   align size
+*****************************************************************************/
+static uint32_t chry_readline_align2(uint32_t size)
+{
+    if (size & 0x1) {
+        return (size & ~0x1) + 2;
+    } else {
+        return size;
+    }
+}
+
+/*****************************************************************************
+* @brief        cache linbuff to history list
+*
+* @param[in]    rl          readline instance
+*
+*****************************************************************************/
+static void chry_readline_history_cache(chry_readline_t *rl)
+{
+    uint16_t unused;
+    uint16_t offset;
+    uint16_t remain;
+    uint16_t lnsize;
+    uint8_t *dst;
+
+    /*!< fifo unused size */
+    unused = rl->hist.size - (rl->hist.cache - rl->hist.out);
+
+    /*!< line and size total size, alignup 2 */
+    lnsize = chry_readline_align2(rl->ln.buff->size + 2);
+
+    /*!< free the oldest history */
+    if (lnsize > unused) {
+        rl->hist.out += lnsize - unused;
+    }
+
+    /*!< fifo write offset */
+    offset = rl->hist.cache & rl->hist.mask;
+
+    /*!< unused size before ringloop */
+    remain = rl->hist.size - offset;
+    remain = remain > lnsize ? lnsize : remain;
+
+    dst = (uint8_t *)(rl->ln.buff) + lnsize;
+
+    chry_readline_rvsememcpy2(rl->hist.pbuf + offset, dst, remain);
+    chry_readline_rvsememcpy2(rl->hist.pbuf, dst - remain, lnsize - remain);
+
+    rl->hist.in = rl->hist.cache + lnsize;
+}
+
+/*****************************************************************************
+* @brief        store linebuff to history list
+*
+* @param[in]    rl          readline instance
+*
+*****************************************************************************/
+static void chry_readline_history_store(chry_readline_t *rl)
+{
+    if (rl->ln.buff->size > 0) {
+        chry_readline_history_cache(rl);
+
+        /*!< update cache index */
+        rl->hist.cache = rl->hist.in;
+    }
+}
+
+/*****************************************************************************
+* @brief        load special index history to linebuff
+*
+* @param[in]    rl          readline instance
+* @param[in]    index       history index
+*
+* @retval                   0:Success -1:Error
+*****************************************************************************/
+static int chry_readline_history_load(chry_readline_t *rl, uint16_t index)
+{
+    uint16_t used;
+    uint16_t offset;
+    uint16_t remain;
+    uint16_t lnsize;
+    uint16_t histin;
+    uint16_t count;
+    uint16_t prevused;
+
+    if (rl->hist.index == 0) {
+        chry_readline_history_cache(rl);
+    }
+
+    lnsize = 0;
+    count = index;
+    histin = rl->hist.in;
+    prevused = rl->hist.in - rl->hist.out;
+
+    do {
+        histin -= lnsize;
+
+        /*!< fifo used size */
+        used = histin - rl->hist.out;
+
+        if ((used == 0) || (used > prevused)) {
+            return 0;
+        }
+
+        prevused = used;
+
+        /*!< fifo read offset */
+        offset = (histin - 2) & rl->hist.mask;
+
+        /*!< read fisrt 2byte and alignup 2 */
+        lnsize = chry_readline_align2(((uint16_t *)(rl->hist.pbuf + offset))[0] + 2);
+
+        if (lnsize > used) {
+            return 0;
+        }
+
+    } while (count--);
+
+    offset = (histin - lnsize) & rl->hist.mask;
+
+    /*!< unused size before ringloop */
+    remain = rl->hist.size - offset;
+    remain = remain > lnsize ? lnsize : remain;
+
+    /*!< temp value */
+    lnsize = lnsize - remain;
+
+    chry_readline_rvsememcpy2((uint8_t *)(rl->ln.buff) + lnsize,
+                              rl->hist.pbuf + offset + remain, remain);
+
+    chry_readline_rvsememcpy2(rl->ln.buff, rl->hist.pbuf + lnsize, lnsize);
+
+    rl->ln.curoff = rl->ln.buff->size;
+    rl->hist.index = index;
+    return chry_readline_edit_refresh(rl);
+}
+
+/*****************************************************************************
+* @brief        load prev history to linebuff
+*
+* @param[in]    rl          readline instance
+*
+* @retval                   0:Success -1:Error
+*****************************************************************************/
+static int chry_readline_history_loadprev(chry_readline_t *rl)
+{
+    uint16_t lnhist = rl->hist.index + 1;
+
+    return chry_readline_history_load(rl, lnhist);
+}
+
+/*****************************************************************************
+* @brief        load next history to linebuff
+*
+* @param[in]    rl          readline instance
+*
+* @retval                   0:Success -1:Error
+*****************************************************************************/
+static int chry_readline_history_loadnext(chry_readline_t *rl)
+{
+    uint16_t lnhist = rl->hist.index > 0 ? rl->hist.index - 1 : 0;
+
+    return chry_readline_history_load(rl, lnhist);
+}
+
+#endif
+
+/*****************************************************************************
+* @brief        auto completion
+*
+* @param[in]    rl          readline instance
+*
+* @retval int               0:Success -1:Error 1:Restart
+*****************************************************************************/
+int chry_readline_complete(chry_readline_t *rl)
+{
+#if defined(CONFIG_READLINE_COMPLETION) && CONFIG_READLINE_COMPLETION
+    uint8_t count;
+    char *pre;
+    uint16_t word_size;
+
+    const char *argv[CONFIG_READLINE_MAX_COMPLETION];
+    uint8_t argl[CONFIG_READLINE_MAX_COMPLETION];
+
+    if (rl->cplt.acb) {
+        chry_readline_edit_getword(rl, &pre, &word_size);
+
+        if ((count = rl->cplt.acb(rl, pre, &word_size, argv, argl, CONFIG_READLINE_MAX_COMPLETION)) == 0) {
+            /*!< if no completions, return */
+            return 0;
+        }
+
+        uint16_t match_size = 0;
+        uint16_t extend_size;
+        if (count == 1) {
+            match_size = argl[0];
+        } else {
+            bool flag = true;
+            while (flag) {
+                for (uint16_t i = 0; i < count - 1; i++) {
+                    char c1 = argv[i + 0][match_size];
+                    char c2 = argv[i + 1][match_size];
+                    if ((0 == c1) || (0 == c2) || (c1 != c2)) {
+                        flag = false;
+                        break;
+                    }
+                }
+                if (flag) {
+                    match_size++;
+                }
+            }
+        }
+
+        if (match_size > word_size) {
+            uint16_t free_size = rl->ln.lnmax - rl->ln.buff->size;
+            extend_size = match_size - word_size;
+            extend_size = extend_size < free_size ? extend_size : free_size;
+            if (0 == extend_size) {
+                return 0;
+            }
+
+            if (rl->ln.buff->size != rl->ln.curoff) {
+                memmove(rl->ln.buff->pbuf + rl->ln.curoff + extend_size,
+                        rl->ln.buff->pbuf + rl->ln.curoff,
+                        rl->ln.buff->size - rl->ln.curoff);
+            }
+
+            memcpy(&(rl->ln.buff->pbuf[rl->ln.curoff]), &argv[0][word_size], extend_size);
+            rl->ln.curoff += extend_size;
+            rl->ln.buff->size += extend_size;
+            return chry_readline_edit_refresh(rl);
+        }
+
+        uint16_t longest_size = 0;
+        for (uint16_t i = 0; i < count; i++) {
+            uint16_t cplt_size = argl[i];
+            if (cplt_size > longest_size) {
+                longest_size = cplt_size;
+            }
+        }
+
+        longest_size += 2;
+
+        uint8_t col_count = rl->term.col / longest_size;
+        if (col_count < 1) {
+            col_count = 1;
+        }
+
+        uint16_t row_count = (count + col_count - 1) / col_count;
+
+        for (uint16_t row = 0; row < row_count; row++) {
+            chry_readline_put(rl, CONFIG_READLINE_NEWLINE, sizeof(CONFIG_READLINE_NEWLINE) ? sizeof(CONFIG_READLINE_NEWLINE) - 1 : 0, -1);
+
+            for (int col = 0; col < col_count; col++) {
+                int idx = (col * row_count) + row;
+                if (idx < count) {
+                    uint16_t cplt_size = argl[idx];
+
+                    chry_readline_put(rl, (void *)argv[idx], cplt_size, -1);
+
+                    if (((col + 1) * row_count) + row < count) {
+                        for (int k = cplt_size; k < longest_size; k++) {
+                            chry_readline_put(rl, " ", 1, -1);
+                        }
+                    }
+                }
+            }
+        }
+    }
+
+    chry_readline_put(rl, CONFIG_READLINE_NEWLINE, sizeof(CONFIG_READLINE_NEWLINE) ? sizeof(CONFIG_READLINE_NEWLINE) - 1 : 0, -1);
+    return 1;
+#else
+    (void)rl;
+    return 0;
+#endif
+}
+
+/*****************************************************************************
+* @brief        calculate prompt strlen and cursor offset
+*****************************************************************************/
+static void chry_readline_calculate_prompt(chry_readline_t *rl)
+{
+    char c;
+    uint8_t flag;
+
+    flag = 0;
+    rl->ln.pptlen = 0;
+    rl->ln.pptoff = 0;
+
+    while (1) {
+        c = rl->prompt[rl->ln.pptlen];
+
+        if (c == '\0') {
+            return;
+        } else if (c == '\r') {
+            rl->ln.pptoff = 0;
+        } else if (c == '\e') {
+            flag = 1;
+        } else if ((flag == 0) && (c != '\n')) {
+            rl->ln.pptoff++;
+        } else if ((flag == 1) && (c == 'm')) {
+            flag = 0;
+        }
+
+        rl->ln.pptlen++;
+        if (rl->ln.pptlen >= rl->ln.pptsize) {
+            rl->ln.pptlen = 0;
+            rl->ln.pptoff = 0;
+            return;
+        }
+    }
+}
+
+/*****************************************************************************
+* @brief        wait switch to altscreen
+* @retval int               0:Success -1:Error
+*****************************************************************************/
+__unused static int chry_readline_wait_altscreen(chry_readline_t *rl)
+{
+    uint32_t c = 0;
+
+    for (;;) {
+        chry_readline_waitkey(rl, &c);
+
+        if ((c == CHRY_READLINE_C0_CR) || (c == CHRY_READLINE_C0_LF)) {
+            chry_readline_altscreen(rl, 1);
+            return 0;
+        }
+    }
+}
+
+/*****************************************************************************
+* @brief        readline internal
+*
+* @param[in]    rl          readline instance
+*
+* @retval char*             line pointer
+*****************************************************************************/
+static char *chry_readline_inernal(chry_readline_t *rl)
+{
+#if defined(CONFIG_READLINE_NOBLOCK) && CONFIG_READLINE_NOBLOCK
+    if (rl->noblock && !rl->block) {
+        goto restore;
+    }
+#endif
+
+#if defined(CONFIG_READLINE_XTERM) && CONFIG_READLINE_XTERM
+    /*!< wait switch to altscreen */
+    if (rl->term.altnsupt == 0) {
+        chry_readline_wait_altscreen(rl);
+    }
+#endif
+
+restart:
+
+    if (rl->auto_refresh) {
+#if defined(CONFIG_READLINE_REFRESH_PROMPT) && CONFIG_READLINE_REFRESH_PROMPT
+        if (chry_readline_edit_refresh(rl)) {
+            return NULL;
+        }
+#else
+        /*!< output prompt */
+        chry_readline_put(rl, rl->prompt, rl->ln.pptlen, NULL);
+
+        if (chry_readline_edit_refresh(rl)) {
+            return NULL;
+        }
+#endif
+    }
+
+    while (1) {
+        uint8_t c = 0;
+        uint16_t pn[4];
+
+#if defined(CONFIG_READLINE_XTERM) && CONFIG_READLINE_XTERM
+        /*!< wait switch to altscreen */
+        if (rl->term.altnsupt == 0) {
+            chry_readline_wait_altscreen(rl);
+        }
+#endif
+
+#if defined(CONFIG_READLINE_NOBLOCK) && CONFIG_READLINE_NOBLOCK
+    restore:
+#endif
+
+        /*!< get a key */
+        chry_readline_getkey(rl, &c);
+
+#if defined(CONFIG_READLINE_NOBLOCK) && CONFIG_READLINE_NOBLOCK
+        if (rl->noblock && !rl->block) {
+            return NULL;
+        }
+#endif
+
+        if (c & 0x80) {
+            /*!< not support 8bit code */
+            continue;
+        }
+
+        if (CHRY_READLINE_G0_BEG <= c) {
+            if (c <= CHRY_READLINE_G0_END) {
+                if (rl->ignore) {
+                    continue;
+                }
+                /*!< printable characters */
+                if (chry_readline_edit_insert(rl, c)) {
+                    return NULL;
+                }
+                continue;
+            } else {
+                /*!< delete */
+                c = CHRY_READLINE_EXEC_BS;
+            }
+        } else if (CHRY_READLINE_C0_ESC == c) {
+            if (chry_readline_seqexec(rl, &c, pn)) {
+                return NULL;
+            }
+        } else {
+            if (chry_readline_dispatch_ctrl(rl, &c, pn)) {
+                return NULL;
+            }
+        }
+
+        if (rl->ignore) {
+            if (c == CHRY_READLINE_EXEC_SIGINT_) {
+                c = CHRY_READLINE_EXEC_SIGINT;
+            }
+
+            if (c < CHRY_READLINE_EXEC_SIGINT || CHRY_READLINE_EXEC_SIGTSTP < c) {
+                continue;
+            }
+        }
+
+    rehandle:
+        /*!< hanlde control */
+        switch (c) {
+            /*!< ignore */
+            case CHRY_READLINE_EXEC_NUL:
+                break;
+
+            /*!< clear screen and refresh line */
+            case CHRY_READLINE_EXEC_CLR:
+                if (chry_readline_edit_clear(rl)) {
+                    return NULL;
+                }
+                break;
+
+            /*!< newline */
+            case CHRY_READLINE_EXEC_NLN:
+#if defined(CONFIG_READLINE_HISTORY) && CONFIG_READLINE_HISTORY
+                if (!rl->ln.mask) {
+                    chry_readline_history_store(rl);
+                }
+#endif
+                return rl->ln.buff->pbuf;
+
+            /*!< abortline */
+            case CHRY_READLINE_EXEC_ALN:
+                rl->ln.buff->size = 0;
+                return rl->ln.buff->pbuf;
+
+            /*!< delete */
+            case CHRY_READLINE_EXEC_DEL:
+                if (chry_readline_edit_delete(rl)) {
+                    return NULL;
+                }
+                break;
+
+            /*!< backspace */
+            case CHRY_READLINE_EXEC_BS:
+                if (chry_readline_edit_backspace(rl)) {
+                    return NULL;
+                }
+                break;
+
+            /*!< move right */
+            case CHRY_READLINE_EXEC_MVRT:
+                if (chry_readline_edit_moveright(rl)) {
+                    return NULL;
+                }
+                break;
+
+            /*!< move left */
+            case CHRY_READLINE_EXEC_MVLT:
+                if (chry_readline_edit_moveleft(rl)) {
+                    return NULL;
+                }
+                break;
+
+            /*!< move end */
+            case CHRY_READLINE_EXEC_MVED:
+                if (chry_readline_edit_moveend(rl)) {
+                    return NULL;
+                }
+                break;
+
+            /*!< move home */
+            case CHRY_READLINE_EXEC_MVHM:
+                if (chry_readline_edit_movehome(rl)) {
+                    return NULL;
+                }
+                break;
+
+            /*!< fetch next history */
+            case CHRY_READLINE_EXEC_NXTH:
+#if defined(CONFIG_READLINE_HISTORY) && CONFIG_READLINE_HISTORY
+                if (!rl->ln.mask) {
+                    if (chry_readline_history_loadnext(rl)) {
+                        return NULL;
+                    }
+                }
+#endif
+                break;
+
+            /*!< fetch prev history */
+            case CHRY_READLINE_EXEC_PRVH:
+#if defined(CONFIG_READLINE_HISTORY) && CONFIG_READLINE_HISTORY
+                if (!rl->ln.mask) {
+                    if (chry_readline_history_loadprev(rl)) {
+                        return NULL;
+                    }
+                }
+#endif
+                break;
+
+            /*!< delete prev word */
+            case CHRY_READLINE_EXEC_DLWD:
+                if (chry_readline_edit_delword(rl)) {
+                    return NULL;
+                }
+                break;
+
+            /*!< delete whole line */
+            case CHRY_READLINE_EXEC_DHLN:
+                if (chry_readline_edit_delline(rl)) {
+                    return NULL;
+                }
+                break;
+
+            /*!< delete cursor to end */
+            case CHRY_READLINE_EXEC_DELN:
+                if (chry_readline_edit_delend(rl)) {
+                    return NULL;
+                }
+                break;
+
+            /*!< auto complete */
+            case CHRY_READLINE_EXEC_CPLT:
+#if defined(CONFIG_READLINE_COMPLETION) && CONFIG_READLINE_COMPLETION
+            {
+                /*!< disable completion in mask mode */
+                if (rl->ln.mask) {
+                    break;
+                }
+
+                int ret = chry_readline_complete(rl);
+                if (ret < 0) {
+                    return NULL;
+                } else if (ret == 0) {
+                    break;
+                } else {
+                    goto restart;
+                }
+            }
+#else
+                break;
+#endif
+
+            case CHRY_READLINE_EXEC_ACPLT: {
+                /*!< if cursor left char is space */
+                if ((rl->ln.curoff == 0) || (rl->ln.buff->pbuf[rl->ln.curoff - 1] == ' ')) {
+                    int spcnt = CONFIG_READLINE_SPACE - (rl->ln.curoff % CONFIG_READLINE_SPACE);
+                    for (uint8_t i = 0; i < spcnt; i++) {
+                        chry_readline_edit_insert(rl, ' ');
+                    }
+                    break;
+                } else {
+                    /*!< disable completion in mask mode */
+                    if (rl->ln.mask) {
+                        break;
+                    }
+
+                    int ret = chry_readline_complete(rl);
+                    if (ret < 0) {
+                        return NULL;
+                    } else if (ret == 0) {
+                        break;
+                    } else {
+                        goto restart;
+                    }
+                }
+            }
+
+            /*!< switch to normal screen */
+            case CHRY_READLINE_EXEC_SWNM:
+                chry_readline_altscreen(rl, 0);
+                break;
+
+            case CHRY_READLINE_EXEC_HELP:
+                if (chry_readline_help(rl)) {
+                    return NULL;
+                }
+                rl->ln.buff->size = 0;
+                return rl->ln.buff->pbuf;
+
+            case CHRY_READLINE_EXEC_EOF_:
+                if (rl->ln.buff->size == 0) {
+                    c = CHRY_READLINE_EXEC_EOF;
+                    goto rehandle;
+                }
+                if (chry_readline_edit_delete(rl)) {
+                    return NULL;
+                }
+                break;
+
+            case CHRY_READLINE_EXEC_SIGINT_:
+                if (rl->ln.buff->size == 0) {
+                    c = CHRY_READLINE_EXEC_SIGINT;
+                    goto rehandle;
+                } else {
+                    rl->ln.buff->size = 0;
+                    return rl->ln.buff->pbuf;
+                }
+
+            case CHRY_READLINE_EXEC_EOF:
+            case CHRY_READLINE_EXEC_SIGINT:
+            case CHRY_READLINE_EXEC_SIGQUIT:
+            case CHRY_READLINE_EXEC_SIGCONT:
+            case CHRY_READLINE_EXEC_SIGSTOP:
+            case CHRY_READLINE_EXEC_SIGTSTP:
+            case CHRY_READLINE_EXEC_F1:
+            case CHRY_READLINE_EXEC_F2:
+            case CHRY_READLINE_EXEC_F3:
+            case CHRY_READLINE_EXEC_F4:
+            case CHRY_READLINE_EXEC_F5:
+            case CHRY_READLINE_EXEC_F6:
+            case CHRY_READLINE_EXEC_F7:
+            case CHRY_READLINE_EXEC_F8:
+            case CHRY_READLINE_EXEC_F9:
+            case CHRY_READLINE_EXEC_F10:
+            case CHRY_READLINE_EXEC_F11:
+            case CHRY_READLINE_EXEC_F12:
+            default:
+                if (rl->ucb) {
+                    int ret = rl->ucb(rl, c);
+                    if (ret == 0) {
+                        goto restart;
+                    } else if (ret < 0) {
+                        return NULL;
+                    } else {
+                        break;
+                    }
+                } else {
+                    break;
+                }
+        }
+    }
+}
+
+/*****************************************************************************
+* @brief        enable or disable altscreen buffer (xterm only)
+*
+* @param[in]    rl          readline instance
+* @param[in]    enable      altscreen enable
+*
+* @retval int               0:Success -1:Error
+*****************************************************************************/
+int chry_readline_altscreen(chry_readline_t *rl, uint8_t enable)
+{
+    (void)enable;
+
+    if (rl->term.nsupt) {
+        return -1;
+    }
+
+#if defined(CONFIG_READLINE_XTERM) && CONFIG_READLINE_XTERM
+    if (enable) {
+        chry_readline_put(rl, "\e[?47h", 6, );
+        rl->term.alt = 1;
+    } else {
+        chry_readline_put(rl, "\e[?47l", 6, );
+        rl->term.alt = 0;
+    }
+#endif
+
+    return 0;
+}
+
+/*****************************************************************************
+* @brief        Fill Character Attributes SGR set to sgrraw
+*
+* @param[in]    buf         buffer for fill, max 17byte
+* @param[in]    sgrraw      sgr attributes, 0 to reset
+*
+*****************************************************************************/
+__unused static uint8_t chry_readline_sgrset(char *buf, uint16_t sgrraw)
+{
+    chry_readline_sgr_t sgr = { .raw = sgrraw };
+    size_t idx = 0;
+    chry_readline_seqgen_csi((void *)buf, &idx);
+
+    if (sgrraw == 0) {
+        buf[idx++] = 'm';
+        buf[idx] = '\0';
+        return idx;
+    }
+
+    if (sgr.bold) {
+        buf[idx + 0] = '1';
+        buf[idx + 1] = ';';
+        idx += 2;
+    }
+
+    if (sgr.underline) {
+        buf[idx + 0] = '4';
+        buf[idx + 1] = ';';
+        idx += 2;
+    }
+
+    if (sgr.blink) {
+        buf[idx + 0] = '5';
+        buf[idx + 1] = ';';
+        idx += 2;
+    }
+
+    if (sgr.inverse) {
+        buf[idx + 0] = '8';
+        buf[idx + 1] = ';';
+        idx += 2;
+    }
+
+    if (sgr.foreground) {
+        buf[idx + 0] = '3';
+        buf[idx + 1] = '0' + (sgr.foreground - 1);
+        buf[idx + 2] = ';';
+        idx += 3;
+    }
+
+    if (sgr.background) {
+        buf[idx + 0] = '4';
+        buf[idx + 1] = '0' + (sgr.background - 1);
+        buf[idx + 2] = ';';
+        idx += 3;
+    }
+
+    buf[idx - 1] = 'm';
+    buf[idx] = '\0';
+
+    return idx;
+}
+
+/*****************************************************************************
+* @brief        output CONFIG_READLINE_NEWLINE
+*
+* @param[in]    rl          readline instance
+*
+*****************************************************************************/
+void chry_readline_newline(chry_readline_t *rl)
+{
+    chry_readline_put(rl, CONFIG_READLINE_NEWLINE, sizeof(CONFIG_READLINE_NEWLINE) ? sizeof(CONFIG_READLINE_NEWLINE) - 1 : 0, );
+}
+
+/*****************************************************************************
+* @brief        clear screen and refresh line
+*
+* @param[in]    rl          readline instance
+*
+*****************************************************************************/
+void chry_readline_clear(chry_readline_t *rl)
+{
+    CHRY_READLINE_PARAM_CHECK(NULL != rl, );
+
+    chry_readline_edit_clear(rl);
+}
+
+/*****************************************************************************
+* @brief        enable or disable block mode
+*
+* @param[in]    rl          readline instance
+* @param[in]    enable      block enable
+*
+*****************************************************************************/
+void chry_readline_block(chry_readline_t *rl, uint8_t enable)
+{
+    CHRY_READLINE_PARAM_CHECK(NULL != rl, );
+
+#if defined(CONFIG_READLINE_NOBLOCK) && CONFIG_READLINE_NOBLOCK
+    rl->block = enable ? 1 : 0;
+#else
+    (void)rl;
+    (void)enable;
+#endif
+}
+
+/*****************************************************************************
+* @brief        enable or disable ignore mode
+*
+* @param[in]    rl          readline instance
+* @param[in]    enable      ignore enable
+*
+*****************************************************************************/
+void chry_readline_ignore(chry_readline_t *rl, uint8_t enable)
+{
+    CHRY_READLINE_PARAM_CHECK(NULL != rl, );
+
+    rl->ignore = enable ? 1 : 0;
+}
+
+/*****************************************************************************
+* @brief        enable or disable ignore mode
+*
+* @param[in]    rl          readline instance
+* @param[in]    enable      ignore enable
+*
+*****************************************************************************/
+void chry_readline_auto_refresh(chry_readline_t *rl, uint8_t enable)
+{
+    CHRY_READLINE_PARAM_CHECK(NULL != rl, );
+    rl->auto_refresh = enable ? 1 : 0;
+}
+
+/*****************************************************************************
+* @brief        enable or disable mask mode
+*
+* @param[in]    rl          readline instance
+* @param[in]    enable      mask enable
+*
+*****************************************************************************/
+void chry_readline_mask(chry_readline_t *rl, uint8_t enable)
+{
+    CHRY_READLINE_PARAM_CHECK(NULL != rl, );
+
+    rl->ln.mask = enable ? 1 : 0;
+
+    if (NULL != rl->ln.buff) {
+        chry_readline_edit_refresh(rl);
+    }
+}
+
+/*****************************************************************************
+* @brief        readline
+*
+* @param[in]    rl          readline instance
+* @param[in]    linebuff    linebuff pointer
+* @param[in]    buffsize    linebuff size
+* @param[in]    linesize    readline size (set NULL to ignore)
+*
+* @retval char*             line pointer
+*****************************************************************************/
+char *chry_readline(chry_readline_t *rl, char *linebuff, uint16_t buffsize, uint16_t *linesize)
+{
+    char *ret;
+    CHRY_READLINE_PARAM_CHECK(NULL != rl, NULL);
+    CHRY_READLINE_PARAM_CHECK(NULL != linebuff, NULL);
+
+    if (buffsize <= 3) {
+        return NULL;
+    }
+
+#if defined(CONFIG_READLINE_NOBLOCK) && CONFIG_READLINE_NOBLOCK
+    if (rl->noblock && !rl->block) {
+        goto restore;
+    }
+#endif
+
+    rl->ln.buff = (void *)linebuff;
+    rl->ln.buff->size = 0;
+    rl->ln.lnmax = buffsize - 3; /*!< reserved for \0 and size */
+    rl->ln.curoff = 0;
+
+#if defined(CONFIG_READLINE_HISTORY) && CONFIG_READLINE_HISTORY
+    rl->hist.index = 0;
+#endif
+
+    /*!< calculate prompt offset and size */
+    chry_readline_calculate_prompt(rl);
+
+#if defined(CONFIG_READLINE_NOBLOCK) && CONFIG_READLINE_NOBLOCK
+restore:
+#endif
+
+    ret = chry_readline_inernal(rl);
+
+#if defined(CONFIG_READLINE_NOBLOCK) && CONFIG_READLINE_NOBLOCK
+    if (rl->noblock && !rl->block) {
+        return (void *)-1;
+    }
+#endif
+
+    /*!< new line */
+    chry_readline_put(rl, CONFIG_READLINE_NEWLINE, sizeof(CONFIG_READLINE_NEWLINE) ? sizeof(CONFIG_READLINE_NEWLINE) - 1 : 0, NULL);
+
+    if (NULL != linesize) {
+        *linesize = rl->ln.buff->size;
+    }
+
+    rl->ln.buff->pbuf[rl->ln.buff->size] = '\0';
+    rl->ln.buff = NULL;
+
+    return ret;
+}
+
+/*****************************************************************************
+* @brief        init readline
+*
+* @param[in]    rl          readline instance
+* @param[in]    init        init param
+*
+* @retval int               0:Success -1:Error
+*****************************************************************************/
+int chry_readline_init(chry_readline_t *rl, chry_readline_init_t *init)
+{
+    CHRY_READLINE_PARAM_CHECK(NULL != rl, -1);
+    CHRY_READLINE_PARAM_CHECK(NULL != init, -1);
+    CHRY_READLINE_PARAM_CHECK(NULL != init->sget, -1);
+    CHRY_READLINE_PARAM_CHECK(NULL != init->sput, -1);
+    CHRY_READLINE_PARAM_CHECK(NULL != init->prompt, -1);
+#if defined(CONFIG_READLINE_HISTORY) && CONFIG_READLINE_HISTORY
+    CHRY_READLINE_PARAM_CHECK(NULL != init->history, -1);
+#endif
+
+    if ((init->histsize < 2) || (init->histsize & (init->histsize - 1))) {
+        return -1;
+    }
+
+    rl->prompt = init->prompt;
+    rl->sget = init->sget;
+    rl->sput = init->sput;
+
+#if defined(CONFIG_READLINE_HISTORY) && CONFIG_READLINE_HISTORY
+    rl->hist.pbuf = init->history;
+    rl->hist.in = 0;
+    rl->hist.out = 0;
+    rl->hist.mask = init->histsize - 1;
+    rl->hist.size = init->histsize;
+    rl->hist.cache = 0;
+#endif
+
+#if defined(CONFIG_READLINE_COMPLETION) && CONFIG_READLINE_COMPLETION
+    rl->cplt.acb = NULL;
+#endif
+
+#if defined(CONFIG_READLINE_PROMPTEDIT) && CONFIG_READLINE_PROMPTEDIT
+    memset(rl->pptseglen, 0, CONFIG_READLINE_PROMPTSEG + 1);
+#endif
+
+    rl->term.nsupt = 1;
+    rl->term.alt = 0;
+    rl->term.row = CONFIG_READLINE_DFTROW;
+    rl->term.col = CONFIG_READLINE_DFTCOL;
+
+    rl->ln.buff = NULL;
+    rl->ln.mask = 0;
+    rl->ln.pptsize = init->pptsize;
+
+    rl->ucb = NULL;
+
+    rl->ignore = false;
+    rl->auto_refresh = true;
+
+#if defined(CONFIG_READLINE_CTRLMAP) && CONFIG_READLINE_CTRLMAP
+    memcpy(rl->ctrlmap, ctrlmap, sizeof(ctrlmap));
+#endif
+
+#if defined(CONFIG_READLINE_ALTMAP) && CONFIG_READLINE_ALTMAP
+    memcpy(rl->altmap, altmap, sizeof(altmap));
+#endif
+
+#if defined(CONFIG_READLINE_NOBLOCK) && CONFIG_READLINE_NOBLOCK
+    rl->noblock = false;
+    rl->block = false;
+#endif
+
+    return 0;
+}
+
+/*****************************************************************************
+* @brief        detects if it is xterm, result will be processed automatically
+*               if not xterm it will be blocked on next character
+*
+* @param[in]    rl          readline instance
+*****************************************************************************/
+void chry_readline_detect(chry_readline_t *rl)
+{
+    uint8_t c;
+    uint16_t pn[4];
+
+    /*!< test sput and get screen size */
+    if (5 != rl->sput(rl, "\e[18t", 5)) {
+        return;
+    }
+
+    chry_readline_waitkey(rl, &c);
+
+    if (c == CHRY_READLINE_C0_ESC) {
+        /*!< execute sequence */
+        chry_readline_seqexec(rl, &c, pn);
+    }
+}
+
+/*****************************************************************************
+* @brief        set auto complete callback
+*
+* @param[in]    rl          readline instance
+* @param[in]    acb         callback
+*
+*****************************************************************************/
+void chry_readline_set_completion_cb(chry_readline_t *rl, uint8_t (*acb)(chry_readline_t *rl, char *pre, uint16_t *size, const char **argv, uint8_t *argl, uint8_t argcmax))
+{
+    (void)rl;
+    (void)acb;
+#if defined(CONFIG_READLINE_COMPLETION) && CONFIG_READLINE_COMPLETION
+    rl->cplt.acb = acb;
+#endif
+}
+
+/*****************************************************************************
+* @brief        set user event exec callback
+*
+* @param[in]    rl          readline instance
+* @param[in]    ucb         callback
+*
+*****************************************************************************/
+void chry_readline_set_user_cb(chry_readline_t *rl, int (*ucb)(chry_readline_t *rl, uint8_t exec))
+{
+    rl->ucb = ucb;
+}
+
+/*****************************************************************************
+* @brief        set ctrl mapping
+*
+* @param[in]    rl          readline instance
+* @param[in]    mapidx      map index
+* @param[in]    exec        exec code
+*
+*****************************************************************************/
+void chry_readline_set_ctrlmap(chry_readline_t *rl, uint8_t mapidx, uint8_t exec)
+{
+    (void)rl;
+
+#if defined(CONFIG_READLINE_CTRLMAP) && CONFIG_READLINE_CTRLMAP
+    rl->ctrlmap[mapidx] = exec;
+#else
+    ctrlmap[mapidx] = exec;
+#endif
+}
+
+/*****************************************************************************
+* @brief        set alt mapping
+*
+* @param[in]    rl          readline instance
+* @param[in]    mapidx      map index
+* @param[in]    exec        exec code
+*
+*****************************************************************************/
+void chry_readline_set_altmap(chry_readline_t *rl, uint8_t mapidx, uint8_t exec)
+{
+    (void)rl;
+
+#if defined(CONFIG_READLINE_ALTMAP) && CONFIG_READLINE_ALTMAP
+    rl->altmap[mapidx] = exec;
+#else
+    altmap[mapidx] = exec;
+#endif
+}
+
+#if defined(CONFIG_READLINE_DEBUG) && CONFIG_READLINE_DEBUG
+/*****************************************************************************
+* @brief        debug for keycode test
+*
+* @param[in]    rl          readline instance
+*
+*****************************************************************************/
+void chry_readline_debug(chry_readline_t *rl)
+{
+    chry_readline_put(rl, "debug keycodes mode\r\n", 22, );
+    char fifo[5] = { 0 };
+
+    while (1) {
+        int8_t len;
+        uint8_t c = 0;
+        char buf[32];
+
+        /*!< get a key */
+        chry_readline_waitkey(rl, &c);
+
+        if (c < CHRY_READLINE_G0_BEG) {
+            len = snprintf(buf, 32, "'^%c' %02x (%3d) /exit to break\r\n", c + 0x40, c, c);
+            chry_readline_put(rl, buf, len, );
+        } else if ((CHRY_READLINE_G0_BEG <= c) && (c <= CHRY_READLINE_G0_END)) {
+            /*!< printable characters */
+            len = snprintf(buf, 32, " '%c' %02x (%3d) /exit to break\r\n", c, c, c);
+            chry_readline_put(rl, buf, len, );
+        } else {
+            len = snprintf(buf, 32, " '?' %02x (%3d) /exit to break\r\n", c, c);
+            chry_readline_put(rl, buf, len, );
+        }
+
+        fifo[4] = fifo[3];
+        fifo[3] = fifo[2];
+        fifo[2] = fifo[1];
+        fifo[1] = fifo[0];
+        fifo[0] = c;
+
+        if (memcmp(fifo, "tixe/", 5) == 0) {
+            break;
+        }
+    }
+}
+#endif
+
+/*****************************************************************************
+* @brief        edit the specified segment of the prompt,
+*               segment will be create at first edit
+*
+* @param[in]    rl          readline instance
+* @param[in]    secidx      segment index, < PPTSEG
+* @param[in]    sgrraw      sgr sequense raw data
+* @param[in]    format      string end with \0
+* @param[in]    ...         params
+*
+* @retval int               0:Success -1:Error -2:No space
+*****************************************************************************/
+int chry_readline_prompt_edit(chry_readline_t *rl, uint8_t segidx, uint16_t sgrraw, const char *format, ...)
+{
+#if defined(CONFIG_READLINE_PROMPTEDIT) && CONFIG_READLINE_PROMPTEDIT
+    va_list ap;
+    char sgrbuf[17];
+    uint16_t pptlen;
+    int freelen;
+    int seglen;
+    uint16_t segoff = 0;
+    uint8_t sgrlen;
+
+    if (segidx >= CONFIG_READLINE_PROMPTSEG) {
+        return -1;
+    }
+
+    /*!< not allowed any free seg exists before this seg */
+    for (uint8_t i = 0; i < segidx; i++) {
+        segoff += rl->pptseglen[i];
+        if (rl->pptseglen[i] == 0) {
+            return -1;
+        }
+    }
+
+    /*!< calculate total prompt len */
+    pptlen = 0;
+    for (uint8_t i = 0; i < CONFIG_READLINE_PROMPTSEG; i++) {
+        if (i == segidx) {
+            continue;
+        }
+        pptlen += rl->pptseglen[i];
+    }
+
+    /*!< freelen reserved 1 for \0, 3 for \e[m */
+    freelen = rl->ln.pptsize - 1 - 3 - pptlen;
+
+    /*!< output sgr sequence and get len */
+    sgrlen = chry_readline_sgrset(sgrbuf, sgrraw);
+
+    if (freelen < (int)sgrlen) {
+        return -2;
+    }
+
+    /*!< if next segment is not used */
+    if (rl->pptseglen[segidx + 1] == 0) {
+        /*!< copy sgrbuff to prompt */
+        memcpy(&(rl->prompt[segoff]), sgrbuf, sgrlen);
+        freelen -= sgrlen;
+
+        /*!< output format to prompt */
+        va_start(ap, format);
+        seglen = vsnprintf(&(rl->prompt[segoff + sgrlen]), freelen + 1, format, ap);
+        va_end(ap);
+
+        if (seglen > freelen) {
+            /*!< set segment len */
+            rl->pptseglen[segidx] = sgrlen + freelen;
+
+            /*!< end with \e0m\0 */
+            memcpy(&(rl->prompt[segoff + sgrlen + freelen]), "\e[m", 4);
+            return -2;
+        } else {
+            /*!< set segment len */
+            rl->pptseglen[segidx] = sgrlen + seglen;
+
+            /*!< end with \e0m\0 */
+            memcpy(&(rl->prompt[segoff + sgrlen + seglen]), "\e[m", 4);
+
+            return 0;
+        }
+    }
+
+    /*!< get the seg len */
+    va_start(ap, format);
+    seglen = vsnprintf(NULL, 0, format, ap);
+    va_end(ap);
+
+    int actlen = sgrlen + seglen;
+    actlen = freelen > actlen ? actlen : freelen;
+
+    memmove(
+        &(rl->prompt[segoff + actlen]),
+        &(rl->prompt[segoff + rl->pptseglen[segidx]]),
+        pptlen - segoff);
+
+    /*!< copy sgrbuff to prompt */
+    memcpy(&(rl->prompt[segoff]), sgrbuf, sgrlen);
+    freelen -= sgrlen;
+
+    /*!< backup vsnprintf overwrite char */
+    char bakc = rl->prompt[segoff + actlen];
+
+    /*!< output format to prompt */
+    va_start(ap, format);
+    seglen = vsnprintf(&(rl->prompt[segoff + sgrlen]), freelen + 1, format, ap);
+    va_end(ap);
+
+    rl->prompt[segoff + actlen] = bakc;
+
+    /*!< set segment len */
+    rl->pptseglen[segidx] = actlen;
+
+    /*!< end with \e0m\0 */
+    memcpy(&(rl->prompt[pptlen + actlen]), "\e[m", 4);
+
+    if (seglen > freelen) {
+        return -2;
+    } else {
+        return 0;
+    }
+#else
+    (void)rl;
+    (void)segidx;
+    (void)sgrraw;
+    (void)format;
+    return 0;
+#endif
+}
+
+/*****************************************************************************
+* @brief        clear all seglen, next edit is first
+*
+* @param[in]    rl          readline instance
+*
+*****************************************************************************/
+void chry_readline_prompt_clear(chry_readline_t *rl)
+{
+#if defined(CONFIG_READLINE_PROMPTEDIT) && CONFIG_READLINE_PROMPTEDIT
+    memset(rl->pptseglen, 0, CONFIG_READLINE_PROMPTSEG + 1);
+#else
+    (void)rl;
+#endif
+}
diff --git a/APP/shell/cherryrl/chry_readline.h b/APP/shell/cherryrl/chry_readline.h
new file mode 100644 (file)
index 0000000..aa3993a
--- /dev/null
@@ -0,0 +1,178 @@
+/*
+ * Copyright (c) 2022, Egahp
+ *
+ * SPDX-License-Identifier: Apache-2.0
+ */
+
+#ifndef CHRY_READLINE_H
+#define CHRY_READLINE_H
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#include <stdint.h>
+#include "chry_readline_keycode.h"
+#include "chry_readline_config.h"
+
+#if defined(CONFIG_READLINE_XTERM) && defined(CONFIG_READLINE_NOBLOCK)
+#if CONFIG_READLINE_XTERM && CONFIG_READLINE_NOBLOCK
+#error "CONFIG_READLINE_XTERM cannot be configured at the same time as CONFIG_READLINE_NOBLOCK"
+#endif
+#endif
+
+enum {
+    CHRY_READLINE_SGR_NONE = 0,
+    CHRY_READLINE_SGR_BLACK = 1,
+    CHRY_READLINE_SGR_RED = 2,
+    CHRY_READLINE_SGR_GREEN = 3,
+    CHRY_READLINE_SGR_YELLOW = 4,
+    CHRY_READLINE_SGR_BLUE = 5,
+    CHRY_READLINE_SGR_MAGENTA = 6,
+    CHRY_READLINE_SGR_CYAN = 7,
+    CHRY_READLINE_SGR_WHITE = 8,
+    CHRY_READLINE_SGR_DEFAULT = 10
+};
+
+typedef struct chry_readline {
+    char *prompt; /*!< prompt pointer */
+    uint16_t (*sput)(struct chry_readline *rl, const void *data, uint16_t size);
+    uint16_t (*sget)(struct chry_readline *rl, void *data, uint16_t size);
+
+    struct
+    {
+        struct {
+            uint16_t size; /*!< linesize         */
+            char pbuf[0];  /*!< linebuff pointer */
+        } *buff;
+
+        uint16_t pptsize; /*!< prompt size   */
+        uint16_t pptoff;  /*!< prompt offset */
+        uint16_t pptlen;  /*!< prompt strlen */
+        uint16_t lnmax;   /*!< linebuff max  */
+        uint16_t curoff;  /*!< cursor offset */
+        uint16_t mask;    /*!< line mask     */
+    } ln;
+
+    struct
+    {
+        union {
+            uint16_t altnsupt; /*!< is screen not supported but alt buffer */
+            struct {
+                uint8_t nsupt; /*!< is screen not supported */
+                uint8_t alt;   /*!< is screen alt buffer */
+            };
+        };
+        uint16_t row; /*!< terminal row     */
+        uint16_t col; /*!< terminal column  */
+    } term;
+
+#if defined(CONFIG_READLINE_COMPLETION) && CONFIG_READLINE_COMPLETION
+    struct {
+        uint8_t (*acb)(struct chry_readline *rl, char *pre, uint16_t *size, const char **argv, uint8_t *argl, uint8_t argcmax);
+    } cplt;
+#endif
+
+#if defined(CONFIG_READLINE_HISTORY) && CONFIG_READLINE_HISTORY
+    struct {
+        char *pbuf;     /*!< histfifo buffer  */
+        uint16_t in;    /*!< histfifo in pos  */
+        uint16_t out;   /*!< histfifo out pos */
+        uint16_t mask;  /*!< histfifo mask    */
+        uint16_t size;  /*!< histfifo size    */
+        uint16_t cache; /*!< history cache    */
+        uint16_t index; /*!< history index    */
+    } hist;
+#endif
+
+    int (*ucb)(struct chry_readline *rl, uint8_t exec);
+
+    uint8_t ignore;       /*!< only accept */
+    uint8_t auto_refresh; /*!< auto refresh */
+
+#if defined(CONFIG_READLINE_CTRLMAP) && CONFIG_READLINE_CTRLMAP
+    uint8_t ctrlmap[32];
+#endif
+
+#if defined(CONFIG_READLINE_ALTMAP) && CONFIG_READLINE_ALTMAP
+    uint8_t altmap[26];
+#endif
+
+#if defined(CONFIG_READLINE_PROMPTEDIT) && CONFIG_READLINE_PROMPTEDIT
+    uint8_t pptseglen[CONFIG_READLINE_PROMPTSEG + 1];
+#endif
+
+#if defined(CONFIG_READLINE_NOBLOCK) && CONFIG_READLINE_NOBLOCK
+    uint8_t noblock;
+    uint8_t block;
+#endif
+
+} chry_readline_t;
+
+typedef struct {
+    char *prompt;      /*!< prompt buffer pointer */
+    uint16_t pptsize;  /*!< prompt buffer size */
+    char *history;     /*!< history buffer pointer */
+    uint16_t histsize; /*!< history buffer size, must be a power of 2 */
+    uint16_t (*sput)(chry_readline_t *rl, const void *, uint16_t);
+    uint16_t (*sget)(chry_readline_t *rl, void *, uint16_t);
+} chry_readline_init_t;
+
+typedef struct
+{
+    union {
+        uint16_t raw;
+        struct
+        {
+            uint16_t foreground : 6;
+            uint16_t bold       : 1;
+            uint16_t underline  : 1;
+            uint16_t background : 6;
+            uint16_t blink      : 1;
+            uint16_t inverse    : 1;
+        };
+    };
+} chry_readline_sgr_t;
+
+extern int chry_readline_init(chry_readline_t *rl, chry_readline_init_t *init);
+extern void chry_readline_debug(chry_readline_t *rl);
+extern char *chry_readline(chry_readline_t *rl, char *linebuff, uint16_t buffsize, uint16_t *linesize);
+
+extern int chry_readline_edit_refresh(chry_readline_t *rl);
+extern int chry_readline_edit_clear(chry_readline_t *rl);
+extern int chry_readline_edit_insert(chry_readline_t *rl, char c);
+extern int chry_readline_edit_backspace(chry_readline_t *rl);
+extern int chry_readline_edit_delete(chry_readline_t *rl);
+extern int chry_readline_edit_moveleft(chry_readline_t *rl);
+extern int chry_readline_edit_moveright(chry_readline_t *rl);
+extern int chry_readline_edit_movehome(chry_readline_t *rl);
+extern int chry_readline_edit_moveend(chry_readline_t *rl);
+extern int chry_readline_edit_delline(chry_readline_t *rl);
+extern int chry_readline_edit_delend(chry_readline_t *rl);
+extern int chry_readline_edit_delword(chry_readline_t *rl);
+
+extern int chry_readline_complete(chry_readline_t *rl);
+
+extern void chry_readline_erase_line(chry_readline_t *rl);
+extern void chry_readline_newline(chry_readline_t *rl);
+extern void chry_readline_detect(chry_readline_t *rl);
+extern void chry_readline_clear(chry_readline_t *rl);
+extern void chry_readline_block(chry_readline_t *rl, uint8_t enable);
+extern void chry_readline_ignore(chry_readline_t *rl, uint8_t enable);
+extern void chry_readline_auto_refresh(chry_readline_t *rl, uint8_t enable);
+extern void chry_readline_mask(chry_readline_t *rl, uint8_t enable);
+extern int chry_readline_altscreen(chry_readline_t *rl, uint8_t enable);
+
+extern void chry_readline_set_completion_cb(chry_readline_t *rl, uint8_t (*acb)(chry_readline_t *rl, char *pre, uint16_t *size, const char **argv, uint8_t *argl, uint8_t argcmax));
+extern void chry_readline_set_user_cb(chry_readline_t *rl, int (*ucb)(chry_readline_t *rl, uint8_t exec));
+extern void chry_readline_set_ctrlmap(chry_readline_t *rl, uint8_t mapidx, uint8_t exec);
+extern void chry_readline_set_altmap(chry_readline_t *rl, uint8_t mapidx, uint8_t exec);
+
+extern int chry_readline_prompt_edit(chry_readline_t *rl, uint8_t segidx, uint16_t sgrraw, const char *format, ...);
+extern void chry_readline_prompt_clear(chry_readline_t *rl);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/APP/shell/cherryrl/chry_readline_config.h b/APP/shell/cherryrl/chry_readline_config.h
new file mode 100644 (file)
index 0000000..c0bc93e
--- /dev/null
@@ -0,0 +1,110 @@
+/*
+ * Copyright (c) 2022, Egahp
+ *
+ * SPDX-License-Identifier: Apache-2.0
+ */
+
+#ifndef CHRY_READLINE_CONFIG_H
+#define CHRY_READLINE_CONFIG_H
+
+#ifdef CONFIG_READLINE_USER_DEFINE_FILE
+#include "chry_readline_user.h"
+#endif
+
+/*!< argument check */
+#ifndef CONFIG_READLINE_DEBUG
+#define CONFIG_READLINE_DEBUG 0
+#endif
+
+/*!< default row */
+#ifndef CONFIG_READLINE_DFTROW
+#define CONFIG_READLINE_DFTROW 25
+#endif
+
+/*!< default column */
+#ifndef CONFIG_READLINE_DFTCOL
+#define CONFIG_READLINE_DFTCOL 80
+#endif
+
+/*!< history support <+600byte> */
+#ifndef CONFIG_READLINE_HISTORY
+#define CONFIG_READLINE_HISTORY 1
+#endif
+
+/*!< completion support <+800byte> */
+#ifndef CONFIG_READLINE_COMPLETION
+#define CONFIG_READLINE_COMPLETION 1
+#endif
+
+/*!< max completion item list count (use stack 4 x count byte) */
+#ifndef CONFIG_READLINE_MAX_COMPLETION
+#define CONFIG_READLINE_MAX_COMPLETION 40
+#endif
+
+/*!< prompt edit support <+900byte>  */
+#ifndef CONFIG_READLINE_PROMPTEDIT
+#define CONFIG_READLINE_PROMPTEDIT 1
+#endif
+
+/*!< prompt segment count */
+#ifndef CONFIG_READLINE_PROMPTSEG
+#define CONFIG_READLINE_PROMPTSEG 7
+#endif
+
+/*!< xterm support */
+#ifndef CONFIG_READLINE_XTERM
+#define CONFIG_READLINE_XTERM 0
+#endif
+
+/*!< newline */
+#ifndef CONFIG_READLINE_NEWLINE
+#define CONFIG_READLINE_NEWLINE "\r\n"
+#endif
+
+/*!< tab space count */
+#ifndef CONFIG_READLINE_SPACE
+#define CONFIG_READLINE_SPACE 4
+#endif
+
+/*!< independent ctrl map */
+#ifndef CONFIG_READLINE_CTRLMAP
+#define CONFIG_READLINE_CTRLMAP 0
+#endif
+
+/*!< independent alt map */
+#ifndef CONFIG_READLINE_ALTMAP
+#define CONFIG_READLINE_ALTMAP 0
+#endif
+
+/*!< refresh prompt */
+#ifndef CONFIG_READLINE_REFRESH_PROMPT
+#define CONFIG_READLINE_REFRESH_PROMPT 1
+#endif
+
+/*!< no waiting for sget */
+#ifndef CONFIG_READLINE_NOBLOCK
+#define CONFIG_READLINE_NOBLOCK 0
+#endif
+
+/*!< help information */
+#ifndef CONFIG_READLINE_HELP
+#define CONFIG_READLINE_HELP ""
+#endif
+
+/*
+"\r\n"
+"\t+-------------------------------------+\r\n"
+"\t|           \e[1;31mCherry ReadLine \e[m          |\r\n"
+"\t|                                     |\r\n"
+"\t| -> CTRL + ^  return normal screen   |\r\n"
+"\t| -> CTRL + -  show this help         |\r\n"
+"\t| -> CTRL + C  abort line             |\r\n"
+"\t| -> CTRL + K  delete cursor to end   |\r\n"
+"\t| -> CTRL + L  clear screen           |\r\n"
+"\t| -> CTRL + U  delete whole line      |\r\n"
+"\t| -> CTRL + W  delete prev word       |\r\n"
+"\t| -> CTRL + Z  abort line             |\r\n"
+"\t+-------------------------------------+\r\n"
+*/
+
+#endif
diff --git a/APP/shell/cherryrl/chry_readline_keycode.h b/APP/shell/cherryrl/chry_readline_keycode.h
new file mode 100644 (file)
index 0000000..35dc371
--- /dev/null
@@ -0,0 +1,394 @@
+/*
+ * Copyright (c) 2022, Egahp
+ *
+ * SPDX-License-Identifier: Apache-2.0
+ */
+
+/*!< VT101 User Guide                                                           */
+/*!< APPENDIX C                                                                 */
+/*!< <1>    Standard Key Character Codes (0x21-0x7E)                            */
+/*!< Lowercase      Lowercase Code      Uppercase       Uppercasee Code         */
+/*!< a              0x61                A               0x41                    */
+/*!< b              0x62                B               0x42                    */
+/*!< c              0x63                C               0x43                    */
+/*!< d              0x64                D               0x44                    */
+/*!< e              0x65                E               0x45                    */
+/*!< f              0x66                F               0x46                    */
+/*!< g              0x67                G               0x47                    */
+/*!< h              0x68                H               0x48                    */
+/*!< i              0x69                I               0x49                    */
+/*!< j              0x6A                J               0x4A                    */
+/*!< k              0x6B                K               0x4B                    */
+/*!< l              0x6C                L               0x4C                    */
+/*!< m              0x6D                M               0x4D                    */
+/*!< n              0x6E                N               0x4E                    */
+/*!< o              0x6F                O               0x4F                    */
+/*!< p              0x70                P               0x50                    */
+/*!< q              0x71                Q               0x51                    */
+/*!< r              0x72                R               0x52                    */
+/*!< s              0x73                S               0x53                    */
+/*!< t              0x74                T               0x54                    */
+/*!< u              0x75                U               0x55                    */
+/*!< v              0x76                V               0x56                    */
+/*!< w              0x77                W               0x57                    */
+/*!< x              0x78                X               0x58                    */
+/*!< y              0x79                Y               0x59                    */
+/*!< z              0x7A                Z               0x5A                    */
+/*!< 1              0x31                !               0x21                    */
+/*!< 2              0x32                @               0x40                    */
+/*!< 3              0x33                #               0x23                    */
+/*!< 4              0x34                $               0x24                    */
+/*!< 5              0x35                %               0x25                    */
+/*!< 6              0x36                ^(circumflex)   0x5E                    */
+/*!< 7              0x37                &               0x26                    */
+/*!< 8              0x38                *               0x2A                    */
+/*!< 9              0x39                (               0x28                    */
+/*!< 0              0x30                )               0x29                    */
+/*!< -(minus)       0x2D                _               0x5F                    */
+/*!< =              0x3D                +               0x2B                    */
+/*!< `(grave)       0x60                ~(tilde)        0x7E                    */
+/*!< [              0x5B                {               0x7B                    */
+/*!< ]              0x5D                }               0x7D                    */
+/*!< ;              0x3B                :               0x3A                    */
+/*!< '(spostrophe)  0x27                "               0x22                    */
+/*!< \              0x5C                |               0x7C                    */
+/*!< ,(comma)       0x2C                <               0x3C                    */
+/*!< .(period)      0x2E                >               0x3E                    */
+/*!< /              0x2F                ?               0x3F                    */
+/*!<                                                                            */
+/*!< <2>    Cursor Control KeyCodes                                             */
+/*!<    Cursor Key      ANSI Mode Reset ANSI Mode Set   VT52 Mode               */
+/*!<    ↑   Up          <esc>[A         <esc>OA         <esc>A                  */
+/*!<    ↓   Down        <esc>[B         <esc>OB         <esc>B                  */
+/*!<    →   Right       <esc>[C         <esc>OC         <esc>C                  */
+/*!<    ←   Left        <esc>[D         <esc>OD         <esc>D                  */
+/*!<                                                                            */
+/*!< <3>    Control Codes Generated (0x00 - 0x1F, 0x7F)                         */
+/*!<    Mnemonic        Code Hex        Key with CTRL   Dedicated Key           */
+/*!<    NUL             0x00            Spcae Bar                               */
+/*!<    SOH             0x01            A                                       */
+/*!<    STX             0x02            B                                       */
+/*!<    ETX             0x03            C                                       */
+/*!<    EOT             0x04            D                                       */
+/*!<    ENQ             0x05            E                                       */
+/*!<    ACK             0x06            F                                       */
+/*!<    BEL             0x07            G                                       */
+/*!<    BS              0x08            H               BACK SPACE              */
+/*!<    HT              0x09            I               TAB                     */
+/*!<    LF              0x0A            J               LINE FEED               */
+/*!<    VT              0x0B            K                                       */
+/*!<    FF              0x0C            L                                       */
+/*!<    CR              0x0D            M               RETURN (ENTER)          */
+/*!<    SO              0x0E            N                                       */
+/*!<    SI              0x0F            O                                       */
+/*!<    DLE             0x10            P                                       */
+/*!<    DC1             0x11            Q                                       */
+/*!<    DC2             0x12            R                                       */
+/*!<    DC3             0x13            S                                       */
+/*!<    DC4             0x14            T                                       */
+/*!<    NAK             0x15            U                                       */
+/*!<    SYN             0x16            V                                       */
+/*!<    ETB             0x17            W                                       */
+/*!<    CAN             0x18            X                                       */
+/*!<    EM              0x19            Y                                       */
+/*!<    SUB             0x1A            Z                                       */
+/*!<    ESC             0x1B            [                                       */
+/*!<    FS              0x1C            \                                       */
+/*!<    GS              0x1D            ]                                       */
+/*!<    RS              0x1E            ~                                       */
+/*!<    US              0x1F            ?                                       */
+/*!<    DEL             0x7F                            DELETE                  */
+/*!<                                                                            */
+/*!< The following control charaters are generated differently from previous    */
+/*!<    NUL             0x00            @                                       */
+/*!<    RS              0x1E            ^                                       */
+/*!<    US              0x1F            - &                                     */
+/*!<                                                                            */
+/*!< <4>    Auxiliary Keypad Codes                                              */
+/*!<    Key     ANSI Numeric    ANSI Alternate  VT52 Numeric    VT52 Alternate  */
+/*!<    0       0               <esc>Op         0               <esc>?p         */
+/*!<    1       1               <esc>Oq         1               <esc>?q         */
+/*!<    2       2               <esc>Or         2               <esc>?r         */
+/*!<    3       3               <esc>Os         3               <esc>?s         */
+/*!<    4       4               <esc>Ot         4               <esc>?t         */
+/*!<    5       5               <esc>Ou         5               <esc>?u         */
+/*!<    6       6               <esc>Ov         6               <esc>?v         */
+/*!<    7       7               <esc>Ow         7               <esc>?w         */
+/*!<    8       8               <esc>Ox         8               <esc>?x         */
+/*!<    9       9               <esc>Oy         9               <esc>?y         */
+/*!<    -       -               <esc>Om         -               <esc>?m         */
+/*!<    ,       ,               <esc>Ol         ,               <esc>?l         */
+/*!<    .       .               <esc>On         .               <esc>?n         */
+/*!<    ENTER   CR              <esc>OM         CR              <esc>?M         */
+/*!<    PF1     <esc>OP         <esc>OP         <esc>P          <esc>?P         */
+/*!<    PF2     <esc>OQ         <esc>OQ         <esc>Q          <esc>?Q         */
+/*!<    PF3     <esc>OR         <esc>OR         <esc>R          <esc>?R         */
+/*!<    PF4     <esc>OS         <esc>OS         <esc>S          <esc>?S         */
+/*!<                                                                            */
+/*!<                                                                            */
+/*!< vt sequences:                                                              */
+/*!< <esc>[1~    - Home        <esc>[16~   -             <esc>[31~   - F17      */
+/*!< <esc>[2~    - Insert      <esc>[17~   - F6          <esc>[32~   - F18      */
+/*!< <esc>[3~    - Delete      <esc>[18~   - F7          <esc>[33~   - F19      */
+/*!< <esc>[4~    - End         <esc>[19~   - F8          <esc>[34~   - F20      */
+/*!< <esc>[5~    - PgUp        <esc>[20~   - F9          <esc>[35~   -          */
+/*!< <esc>[6~    - PgDn        <esc>[21~   - F10                                */
+/*!< <esc>[7~    - Home        <esc>[22~   -                                    */
+/*!< <esc>[8~    - End         <esc>[23~   - F11                                */
+/*!< <esc>[9~    -             <esc>[24~   - F12                                */
+/*!< <esc>[10~   - F0          <esc>[25~   - F13                                */
+/*!< <esc>[11~   - F1          <esc>[26~   - F14                                */
+/*!< <esc>[12~   - F2          <esc>[27~   -                                    */
+/*!< <esc>[13~   - F3          <esc>[28~   - F15                                */
+/*!< <esc>[14~   - F4          <esc>[29~   - F16                                */
+/*!< <esc>[15~   - F5          <esc>[30~   -                                    */
+/*!<                                                                            */
+/*!< xterm sequences:                                                           */
+/*!< <esc>[A     - Up          <esc>[K     -             <esc>[U     -          */
+/*!< <esc>[B     - Down        <esc>[L     -             <esc>[V     -          */
+/*!< <esc>[C     - Right       <esc>[M     -             <esc>[W     -          */
+/*!< <esc>[D     - Left        <esc>[N     -             <esc>[X     -          */
+/*!< <esc>[E     -             <esc>[O     -             <esc>[Y     -          */
+/*!< <esc>[F     - End         <esc>[P     - F1          <esc>[Z     -          */
+/*!< <esc>[G     - Keypad 5    <esc>[Q     - F2                                 */
+/*!< <esc>[H     - Home        <esc>[R     - F3                                 */
+/*!< <esc>[I     -             <esc>[S     - F4                                 */
+/*!< <esc>[J     -             <esc>[T     -                                    */
+/*!<                                                                            */
+/*!< Host -> Terminal input sequences                                           */
+/*!< Pressing special keys on the keyboard, as well as outputting many          */
+/*!< xterm CSI, DCS, or OSC sequences, often produces a CSI, DCS, or OSC        */
+/*!< sequence,  sent from the terminal to the computer as though the user       */
+/*!< typed it.                                                                  */
+/*!< When typing input on a terminal keypresses outside the normal main         */
+/*!< alphanumeric keyboard area can be sent to the host as ANSI sequences.      */
+/*!< For keys that have an equivalent output function, such as the cursor       */
+/*!< keys, these often mirror the output sequences. However, for most           */
+/*!< keypresses there isn't an equivalent output sequence to use.               */
+/*!<                                                                            */
+/*!< There are several encoding schemes, and unfortunately most terminals       */
+/*!< mix sequences from different schemes, so host software has to be able      */
+/*!< to deal  with input sequences using any scheme. To complicate the          */
+/*!< matter, the VT  terminals themselves have two schemes of input, normal     */
+/*!< mode and application mode that can be switched by the application.         */
+/*!<                                                                            */
+/*!<                                                                            */
+/*!< Pn     ->  Numeric Parameter                                               */
+/*!<    A parameter that represents a number, designated by Pn.                 */
+/*!< Ps     ->  Selective Parameter                                             */
+/*!<    A parameter that selects a subfunction from a specified list of         */
+/*!<    subfunctions, designated by Ps. In general, a control sequence with     */
+/*!<    more than one selective parameter causes the same effect as several     */
+/*!<    control sequences, each with one selective parameter, e.g.,             */
+/*!<    CSI Psa; Psb; Psc F is identical to CSI Psa F CSI Psb F CSI Psc F.      */
+/*!< Parameter String                                                           */
+/*!<    A string of parameters separated by a semicolon -> ;                    */
+/*!< Default                                                                    */
+/*!<    A function-dependent value that is assumed when no explicit value,      */
+/*!<    or a value of 0, is specified.                                          */
+/*!< F      ->  Final character                                                 */
+/*!<    A character whose bit combination terminates an escape or control       */
+/*!<    sequence.                                                               */
+/*!<                                                                            */
+/*!< <esc> c        ->      RIS Reset to initial State                          */
+/*!< <esc> N        ->      SS2 Single Shift Select of G2 Character Set         */
+/*!< <esc> O        ->      SS3 Single Shift Select of G3 Character Set         */
+/*!< <esc> P        ->      DCS Device Control String                           */
+/*!< <esc> [        ->      CSI Control Sequence Introducer                         */
+/*!< <esc> \        ->      ST  String Terminator                                       */
+/*!< <esc> ]        ->      OSC Operating System Command                                    */
+/*!<                                                                                            */
+/*!< CSI Ps A       ->      CUU Cursor Up                       Cursor Up Ps Times                  */
+/*!< CSI Ps B       ->      CUD Cursor Down                     Cursor Down Ps Times                */
+/*!< CSI Ps C       ->      CUF Cursor Forward                  Cursor Forward Ps Times             */
+/*!< CSI Ps D       ->      CUB Cursor Back                     Cursor Backward Ps Times            */
+/*!< CSI Ps E       ->      CNL Cursor Next Line                Cursor Next Line Ps Times           */
+/*!< CSI Ps F       ->      CPL Cursor Previous Line            Cursor Previous Line Ps Times       */
+/*!< CSI Ps G       ->      CHA Cursor Horizontal Absolute      Cursor Character Absolute [column]  */
+/*!< CSI Ps ; Ps H  ->      CUP Cursor Position                 Cursor Position [row;column]        */
+/*!< CSI Ps J       ->      ED Erase in Display                                                     */
+/*!<                            Ps = 0 -> Erase Below (default)                                     */
+/*!<                            Ps = 1 -> Erase Above                                               */
+/*!<                            Ps = 2 -> Erase All                                                 */
+/*!<                            Ps = 3 -> Erase Saved Lines (xterm)                                 */
+/*!< CSI Ps K       ->      EL Erase in Line                                                        */
+/*!<                            Ps = 0 -> Erase to Right (default)                                  */
+/*!<                            Ps = 1 -> Erase to Left                                             */
+/*!<                            Ps = 2 -> Erase All                                                 */
+/*!< CSI Ps L       ->      IL  Insert Line                     Insert Ps Lines                     */
+/*!< CSI Ps M       ->      DL  Delete Line                     Delete Ps Lines                     */
+/*!< CSI Ps S       ->      SU  Scroll Up                       Scroll up Ps lines                  */
+/*!< CSI Ps T       ->      SD  Scroll Down                     Scroll down Ps lines                */
+/*!< CSI Ps n       ->      DSR Device Status Report                                                */
+/*!<                            Ps = 5 -> Status Report CSI 0 n                                     */
+/*!<                            Ps = 6 -> Report Cursor Position [row;column] as CSI r ; c R        */
+/*!< CSI s          ->      SCP Save Current Cursor Position                                        */
+/*!< CSI u          ->      RCP Restore Saved Cursor Position                                       */
+/*!< CSI Ps t       ->      WM  Window manipulation                                                 */
+/*!<                            Ps = 18 -> Report the size of the text area in characters           */
+/*!<                                as CSI 8 ; height ; width t                                     */
+/*!< CSI ? Ps h     ->      DECSET DEC Private Mode Set                                             */
+/*!<                            Ps = 47 -> UUse Alternate Screen Buffer                             */
+/*!< CSI ? Ps l     ->      DECRST DEC Private Mode Reset                                           */
+/*!<                            Ps = 47 -> Use Normal Screen Buffer                                 */
+
+#ifndef CHRY_READLINE_KEYCODE_H
+#define CHRY_READLINE_KEYCODE_H
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+enum {
+    /*!< C0 control codes for general use                                       */
+    CHRY_READLINE_C0_NUL = 0x00, /*!< Null                      \0              */
+    CHRY_READLINE_C0_SOH = 0x01, /*!< Start of Heading                          */
+    CHRY_READLINE_C0_STX = 0x02, /*!< Start of Text                             */
+    CHRY_READLINE_C0_ETX = 0x03, /*!< End of Text                               */
+    CHRY_READLINE_C0_EOT = 0x04, /*!< End of Transmission                       */
+    CHRY_READLINE_C0_ENQ = 0x05, /*!< Enquiry                                   */
+    CHRY_READLINE_C0_ACK = 0x06, /*!< Acknowledge                               */
+    CHRY_READLINE_C0_BEL = 0x07, /*!< Bell, Alert               \a              */
+    CHRY_READLINE_C0_BS = 0x08,  /*!< Backspace                 \b              */
+    CHRY_READLINE_C0_HT = 0x09,  /*!< Horizontal Tabulation     \t              */
+    CHRY_READLINE_C0_LF = 0x0A,  /*!< Line Feed                 \n              */
+    CHRY_READLINE_C0_VT = 0x0B,  /*!< Vertical Tabulation       \v              */
+    CHRY_READLINE_C0_FF = 0x0C,  /*!< Form Feed                 \f              */
+    CHRY_READLINE_C0_CR = 0x0D,  /*!< Carriage Return           \r              */
+    CHRY_READLINE_C0_SO = 0x0E,  /*!< Shift Out                                 */
+    CHRY_READLINE_C0_SI = 0x0F,  /*!< Shift In                                  */
+    CHRY_READLINE_C0_DLE = 0x10, /*!< Data Link Escape                          */
+    CHRY_READLINE_C0_DC1 = 0x11, /*!< Device Control One        XON             */
+    CHRY_READLINE_C0_DC2 = 0x12, /*!< Device Control Two                        */
+    CHRY_READLINE_C0_DC3 = 0x13, /*!< Device Control Three      XOFF            */
+    CHRY_READLINE_C0_DC4 = 0x14, /*!< Device Control Four                       */
+    CHRY_READLINE_C0_NAK = 0x15, /*!< Negative Acknowledge                      */
+    CHRY_READLINE_C0_SYN = 0x16, /*!< Synchronous Idle                          */
+    CHRY_READLINE_C0_ETB = 0x17, /*!< End of Transmission Block                 */
+    CHRY_READLINE_C0_CAN = 0x18, /*!< Cancel                                    */
+    CHRY_READLINE_C0_EM = 0x19,  /*!< End of medium                             */
+    CHRY_READLINE_C0_SUB = 0x1A, /*!< Substitute                                */
+    CHRY_READLINE_C0_ESC = 0x1B, /*!< Escape                    \e              */
+    CHRY_READLINE_C0_FS = 0x1C,  /*!< File Separator                            */
+    CHRY_READLINE_C0_GS = 0x1D,  /*!< Group Separator                           */
+    CHRY_READLINE_C0_RS = 0x1E,  /*!< Record Separator                          */
+    CHRY_READLINE_C0_US = 0x1F,  /*!< Unit Separator                            */
+    /*!< While not technically part of the C0 control  character range, the     */
+    /*!< following two characters are defined in ISO/IEC 2022 as always being   */
+    /*!< available regardless of which sets of control characters and graphics  */
+    /*!< characters have been registered. They can be thought of as having some */
+    /*!< characteristics of control characters.                                 */
+    CHRY_READLINE_C0_SP = 0x20,  /*!< Space                                     */
+    CHRY_READLINE_G0_BEG = 0x20, /*!< G0 Code Start                             */
+    CHRY_READLINE_G0_END = 0x7E, /*!< G0 Code End                               */
+    CHRY_READLINE_C0_DEL = 0x7F, /*!< Delete                                    */
+    /*!< Not support 8bit codes                                                 */
+};
+
+enum {
+    CHRY_READLINE_EXEC_NUL = 0,   /*!< Null                      */
+    CHRY_READLINE_EXEC_CLR,       /*!< Clear screen refresh line */
+    CHRY_READLINE_EXEC_NLN,       /*!< Newline                   */
+    CHRY_READLINE_EXEC_ALN,       /*!< Abortline                 */
+    CHRY_READLINE_EXEC_DEL,       /*!< Delete character          */
+    CHRY_READLINE_EXEC_BS,        /*!< Backspace character       */
+    CHRY_READLINE_EXEC_MVRT,      /*!< Move Right                */
+    CHRY_READLINE_EXEC_MVLT,      /*!< Move Left                 */
+    CHRY_READLINE_EXEC_MVED,      /*!< Move End                  */
+    CHRY_READLINE_EXEC_MVHM,      /*!< Move Home                 */
+    CHRY_READLINE_EXEC_NXTH,      /*!< Next History              */
+    CHRY_READLINE_EXEC_PRVH,      /*!< Prev History              */
+    CHRY_READLINE_EXEC_DLWD,      /*!< Delete prev word          */
+    CHRY_READLINE_EXEC_DHLN,      /*!< Delete whole line         */
+    CHRY_READLINE_EXEC_DELN,      /*!< Delete cursor to end line */
+    CHRY_READLINE_EXEC_CPLT,      /*!< Complete                  */
+    CHRY_READLINE_EXEC_ACPLT,     /*!< Autocomplete or space     */
+    CHRY_READLINE_EXEC_SWNM,      /*!< Switch to Normal Screen   */
+    CHRY_READLINE_EXEC_HELP,      /*!< Show help                 */
+    CHRY_READLINE_EXEC_EOF_,      /*!< End of file               */
+    CHRY_READLINE_EXEC_SIGINT_,   /*!< SIGINT                    */
+    CHRY_READLINE_EXEC_EOF,       /*!< End of file               */
+    CHRY_READLINE_EXEC_SIGINT,    /*!< SIGINT                    */
+    CHRY_READLINE_EXEC_SIGQUIT,   /*!< SIGQUIT                   */
+    CHRY_READLINE_EXEC_SIGCONT,   /*!< SIGTCONT                  */
+    CHRY_READLINE_EXEC_SIGSTOP,   /*!< SIGSTOP                   */
+    CHRY_READLINE_EXEC_SIGTSTP,   /*!< SIGTSTP                   */
+    CHRY_READLINE_EXEC_F1,        /*!< Fucntion 1                */
+    CHRY_READLINE_EXEC_F2,        /*!< Fucntion 2                */
+    CHRY_READLINE_EXEC_F3,        /*!< Fucntion 3                */
+    CHRY_READLINE_EXEC_F4,        /*!< Fucntion 4                */
+    CHRY_READLINE_EXEC_F5,        /*!< Fucntion 5                */
+    CHRY_READLINE_EXEC_F6,        /*!< Fucntion 6                */
+    CHRY_READLINE_EXEC_F7,        /*!< Fucntion 7                */
+    CHRY_READLINE_EXEC_F8,        /*!< Fucntion 8                */
+    CHRY_READLINE_EXEC_F9,        /*!< Fucntion 9                */
+    CHRY_READLINE_EXEC_F10,       /*!< Fucntion 10               */
+    CHRY_READLINE_EXEC_F11,       /*!< Fucntion 11               */
+    CHRY_READLINE_EXEC_F12,       /*!< Fucntion 12               */
+    CHRY_READLINE_EXEC_USER,      /*!< User Event Start          */
+    CHRY_READLINE_EXEC_END = 255, /*!< Max Value is 255          */
+};
+
+enum {
+    CHRY_READLINE_CTRLMAP_A = 1, /*!< defalut is MVHM   */
+    CHRY_READLINE_CTRLMAP_B,     /*!< default is MVLT   */
+    CHRY_READLINE_CTRLMAP_C,     /*!< default is ALN    */
+    CHRY_READLINE_CTRLMAP_D,     /*!< default is DEL    */
+    CHRY_READLINE_CTRLMAP_E,     /*!< default is MVED   */
+    CHRY_READLINE_CTRLMAP_F,     /*!< default is MVRT   */
+    CHRY_READLINE_CTRLMAP_G,     /*!< default is ALN    */
+    CHRY_READLINE_CTRLMAP_H,     /*!< default is BS     */
+    CHRY_READLINE_CTRLMAP_I,     /*!< default is CPLT   */
+    CHRY_READLINE_CTRLMAP_J,     /*!< default is NLN    */
+    CHRY_READLINE_CTRLMAP_K,     /*!< default is DELN   */
+    CHRY_READLINE_CTRLMAP_L,     /*!< default is CLR    */
+    CHRY_READLINE_CTRLMAP_M,     /*!< default is NLN    */
+    CHRY_READLINE_CTRLMAP_N,     /*!< default is NXTH   */
+    CHRY_READLINE_CTRLMAP_O,     /*!< default is NLN    */
+    CHRY_READLINE_CTRLMAP_P,     /*!< default is PRVH   */
+    CHRY_READLINE_CTRLMAP_Q,     /*!< default is NUL    */
+    CHRY_READLINE_CTRLMAP_R,     /*!< default is NUL    */
+    CHRY_READLINE_CTRLMAP_S,     /*!< default is NUL    */
+    CHRY_READLINE_CTRLMAP_T,     /*!< default is NUL    */
+    CHRY_READLINE_CTRLMAP_U,     /*!< default is DHLN   */
+    CHRY_READLINE_CTRLMAP_V,     /*!< default is NUL    */
+    CHRY_READLINE_CTRLMAP_W,     /*!< default is DLWD   */
+    CHRY_READLINE_CTRLMAP_X,     /*!< default is NUL    */
+    CHRY_READLINE_CTRLMAP_Y,     /*!< default is NUL    */
+    CHRY_READLINE_CTRLMAP_Z,     /*!< default is ALN    */
+};
+
+enum {
+    CHRY_READLINE_ALTMAP_A = 0, /*!< default is NUL     */
+    CHRY_READLINE_ALTMAP_B,     /*!< default is NUL     */
+    CHRY_READLINE_ALTMAP_C,     /*!< default is NUL     */
+    CHRY_READLINE_ALTMAP_D,     /*!< default is NUL     */
+    CHRY_READLINE_ALTMAP_E,     /*!< default is NUL     */
+    CHRY_READLINE_ALTMAP_F,     /*!< default is NUL     */
+    CHRY_READLINE_ALTMAP_G,     /*!< default is NUL     */
+    CHRY_READLINE_ALTMAP_H,     /*!< default is NUL     */
+    CHRY_READLINE_ALTMAP_I,     /*!< default is NUL     */
+    CHRY_READLINE_ALTMAP_J,     /*!< default is NUL     */
+    CHRY_READLINE_ALTMAP_K,     /*!< default is NUL     */
+    CHRY_READLINE_ALTMAP_L,     /*!< default is NUL     */
+    CHRY_READLINE_ALTMAP_M,     /*!< default is NUL     */
+    CHRY_READLINE_ALTMAP_N,     /*!< default is NUL     */
+    CHRY_READLINE_ALTMAP_O,     /*!< default is NUL     */
+    CHRY_READLINE_ALTMAP_P,     /*!< default is NUL     */
+    CHRY_READLINE_ALTMAP_Q,     /*!< default is NUL     */
+    CHRY_READLINE_ALTMAP_R,     /*!< default is NUL     */
+    CHRY_READLINE_ALTMAP_S,     /*!< default is NUL     */
+    CHRY_READLINE_ALTMAP_T,     /*!< default is NUL     */
+    CHRY_READLINE_ALTMAP_U,     /*!< default is NUL     */
+    CHRY_READLINE_ALTMAP_V,     /*!< default is NUL     */
+    CHRY_READLINE_ALTMAP_W,     /*!< default is NUL     */
+    CHRY_READLINE_ALTMAP_X,     /*!< default is NUL     */
+    CHRY_READLINE_ALTMAP_Y,     /*!< default is NUL     */
+    CHRY_READLINE_ALTMAP_Z,     /*!< default is NUL     */
+};
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/APP/shell/chry_shell.c b/APP/shell/chry_shell.c
new file mode 100644 (file)
index 0000000..6bd0a27
--- /dev/null
@@ -0,0 +1,1065 @@
+/*
+ * Copyright (c) 2022, Egahp
+ *
+ * SPDX-License-Identifier: Apache-2.0
+ */
+
+#include <stdio.h>
+#include <stdarg.h>
+#include <stddef.h>
+#include <stdlib.h>
+#include <stdint.h>
+#include <stdbool.h>
+#include <string.h>
+#include <signal.h>
+#include "csh.h"
+
+__CSH_WEAK size_t strnlen(const char *s, size_t maxlen)
+{
+    const char *p = (const char *)memchr(s, '\0', maxlen);
+    return (p == NULL) ? maxlen : (size_t)(p - s);
+}
+
+#if defined(CONFIG_CSH_DEBUG) && CONFIG_CSH_DEBUG
+#define CHRY_SHELL_PARAM_CHECK(__expr, __ret) \
+    do {                                      \
+        if (!(__expr)) {                      \
+            return __ret;                     \
+        }                                     \
+    } while (0)
+
+#else
+#define CHRY_SHELL_PARAM_CHECK(__expr, __ret) ((void)0)
+#endif
+
+#if defined(__CC_ARM) || defined(__CLANG_ARM) || defined(__GNUC__) || defined(__ADSPBLACKFIN__)
+#ifndef __weak
+#define __weak __attribute__((weak))
+#endif
+#else
+#ifndef __weak
+#define __weak
+#endif
+#endif
+
+#define chry_shell_offsetof(type, member)          ((size_t)&(((type *)0)->member))
+#define chry_shell_container_of(ptr, type, member) ((type *)((char *)(ptr) - chry_shell_offsetof(type, member)))
+
+/*!< prompt segment index */
+#define CSH_PROMPT_SEG_USER 0
+#define CSH_PROMPT_SEG_HOST 2
+#define CSH_PROMPT_SEG_PATH 4
+
+extern void chry_shell_port_default_handler(chry_shell_t *csh, int sig);
+extern int chry_shell_port_create_context(chry_shell_t *csh, int argc, const char **argv);
+extern int chry_shell_port_hash_strcmp(const char *hash, const char *str);
+
+#if defined(CONFIG_CSH_MULTI_THREAD) && CONFIG_CSH_MULTI_THREAD
+/* static const uint8_t sigmap[CSH_SIGNAL_COUNT] = { CSH_SIGINT, CSH_SIGQUIT, CSH_SIGKILL, CSH_SIGTERM, CSH_SIGSTOP, CSH_SIGTSTP, CSH_SIGCONT }; */
+#if !defined(CONFIG_CSH_SIGNAL_HANDLER) || (CONFIG_CSH_SIGNAL_HANDLER == 0)
+static chry_sighandler_t sighdl[CSH_SIGNAL_COUNT] = {
+    chry_shell_port_default_handler,
+    chry_shell_port_default_handler,
+    chry_shell_port_default_handler,
+    chry_shell_port_default_handler,
+    chry_shell_port_default_handler,
+    chry_shell_port_default_handler,
+    chry_shell_port_default_handler,
+};
+#endif
+
+#if defined(__CC_ARM)
+__CSH_WEAK size_t strnlen(const char *s, size_t maxlen)
+{
+    const char *p = (const char *)memchr(s, '\0', maxlen);
+    return (p == NULL) ? maxlen : (size_t)(p - s);
+}
+#endif
+
+/*****************************************************************************
+* @brief        default signal handler
+*
+* @param[in]    signum      signal number
+*
+*****************************************************************************/
+__weak void chry_shell_port_default_handler(chry_shell_t *csh, int sig)
+{
+    (void)csh;
+    switch (sig) {
+        case CSH_SIGINT:
+            break;
+        case CSH_SIGQUIT:
+            break;
+        case CSH_SIGKILL:
+            break;
+        case CSH_SIGTERM:
+            break;
+        case CSH_SIGSTOP:
+            break;
+        case CSH_SIGTSTP:
+            break;
+        case CSH_SIGCONT:
+            break;
+        default:
+            break;
+    }
+}
+
+/*****************************************************************************
+* @brief        create context to execute
+*
+* @param[in]    csh         shell instance
+* @param[in]    argc        argument count
+* @param[in]    argv        argument value
+*
+* @retval                   0:success -1:error
+*****************************************************************************/
+__weak int chry_shell_port_create_context(chry_shell_t *csh, int argc, const char **argv)
+{
+    (void)csh;
+    (void)argc;
+    (void)argv;
+    return -1;
+}
+
+/*****************************************************************************
+* @brief        conversion signum
+*
+* @param[in]    signum      signal number
+*
+* @retval                   0<= signal index -1:not find
+*****************************************************************************/
+/*
+static int chry_shell_conversion_signum(int signum)
+{
+    int sigidx = -1;
+
+    for (uint8_t i = 0; i < CSH_SIGNAL_COUNT; i++) {
+        if (sigmap[i] == signum) {
+            sigidx = i;
+            break;
+        }
+    }
+
+    return sigidx;
+}
+*/
+#endif
+
+/*****************************************************************************
+* @brief        hash str then compare
+*
+* @param[in]    hash        hash
+* @param[in]    str         string
+*
+* @retval                   0:Equal 1:hash>str -1:str>hash
+*****************************************************************************/
+__weak int chry_shell_port_hash_strcmp(const char *hash, const char *str)
+{
+    /*!< simple demo */
+    return strcmp(hash, str);
+}
+
+#if defined(CONFIG_CSH_COMPLETION) && CONFIG_CSH_COMPLETION
+/*****************************************************************************
+* @brief        completion callback
+*
+* @param[in]    rl          readline instance
+* @param[in]    pre         pre string
+* @param[in]    size        strlen(pre)
+* @param[in]    argv        argument value (completion)
+* @param[in]    argl        argument length (completion length)
+* @param[in]    argcmax     argument max count (max completion count)
+*
+* @retval                   argc:argument count, max is argcmax
+*****************************************************************************/
+static uint8_t chry_shell_completion_callback(chry_readline_t *rl, char *pre, uint16_t *size, const char **argv, uint8_t *argl, uint8_t argcmax)
+{
+    chry_shell_t *csh = chry_shell_container_of(rl, chry_shell_t, rl);
+    uint8_t argc = 0;
+
+    if (*size == 0) {
+        return argc;
+    }
+
+    /*!< environment variable */
+    if (*size && pre[0] == '$') {
+        pre++;             /*!< skip $ */
+        *size = *size - 1; /*!< skip $ */
+        for (const chry_sysvar_t *var = csh->var_tbl_beg; var < csh->var_tbl_end; var++) {
+            if (strncmp(pre, var->name, *size) == 0) {
+                argv[argc] = var->name;
+                argl[argc] = strlen(var->name);
+                argc++;
+                if (argc >= argcmax) {
+                    break;
+                }
+            }
+        }
+
+        return argc;
+    }
+
+    const char *PATH = NULL;
+    uint8_t Pargc;
+    uint8_t Pargl[CONFIG_CSH_MAXSEG_PATH + 1];
+    const char *Pargv[CONFIG_CSH_MAXSEG_PATH + 1];
+
+    if (((*size >= 1) && (pre[0] == '/')) ||
+        ((*size >= 2) && (pre[0] == '.') && (pre[1] == '/')) ||
+        ((*size >= 3) && (pre[0] == '.') && (pre[1] == '.') && (pre[2] == '/'))) {
+        /*!< search from the current path */
+        PATH = csh->path;
+    } else {
+        /*!< search from the environment PATH */
+        for (const chry_sysvar_t *var = csh->var_tbl_beg; var < csh->var_tbl_end; var++) {
+            if (strcmp("PATH", var->name) == 0) {
+                PATH = var->var;
+                break;
+            }
+        }
+    }
+
+    while (PATH != NULL) {
+        Pargc = chry_shell_path_resolve(PATH, pre, Pargv, Pargl, CONFIG_CSH_MAXSEG_PATH + 1);
+        *size = Pargl[Pargc - 1];
+
+        /*!< match from system path */
+        for (const chry_syscall_t *call = csh->cmd_tbl_beg; call < csh->cmd_tbl_end; call++) {
+            uint8_t clen = 0;
+            const char *cpath_next;
+            const char *cpath_prev = NULL;
+            const char *cpath = call->path;
+            bool match = true;
+
+            for (uint8_t Pargi = 0;; Pargi++) {
+                if (Pargi >= Pargc) {
+                    bool exist = false;
+
+                    for (uint8_t i = 0; i < argc; i++) {
+                        if ((clen == argl[i]) && (strncmp(argv[i], cpath_prev, clen) == 0)) {
+                            exist = true;
+                            break;
+                        }
+                    }
+
+                    if (exist == false) {
+                        argv[argc] = cpath_prev;
+                        argl[argc] = clen;
+                        argc++;
+                        if (argc >= argcmax) {
+                            return argc;
+                        }
+                    }
+
+                    break;
+                }
+
+                if ((cpath == NULL) || (match == false)) {
+                    break;
+                }
+
+                cpath++;
+
+                if (strncmp(cpath, Pargv[Pargi], Pargl[Pargi]) != 0) {
+                    break;
+                }
+
+                cpath_next = strchr(cpath, '/');
+
+                if (cpath_next == NULL) {
+                    clen = strlen(cpath);
+                } else {
+                    clen = (uint8_t)(cpath_next - cpath);
+                }
+
+                match = (clen == Pargl[Pargi]);
+                cpath_prev = cpath;
+
+                if (cpath != call->name) {
+                    cpath = cpath_next == NULL ? (call->name - 1) : cpath_next;
+                } else {
+                    cpath = cpath_next;
+                }
+            }
+        }
+
+        /*!< match from port of file system */
+        PATH = strchr(PATH, ':');
+        PATH = (PATH != NULL) ? PATH + 1 : PATH;
+    }
+
+    return argc;
+}
+#endif
+
+#if defined(CONFIG_CSH_USER_CALLBACK) && CONFIG_CSH_USER_CALLBACK
+/*****************************************************************************
+* @brief        user callback
+*
+* @param[in]    rl          readline instance
+* @param[in]    exec        exec code
+*
+* @retval                   status
+*****************************************************************************/
+static int chry_shell_user_callback(chry_readline_t *rl, uint8_t exec)
+{
+    chry_shell_t *csh = chry_shell_container_of(rl, chry_shell_t, rl);
+    (void)csh;
+    /*!< user event callback will not output newline automatically */
+
+    switch (exec) {
+        case CHRY_READLINE_EXEC_EOF:
+            chry_readline_newline(rl);
+            break;
+
+#if defined(CONFIG_CSH_MULTI_THREAD) && CONFIG_CSH_MULTI_THREAD
+#if defined(CONFIG_CSH_SIGNAL_HANDLER) && CONFIG_CSH_SIGNAL_HANDLER
+        case CHRY_READLINE_EXEC_SIGINT:
+            csh->sighdl[0](csh, CSH_SIGINT);
+            return 0;
+        case CHRY_READLINE_EXEC_SIGQUIT:
+            csh->sighdl[1](csh, CSH_SIGQUIT);
+            return 0;
+        case CHRY_READLINE_EXEC_SIGCONT:
+            csh->sighdl[6](csh, CSH_SIGCONT);
+            return 1;
+        case CHRY_READLINE_EXEC_SIGSTOP:
+            csh->sighdl[4](csh, CSH_SIGSTOP);
+            return 1;
+        case CHRY_READLINE_EXEC_SIGTSTP:
+            csh->sighdl[5](csh, CSH_SIGTSTP);
+            return 1;
+#else
+        case CHRY_READLINE_EXEC_SIGINT:
+            sighdl[0](csh, CSH_SIGINT);
+            return 0;
+        case CHRY_READLINE_EXEC_SIGQUIT:
+            sighdl[1](csh, CSH_SIGQUIT);
+            return 0;
+        case CHRY_READLINE_EXEC_SIGCONT:
+            sighdl[6](csh, CSH_SIGCONT);
+            return 1;
+        case CHRY_READLINE_EXEC_SIGSTOP:
+            sighdl[4](csh, CSH_SIGSTOP);
+            return 1;
+        case CHRY_READLINE_EXEC_SIGTSTP:
+            sighdl[5](csh, CSH_SIGTSTP);
+            return 1;
+#endif
+#else
+        case CHRY_READLINE_EXEC_SIGINT:
+            return 0;
+        case CHRY_READLINE_EXEC_SIGQUIT:
+            return 0;
+        case CHRY_READLINE_EXEC_SIGCONT:
+            return 1;
+        case CHRY_READLINE_EXEC_SIGSTOP:
+            return 1;
+        case CHRY_READLINE_EXEC_SIGTSTP:
+            return 1;
+#endif
+        case CHRY_READLINE_EXEC_F1 ... CHRY_READLINE_EXEC_F12:
+            chry_readline_newline(rl);
+            break;
+        case CHRY_READLINE_EXEC_USER ... CHRY_READLINE_EXEC_END:
+            chry_readline_newline(rl);
+            break;
+        default:
+            return -1;
+    }
+
+    /*!< return 1 will not refresh */
+    /*!< return 0 to refresh whole line (include prompt) */
+    /*!< return -1 to end readline (error) */
+    return 0;
+}
+#endif
+
+/*****************************************************************************
+* @brief        init shell
+*
+* @param[in]    csh         shell instance
+* @param[in]    init        init config
+*
+* @retval                   0:Success -1:Error
+*****************************************************************************/
+int chry_shell_init(chry_shell_t *csh, const chry_shell_init_t *init)
+{
+    CHRY_SHELL_PARAM_CHECK(NULL != csh, -1);
+    CHRY_SHELL_PARAM_CHECK(NULL != init, -1);
+    CHRY_SHELL_PARAM_CHECK(NULL != init->sget, -1);
+    CHRY_SHELL_PARAM_CHECK(NULL != init->sput, -1);
+
+#if defined(CONFIG_CSH_PROMPTEDIT) && CONFIG_CSH_PROMPTEDIT
+    CHRY_SHELL_PARAM_CHECK(NULL != init->prompt_buffer, -1);
+#endif
+
+#if defined(CONFIG_CSH_HISTORY) && CONFIG_CSH_HISTORY
+    CHRY_SHELL_PARAM_CHECK(NULL != init->history_buffer, -1);
+#endif
+
+#if defined(CONFIG_CSH_LNBUFF_STATIC) && CONFIG_CSH_LNBUFF_STATIC
+    CHRY_SHELL_PARAM_CHECK(NULL != init->line_buffer, -1);
+#endif
+
+    int ret = 0;
+    chry_readline_init_t rl_init;
+
+    /*!< do readline init */
+#if defined(CONFIG_CSH_PROMPTEDIT) && CONFIG_CSH_PROMPTEDIT
+    rl_init.prompt = init->prompt_buffer;
+    rl_init.pptsize = init->prompt_buffer_size;
+#else
+    rl_init.prompt = "$ ";
+    rl_init.pptsize = 3;
+#endif
+    rl_init.history = init->history_buffer;
+    rl_init.histsize = init->history_buffer_size;
+    rl_init.sput = init->sput;
+    rl_init.sget = init->sget;
+
+    if (chry_readline_init(&csh->rl, &rl_init)) {
+        return -1;
+    }
+
+    csh->cmd_tbl_beg = init->command_table_beg;
+    csh->cmd_tbl_end = init->command_table_end;
+    csh->var_tbl_beg = init->variable_table_beg;
+    csh->var_tbl_end = init->variable_table_end;
+
+#if defined(CONFIG_CSH_LNBUFF_STATIC) && CONFIG_CSH_LNBUFF_STATIC
+    csh->linebuff = init->line_buffer;
+    csh->buffsize = init->line_buffer_size;
+    csh->linesize = 0;
+#endif
+
+    csh->exec_code = 0;
+    csh->exec = CSH_STATUS_EXEC_IDLE;
+
+    /*!< set default user id */
+    if ((init->uid >= CONFIG_CSH_MAX_USER) || (init->uid < 0)) {
+        return -1;
+    }
+    csh->uid = init->uid;
+
+    /*!< set host name */
+    if (strnlen(init->host, 255) == 255) {
+        return -1;
+    }
+    csh->host = init->host;
+
+    /*!< set users name */
+    for (uint8_t i = 0; i < CONFIG_CSH_MAX_USER; i++) {
+        if (strnlen(init->user[i], 255) == 255) {
+            return -1;
+        }
+        if (strnlen(init->hash[i], 255) == 255) {
+            return -1;
+        }
+        csh->user[i] = init->user[i];
+        csh->hash[i] = init->hash[i];
+    }
+
+    /*!< set default path */
+#if defined(CONFIG_CSH_MAXLEN_PATH) && CONFIG_CSH_MAXLEN_PATH
+    csh->path[0] = '/';
+    csh->path[1] = '\0';
+#else
+    csh->path = "/";
+#endif
+
+    csh->data = NULL;
+    csh->user_data = init->user_data;
+
+#if defined(CONFIG_CSH_COMPLETION) && CONFIG_CSH_COMPLETION
+    chry_readline_set_completion_cb(&csh->rl, chry_shell_completion_callback);
+#endif
+
+#if defined(CONFIG_CSH_USER_CALLBACK) && CONFIG_CSH_USER_CALLBACK
+    chry_readline_set_user_cb(&csh->rl, chry_shell_user_callback);
+#endif
+
+#if defined(CONFIG_CSH_PROMPTEDIT) && CONFIG_CSH_PROMPTEDIT
+    ret |= chry_readline_prompt_edit(&csh->rl, CSH_PROMPT_SEG_USER, (chry_readline_sgr_t){ .foreground = CHRY_READLINE_SGR_GREEN, .bold = 1 }.raw, csh->user[csh->uid]);
+    ret |= chry_readline_prompt_edit(&csh->rl, CSH_PROMPT_SEG_USER + 1, (chry_readline_sgr_t){ .foreground = CHRY_READLINE_SGR_GREEN, .bold = 1 }.raw, "@");
+    ret |= chry_readline_prompt_edit(&csh->rl, CSH_PROMPT_SEG_HOST, (chry_readline_sgr_t){ .foreground = CHRY_READLINE_SGR_GREEN, .bold = 1 }.raw, csh->host);
+    ret |= chry_readline_prompt_edit(&csh->rl, CSH_PROMPT_SEG_HOST + 1, 0, ":");
+    ret |= chry_readline_prompt_edit(&csh->rl, CSH_PROMPT_SEG_PATH, (chry_readline_sgr_t){ .foreground = CHRY_READLINE_SGR_BLUE, .bold = 1 }.raw, csh->path);
+    ret |= chry_readline_prompt_edit(&csh->rl, CSH_PROMPT_SEG_PATH + 1, 0, "$ ");
+#else
+
+#endif
+    return ret;
+}
+
+/*****************************************************************************
+* @brief        execute task internal
+*
+* @param[in]    csh         shell instance
+*
+*****************************************************************************/
+static void chry_shell_task_exec_internal(chry_shell_t *csh, int argc, const char **argv)
+{
+    volatile uint8_t *pexec = (void *)&csh->exec;
+    volatile int *pcode = (void *)&csh->exec_code;
+
+    /*!< if stage find */
+    if (*pexec == CSH_STATUS_EXEC_FIND) {
+        /*!< stage prepare */
+        *pexec = CSH_STATUS_EXEC_PREP;
+
+        *pcode = ((chry_syscall_func_t)argv[argc + 2])(argc, (void *)argv);
+
+        /*!< stage done */
+        *pexec = CSH_STATUS_EXEC_DONE;
+    }
+}
+
+/*****************************************************************************
+* @brief        execute task
+*
+* @param[in]    csh         shell instance
+*
+*****************************************************************************/
+void chry_shell_task_exec(chry_shell_t *csh)
+{
+    CHRY_SHELL_PARAM_CHECK(NULL != csh, );
+    (void)csh;
+#if defined(CONFIG_CSH_MULTI_THREAD) && CONFIG_CSH_MULTI_THREAD
+    chry_shell_task_exec_internal(csh, csh->exec_argc, &csh->exec_argv[0]);
+#endif
+}
+
+/*****************************************************************************
+* @brief        read eval print loop task
+*
+* @param[in]    csh         shell instance
+*
+* @retval                   0:Success -1:Error 1:Continue
+*****************************************************************************/
+int chry_shell_task_repl(chry_shell_t *csh)
+{
+    CHRY_SHELL_PARAM_CHECK(NULL != csh, -1);
+    char *csh_linebuff;
+    uint16_t *csh_linesize;
+
+#if defined(CONFIG_CSH_LNBUFF_STATIC) && CONFIG_CSH_LNBUFF_STATIC
+    csh_linebuff = csh->linebuff;
+    csh_linesize = &csh->linesize;
+
+    char *line = chry_readline(&csh->rl, csh_linebuff, csh->buffsize, csh_linesize);
+#else
+    char linebuff[CONFIG_CSH_LNBUFF_SIZE];
+    uint16_t linesize;
+
+    csh_linebuff = linebuff;
+    csh_linesize = &linesize;
+
+    char *line = chry_readline(&csh->rl, csh_linebuff, CONFIG_CSH_LNBUFF_SIZE, csh_linesize);
+#endif
+
+    if (line == NULL) {
+        return -1;
+    } else if (line == (void *)-1) {
+        return 1;
+    } else if (*csh_linesize) {
+        int *argc;
+        const char **argv;
+        volatile uint8_t *pexec = (void *)&csh->exec;
+        volatile uint32_t *pcode = (void *)&csh->exec_code;
+        *pcode = 0xBAD2BE8E; /*!< a magic number */
+
+#if defined(CONFIG_CSH_MULTI_THREAD) && CONFIG_CSH_MULTI_THREAD
+        argc = &csh->exec_argc;
+        argv = &csh->exec_argv[0];
+#else
+        int csh_exec_argc;
+        const char *csh_exec_argv[CONFIG_CSH_MAX_ARG + 3];
+        argc = &csh_exec_argc;
+        argv = &csh_exec_argv[0];
+#endif
+
+        *argc = chry_shell_parse(line, *csh_linesize, argv, CONFIG_CSH_MAX_ARG + 1);
+
+        /*!< compile environment variable */
+        for (uint8_t i = 0; i < *argc;) {
+            if (argv[i][0] == '$') {
+                const char *param = chry_shell_getenv(csh, argv[i] + 1);
+
+                if (param == NULL) {
+                    memmove(&argv[i], &argv[i + 1], (*argc - i) * sizeof(char *));
+                    *argc = (*argc > 0) ? *argc - 1 : 0;
+                } else {
+                    argv[i] = param;
+                    i++;
+                }
+            } else {
+                i++;
+            }
+        }
+
+        argv[*argc + 1] = (void *)csh;
+        argv[*argc + 2] = NULL;
+
+        if (*argc) {
+            uint8_t size = strlen(argv[0]);
+            const char *PATH = NULL;
+            uint8_t Pargc;
+            uint8_t Pargl[CONFIG_CSH_MAXSEG_PATH + 1];
+            const char *Pargv[CONFIG_CSH_MAXSEG_PATH + 1];
+
+            if (((size >= 1) && (argv[0][0] == '/')) ||
+                ((size >= 2) && (argv[0][0] == '.') && (argv[0][1] == '/')) ||
+                ((size >= 3) && (argv[0][0] == '.') && (argv[0][1] == '.') && (argv[0][2] == '/'))) {
+                /*!< search from the current path */
+                PATH = csh->path;
+            } else {
+                /*!< search from the environment PATH */
+                for (const chry_sysvar_t *var = csh->var_tbl_beg; var < csh->var_tbl_end; var++) {
+                    if (strcmp("PATH", var->name) == 0) {
+                        PATH = var->var;
+                        break;
+                    }
+                }
+            }
+
+            while (PATH != NULL) {
+                Pargc = chry_shell_path_resolve(PATH, argv[0], Pargv, Pargl, CONFIG_CSH_MAXSEG_PATH + 1);
+
+                /*!< match from system path */
+                for (const chry_syscall_t *call = csh->cmd_tbl_beg; call < csh->cmd_tbl_end; call++) {
+                    uint8_t clen = 0;
+                    const char *cpath_next;
+                    const char *cpath = call->path;
+
+                    for (uint8_t Pargi = 0;; Pargi++) {
+                        if (Pargi >= Pargc) {
+                            if (cpath == NULL) {
+                                /*!< match success */
+                                argv[*argc + 2] = (void *)call->func;
+                                goto found;
+                            } else {
+                                /*!< argv[0] end */
+                                break;
+                            }
+                        }
+
+                        if (cpath == NULL) {
+                            /*!< path+name end */
+                            break;
+                        }
+
+                        cpath++;
+
+                        if (strncmp(cpath, Pargv[Pargi], Pargl[Pargi]) != 0) {
+                            /*!< match failed */
+                            break;
+                        }
+
+                        cpath_next = strchr(cpath, '/');
+
+                        if (cpath_next == NULL) {
+                            clen = strlen(cpath);
+                        } else {
+                            clen = (uint8_t)(cpath_next - cpath);
+                        }
+
+                        if (clen != Pargl[Pargi]) {
+                            /*!< len not equal */
+                            break;
+                        }
+
+                        if (cpath != call->name) {
+                            cpath = cpath_next == NULL ? (call->name - 1) : cpath_next;
+                        } else {
+                            cpath = cpath_next;
+                        }
+                    }
+                }
+
+                /*!< match from port of file system */
+                PATH = strchr(PATH, ':');
+                PATH = (PATH != NULL) ? PATH + 1 : PATH;
+            }
+
+        found:
+
+            if (NULL == argv[*argc + 2]) {
+                *pexec = CSH_STATUS_EXEC_IDLE;
+
+                csh->rl.sput(&csh->rl, argv[0], strlen(argv[0]));
+                csh->rl.sput(&csh->rl, ": command not found" CONFIG_CSH_NEWLINE CONFIG_CSH_NEWLINE,
+                             19 + (sizeof(CONFIG_CSH_NEWLINE) ? (sizeof(CONFIG_CSH_NEWLINE) - 1) * 2 : 0));
+            } else {
+#if defined(CONFIG_CSH_MULTI_THREAD) && CONFIG_CSH_MULTI_THREAD
+                *pexec = CSH_STATUS_EXEC_FIND;
+
+                chry_readline_ignore(&csh->rl, true); /*!< accepts only signal inputs */
+                chry_readline_auto_refresh(&csh->rl, false);
+
+                /*!< reset signal handler to default */
+                for (uint8_t i = 0; i < CSH_SIGNAL_COUNT; i++) {
+#if defined(CONFIG_CSH_SIGNAL_HANDLER) && CONFIG_CSH_SIGNAL_HANDLER
+                    csh->sighdl[i] = chry_shell_port_default_handler;
+#else
+                    sighdl[i] = chry_shell_port_default_handler;
+#endif
+                }
+
+                /*!< try to create execute context */
+                if (0 != chry_shell_port_create_context(csh, *argc, argv)) {
+                    *pexec = CSH_STATUS_EXEC_IDLE;
+
+                    csh->rl.sput(&csh->rl, argv[0], strlen(argv[0]));
+                    csh->rl.sput(&csh->rl, ": context creation error" CONFIG_CSH_NEWLINE CONFIG_CSH_NEWLINE,
+                                 24 + (sizeof(CONFIG_CSH_NEWLINE) ? (sizeof(CONFIG_CSH_NEWLINE) - 1) * 2 : 0));
+                }
+#else
+                *pexec = CSH_STATUS_EXEC_FIND;
+                chry_shell_task_exec_internal(csh, *argc, argv);
+                *pexec = CSH_STATUS_EXEC_IDLE;
+#endif
+            }
+        }
+
+        return 0;
+    }
+
+    return 0;
+}
+
+/*****************************************************************************
+* @brief        parse line to argc,argv[]
+*
+* @param[in]    line        read line
+* @param[in]    linesize    strlen(line)
+* @param[out]   argv        argument value
+* @param[out]   argcmax     max argument count (max segment count)
+*
+* @retval                   argc:argument count, max is argcmax
+*****************************************************************************/
+int chry_shell_parse(char *line, uint32_t linesize, const char **argv, uint8_t argcmax)
+{
+    int argc = 0;
+    bool ignore = false;
+    bool start = false;
+    bool escape = false;
+
+    argcmax = (argcmax > 0) ? argcmax - 1 : argcmax;
+
+    while (linesize) {
+        char c = *line;
+
+        if (c == '\0') {
+            break;
+        } else if ((escape == false) && (c == '\\')) {
+            escape = true;
+            memmove(line, line + 1, linesize);
+            line--;
+        } else if ((escape == false) && (ignore == false) && (c == ' ')) {
+            start = false;
+            *line = '\0';
+        } else if ((escape == false) && (c == '"')) {
+            memmove(line, line + 1, linesize);
+            line--;
+            ignore = !ignore;
+        } else if (!start) {
+            argv[argc] = line;
+            if (argc < argcmax) {
+                argc++;
+            } else {
+                break;
+            }
+            start = true;
+            escape = false;
+        } else {
+            escape = false;
+        }
+
+        line++;
+        linesize--;
+    }
+
+    *line = '\0';
+    argv[argc] = NULL;
+
+    return argc;
+}
+
+/*****************************************************************************
+* @brief        resolve path to argc,argv[],argl[]
+*
+* @param[in]    cur         current path
+* @param[in]    path        path
+* @param[out]   argv        argument value (path segment)
+* @param[out]   argl        argument length (path segment length)
+* @param[out]   argcmax     argument max count (max segment count)
+*
+* @retval                   argc:argument count, max is argcmax
+*****************************************************************************/
+int chry_shell_path_resolve(const char *cur, const char *path, const char **argv, uint8_t *argl, uint8_t argcmax)
+{
+    uint8_t len;
+    uint8_t argc = 0;
+    bool expr;
+
+    if (cur == NULL || path == NULL) {
+        return argc;
+    }
+
+    expr = (*path == '/') || ((cur[0] == '/') && (cur[1] == '\0'));
+
+    if (expr) {
+        cur = path;
+    }
+
+    argcmax = (argcmax > 0) ? argcmax - 1 : argcmax;
+
+resolve:
+
+    while ((cur != NULL) && (*cur != '\0') && (*cur != ':')) {
+        while (*cur == '/') {
+            cur++;
+        }
+        argv[argc] = cur;
+        cur = strchr(cur, '/');
+
+        if (cur == NULL) {
+            len = strlen(argv[argc]);
+        } else {
+            len = (uint8_t)(cur - argv[argc]);
+            const char *sep = memchr(argv[argc], ':', len);
+            if (sep != NULL) {
+                len = (uint8_t)(sep - argv[argc]);
+                cur = NULL;
+            }
+        }
+
+        if (len == 1) {
+            bool match_dot1 = argv[argc][0] == '.';
+            if (!match_dot1) {
+                argl[argc] = len;
+                argc++;
+            }
+        } else if (len == 2) {
+            bool match_dot1 = argv[argc][0] == '.';
+            bool match_dot2 = argv[argc][1] == '.';
+
+            if (match_dot1 && match_dot2) {
+                if (argc > 0) {
+                    argc--;
+                }
+            } else {
+                argl[argc] = len;
+                argc++;
+            }
+        } else {
+            argl[argc] = len;
+            argc++;
+        }
+
+        if (argc >= argcmax) {
+            argv[argc] = NULL;
+            argl[argc] = 0;
+            return argcmax;
+        }
+    }
+
+    if (!expr) {
+        cur = path;
+        expr = true;
+        goto resolve;
+    }
+
+    argv[argc] = NULL;
+    argl[argc] = 0;
+    return argc;
+}
+
+/*****************************************************************************
+* @brief        set host
+*
+* @param[in]    csh         shell instance
+* @param[in]    host        pointer of host
+*
+* @retval                   0:Success -1:Error
+*****************************************************************************/
+int chry_shell_set_host(chry_shell_t *csh, const char *host)
+{
+    CHRY_SHELL_PARAM_CHECK(NULL != csh, -1);
+    CHRY_SHELL_PARAM_CHECK(NULL != host, -1);
+
+    if (strnlen(host, 255) == 255) {
+        return -1;
+    }
+
+    csh->host = host;
+
+    return chry_readline_prompt_edit(&csh->rl, CSH_PROMPT_SEG_HOST, (chry_readline_sgr_t){ .foreground = CHRY_READLINE_SGR_GREEN, .bold = 1 }.raw, csh->host);
+}
+
+/*****************************************************************************
+* @brief        set user
+*
+* @param[in]    csh         shell instance
+* @param[in]    uid         user id
+* @param[in]    user        pointer of user
+* @param[in]    user        pointer of user password hash
+*
+* @retval                   0:Success -1:Error
+*****************************************************************************/
+int chry_shell_set_user(chry_shell_t *csh, uint8_t uid, const char *user, const char *hash)
+{
+    CHRY_SHELL_PARAM_CHECK(NULL != csh, -1);
+    CHRY_SHELL_PARAM_CHECK(NULL != user, -1);
+
+    if (uid < CONFIG_CSH_MAX_USER) {
+        if (strnlen(user, 255) == 255) {
+            return -1;
+        }
+        if (strnlen(hash, 255) == 255) {
+            return -1;
+        }
+
+        csh->user[uid] = user;
+        csh->hash[uid] = hash;
+        if (uid == csh->uid) {
+            return chry_readline_prompt_edit(&csh->rl, CSH_PROMPT_SEG_USER, (chry_readline_sgr_t){ .foreground = CHRY_READLINE_SGR_GREEN, .bold = 1 }.raw, csh->user[uid]);
+        }
+        return 0;
+    }
+
+    return -1;
+}
+
+/*****************************************************************************
+* @brief        set path
+*
+* @param[in]    csh         shell instance
+* @param[in]    size        strlen(path) + 1, include \0.
+*                           ignore when CONFIG_CSH_MAXLEN_PATH = 0
+* @param[in]    path        shell instance
+*
+* @retval                   0:Success -1:Error
+*****************************************************************************/
+int chry_shell_set_path(chry_shell_t *csh, uint8_t size, const char *path)
+{
+    CHRY_SHELL_PARAM_CHECK(NULL != csh, -1);
+    CHRY_SHELL_PARAM_CHECK(NULL != path, -1);
+
+#if defined(CONFIG_CSH_MAXLEN_PATH) && CONFIG_CSH_MAXLEN_PATH
+    if (size > CONFIG_CSH_MAXLEN_PATH) {
+        return -1;
+    }
+
+    memcpy(csh->path, path, size);
+    csh->path[size] = '\0';
+
+#else
+    if (strnlen(path, 255) == 255) {
+        return -1;
+    }
+    csh->path = path;
+#endif
+
+    return chry_readline_prompt_edit(&csh->rl, CSH_PROMPT_SEG_PATH, (chry_readline_sgr_t){ .foreground = CHRY_READLINE_SGR_BLUE, .bold = 1 }.raw, csh->path);
+}
+
+/*****************************************************************************
+* @brief        get path
+*
+* @param[in]    csh         shell instance
+* @param[in]    size        path buffer size
+* @param[in]    path        path buffer
+*
+*****************************************************************************/
+void chry_shell_get_path(chry_shell_t *csh, uint8_t size, char *path)
+{
+    CHRY_SHELL_PARAM_CHECK(NULL != csh, );
+    CHRY_SHELL_PARAM_CHECK(NULL != path, );
+
+#if defined(CONFIG_CSH_MAXLEN_PATH) && CONFIG_CSH_MAXLEN_PATH
+    size = size < CONFIG_CSH_MAXLEN_PATH ? size : CONFIG_CSH_MAXLEN_PATH;
+#endif
+
+    strncpy(path, csh->path, size);
+    path[size - 1] = '\0';
+}
+
+/*****************************************************************************
+* @brief        substitute user
+*
+* @param[in]    csh         shell instance
+* @param[in]    uid         user id
+* @param[in]    password    password
+*
+* @retval                   0:Success -1:Error
+*****************************************************************************/
+int chry_shell_substitute_user(chry_shell_t *csh, uint8_t uid, const char *password)
+{
+    CHRY_SHELL_PARAM_CHECK(NULL != csh, -1);
+
+    if (uid < CONFIG_CSH_MAX_USER) {
+        if (csh->hash[uid]) {
+            if (chry_shell_port_hash_strcmp(csh->hash[uid], password) != 0) {
+                return -1;
+            }
+        }
+
+        csh->uid = uid;
+
+        return chry_readline_prompt_edit(&csh->rl, CSH_PROMPT_SEG_USER, (chry_readline_sgr_t){ .foreground = CHRY_READLINE_SGR_GREEN, .bold = 1 }.raw, csh->user[uid]);
+    }
+
+    return -1;
+}
+
+/*****************************************************************************
+* @brief        get environment variable
+*
+* @param[in]    csh         shell instance
+* @param[in]    name        env name
+*
+* @retval                   env string pointer or NULL
+* @note                     env string maybe read-only
+*****************************************************************************/
+char *chry_shell_getenv(chry_shell_t *csh, const char *name)
+{
+    CHRY_SHELL_PARAM_CHECK(NULL != csh, NULL);
+
+    char *env = NULL;
+    for (const chry_sysvar_t *var = csh->var_tbl_beg; var < csh->var_tbl_end; var++) {
+        if (strcmp(name, var->name) == 0) {
+            env = var->var;
+            break;
+        }
+    }
+
+    return env;
+}
+
+/*****************************************************************************
+* @brief        print from shell
+*
+* @param[in]    csh         shell instance
+* @param[in]    fmt         string format
+*
+* @retval                   size that has printed
+*****************************************************************************/
+int csh_printf(chry_shell_t *csh, const char *fmt, ...)
+{
+    int n;
+    char shell_printf_buffer[CONFIG_CSH_PRINT_BUFFER_SIZE];
+    va_list args;
+
+    va_start(args, fmt);
+    n = vsnprintf(shell_printf_buffer, sizeof(shell_printf_buffer), fmt, args);
+    if (n > (int)sizeof(shell_printf_buffer)) {
+        csh->rl.sput(&csh->rl, shell_printf_buffer, sizeof(shell_printf_buffer));
+    } else if (n > 0) {
+        csh->rl.sput(&csh->rl, shell_printf_buffer, n);
+    }
+    va_end(args);
+    return n;
+}
diff --git a/APP/shell/chry_shell.h b/APP/shell/chry_shell.h
new file mode 100644 (file)
index 0000000..82bc258
--- /dev/null
@@ -0,0 +1,205 @@
+/*
+ * Copyright (c) 2022, Egahp
+ *
+ * SPDX-License-Identifier: Apache-2.0
+ */
+
+#ifndef CHRY_SHELL_H
+#define CHRY_SHELL_H
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#include <stdint.h>
+#include <setjmp.h>
+#include <signal.h>
+#include "cherryrl/chry_readline.h"
+
+/*!< check maxlen */
+#if defined(CONFIG_CSH_MAXLEN_PATH) && CONFIG_CSH_MAXLEN_PATH
+#if CONFIG_CSH_MAXLEN_PATH > 255
+#error "CONFIG_CSH_MAXLEN_PATH cannot be greater than 255."
+#endif
+#endif
+
+/*!< check multi-thread and lnbuff static */
+#if (defined(CONFIG_CSH_MULTI_THREAD) && CONFIG_CSH_MULTI_THREAD)
+#if !defined(CONFIG_CSH_LNBUFF_STATIC) || (CONFIG_CSH_LNBUFF_STATIC == 0)
+#error "CONFIG_CSH_LNBUFF_STATIC and CONFIG_CSH_MULTI_THREAD cannot be enabled at the same time."
+#endif
+#endif
+
+#if ((defined(CONFIG_CSH_NOBLOCK) && CONFIG_CSH_NOBLOCK) && \
+     (!defined(CONFIG_CSH_LNBUFF_STATIC) || (CONFIG_CSH_LNBUFF_STATIC == 0)))
+#error "CONFIG_CSH_LNBUFF_STATIC and CONFIG_CSH_NOBLOCK must be enabled at the same time."
+#endif
+
+/*!< signal count */
+#define CSH_SIGNAL_COUNT 7
+
+/*!< signal */
+#define CSH_SIGINT  1
+#define CSH_SIGQUIT 3
+#define CSH_SIGKILL 9
+#define CSH_SIGTERM 15
+#define CSH_SIGSTOP 17
+#define CSH_SIGTSTP 18
+#define CSH_SIGCONT 19
+
+#define CSH_VAR_READ  0x80000000
+#define CSH_VAR_WRITE 0x40000000
+#define CSH_VAR_SIZE  0x3fffffff
+
+#define CSH_SIG_DFL ((chry_sighandler_t)0)  /* Default action */
+#define CSH_SIG_IGN ((chry_sighandler_t)1)  /* Ignore action */
+#define CSH_SIG_ERR ((chry_sighandler_t)-1) /* Error return */
+
+/*!< exec status */
+#define CSH_STATUS_EXEC_IDLE 0
+#define CSH_STATUS_EXEC_FIND 1
+#define CSH_STATUS_EXEC_PREP 2
+#define CSH_STATUS_EXEC_DONE 3
+
+typedef int (*chry_syscall_func_t)(int argc, char **argv);
+
+typedef struct {
+    const char *path;
+    const char *name;
+    const char *usage;
+    const char *help;
+    chry_syscall_func_t func;
+} chry_syscall_t;
+
+typedef struct {
+    const char *name;
+    void *var;
+    uint32_t attr;
+} chry_sysvar_t;
+
+typedef struct {
+    uint32_t exec;
+
+    /*!< readline section */
+#if defined(CONFIG_CSH_LNBUFF_STATIC) && CONFIG_CSH_LNBUFF_STATIC
+    chry_readline_t rl; /*!< readline instance */
+    char *linebuff;     /*!< readline buffer */
+    uint16_t buffsize;  /*!< readline buffer size */
+    uint16_t linesize;  /*!< readline size */
+#else
+    chry_readline_t rl; /*!< readline instance */
+    /*!< (on stack)          readline buffer */
+    /*!< (on stack)          readline buffer size */
+    /*!< (on stack)          readline size */
+#endif
+
+    /*!< commmand table section */
+    const chry_syscall_t *cmd_tbl_beg; /*!< command table begin */
+    const chry_syscall_t *cmd_tbl_end; /*!< command table end */
+
+    /*!< variable table section */
+    const chry_sysvar_t *var_tbl_beg; /*!< variable table begin */
+    const chry_sysvar_t *var_tbl_end; /*!< variable table end */
+
+    /*!< execute section */
+#if defined(CONFIG_CSH_MULTI_THREAD) && CONFIG_CSH_MULTI_THREAD
+    int exec_code;                                 /*!< exec return code */
+    int exec_argc;                                 /*!< exec argument count */
+    const char *exec_argv[CONFIG_CSH_MAX_ARG + 3]; /*!< exec argument value */
+#else
+    int exec_code; /*!< exec return code    */
+    /*!< (on stack)     exec argument count */
+    /*!< (on stack)     exec argument value */
+#endif
+
+    /*!< user host and path section */
+#if defined(CONFIG_CSH_MAXLEN_PATH) && CONFIG_CSH_MAXLEN_PATH
+    int uid;                               /*!< now user id        */
+    const char *host;                      /*!< host name          */
+    const char *user[CONFIG_CSH_MAX_USER]; /*!< user name          */
+    const char *hash[CONFIG_CSH_MAX_USER]; /*!< user password hash */
+    char path[CONFIG_CSH_MAXLEN_PATH];     /*!< path               */
+#else
+    int uid;                               /*!< now user id        */
+    const char *host;                      /*!< host name          */
+    const char *user[CONFIG_CSH_MAX_USER]; /*!< user name          */
+    const char *hash[CONFIG_CSH_MAX_USER]; /*!< user password hash */
+    const char *path;                      /*!< path               */
+#endif
+
+#if defined(CONFIG_CSH_SIGNAL_HANDLER) && CONFIG_CSH_SIGNAL_HANDLER
+    void (*sighdl[CSH_SIGNAL_COUNT])(void *, int);
+#endif
+
+    /*!< reserved section */
+    void *data;      /*!< frame data */
+    void *user_data; /*!< user data  */
+} chry_shell_t;
+
+typedef void (*chry_sighandler_t)(chry_shell_t *csh, int signum);
+
+typedef struct {
+    /*!< I/O section */
+    uint16_t (*sput)(chry_readline_t *rl, const void *, uint16_t); /*!< output callback */
+    uint16_t (*sget)(chry_readline_t *rl, void *, uint16_t);       /*!< input callback  */
+
+    /*!< command table section */
+    const void *command_table_beg; /*!< static command table begin */
+    const void *command_table_end; /*!< static command table end   */
+
+    /*!< variable table section */
+    const void *variable_table_beg; /*!< static environment variable begin */
+    const void *variable_table_end; /*!< static environment variable end   */
+
+    /*!< prompt buffer setcion */
+    char *prompt_buffer;         /*!< prompt buffer      */
+    uint16_t prompt_buffer_size; /*!< prompt buffer size */
+
+    /*!< history buffer setcion */
+    char *history_buffer;         /*!< history buffer      */
+    uint16_t history_buffer_size; /*!< history buffer size */
+
+    /*!< line buffer setcion */
+    char *line_buffer;         /*!< line buffer */
+    uint32_t line_buffer_size; /*!< line buffer size */
+
+    /*!< user host section */
+    int uid;                               /*!< default user id */
+    const char *host;                      /*!< host name */
+    const char *user[CONFIG_CSH_MAX_USER]; /*!< user name */
+    const char *hash[CONFIG_CSH_MAX_USER]; /*!< user password hash */
+
+    /*!< reserved section */
+    void *user_data;
+} chry_shell_init_t;
+
+int chry_shell_init(chry_shell_t *csh, const chry_shell_init_t *init);
+int chry_shell_task_repl(chry_shell_t *csh);
+void chry_shell_task_exec(chry_shell_t *csh);
+
+int chry_shell_parse(char *line, uint32_t linesize, const char **argv, uint8_t argcmax);
+int chry_shell_path_resolve(const char *cur, const char *path, const char **argv, uint8_t *argl, uint8_t argcmax);
+
+int chry_shell_set_host(chry_shell_t *csh, const char *host);
+int chry_shell_set_user(chry_shell_t *csh, uint8_t uid, const char *user, const char *hash);
+int chry_shell_set_path(chry_shell_t *csh, uint8_t size, const char *path);
+void chry_shell_get_path(chry_shell_t *csh, uint8_t size, char *path);
+int chry_shell_substitute_user(chry_shell_t *csh, uint8_t uid, const char *password);
+
+char *chry_shell_getenv(chry_shell_t *csh, const char *name);
+int chry_shell_execl(chry_shell_t *csh, const char *__path, const char *, ...);
+int chry_shell_execle(chry_shell_t *csh, const char *__path, const char *, ...);
+int chry_shell_execlp(chry_shell_t *csh, const char *__file, const char *, ...);
+int chry_shell_execv(chry_shell_t *csh, const char *__path, char *const __argv[]);
+int chry_shell_execve(chry_shell_t *csh, const char *__path, char *const __argv[], char *const __envp[]);
+int chry_shell_execvp(chry_shell_t *csh, const char *__file, char *const __argv[]);
+
+int csh_printf(chry_shell_t *csh, const char *fmt, ...);
+
+int csh_login(chry_shell_t *csh);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/APP/shell/csh.h b/APP/shell/csh.h
new file mode 100644 (file)
index 0000000..c141420
--- /dev/null
@@ -0,0 +1,482 @@
+/*
+ * Copyright (c) 2022, Egahp
+ *
+ * SPDX-License-Identifier: Apache-2.0
+ */
+
+#ifndef CSH_H
+#define CSH_H
+
+#include <stdint.h>
+#include "csh_config.h"
+
+/*!< argument check */
+#ifndef CONFIG_CSH_DEBUG
+#define CONFIG_CSH_DEBUG 0
+#endif
+
+/* enable short usage message */
+#ifndef CONFIG_CSH_USAGE_MSG
+#define CONFIG_CSH_USAGE_MSG 1
+#endif
+
+/* enable long help message */
+#ifndef CONFIG_CSH_HELP_MSG
+#define CONFIG_CSH_HELP_MSG 1
+#endif
+
+/*!< default row */
+#ifndef CONFIG_CSH_DFTROW
+#define CONFIG_CSH_DFTROW 25
+#endif
+
+/*!< default column */
+#ifndef CONFIG_CSH_DFTCOL
+#define CONFIG_CSH_DFTCOL 80
+#endif
+
+/*!< history support <+550byte> */
+#ifndef CONFIG_CSH_HISTORY
+#define CONFIG_CSH_HISTORY 1
+#endif
+
+/*!< completion support <+1100byte> */
+#ifndef CONFIG_CSH_COMPLETION
+#define CONFIG_CSH_COMPLETION 1
+#endif
+
+/*!< max completion item list count (use stack 4 x count byte) */
+#ifndef CONFIG_CSH_MAX_COMPLETION
+#define CONFIG_CSH_MAX_COMPLETION 48
+#endif
+
+/*!< prompt edit support <+1000byte>  */
+#ifndef CONFIG_CSH_PROMPTEDIT
+#define CONFIG_CSH_PROMPTEDIT 1
+#endif
+
+/*!< prompt segment count */
+#ifndef CONFIG_CSH_PROMPTSEG
+#define CONFIG_CSH_PROMPTSEG 7
+#endif
+
+/*!< xterm support */
+#ifndef CONFIG_CSH_XTERM
+#define CONFIG_CSH_XTERM 0
+#endif
+
+/*!< newline */
+#ifndef CONFIG_CSH_NEWLINE
+#define CONFIG_CSH_NEWLINE "\r\n"
+#endif
+
+/*!< tab space count */
+#ifndef CONFIG_CSH_SPACE
+#define CONFIG_CSH_SPACE 4
+#endif
+
+/*!< independent ctrl map */
+#ifndef CONFIG_CSH_CTRLMAP
+#define CONFIG_CSH_CTRLMAP 0
+#endif
+
+/*!< independent alt map */
+#ifndef CONFIG_CSH_ALTMAP
+#define CONFIG_CSH_ALTMAP 0
+#endif
+
+/*!< refresh prompt */
+#ifndef CONFIG_CSH_REFRESH_PROMPT
+#define CONFIG_CSH_REFRESH_PROMPT 1
+#endif
+
+/*!< no waiting for sget */
+#ifndef CONFIG_CSH_NOBLOCK
+#define CONFIG_CSH_NOBLOCK 0
+#endif
+
+/*!< help information */
+#ifndef CONFIG_CSH_HELP
+#define CONFIG_CSH_HELP ""
+#endif
+
+/*!< path length 0:const path, <=255:variable path */
+#ifndef CONFIG_CSH_MAXLEN_PATH
+#define CONFIG_CSH_MAXLEN_PATH 128
+#endif
+
+/*!< path segment count */
+#ifndef CONFIG_CSH_MAXSEG_PATH
+#define CONFIG_CSH_MAXSEG_PATH 16
+#endif
+
+/*!< user count */
+#ifndef CONFIG_CSH_MAX_USER
+#define CONFIG_CSH_MAX_USER 1
+#endif
+
+/*!< max argument count */
+#ifndef CONFIG_CSH_MAX_ARG
+#define CONFIG_CSH_MAX_ARG 8
+#endif
+
+/*!< linebuffer static or on stack */
+#ifndef CONFIG_CSH_LNBUFF_STATIC
+#define CONFIG_CSH_LNBUFF_STATIC 1
+#endif
+
+/*!< linebuffer size (valid only if lnbuff on stack) */
+#ifndef CONFIG_CSH_LNBUFF_SIZE
+#define CONFIG_CSH_LNBUFF_SIZE 256
+#endif
+
+/*!< multi-thread mode */
+#ifndef CONFIG_CSH_MULTI_THREAD
+#define CONFIG_CSH_MULTI_THREAD 0
+#endif
+
+/*!< independent signal handler (for multi instances) */
+#ifndef CONFIG_CSH_SIGNAL_HANDLER
+#define CONFIG_CSH_SIGNAL_HANDLER 0
+#endif
+
+/*!< Ctrl+c/d/q/s/z/\ F1-F12 UE <+120byte> */
+#ifndef CONFIG_CSH_USER_CALLBACK
+#define CONFIG_CSH_USER_CALLBACK 1
+#endif
+
+/*!< enable macro export symbol table */
+#ifndef CONFIG_CSH_SYMTAB
+#define CONFIG_CSH_SYMTAB 1
+#endif
+
+/*!< print buffer size */
+#ifndef CONFIG_CSH_PRINT_BUFFER_SIZE
+#define CONFIG_CSH_PRINT_BUFFER_SIZE 512
+#endif
+
+#define CONFIG_READLINE_DEBUG          CONFIG_CSH_DEBUG
+#define CONFIG_READLINE_DFTROW         CONFIG_CSH_DFTROW
+#define CONFIG_READLINE_DFTCOL         CONFIG_CSH_DFTCOL
+#define CONFIG_READLINE_HISTORY        CONFIG_CSH_HISTORY
+#define CONFIG_READLINE_COMPLETION     CONFIG_CSH_COMPLETION
+#define CONFIG_READLINE_MAX_COMPLETION CONFIG_CSH_MAX_COMPLETION
+#define CONFIG_READLINE_PROMPTEDIT     CONFIG_CSH_PROMPTEDIT
+#define CONFIG_READLINE_PROMPTSEG      CONFIG_CSH_PROMPTSEG
+#define CONFIG_READLINE_XTERM          CONFIG_CSH_XTERM
+#define CONFIG_READLINE_NEWLINE        CONFIG_CSH_NEWLINE
+#define CONFIG_READLINE_SPACE          CONFIG_CSH_SPACE
+#define CONFIG_READLINE_CTRLMAP        CONFIG_CSH_CTRLMAP
+#define CONFIG_READLINE_ALTMAP         CONFIG_CSH_ALTMAP
+#define CONFIG_READLINE_REFRESH_PROMPT CONFIG_CSH_REFRESH_PROMPT
+#define CONFIG_READLINE_NOBLOCK        CONFIG_CSH_NOBLOCK
+#define CONFIG_READLINE_HELP           CONFIG_CSH_HELP
+
+#include "cherryrl/chry_readline.h"
+#include "chry_shell.h"
+
+#if defined(__CC_ARM) || defined(__CLANG_ARM) || defined(__GNUC__) || defined(__ADSPBLACKFIN__)
+#define __CSH_SECTION(x) __attribute__((section(x)))
+#define __CSH_USED       __attribute__((used))
+#define __CSH_WEAK       __attribute__((weak))
+#elif defined(__IAR_SYSTEMS_ICC__)
+#define __CSH_SECTION(x) @x
+#define __CSH_USED       __root
+#define __CSH_WEAK       __weak
+#else
+#define __CSH_SECTION(x)
+#define __CSH_USED
+#define __CSH_WEAK
+#endif
+
+#if defined(CONFIG_CSH_USAGE_MSG) && CONFIG_CSH_USAGE_MSG
+#define __CSH_USAGE(x) x
+#else
+#define __CSH_USAGE(x) ((void)x, NULL)
+#endif
+
+#if defined(CONFIG_CSH_HELP_MSG) && CONFIG_CSH_HELP_MSG
+#define __CSH_HELP(x) x
+#else
+#define __CSH_HELP(x) ((void)x, NULL)
+#endif
+
+#if defined(CONFIG_CSH_SYMTAB) && CONFIG_CSH_SYMTAB
+
+#if defined(_MSC_VER)
+#pragma section("FSymTab$f", read)
+#pragma section("VSymTab", read)
+#endif
+
+#if defined(__TI_COMPILER_VERSION__)
+#defien __TI_CSH_PRAGMA(x) _Pragma(#x)
+#endif
+
+#endif
+
+#if defined(CONFIG_CSH_SYMTAB) && CONFIG_CSH_SYMTAB
+#if defined(_MSC_VER)
+
+#define CSH_EXPORT_CALL(name, func, path)        \
+    __declspec(allocate("FSymTab$f"))            \
+    const chry_syscall_t __fsym_##name##func = { \
+        path,                                    \
+        #name,                                   \
+        NULL,                                    \
+        NULL,                                    \
+        (chry_syscall_func_t)func,               \
+    };
+
+#define CSH_EXPORT_CALL_FULL(name, func, path, usage, help) \
+    __declspec(allocate("FSymTab$f"))                       \
+    const chry_syscall_t __fsym_##name##func = {            \
+        path,                                               \
+        #name,                                              \
+        __CSH_USAGE(usage),                                 \
+        __CSH_HELP(help),                                   \
+        (chry_syscall_func_t)func,                          \
+    };
+
+#pragma comment(linker, "/merge:FSymTab=mytext")
+
+#define CSH_EXPORT_VAR(name, var, attr)                                        \
+    __declspec(allocate("VSymTab")) const chry_sysvar_t __vsym_##name##var = { \
+        #name,                                                                 \
+        (void *)&var,                                                          \
+        attr,                                                                  \
+    };
+
+#elif defined(__TI_COMPILER_VERSION__)
+
+#define CSH_EXPORT_CALL(name, func, path)                              \
+    __TI_CSH_PRAGMA(DATA_SECTION(__fsym_##name##func, "FSymTab"));     \
+    __attribute__((used)) const chry_syscall_t __fsym_##name##func = { \
+        path,                                                          \
+        #name,                                                         \
+        NULL,                                                          \
+        NULL,                                                          \
+        (chry_syscall_func_t)func,                                     \
+    };
+
+#define CSH_EXPORT_CALL_FULL(name, func, path, usage, help)            \
+    __TI_CSH_PRAGMA(DATA_SECTION(__fsym_##name##func, "FSymTab"));     \
+    __attribute__((used)) const chry_syscall_t __fsym_##name##func = { \
+        path,                                                          \
+        #name,                                                         \
+        usage,                                                         \
+        help,                                                          \
+        (chry_syscall_func_t)func,                                     \
+    };
+
+#define CSH_EXPORT_VAR(name, var, attr)                              \
+    __TI_CSH_PRAGMA(DATA_SECTION(__vsym_##name##var, "VSymTab"));    \
+    __attribute__((used)) const chry_sysvar_t __vsym_##name##var = { \
+        #name,                                                       \
+        (void *)&var,                                                \
+        attr,                                                        \
+    };
+
+#else
+
+#define CSH_LINENUMBER() __LINE__
+
+#define CSH_EXPORT_CALL(name, func, path)                                            \
+    __CSH_USED const chry_syscall_t __fsym_##name##func __CSH_SECTION("FSymTab") = { \
+        path,                                                                        \
+        #name,                                                                       \
+        NULL,                                                                        \
+        NULL,                                                                        \
+        (chry_syscall_func_t)func,                                                   \
+    };
+
+#define CSH_EXPORT_CALL_FULL(name, func, path, usage, help)                          \
+    __CSH_USED const chry_syscall_t __fsym_##name##func __CSH_SECTION("FSymTab") = { \
+        path,                                                                        \
+        #name,                                                                       \
+        usage,                                                                       \
+        help,                                                                        \
+        (chry_syscall_func_t)func,                                                   \
+    };
+
+#define CSH_EXPORT_VAR(name, var, attr)                                            \
+    __CSH_USED const chry_sysvar_t __vsym_##name##var __CSH_SECTION("VSymTab") = { \
+        #name,                                                                     \
+        (void *)var,                                                               \
+        attr,                                                                      \
+    };
+
+#endif
+#else
+#define CSH_EXPORT_CALL(name, func, path)
+#define CSH_EXPORT_CALL_FULL(name, func, path, usage, help)
+#define CSH_EXPORT_VAR(name, var, attr)
+#endif
+
+/*****************************************************************************
+* @brief        export csh command (default path "/bin")
+*
+* @param[in]    func        function pointer
+* @param[in]    _dummy      (compatible descriptions)
+*
+*****************************************************************************/
+#define CSH_CMD_EXPORT(func, _dummy) \
+    CSH_EXPORT_CALL(func, func, "/bin")
+
+/*****************************************************************************
+* @brief        export csh command with alias  (default path "/bin" )
+*
+* @param[in]    func        function pointer
+* @param[in]    name        command name
+* @param[in]    _dummy      (compatible descriptions)
+*
+*****************************************************************************/
+#define CSH_CMD_EXPORT_ALIAS(func, name, _dummy) \
+    CSH_EXPORT_CALL(name, func, "/bin")
+
+/*****************************************************************************
+* @brief        export csh command (default path "/sbin")
+*
+* @param[in]    func        function pointer
+* @param[in]    _dummy      (compatible descriptions)
+*
+*****************************************************************************/
+#define CSH_SCMD_EXPORT(func, _dummy) \
+    CSH_EXPORT_CALL(func, func, "/sbin")
+
+/*****************************************************************************
+* @brief        export csh command with alias  (default path "/sbin" )
+*
+* @param[in]    func        function pointer
+* @param[in]    name        command name
+* @param[in]    _dummy      (compatible descriptions)
+*
+*****************************************************************************/
+#define CSH_SCMD_EXPORT_ALIAS(func, name, _dummy) \
+    CSH_EXPORT_CALL(name, func, "/sbin")
+
+/*****************************************************************************
+* @brief        export csh command with path
+*
+* @param[in]    func        function pointer
+* @param[in]    name        command name
+* @param[in]    path        command path
+*
+* @example      CSH_CMD_EXPORT_PATH(test_func1, test1, "/bin");       // ok
+*               CSH_CMD_EXPORT_PATH(test_func2, test2, "/sbin/test"); // ok
+*               CSH_CMD_EXPORT_PATH(test_func2, test2, "/sbin/test/");// error, cannot end with '/'
+*               CSH_CMD_EXPORT_PATH(test_func2, test2, "/");          // error, cannot be the root path "/"
+*
+*****************************************************************************/
+#define CSH_CMD_EXPORT_PATH(func, name, path) \
+    CSH_EXPORT_CALL(name, func, path)
+
+/*****************************************************************************
+* @brief        export csh command (default path "/bin")
+*
+* @param[in]    func        function pointer
+* @param[in]    usage       short usage message
+* @param[in]    help        lone help message
+*
+*****************************************************************************/
+#define CSH_CMD_EXPORT_FULL(func, usage, help) \
+    CSH_EXPORT_CALL_FULL(func, func, "/bin", usage, help)
+
+/*****************************************************************************
+* @brief        export csh command with alias  (default path "/bin" )
+*
+* @param[in]    func        function pointer
+* @param[in]    name        command name
+* @param[in]    usage       short usage message
+* @param[in]    help        lone help message
+*
+*****************************************************************************/
+#define CSH_CMD_EXPORT_ALIAS_FULL(func, name, usage, help) \
+    CSH_EXPORT_CALL_FULL(name, func, "/bin", usage, help)
+
+/*****************************************************************************
+* @brief        export csh command (default path "/sbin")
+*
+* @param[in]    func        function pointer
+* @param[in]    usage       short usage message
+* @param[in]    help        lone help message
+*
+*****************************************************************************/
+#define CSH_SCMD_EXPORT_FULL(func, usage, help) \
+    CSH_EXPORT_CALL_FULL(func, func, "/sbin", usage, help)
+
+/*****************************************************************************
+* @brief        export csh command with alias  (default path "/sbin" )
+*
+* @param[in]    func        function pointer
+* @param[in]    name        command name
+* @param[in]    usage       short usage message
+* @param[in]    help        lone help message
+*
+*****************************************************************************/
+#define CSH_SCMD_EXPORT_ALIAS_FULL(func, name, usage, help) \
+    CSH_EXPORT_CALL_FULL(name, func, "/sbin", usage, help)
+
+/*****************************************************************************
+* @brief        export csh command with path
+*
+* @param[in]    func        function pointer
+* @param[in]    name        command name
+* @param[in]    path        command path
+* @param[in]    usage       short usage message
+* @param[in]    help        lone help message
+*
+* @example      CSH_CMD_EXPORT_PATH(test_func1, test1, "/bin");       // ok
+*               CSH_CMD_EXPORT_PATH(test_func2, test2, "/sbin/test"); // ok
+*               CSH_CMD_EXPORT_PATH(test_func2, test2, "/sbin/test/");// error, cannot end with '/'
+*               CSH_CMD_EXPORT_PATH(test_func2, test2, "/");          // error, cannot be the root path "/"
+*
+*****************************************************************************/
+#define CSH_CMD_EXPORT_PATH_FULL(func, name, path, usage, help) \
+    CSH_EXPORT_CALL_FULL(name, func, path, usage, help)
+
+/*****************************************************************************
+* @brief        export csh read-only variable
+*
+* @param[in]    var         variable
+* @param[in]    name        variable name
+* @param[in]    size        variable size
+*
+*****************************************************************************/
+#define CSH_RVAR_EXPORT(var, name, size) \
+    CSH_EXPORT_VAR(name, var, 0x80000000 | (size))
+
+/*****************************************************************************
+* @brief        export csh write-only variable
+*
+* @param[in]    var         variable
+* @param[in]    name        variable name
+* @param[in]    size        variable size
+*
+*****************************************************************************/
+#define CSH_WVAR_EXPORT(var, name, size) \
+    CSH_EXPORT_VAR(name, var, 0x40000000 | (size))
+
+/*****************************************************************************
+* @brief        export csh read-write variable
+*
+* @param[in]    var         variable
+* @param[in]    name        variable name
+* @param[in]    size        variable size
+*
+*****************************************************************************/
+#define CSH_RWVAR_EXPORT(var, name, size) \
+    CSH_EXPORT_VAR(name, var, 0xc0000000 | (size))
+
+extern int csh_builtin_help(int argc, char **argv);
+
+#define CSH_CALL_HELP(name)             \
+    do {                                \
+        char *help_argv[4];             \
+        help_argv[0] = "help";          \
+        help_argv[1] = name;            \
+        help_argv[2] = NULL;            \
+        help_argv[3] = (void *)csh;     \
+        csh_builtin_help(2, help_argv); \
+    } while (0)
+
+#endif
diff --git a/APP/shell/csh_config.h b/APP/shell/csh_config.h
new file mode 100644 (file)
index 0000000..e106657
--- /dev/null
@@ -0,0 +1,91 @@
+/*
+ * Copyright (c) 2022, Egahp
+ *
+ * SPDX-License-Identifier: Apache-2.0
+ */
+
+#ifndef CSH_CONFIG_H
+#define CSH_CONFIG_H
+
+/*!< argument check */
+#define CONFIG_CSH_DEBUG 0
+
+/*!< default row */
+#define CONFIG_CSH_DFTROW 25
+
+/*!< default column */
+#define CONFIG_CSH_DFTCOL 80
+
+/*!< history support <+550byte> */
+#define CONFIG_CSH_HISTORY 1
+
+/*!< completion support <+1100byte> */
+#define CONFIG_CSH_COMPLETION 1
+
+/*!< max completion item list count (use stack 4 x count byte) */
+#define CONFIG_CSH_MAX_COMPLETION 40
+
+/*!< prompt edit support <+1000byte>  */
+#define CONFIG_CSH_PROMPTEDIT 1
+
+/*!< prompt segment count */
+#define CONFIG_CSH_PROMPTSEG 7
+
+/*!< xterm support */
+#define CONFIG_CSH_XTERM 0
+
+/*!< newline */
+#define CONFIG_CSH_NEWLINE "\r\n"
+
+/*!< tab space count */
+#define CONFIG_CSH_SPACE 4
+
+/*!< independent ctrl map */
+#define CONFIG_CSH_CTRLMAP 0
+
+/*!< independent alt map */
+#define CONFIG_CSH_ALTMAP 0
+
+/*!< refresh prompt */
+#define CONFIG_CSH_REFRESH_PROMPT 1
+
+/*!< no waiting for sget (单任务轮询) */
+#define CONFIG_CSH_NOBLOCK 1
+
+/*!< help information */
+#define CONFIG_CSH_HELP ""
+
+/*!< path length 0:const path, <=255:variable path */
+#define CONFIG_CSH_MAXLEN_PATH 128
+
+/*!< path segment count */
+#define CONFIG_CSH_MAXSEG_PATH 16
+
+/*!< user count */
+#define CONFIG_CSH_MAX_USER 1
+
+/*!< max argument count */
+#define CONFIG_CSH_MAX_ARG 8
+
+/*!< linebuffer static or on stack */
+#define CONFIG_CSH_LNBUFF_STATIC 1
+
+/*!< linebuffer size (valid only if lnbuff on stack) */
+#define CONFIG_CSH_LNBUFF_SIZE 256
+
+/*!< multi-thread mode (单任务模式, 命令在 shell 任务内同步执行) */
+#define CONFIG_CSH_MULTI_THREAD 0
+
+/*!< independent signal handler (for multi instances) */
+#define CONFIG_CSH_SIGNAL_HANDLER 0
+
+/*!< Ctrl+c/d/q/s/z/\ F1-F12 UE <+120byte> */
+#define CONFIG_CSH_USER_CALLBACK 1
+
+/*!< enable macro export symbol table */
+#define CONFIG_CSH_SYMTAB 1
+
+/*!< print buffer size */
+#define CONFIG_CSH_PRINT_BUFFER_SIZE 256
+
+#endif
\ No newline at end of file
diff --git a/APP/shell/shell.c b/APP/shell/shell.c
new file mode 100644 (file)
index 0000000..2d1c5d7
--- /dev/null
@@ -0,0 +1,306 @@
+/*
+ * shell.c - CherrySH Shell 移植层 (UART1, FreeRTOS 单任务模式)
+ *
+ * 收发分工:
+ *   - 发送:  复用现有 uart_send_msg(UART1, ...), 即 csh sput 回调;
+ *   - 接收:  UART1 中断每收到一字节调用 shell_uart_rx_byte(), 写入环形缓冲,
+ *            csh sget 回调从此缓冲读取 (单写单读, 中断写/任务读, 无需加锁)。
+ *
+ * 模式: CONFIG_CSH_MULTI_THREAD=0 + CONFIG_CSH_NOBLOCK=1
+ *   shell_task 循环调用 chry_shell_task_repl(), 命令在任务内同步执行。
+ */
+
+#include <stdlib.h>
+#include <string.h>
+
+#include "FreeRTOS.h"
+#include "task.h"
+
+#include "csh.h"
+#include "shell.h"
+#include "dev_uart.h"
+#include "SWM341.h"
+
+/* 输入环形缓冲大小 (须为 2 的幂) */
+#define SHELL_RB_SIZE   256
+#define SHELL_RB_MASK   (SHELL_RB_SIZE - 1)
+
+static chry_shell_t  s_csh;
+
+typedef struct {
+    volatile uint16_t head;   /* 写指针 (中断) */
+    volatile uint16_t tail;   /* 读指针 (shell 任务) */
+    uint8_t buf[SHELL_RB_SIZE];
+} shell_rb_t;
+
+static shell_rb_t s_rb;
+
+static uint16_t rb_count(void)
+{
+    return (uint16_t)((s_rb.head - s_rb.tail) & SHELL_RB_MASK);
+}
+
+/* 串口 UART1 接收中断字节回调 (由 BSP 逐字节调用) */
+void shell_uart_rx_byte(uint8_t byte)
+{
+    uint16_t next = (uint16_t)((s_rb.head + 1) & SHELL_RB_MASK);
+    if (next != s_rb.tail) {          /* 缓冲未满才写入, 满则丢弃 */
+        s_rb.buf[s_rb.head] = byte;
+        s_rb.head = next;
+    }
+}
+
+/* 发送回调: 复用现有 UART1 发送函数 */
+static uint16_t csh_sput_cb(chry_readline_t *rl, const void *data, uint16_t size)
+{
+    (void)rl;
+    uart_send_msg(UART1, data, size);
+    return size;
+}
+
+/* 接收回调: 从输入环形缓冲非阻塞读 (NOBLOCK) */
+static uint16_t csh_sget_cb(chry_readline_t *rl, void *data, uint16_t size)
+{
+    uint16_t cnt = 0;
+    uint8_t *p = (uint8_t *)data;
+    (void)rl;
+
+    while (cnt < size && rb_count() > 0) {
+        p[cnt++] = s_rb.buf[s_rb.tail];
+        s_rb.tail = (uint16_t)((s_rb.tail + 1) & SHELL_RB_MASK);
+    }
+    return cnt;
+}
+
+/* 初始化 Shell 并注册串口字节接收回调 */
+int shell_init(void)
+{
+    chry_shell_init_t csh_init;
+
+    /* 初始化 UART1(调试串口复用为 Shell 交互口), 并打开接收中断 */
+    uart_debug_init();
+
+    memset(&csh_init, 0, sizeof(csh_init));
+
+    csh_init.sput = csh_sput_cb;
+    csh_init.sget = csh_sget_cb;
+
+#if defined(CONFIG_CSH_SYMTAB) && CONFIG_CSH_SYMTAB
+    /* Keil/ARMCC 链接器符号表段 */
+    extern const int FSymTab$$Base;
+    extern const int FSymTab$$Limit;
+    extern const int VSymTab$$Base;
+    extern const int VSymTab$$Limit;
+
+    csh_init.command_table_beg = &FSymTab$$Base;
+    csh_init.command_table_end = &FSymTab$$Limit;
+    csh_init.variable_table_beg = &VSymTab$$Base;
+    csh_init.variable_table_end = &VSymTab$$Limit;
+#endif
+
+#if defined(CONFIG_CSH_PROMPTEDIT) && CONFIG_CSH_PROMPTEDIT
+    static char shell_prompt_buf[64];
+    csh_init.prompt_buffer = shell_prompt_buf;
+    csh_init.prompt_buffer_size = sizeof(shell_prompt_buf);
+#endif
+
+#if defined(CONFIG_CSH_HISTORY) && CONFIG_CSH_HISTORY
+    static char shell_history_buf[128];   /* 须为 2 的幂 */
+    csh_init.history_buffer = shell_history_buf;
+    csh_init.history_buffer_size = sizeof(shell_history_buf);
+#endif
+
+#if defined(CONFIG_CSH_LNBUFF_STATIC) && CONFIG_CSH_LNBUFF_STATIC
+    static char shell_line_buf[CONFIG_CSH_LNBUFF_SIZE];
+    csh_init.line_buffer = shell_line_buf;
+    csh_init.line_buffer_size = CONFIG_CSH_LNBUFF_SIZE;
+#endif
+
+    csh_init.uid = 0;
+    csh_init.user[0] = "root";
+    csh_init.hash[0] = NULL;            /* 免登录 */
+    csh_init.host = "dispboard";
+    csh_init.user_data = NULL;
+
+    if (chry_shell_init(&s_csh, &csh_init)) {
+        return -1;
+    }
+
+    /* 注册 UART1 中断字节回调 */
+    uart_set_rx_byte_cb(shell_uart_rx_byte);
+
+    return 0;
+}
+
+/* Shell 任务入口 */
+void shell_task(void *arg)
+{
+    (void)arg;
+
+    shell_init();
+
+    for (;;) {
+        chry_shell_task_repl(&s_csh);
+        vTaskDelay(2);
+    }
+}
+
+/* ======================== 示例命令 ======================== */
+
+static int cmd_hello(int argc, char **argv)
+{
+    (void)argc;
+    (void)argv;
+    csh_printf(&s_csh, "hello from dispboard shell\r\n");
+    return 0;
+}
+CSH_SCMD_EXPORT_FULL(cmd_hello, "print hello", "hello\r\n  - print hello message\r\n");
+
+static int cmd_clear(int argc, char **argv)
+{
+    (void)argc;
+    (void)argv;
+    csh_printf(&s_csh, "\33[2J\33[H");
+    return 0;
+}
+CSH_SCMD_EXPORT_FULL(cmd_clear, "clear screen", "clear\r\n  - clear terminal screen\r\n");
+
+/* 环境变量: 命令搜索路径 */
+#define __ENV_PATH "/sbin:/bin"
+const char ENV_PATH[] = __ENV_PATH;
+CSH_RVAR_EXPORT(ENV_PATH, PATH, sizeof(__ENV_PATH));
+
+/* ======================== 内置 help 命令 ======================== */
+/* CherrySH 不自带 help, 这里遍历符号表列出所有已注册命令 (参照 builtin/help.c) */
+static void print_cmdline(chry_shell_t *csh, const chry_syscall_t *call,
+                          uint16_t longest_name, uint16_t longest_path)
+{
+    uint16_t len = strlen(call->name);
+
+    csh_printf(csh, "  \e[32m%s\e[m", call->name);
+    for (uint16_t k = len; k < longest_name; k++) {
+        csh_printf(csh, " ");
+    }
+    csh_printf(csh, " -> \e[36m%s\e[m", call->path);
+
+    if (call->usage) {
+        csh_printf(csh, " - ");
+        len = strlen(call->path);
+        for (uint16_t k = len; k < longest_path; k++) {
+            csh_printf(csh, " ");
+        }
+        csh_printf(csh, call->usage);
+    }
+    csh_printf(csh, "\r\n");
+}
+
+static int cmd_help(int argc, char **argv)
+{
+    chry_shell_t *csh = (void *)argv[argc + 1];
+
+    if (argc > 1) {
+        for (const chry_syscall_t *call = csh->cmd_tbl_beg; call < csh->cmd_tbl_end; call++) {
+            if (!strcmp(argv[1], call->name)) {
+                print_cmdline(csh, call, 0, 0);
+                csh_printf(csh, "\r\nUsage:\r\n\r\n");
+                if (call->help) {
+                    csh->rl.sput(&csh->rl, call->help, strlen(call->help));
+                    csh_printf(csh, "\r\n");
+                } else {
+                    csh_printf(csh, "    help message not provided\r\n");
+                }
+                return 0;
+            }
+        }
+        csh_printf(csh, "%s: command not found\r\n", argv[1]);
+        return -1;
+    }
+
+    csh_printf(csh, "total function %d\r\n",
+               ((uintptr_t)csh->cmd_tbl_end - (uintptr_t)csh->cmd_tbl_beg) / sizeof(chry_syscall_t));
+
+    uint16_t longest_name = 0, longest_path = 0;
+    for (const chry_syscall_t *call = csh->cmd_tbl_beg; call < csh->cmd_tbl_end; call++) {
+        uint16_t len = strlen(call->name);
+        longest_name = len > longest_name ? len : longest_name;
+        len = strlen(call->path);
+        longest_path = len > longest_path ? len : longest_path;
+    }
+    for (const chry_syscall_t *call = csh->cmd_tbl_beg; call < csh->cmd_tbl_end; call++) {
+        print_cmdline(csh, call, longest_name, longest_path);
+    }
+
+    csh_printf(csh, "\r\ntotal variable %d\r\n",
+               ((uintptr_t)csh->var_tbl_end - (uintptr_t)csh->var_tbl_beg) / sizeof(chry_sysvar_t));
+
+    uint16_t vname = 0;
+    for (const chry_sysvar_t *var = csh->var_tbl_beg; var < csh->var_tbl_end; var++) {
+        uint16_t len = strlen(var->name);
+        vname = len > vname ? len : vname;
+    }
+    for (const chry_sysvar_t *var = csh->var_tbl_beg; var < csh->var_tbl_end; var++) {
+        csh_printf(csh, "  $\e[33m%s\e[m", var->name);
+        uint16_t len = strlen(var->name);
+        for (uint16_t k = len; k < vname; k++) {
+            csh_printf(csh, " ");
+        }
+        char cr = var->attr & CSH_VAR_READ ? 'r' : '-';
+        char cw = var->attr & CSH_VAR_WRITE ? 'w' : '-';
+        csh_printf(csh, " %c%c %3d\r\n", cr, cw, var->attr & CSH_VAR_SIZE);
+    }
+    return 0;
+}
+CSH_SCMD_EXPORT_ALIAS_FULL(cmd_help, help, "display command usage",
+    "help\r\n    - show a brief overview of all commands\r\nhelp <command>\r\n    - display detailed information for 'command'\r\n");
+
+/* ======================== LED 控制命令 ======================== */
+/* 引脚/极性参照 ui_test_button.c (LED0~LED4, 低电平点亮) */
+static GPIO_TypeDef *led_cmd_port[5] = { GPIOD, GPIOD, GPIOC, GPIOC, GPIOC };
+static uint32_t      led_cmd_pin[5]  = { PIN7, PIN0, PIN4, PIN5, PIN8 };
+
+static void led_cmd_set(int n, int on)
+{
+    int i = n - 1;
+    if (i < 0 || i >= 5) return;
+    if (on) {
+        GPIO_ClrBit(led_cmd_port[i], led_cmd_pin[i]);   /* active low -> on */
+    } else {
+        GPIO_SetBit(led_cmd_port[i], led_cmd_pin[i]);   /* high -> off */
+    }
+}
+
+static int cmd_ledon(int argc, char **argv)
+{
+    if (argc < 2) {
+        csh_printf(&s_csh, "usage: ledon <1~5>\r\n");
+        return -1;
+    }
+    int n = atoi(argv[1]);
+    if (n < 1 || n > 5) {
+        csh_printf(&s_csh, "error: led index out of range (1~5)\r\n");
+        return -1;
+    }
+    led_cmd_set(n, 1);
+    csh_printf(&s_csh, "LED%d on\r\n", n);
+    return 0;
+}
+CSH_SCMD_EXPORT_ALIAS_FULL(cmd_ledon, led_on, "turn on LED (param 1~5)",
+    "ledon <1~5>\r\n  - turn on the specified LED\r\n");
+
+static int cmd_ledoff(int argc, char **argv)
+{
+    if (argc < 2) {
+        csh_printf(&s_csh, "usage: ledoff <1~5>\r\n");
+        return -1;
+    }
+    int n = atoi(argv[1]);
+    if (n < 1 || n > 5) {
+        csh_printf(&s_csh, "error: led index out of range (1~5)\r\n");
+        return -1;
+    }
+    led_cmd_set(n, 0);
+    csh_printf(&s_csh, "LED%d off\r\n", n);
+    return 0;
+}
+CSH_SCMD_EXPORT_FULL(cmd_ledoff, "turn off LED (param 1~5)",
+    "ledoff <1~5>\r\n  - turn off the specified LED\r\n");
\ No newline at end of file
diff --git a/APP/shell/shell.h b/APP/shell/shell.h
new file mode 100644 (file)
index 0000000..d7f93c9
--- /dev/null
@@ -0,0 +1,19 @@
+/*
+ * shell.h - 基于 CherrySH 的串口 Shell(运行于 UART1)
+ */
+
+#ifndef SHELL_H
+#define SHELL_H
+
+#include <stdint.h>
+
+/* 初始化 Shell 并注册串口字节接收回调 */
+int shell_init(void);
+
+/* Shell 任务入口 (FreeRTOS task) */
+void shell_task(void *arg);
+
+/* 串口 UART1 接收中断字节回调: 由 BSP 在收到每字节时调用 */
+void shell_uart_rx_byte(uint8_t byte);
+
+#endif /* SHELL_H */
\ No newline at end of file
index 5e5fdc4c393ed27dc585ac1ab9d347b970eebb8d..a8e2f53f0cf819968322423756862fe83e38b6da 100644 (file)
 #include "load_file.h"
 #include "ff.h"
 #include "usbh_user.h"
+#include "dev_uart.h"
+#if SHELL_ENABLE
+#include "shell.h"
+#endif
 
 
 /*******************************************************************************************************************************************
@@ -54,6 +58,9 @@ void user_app(void)
     xTaskCreate(task_ui,  (const char *)"ui", 1024, NULL, 2, NULL);
     xTaskCreate(task_app, (const char *)"app", 2048, NULL, 2, NULL);
     xTaskCreate(task_usbh, (const char *)"usbh", 4096, NULL, 2, NULL);
+#if SHELL_ENABLE
+    xTaskCreate(shell_task, (const char *)"shell", 1024, NULL, 2, NULL);
+#endif
        user_mb_start();
     vTaskStartScheduler();
 }
index 6d6ec171be2fc27c6896ce07336431734667b4ac..29a0d5051d62296fbd7667de87f709d061ed2a73 100644 (file)
@@ -75,6 +75,16 @@ typedef struct {
 
 static mb_token_t s_tok = { 0, false };
 
+/* ======================== 链路连接状态 ========================
+ * 令牌模式下, 有令牌时发送指令(查询实时数据)存在响应 => connected=1;
+ * 连续 MB_LINK_FAIL_LIMIT 次查询实时数据均无响应 => connected=0。
+ * 状态翻转时打印对应日志。
+ */
+#define MB_LINK_FAIL_LIMIT          3      /* 连续无响应次数上限 */
+
+static bool     s_link_connected = false;   /* true = 与对端链路正常 */
+static uint16_t s_link_fail_cnt  = 0;       /* 连续无响应累计次数 */
+
 /* ======================== 共享数据保护 ======================== */
 static SemaphoreHandle_t s_lock = NULL;     /* g_device 读写互斥锁 */
 static QueueHandle_t      s_cmd_q = NULL;   /* 异步写寄存器命令队列 */
@@ -251,24 +261,64 @@ static void mb_token_relinquish(void)
     uint16_t req_len  = mb_token_build_pass(seq, req);
     uint16_t resp_len = 0;
 
-    /* 发送令牌 (参照 can_token_after_send) */
-    mb_task_request(req, req_len, resp, &resp_len, MB_POLL_TIMEOUT_MS);
+    /* 发送令牌 (参照 can_token_after_send)
+     * 只有对端确认收到令牌(返回 MB_OK)才真正让渡, 否则保留令牌, 下一轮重试,
+     * 避免发送失败/busy 时把令牌"弄丢"。 */
+    int rc = mb_task_request(req, req_len, resp, &resp_len, MB_POLL_TIMEOUT_MS);
+
+    if (rc != MB_OK) {
+        mb_log("[MB] token pass fail rc=%d, keep token\n", rc);
+        return;
+    }
 
     s_tok.token_seq = seq;
     s_tok.has_token = false;
 }
 
+/* ======================== 连接状态更新 ========================
+ * resp_ok: 本轮实时数据查询是否有任一响应。
+ * 有响应 => 清空失败计数并置已连接; 连续 10 次无响应 => 置断开;
+ * 状态翻转时打印对应变化日志。
+ */
+static void mb_link_update(bool resp_ok)
+{
+    bool old = s_link_connected;
+
+    if (resp_ok) {
+        s_link_fail_cnt = 0;
+        if (!old) {
+            s_link_connected = true;
+            mb_log("[MB] link connected\n");
+        }
+    } else {
+        s_link_fail_cnt++;
+        if (old && s_link_fail_cnt >= MB_LINK_FAIL_LIMIT) {
+            s_link_connected = false;
+            s_link_fail_cnt = 0;
+            mb_log("[MB] link disconnected (x%d no response)\n",
+                   MB_LINK_FAIL_LIMIT);
+        }
+    }
+}
+
 /* ======================== 轮询全部数据区 ========================
  * 依次 mb_read_regs 读取各区间, 更新 reg_cache, 并刷新 g_device。
+ * 同时统计本轮是否有响应, 用于连接状态判定。
  */
+extern int event_read_change(void);
+extern int event_read_action(void);
+
 static void mb_poll_all_areas(void)
 {
     uint16_t count = 0;
     const reg_area_def_t *areas = reg_get_poll_areas(&count);
-    if (!areas || count == 0)
+    if (!areas || count == 0) {
+        mb_link_update(false);
         return;
+    }
 
     uint16_t buf[MB_MAX_AREA_COUNT];
+    bool resp = false;
 
     for (uint16_t i = 0; i < count; i++) {
         const reg_area_def_t *a = &areas[i];
@@ -281,9 +331,17 @@ static void mb_poll_all_areas(void)
 
         int n = mb_read_regs(USER_MB_TARGET_SLAVE, a->start_addr, a->count,
                              buf, MB_POLL_TIMEOUT_MS);
-        if (n > 0 && (uint16_t)n <= a->count)
+        if (n > 0 && (uint16_t)n <= a->count) {
             reg_update_area(a, buf);
+            resp = true;
+        }
     }
+    {
+      event_read_change(); //读取变位报告
+      event_read_action(); //读取动作报告
+    }
+
+    mb_link_update(resp);
 
     /* 解析刷新共享数据 (上次写命令也可能修改, 一并刷新) */
     umb_lock();
@@ -356,6 +414,11 @@ int user_mb_init(void)
     return (s_lock && s_cmd_q) ? MB_OK : MB_ERR_PARAM;
 }
 
+bool user_mb_is_connected(void)
+{
+    return s_link_connected;
+}
+
 void user_mb_start(void)
 {
     user_mb_init();
diff --git a/APP/user_mb.h b/APP/user_mb.h
new file mode 100644 (file)
index 0000000..d39eddc
--- /dev/null
@@ -0,0 +1,390 @@
+#ifndef __USER_MB_H__
+#define __USER_MB_H__
+
+#include <stdint.h>
+#include <stdbool.h>
+
+#include "mb_api.h"
+#include "device_model.h"
+
+#include "mb_proto.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/* ======================== 通用配置 ======================== */
+/* 本装置作为主站, 被轮询的从站(BDM120)地址, 与 user_mb.c 保持一致 */
+#define USER_MB_TARGET_SLAVE    MB_DEFAULT_ADDR
+
+/* ======================== 生命周期 ======================== */
+/** 启动 user_mb 业务 (初始化锁/命令队列并创建 task_mb) */
+void user_mb_start(void);
+
+/** 初始化共享数据锁与写命令队列 (task_mb 启动时内部调用, 可对外显式预置) */
+int  user_mb_init(void);
+
+/** 查询与对端的链路连接状态: true=已连接, false=连续多次查询无响应断开 */
+bool user_mb_is_connected(void);
+
+/* ======================== 实时数据: 锁保护读取 ========================
+ * task_mb 每读回一个实时区间, 在锁保护下更新共享 g_device;
+ * 下列读取接口同样在加锁保护下, 将对应区间快照拷贝到调用方提供的 out 缓冲区,
+ * 并返回 out 指针 (内容与 g_device 一致)。out 传 NULL 时返回内部只读地址
+ * (不加锁, 仅用于确定数据不会并发变化、无需线程安全的场合)。
+ *
+ * 每个接口对应 reg_cache.c 中定义的一个读取区间:
+ *   telemetry  ≈ 遥测遥信  0~77
+ *   primary    ≈ 遥测一次值 100~139
+ *   statistics ≈ 统计信息  200~211
+ *   logic      ≈ 逻辑变量  400~434
+ *   version    ≈ 版本信息  600~678
+ *   ext_status ≈ IAP/LED/CMT测温 30000~
+ *   meter      ≈ 计量芯片转换值/状态 40000~40050
+ *   meter_raw  ≈ 计量芯片寄存器 40100~
+ *   harmonic   ≈ A/B/C 三相谐波 40200~
+ */
+const realtime_telemetry_t  *user_mb_get_realtime_telemetry(realtime_telemetry_t *out);
+const realtime_primary_t    *user_mb_get_realtime_primary(realtime_primary_t *out);
+const realtime_statistics_t *user_mb_get_realtime_statistics(realtime_statistics_t *out);
+const realtime_logic_t      *user_mb_get_realtime_logic(realtime_logic_t *out);
+const realtime_version_t    *user_mb_get_realtime_version(realtime_version_t *out);
+const realtime_ext_status_t *user_mb_get_realtime_ext_status(realtime_ext_status_t *out);
+const realtime_meter_chip_t *user_mb_get_realtime_meter(realtime_meter_chip_t *out);
+const realtime_meter_raw_t  *user_mb_get_realtime_meter_raw(realtime_meter_raw_t *out);
+const realtime_harmonic_t   *user_mb_get_realtime_harmonic(realtime_harmonic_t *out);
+
+/** 整块实时数据聚合 (锁保护快照拷贝到 out) */
+const realtime_t *user_mb_get_realtime(realtime_t *out);
+
+/* ======================== 控制信号: 线圈读写 ======================== */
+/* 控制线圈地址枚举 (0~45), 用于读写函数传参 */
+typedef enum {
+    USER_MB_COIL_REMOTE_DO1        = 0,   /* 遥控出口1 */
+    USER_MB_COIL_REMOTE_DO2        = 1,   /* 遥控出口2 */
+    USER_MB_COIL_REMOTE_DO3        = 2,   /* 遥控出口3 */
+    USER_MB_COIL_REMOTE_DO4        = 3,   /* 遥控出口4 */
+    USER_MB_COIL_REMOTE_DO5        = 4,   /* 遥控出口5 */
+    USER_MB_COIL_REMOTE_DO6        = 5,   /* 遥控出口6 */
+    USER_MB_COIL_DEVICE_RESET      = 6,   /* 装置复归 */
+    USER_MB_COIL_DEVICE_REBOOT     = 7,   /* 装置复位 */
+    USER_MB_COIL_CLEAR_STAT        = 8,   /* 清除统计 */
+    USER_MB_COIL_CLEAR_SOE         = 9,   /* 清除SOE */
+    USER_MB_COIL_CLEAR_ENERGY      = 10,  /* 清除电能 */
+    USER_MB_COIL_LOAD_DEFAULT      = 11,  /* 调用初始定值参数 */
+    USER_MB_COIL_RESET_CLOCK       = 12,  /* 重置时钟 */
+    USER_MB_COIL_MANUAL_WAVE       = 13,  /* 手动录波 */
+    USER_MB_COIL_ENABLE_USB        = 14,  /* 使能USB */
+    USER_MB_COIL_DISABLE_USB       = 15,  /* 禁用USB */
+    USER_MB_COIL_ENABLE_EXT        = 16,  /* 使能扩展设备 */
+    USER_MB_COIL_DISABLE_EXT       = 17,  /* 禁用扩展设备 */
+    USER_MB_COIL_COMM_START_A_BTN  = 18,  /* 通讯起动A-按键 */
+    USER_MB_COIL_COMM_START_B_BTN  = 19,  /* 通讯起动B-按键 */
+    USER_MB_COIL_COMM_STOP_BTN     = 20,  /* 停车-按键 */
+    USER_MB_COIL_COMM_START_A      = 21,  /* 通讯起动A-通讯 */
+    USER_MB_COIL_COMM_START_B      = 22,  /* 通讯起动B-通讯 */
+    USER_MB_COIL_COMM_STOP         = 23,  /* 停车-通讯 */
+    USER_MB_COIL_CLEAR_POWER_TIME  = 24,  /* 清除装置上电时间 */
+    USER_MB_COIL_RESET_RUN_CYCLE   = 25,  /* 重置运行周期 */
+    USER_MB_COIL_USB_TO_PARAM      = 26,  /* USB到定值 */
+    USER_MB_COIL_PARAM_TO_USB      = 27,  /* 定值到USB */
+    USER_MB_COIL_SOE_TO_USB        = 28,  /* SOE到USB */
+    USER_MB_COIL_WAVE_TO_USB       = 29,  /* 录波到USB */
+    USER_MB_COIL_USB_TO_EQUIP_TAG  = 30,  /* USB到设备位号 */
+    USER_MB_COIL_IAP_START         = 31,  /* IAP升级开始 */
+    USER_MB_COIL_UPGRADE_PROT      = 32,  /* 升级[保护板] */
+    USER_MB_COIL_UPGRADE_LCD       = 33,  /* 升级[液晶板] */
+    USER_MB_COIL_UPGRADE_ENH       = 34,  /* 升级[增强板] */
+    USER_MB_COIL_UPGRADE_OK        = 35,  /* 升级成功 */
+    USER_MB_COIL_UPGRADE_FAIL      = 36,  /* 升级失败 */
+    USER_MB_COIL_REBOOT_NO_REPORT  = 37,  /* 重启装置, 不生成报告 */
+    USER_MB_COIL_MODIFY_PARAM      = 38,  /* 修改定值 */
+    USER_MB_COIL_PARAM_MODIFIED    = 39,  /* 定值修改好了 */
+    USER_MB_COIL_REPORT_MOD_PARAM  = 40,  /* 生成修改定值的报告 */
+    USER_MB_COIL_REPORT_RESET_CLK  = 41,  /* 仅生成重置时钟的报告 */
+    USER_MB_COIL_DEBUG_ENTER       = 42,  /* 进入Debug模式 */
+    USER_MB_COIL_DEBUG_EXIT        = 43,  /* 退出Debug模式 */
+    USER_MB_COIL_TOKEN             = 44,  /* 传递令牌 */
+    USER_MB_COIL_CMT_FAULT         = 45,  /* CMT2300A出状况了 */
+    USER_MB_COIL_COUNT                       /* 线圈总数(=46) */
+} user_mb_coil_t;
+
+/**
+ * @brief 读控制线圈 (一次读出, 0x01)
+ * @param start 起始线圈地址(user_mb_coil_t, 0~45)
+ * @param count 数量(<= USER_MB_COIL_COUNT)
+ * @param out   输出线圈值数组
+ * @return MB_OK / MB_ERR_*
+ */
+int user_mb_read_control(user_mb_coil_t start, uint16_t count, bool *out);
+
+/**
+ * @brief 写控制线圈 (每次写一个, 0x05)
+ * @param coil 线圈地址(user_mb_coil_t, 0~45)
+ * @param on   ON/FF00, OFF/0000
+ * @return MB_OK / MB_ERR_*
+ */
+int user_mb_write_control(user_mb_coil_t coil, bool on);
+
+/* ======================== 定值数据: 锁保护读取 ========================
+ * 语义同上: 加锁拷贝对应定值区间到调用方 out 并返回; out=NULL 返回内部只读地址。
+ */
+const setting_protection_t        *user_mb_get_setting_protection(setting_protection_t *out);
+const setting_interlock_t         *user_mb_get_setting_interlock(setting_interlock_t *out);
+const setting_datetime_t          *user_mb_get_setting_datetime(setting_datetime_t *out);
+const setting_general_t           *user_mb_get_setting_general(setting_general_t *out);
+const uint16_t                    *user_mb_get_setting_di_map(uint16_t *out, uint16_t max);
+const uint16_t                    *user_mb_get_setting_do_map(uint16_t *out, uint16_t max);
+const uint16_t                    *user_mb_get_setting_led_map(uint16_t *out, uint16_t max);
+const uint16_t                    *user_mb_get_setting_screen_map(uint16_t *out, uint16_t max);
+const setting_comm_t              *user_mb_get_setting_comm(setting_comm_t *out);
+const char                        *user_mb_get_setting_equip_tag(char *out, uint16_t size);
+const setting_transmitter_t       *user_mb_get_setting_transmitter(setting_transmitter_t *out);
+const setting_energy_init_t       *user_mb_get_setting_energy_init(setting_energy_init_t *out);
+const setting_precision_t         *user_mb_get_setting_precision(setting_precision_t *out);
+const setting_transmitter_param_t *user_mb_get_setting_transmitter_param(setting_transmitter_param_t *out);
+const char                        *user_mb_get_setting_serial_no(char *out, uint16_t size);
+const char                        *user_mb_get_setting_device_model(char *out, uint16_t size);
+const char                        *user_mb_get_setting_reg_code(char *out, uint16_t size);
+uint16_t                           user_mb_get_setting_option_model(void);
+const setting_meter_precision_t   *user_mb_get_setting_meter_precision(setting_meter_precision_t *out);
+const setting_enhance_t           *user_mb_get_setting_enhance(setting_enhance_t *out);
+
+/** 整块定值数据聚合 (锁保护快照拷贝到 out) */
+const setting_t *user_mb_get_setting(setting_t *out);
+
+/* ======================== 参数写入接口 ========================
+ * 用户界面修改某个参数后, 调用对应区间接口将参数写回装置 (modbus 写寄存器),
+ * 全程持锁保护。返回 MB_OK / MB_ERR_* (见 mb_task.h)。
+ */
+
+/** 通用: 锁保护直接写单个寄存器 (实时调用 mb_write_reg, 同步等待) */
+int user_mb_write_register(uint16_t addr, uint16_t value);
+
+/** 通用: 写单个线圈 (锁保护, 同步等待) */
+int user_mb_write_coil(uint16_t addr, bool on);
+
+/** 通用: 异步写寄存器指令 (投递到命令队列, 由 task_mb 事件触发后执行写入) */
+int user_mb_write_register_async(uint16_t addr, uint16_t value);
+
+/* ---- 控制信号写入 (见上方 user_mb_coil_t 枚举, 每次写一个线圈) ---- */
+
+/* 定值数据: 分项写入 (一项一个写接口, 值由调用方传入; 返回 MB_OK / MB_ERR_*)*/
+
+/* ---- 保护参数 1000~1079 ---- */
+int user_mb_write_setting_protection_ie(uint16_t val);
+int user_mb_write_setting_protection_ct_range_sel(uint16_t val);
+int user_mb_write_setting_protection_cta0(uint16_t val);
+int user_mb_write_setting_protection_cta1(float val);
+int user_mb_write_setting_protection_il_ct_sel(uint16_t val);
+int user_mb_write_setting_protection_v_input_mode(uint16_t val);
+int user_mb_write_setting_protection_pt_ratio(float val);
+int user_mb_write_setting_protection_allow_start_time(uint16_t val);
+int user_mb_write_setting_protection_prot_start_long(uint16_t val);
+int user_mb_write_setting_protection_td(float val);
+int user_mb_write_setting_protection_prot_phase_loss(uint16_t val);
+int user_mb_write_setting_protection_m0(float val);
+int user_mb_write_setting_protection_t0(float val);
+int user_mb_write_setting_protection_prot_zero_seq(uint16_t val);
+int user_mb_write_setting_protection_i_delta(uint16_t val);
+int user_mb_write_setting_protection_t_delta(uint16_t val);
+int user_mb_write_setting_protection_prot_unbalance(uint16_t val);
+int user_mb_write_setting_protection_mr(float val);
+int user_mb_write_setting_protection_tr(float val);
+int user_mb_write_setting_protection_prot_stall(uint16_t val);
+int user_mb_write_setting_protection_tl(float val);
+int user_mb_write_setting_protection_tre(uint16_t val);
+int user_mb_write_setting_protection_prot_thermal(uint16_t val);
+int user_mb_write_setting_protection_te(float val);
+int user_mb_write_setting_protection_prot_te(uint16_t val);
+int user_mb_write_setting_protection_uh(float val);
+int user_mb_write_setting_protection_tint(float val);
+int user_mb_write_setting_protection_trs(float val);
+int user_mb_write_setting_protection_delta_t(uint16_t val);
+int user_mb_write_setting_protection_restart_imm(uint16_t val);
+int user_mb_write_setting_protection_uf(float val);
+int user_mb_write_setting_protection_tf(float val);
+int user_mb_write_setting_protection_prot_uv(uint16_t val);
+int user_mb_write_setting_protection_mp(float val);
+int user_mb_write_setting_protection_tp(uint16_t val);
+int user_mb_write_setting_protection_tpre(uint16_t val);
+int user_mb_write_setting_protection_prot_upower(uint16_t val);
+int user_mb_write_setting_protection_ile(float val);
+int user_mb_write_setting_protection_tle(uint16_t val);
+int user_mb_write_setting_protection_prot_leak(uint16_t val);
+int user_mb_write_setting_protection_uov(float val);
+int user_mb_write_setting_protection_tov(float val);
+int user_mb_write_setting_protection_prot_ov(uint16_t val);
+int user_mb_write_setting_protection_im(float val);
+int user_mb_write_setting_protection_prot_contactor(uint16_t val);
+int user_mb_write_setting_protection_iqd(float val);
+int user_mb_write_setting_protection_iq_run(float val);
+int user_mb_write_setting_protection_tq(float val);
+int user_mb_write_setting_protection_prot_run_break(uint16_t val);
+int user_mb_write_setting_protection_ikm(float val);
+int user_mb_write_setting_protection_tkm(float val);
+int user_mb_write_setting_protection_prot_cont_fail(uint16_t val);
+int user_mb_write_setting_protection_mi(float val);
+int user_mb_write_setting_protection_ti(uint16_t val);
+int user_mb_write_setting_protection_prot_ucurr(uint16_t val);
+int user_mb_write_setting_protection_ol_current(float val);
+int user_mb_write_setting_protection_ol_delay(float val);
+int user_mb_write_setting_protection_prot_overload(uint16_t val);
+int user_mb_write_setting_protection_phase_rev_delay(float val);
+int user_mb_write_setting_protection_prot_phase_rev(uint16_t val);
+int user_mb_write_setting_protection_prot_pt_break(uint16_t val);
+int user_mb_write_setting_protection_zero_seq_brake(uint16_t val);
+int user_mb_write_setting_protection_start_mode_sel(uint16_t val);
+int user_mb_write_setting_protection_flf(float val);
+int user_mb_write_setting_protection_tlf(float val);
+int user_mb_write_setting_protection_lf_block_v(float val);
+int user_mb_write_setting_protection_lf_block_slip(float val);
+int user_mb_write_setting_protection_prot_low_freq(uint16_t val);
+int user_mb_write_setting_protection_cot(uint16_t val);
+int user_mb_write_setting_protection_tot(uint16_t val);
+int user_mb_write_setting_protection_prot_temp(uint16_t val);
+int user_mb_write_setting_protection_run_time_limit(uint16_t val);
+int user_mb_write_setting_protection_prot_run_time(uint16_t val);
+int user_mb_write_setting_protection_tqqd(float val);
+int user_mb_write_setting_protection_prot_start_break(uint16_t val);
+int user_mb_write_setting_protection_ucurr_re_delay(uint16_t val);
+int user_mb_write_setting_protection_ol_re_delay(uint16_t val);
+int user_mb_write_setting_protection_temp_diff_warn(float val);
+int user_mb_write_setting_protection_prot_temp_diff(uint16_t val);
+int user_mb_write_setting_protection_restart_delay_en(uint16_t val);
+
+/* ---- 工艺联锁 1200~1225 ---- */
+int user_mb_write_setting_interlock_ext_fault_delay(float val);
+int user_mb_write_setting_interlock_ext_fault_en(uint16_t val);
+int user_mb_write_setting_interlock_ot_warn_delay(float val);
+int user_mb_write_setting_interlock_ot_warn_en(uint16_t val);
+int user_mb_write_setting_interlock_ot_trip_delay(float val);
+int user_mb_write_setting_interlock_ot_trip_en(uint16_t val);
+int user_mb_write_setting_interlock_di_break_km(uint16_t val);
+int user_mb_write_setting_interlock_di_break_qf(uint16_t val);
+int user_mb_write_setting_interlock_di_close_km(uint16_t val);
+int user_mb_write_setting_interlock_di_close_rev_km(uint16_t val);
+int user_mb_write_setting_interlock_di_signal(uint16_t val);
+int user_mb_write_setting_interlock_prot_act_delay(float val);
+int user_mb_write_setting_interlock_prot_act_en(uint16_t val);
+int user_mb_write_setting_interlock_emerg_stop_en(uint16_t val);
+int user_mb_write_setting_interlock_remote_reset_en(uint16_t val);
+int user_mb_write_setting_interlock_motor_run_en(uint16_t val);
+int user_mb_write_setting_interlock_panel_ctrl_en(uint16_t val);
+int user_mb_write_setting_interlock_step_start_delay(float val);
+int user_mb_write_setting_interlock_vfd_start_delay(float val);
+int user_mb_write_setting_interlock_fan_trip_delay(float val);
+int user_mb_write_setting_interlock_big_motor_delay(float val);
+int user_mb_write_setting_interlock_small_motor_delay(float val);
+int user_mb_write_setting_interlock_ie2(uint16_t val);
+int user_mb_write_setting_interlock_cta2(uint16_t val);
+int user_mb_write_setting_interlock_close_hold_time(float val);
+int user_mb_write_setting_interlock_start_ctrl_tout(uint16_t val);
+
+/* ---- 日期时间 2000~2006 (一次整体写入) ---- */
+int user_mb_write_setting_datetime(const setting_datetime_t *dt);
+
+/* ---- 通用参数 2100~2111 ---- */
+int user_mb_write_setting_general_run_pwd(uint16_t val);
+int user_mb_write_setting_general_di_filter_time(uint16_t val);
+int user_mb_write_setting_general_display_contrast(uint16_t val);
+int user_mb_write_setting_general_language(uint16_t val);
+int user_mb_write_setting_general_d1d2_func_sel(uint16_t val);
+int user_mb_write_setting_general_di_type_set(uint16_t val);
+int user_mb_write_setting_general_max_wave_len(uint16_t val);
+int user_mb_write_setting_general_trig_wave_ctrl1(uint16_t val);
+int user_mb_write_setting_general_trig_wave_ctrl2(uint16_t val);
+int user_mb_write_setting_general_temp_sensor_cnt(uint16_t val);
+int user_mb_write_setting_general_scroll_freq(uint16_t val);
+int user_mb_write_setting_general_backlight_time(uint16_t val);
+
+/* ---- 通讯参数 3400~3409 ---- */
+int user_mb_write_setting_comm_addr1(uint16_t val);
+int user_mb_write_setting_comm_baud1(uint16_t val);
+int user_mb_write_setting_comm_parity1(uint16_t val);
+int user_mb_write_setting_comm_stop1(uint16_t val);
+int user_mb_write_setting_comm_proto1(uint16_t val);
+int user_mb_write_setting_comm_addr2(uint16_t val);
+int user_mb_write_setting_comm_baud2(uint16_t val);
+int user_mb_write_setting_comm_parity2(uint16_t val);
+int user_mb_write_setting_comm_stop2(uint16_t val);
+int user_mb_write_setting_comm_proto2(uint16_t val);
+
+/* ---- 变送器配置 3600~3605 ---- */
+int user_mb_write_setting_transmitter_pwm_set1(uint16_t val);
+int user_mb_write_setting_transmitter_ma4_init1(uint16_t val);
+int user_mb_write_setting_transmitter_pwm_full1(uint16_t val);
+int user_mb_write_setting_transmitter_pwm_set2(uint16_t val);
+int user_mb_write_setting_transmitter_ma4_init2(uint16_t val);
+int user_mb_write_setting_transmitter_pwm_full2(uint16_t val);
+
+/* ---- 电度初值 3700~3704 (32 位, 各占 2 个寄存器) ---- */
+int user_mb_write_setting_energy_init_ph_low(uint32_t val);
+int user_mb_write_setting_energy_init_ph_high(uint32_t val);
+int user_mb_write_setting_energy_init_qh_low(uint32_t val);
+int user_mb_write_setting_energy_init_qh_high(uint32_t val);
+int user_mb_write_setting_energy_init_run_hours(uint32_t val);
+
+/* ---- 精度系数 4000~4008 ---- */
+int user_mb_write_setting_precision_xsh_ia(uint16_t val);
+int user_mb_write_setting_precision_xsh_ib(uint16_t val);
+int user_mb_write_setting_precision_xsh_ic(uint16_t val);
+int user_mb_write_setting_precision_xsh_il(uint16_t val);
+int user_mb_write_setting_precision_xsh_ua(uint16_t val);
+int user_mb_write_setting_precision_xsh_ub(uint16_t val);
+int user_mb_write_setting_precision_xsh_uc(uint16_t val);
+int user_mb_write_setting_precision_xsht1(uint16_t val);
+int user_mb_write_setting_precision_xsht2(uint16_t val);
+
+/* ---- 变送器参数 4100~4103 ---- */
+int user_mb_write_setting_transmitter_param_pwm_st1(uint16_t val);
+int user_mb_write_setting_transmitter_param_pwm_ed1(uint16_t val);
+int user_mb_write_setting_transmitter_param_pwm_st2(uint16_t val);
+int user_mb_write_setting_transmitter_param_pwm_ed2(uint16_t val);
+
+/* ---- 计量芯片精度系数 4500~4516 ---- */
+int user_mb_write_setting_meter_precision_engy_xsh_ia(uint16_t val);
+int user_mb_write_setting_meter_precision_engy_xsh_ib(uint16_t val);
+int user_mb_write_setting_meter_precision_engy_xsh_ic(uint16_t val);
+int user_mb_write_setting_meter_precision_engy_xsh_il(uint16_t val);
+int user_mb_write_setting_meter_precision_engy_xsh_ua(uint16_t val);
+int user_mb_write_setting_meter_precision_engy_xsh_ub(uint16_t val);
+int user_mb_write_setting_meter_precision_engy_xsh_uc(uint16_t val);
+int user_mb_write_setting_meter_precision_engy_fa(uint16_t val);
+int user_mb_write_setting_meter_precision_engy_fb(uint16_t val);
+int user_mb_write_setting_meter_precision_engy_fc(uint16_t val);
+int user_mb_write_setting_meter_precision_engy_offset_a(uint16_t val);
+int user_mb_write_setting_meter_precision_engy_offset_b(uint16_t val);
+int user_mb_write_setting_meter_precision_engy_offset_c(uint16_t val);
+int user_mb_write_setting_meter_precision_engy_offset_l(uint16_t val);
+int user_mb_write_setting_meter_precision_engy_offset_ua(uint16_t val);
+int user_mb_write_setting_meter_precision_engy_offset_ub(uint16_t val);
+int user_mb_write_setting_meter_precision_engy_offset_uc(uint16_t val);
+
+/* ---- 映射表 / 字符串等特殊项 (整表一次写入) ---- */
+int user_mb_write_setting_di_map(const uint16_t *map, uint16_t count);    /* 开入映射, count<=13 */
+int user_mb_write_setting_do_map(const uint16_t *map, uint16_t count);    /* 开出映射, count<=6  */
+int user_mb_write_setting_led_map(const uint16_t *map, uint16_t count);   /* LED 映射, count<=5  */
+int user_mb_write_setting_screen_map(const uint16_t *map, uint16_t count);/* 主画面组态, count<=16 */
+int user_mb_write_setting_equip_tag(const char *tag, uint16_t len);  /* 设备位号 */
+int user_mb_write_setting_serial_no(const char *str);                /* 序列号   */
+int user_mb_write_setting_device_model(const char *str);             /* 装置型号 */
+int user_mb_write_setting_reg_code(const char *str);                 /* 装置注册码 */
+int user_mb_write_setting_option_model(uint16_t val);                /* 选配型号 */
+
+/* ---- 增强板参数 ---- */
+int user_mb_write_setting_enhance_serial_addr(uint16_t val);
+int user_mb_write_setting_enhance_serial_baud(uint16_t val);
+int user_mb_write_setting_enhance_serial_parity(uint16_t val);
+int user_mb_write_setting_enhance_serial_stop(uint16_t val);
+int user_mb_write_setting_enhance_serial_proto(uint16_t val);
+int user_mb_write_setting_enhance_profibus_addr(uint16_t val);
+int user_mb_write_setting_enhance_bluetooth_id(uint16_t val);
+int user_mb_write_setting_enhance_temp_sensor_id(uint16_t idx, uint32_t val); /* idx=0~8 */
+int user_mb_write_setting_enhance_ip_addr(uint16_t idx, uint8_t val);         /* idx=0~3 */
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
\ No newline at end of file
index 9983c2670a9e64d1471108cef443ea428a52c0c6..b0a7ad9060fc788702742b1230922599e3295495 100644 (file)
@@ -16,6 +16,8 @@ LR_IROM1 0x00000000 0x00080000  {    ; load region size_region
    .ANY (+RO)
    .ANY (+XO)
   }
+  FSymTab +0 { *(FSymTab) }  ; CherrySH 命令符号表
+  VSymTab +0 { *(VSymTab) }  ; CherrySH 变量符号表
   RW_IRAM1 0x20000000 0x00010000  {  ; RW data
    .ANY (+RW +ZI)
    *(.SRAM)
@@ -32,4 +34,4 @@ LR_SPIFLASH 0x70000000 0x01000000  {      ; load region size_region
   ER_SDRAM2 0x80500000 0x00300000  {      ; execution address
     *(.SDRAM2)
   }
-}
+}
\ No newline at end of file
index 8d8a2db20f186acde5193584222cb819b4b4ca07..130b87033f04e2328b7a2b1f06748580ff58e072 100644 (file)
@@ -16,6 +16,8 @@ LR_IROM1 0x00000000 0x00080000  {    ; load region size_region
    .ANY (+RO)
    .ANY (+XO)
   }
+  FSymTab +0 { *(FSymTab) }  ; CherrySH 命令符号表
+  VSymTab +0 { *(VSymTab) }  ; CherrySH 变量符号表
   RW_IRAM1 0x20000000 0x00010000  {  ; RW data
    .ANY (+RW +ZI)
    ;*(.SRAM)
index 4efeee69b6c5ce9a586a576e0bc2e6239bba26ab..ae8a480daf2619f25819422c4f00edd66e29b34d 100644 (file)
               <MiscControls>-Wno-invalid-source-encoding</MiscControls>
               <Define>__TARGET_CONST__=0,</Define>
               <Undefine></Undefine>
-              <IncludePath>.\CSL\CMSIS\CoreSupport;.\CSL\CMSIS\DeviceSupport;.\CSL\SWM341_StdPeriph_Driver;.\CSL\SWM341_UsbHost_Lib;.\CSL\SWM341_UsbHost_Lib\CDC;.\CSL\SWM341_UsbHost_Lib\HID;.\CSL\SWM341_UsbHost_Lib\MSC;.\CSL\SWM341_UsbHost_Lib\MTP;.\Middleware\FatFs\source;.\Middleware\lvgl;.\Middleware\lvgl\lvgl;.\Middleware\lvgl\lvgl\src;.\Middleware\lvgl\lvgl\src\lv_core;.\Middleware\lvgl\lvgl\src\lv_draw;.\Middleware\lvgl\lvgl\src\lv_font;.\Middleware\lvgl\lvgl\src\lv_gpu;.\Middleware\lvgl\lvgl\src\lv_hal;.\Middleware\lvgl\lvgl\src\lv_misc;.\Middleware\lvgl\lvgl\src\lv_themes;.\Middleware\lvgl\lvgl\src\lv_widgets;.\Middleware\lvgl\lvgl\examples\porting;.\Middleware\lvgl\lv_examples;.\Middleware\lvgl\lv_examples\src;.\Middleware\lvgl\lv_examples\src\lv_demo_widgets;.\Middleware\lvgl\lv_examples\src\lv_demo_benchmark;.\Middleware\lvgl\lv_examples\src\lv_demo_stress;.\Middleware\lvgl\lv_examples\src\lv_demo_music;.\APP;.\APP\can_comm;.\APP\BSP;.\APP\IC_Driver;.\APP\Common Module;.\APP\Software_Parser;.\APP\USB\Device;.\APP\USB\Host;.\APP\UI;.\APP\UI\Resource;.\APP\UI\Page;.\Middleware\FreeRTOS-Kernel;.\Middleware\FreeRTOS-Kernel\include;.\Middleware\FreeRTOS-Kernel\portable\GCC\ARM_CM33_NTZ\non_secure;.\Middleware\FreeRTOS-Kernel\portable\MemMang;.\APP\can_comm;.\APP\mb</IncludePath>
+              <IncludePath>.\CSL\CMSIS\CoreSupport;.\CSL\CMSIS\DeviceSupport;.\CSL\SWM341_StdPeriph_Driver;.\CSL\SWM341_UsbHost_Lib;.\CSL\SWM341_UsbHost_Lib\CDC;.\CSL\SWM341_UsbHost_Lib\HID;.\CSL\SWM341_UsbHost_Lib\MSC;.\CSL\SWM341_UsbHost_Lib\MTP;.\Middleware\FatFs\source;.\Middleware\lvgl;.\Middleware\lvgl\lvgl;.\Middleware\lvgl\lvgl\src;.\Middleware\lvgl\lvgl\src\lv_core;.\Middleware\lvgl\lvgl\src\lv_draw;.\Middleware\lvgl\lvgl\src\lv_font;.\Middleware\lvgl\lvgl\src\lv_gpu;.\Middleware\lvgl\lvgl\src\lv_hal;.\Middleware\lvgl\lvgl\src\lv_misc;.\Middleware\lvgl\lvgl\src\lv_themes;.\Middleware\lvgl\lvgl\src\lv_widgets;.\Middleware\lvgl\lvgl\examples\porting;.\Middleware\lvgl\lv_examples;.\Middleware\lvgl\lv_examples\src;.\Middleware\lvgl\lv_examples\src\lv_demo_widgets;.\Middleware\lvgl\lv_examples\src\lv_demo_benchmark;.\Middleware\lvgl\lv_examples\src\lv_demo_stress;.\Middleware\lvgl\lv_examples\src\lv_demo_music;.\APP;.\APP\can_comm;.\APP\BSP;.\APP\IC_Driver;.\APP\Common Module;.\APP\Software_Parser;.\APP\USB\Device;.\APP\USB\Host;.\APP\UI;.\APP\UI\Resource;.\APP\UI\Page;.\Middleware\FreeRTOS-Kernel;.\Middleware\FreeRTOS-Kernel\include;.\Middleware\FreeRTOS-Kernel\portable\GCC\ARM_CM33_NTZ\non_secure;.\Middleware\FreeRTOS-Kernel\portable\MemMang;.\APP\can_comm;.\APP\mb;.\APP\shell;.\APP\shell\cherryrl</IncludePath>
             </VariousControls>
           </Cads>
           <Aads>
               <FileType>1</FileType>
               <FilePath>.\APP\mb\reg_cache.c</FilePath>
             </File>
+            <File>
+              <FileName>event.c</FileName>
+              <FileType>1</FileType>
+              <FilePath>.\APP\mb\event.c</FilePath>
+            </File>
+          </Files>
+        </Group>
+        <Group>
+          <GroupName>shell</GroupName>
+          <Files>
+            <File>
+              <FileName>shell.c</FileName>
+              <FileType>1</FileType>
+              <FilePath>.\APP\shell\shell.c</FilePath>
+            </File>
+            <File>
+              <FileName>chry_shell.c</FileName>
+              <FileType>1</FileType>
+              <FilePath>.\APP\shell\chry_shell.c</FilePath>
+            </File>
+            <File>
+              <FileName>chry_readline.c</FileName>
+              <FileType>1</FileType>
+              <FilePath>.\APP\shell\cherryrl\chry_readline.c</FilePath>
+            </File>
           </Files>
         </Group>
       </Groups>
               <FileType>1</FileType>
               <FilePath>.\APP\mb\reg_cache.c</FilePath>
             </File>
+            <File>
+              <FileName>event.c</FileName>
+              <FileType>1</FileType>
+              <FilePath>.\APP\mb\event.c</FilePath>
+            </File>
+          </Files>
+        </Group>
+        <Group>
+          <GroupName>shell</GroupName>
+          <Files>
+            <File>
+              <FileName>shell.c</FileName>
+              <FileType>1</FileType>
+              <FilePath>.\APP\shell\shell.c</FilePath>
+            </File>
+            <File>
+              <FileName>chry_shell.c</FileName>
+              <FileType>1</FileType>
+              <FilePath>.\APP\shell\chry_shell.c</FilePath>
+            </File>
+            <File>
+              <FileName>chry_readline.c</FileName>
+              <FileType>1</FileType>
+              <FilePath>.\APP\shell\cherryrl\chry_readline.c</FilePath>
+            </File>
           </Files>
         </Group>
       </Groups>