zhunk il y a 9 mois
Parent
commit
71a00ebe54

+ 135 - 0
Application_cbd_apm32f1/applications/cpu_usage.c

@@ -0,0 +1,135 @@
+/*
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ * Change Logs:
+ * Date           Author       Notes
+ * 2020-12-04     tyx          first implementation
+ */
+
+#include "cpu_usage.h"
+
+#ifndef CPU_USAGE_PERIOD_TICK
+#define CPU_USAGE_PERIOD_TICK RT_TICK_PER_SECOND
+#endif
+
+cpu_usage_t *cpu_usage_obj(void)
+{
+    static struct cpu_usage _usage;
+    return &_usage;
+}
+
+static void timeout(void *param)
+{
+    cpu_usage_t *obj = param;
+
+    if (obj->state == CPU_USAGE_STATE_ACTIVATED)
+    {
+        if (++obj->period == CPU_USAGE_PERIOD_TICK)
+        {
+            obj->period = 0;
+            obj->idle_stat[0].load = CPU_USAGE_PERIOD_TICK -
+                (obj->idle_stat[0].idle_tick - obj->idle_stat[0].last_tick);
+            obj->idle_stat[0].last_tick = obj->idle_stat[0].idle_tick;
+        }
+
+        if (rt_thread_self() == obj->idle_stat[0].tid)
+        {
+            obj->idle_stat[0].idle_tick++;
+        }
+    }
+}
+
+int cpu_usage_init(void)
+{
+    cpu_usage_t *obj = cpu_usage_obj();
+    rt_timer_t t = &obj->time;
+    char idle_name[RT_NAME_MAX];
+    int i;
+
+    if (rt_object_get_type(&t->parent) != RT_Object_Class_Timer)
+    {
+        /* init time */
+        rt_timer_init(t, "usage", timeout, obj, 1,
+            RT_TIMER_FLAG_PERIODIC | RT_TIMER_FLAG_HARD_TIMER);
+        /* set cpus */
+        obj->cpus = sizeof(obj->idle_stat) / sizeof(obj->idle_stat[0]);
+        /* get idle thread handle */
+        for (i = 0; i < obj->cpus; i++)
+        {
+            rt_snprintf(idle_name, sizeof(idle_name), "tidle%d", i);
+            obj->idle_stat[i].tid = rt_thread_find(idle_name);
+        }
+        /* set flags */
+        obj->state = CPU_USAGE_STATE_ACTIVATED;
+        /* start */
+        rt_timer_start(t);
+    }
+    return 0;
+}
+
+void cpu_usage_deinit(void)
+{
+    cpu_usage_t *obj = cpu_usage_obj();
+    rt_timer_t t = &obj->time;
+
+    if (rt_object_get_type(&t->parent) == RT_Object_Class_Timer)
+    {
+        rt_timer_stop(t);
+        rt_timer_detach(t);
+        rt_memset(obj, 0, sizeof(*obj));
+    }
+}
+
+void cpu_usage_suspend(void)
+{
+    cpu_usage_t *obj = cpu_usage_obj();
+    rt_timer_t t = &obj->time;
+
+    if (obj->state == CPU_USAGE_STATE_ACTIVATED)
+    {
+        rt_timer_stop(t);
+        obj->state = CPU_USAGE_STATE_SUSPEND;
+        obj->suspend_tick = rt_tick_get();
+    }
+}
+
+void cpu_usage_resume(void)
+{
+    cpu_usage_t *obj = cpu_usage_obj();
+    rt_timer_t t = &obj->time;
+    rt_tick_t tick;
+    int i;
+
+    if (obj->state == CPU_USAGE_STATE_SUSPEND)
+    {
+        tick = rt_tick_get() - obj->suspend_tick;
+        for (i = 0; i < obj->cpus; i++)
+        {
+            obj->idle_stat[i].idle_tick += tick;
+        }
+        obj->state = CPU_USAGE_STATE_ACTIVATED;
+        rt_timer_start(t);
+    }
+}
+
+float cpu_load_average(void)
+{
+    cpu_usage_t *obj = cpu_usage_obj();
+    rt_tick_t usage = 0;
+    float load = 0.0;
+    int i;
+
+    if (obj->state == CPU_USAGE_STATE_ACTIVATED)
+    {
+        for (i = 0; i < obj->cpus; i++)
+        {
+            usage += obj->idle_stat[i].load;
+        }
+        load = 100.0 * usage / (CPU_USAGE_PERIOD_TICK * obj->cpus);
+    }
+    return load;
+}
+
+#ifdef RT_USING_COMPONENTS_INIT
+INIT_APP_EXPORT(cpu_usage_init);
+#endif

+ 52 - 0
Application_cbd_apm32f1/applications/cpu_usage.h

@@ -0,0 +1,52 @@
+/*
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ * Change Logs:
+ * Date           Author       Notes
+ * 2020-12-04     tyx          first implementation
+ */
+
+#ifndef __CPU_USAGE_H__
+#define __CPU_USAGE_H__
+
+#include "rtthread.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#define CPU_USAGE_STATE_DEACTIVATED  (0x0)
+#define CPU_USAGE_STATE_ACTIVATED    (0x1)
+#define CPU_USAGE_STATE_SUSPEND      (0x2)
+
+struct cpu_usage
+{
+    struct rt_timer time;           /* Period timer */
+    rt_uint8_t state;               /* Running state */
+    rt_uint8_t cpus;                /* Number of CPUs */
+    rt_uint16_t reserved;
+    rt_tick_t suspend_tick;         /* CPU suspend timestamp */
+    rt_tick_t period;               /* Stat Period */
+    struct _idle_stat
+    {
+        rt_tick_t idle_tick;
+        rt_tick_t last_tick;
+        rt_tick_t load;
+        rt_thread_t tid;
+    }
+    idle_stat[1];
+};
+typedef struct cpu_usage cpu_usage_t;
+
+int cpu_usage_init(void);
+void cpu_usage_deinit(void);
+cpu_usage_t *cpu_usage_obj(void);
+void cpu_usage_suspend(void);
+void cpu_usage_resume(void);
+float cpu_load_average(void);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif

+ 54 - 0
Application_cbd_apm32f1/applications/cpu_usage_cmd.c

@@ -0,0 +1,54 @@
+/*
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ * Change Logs:
+ * Date           Author       Notes
+ * 2020-12-04     tyx          first implementation
+ * 2021-01-17     Meco Man     beautify cmd
+ */
+#include <stdlib.h>
+#include "cpu_usage.h"
+
+static volatile rt_thread_t tid;
+
+static void load_thread(void *param)
+{
+    while (tid != RT_NULL && (int)tid->user_data)
+    {
+        while ((int)tid->user_data >= rt_tick_get() % 100);
+        rt_thread_delay(1);
+    }
+    tid = RT_NULL;
+}
+
+void cpu_usage_msh(int argc, char *argv[])
+{
+    if (argc == 3 && rt_strcmp(argv[1], "-l") == 0)
+    {
+        if (tid)
+        {
+            tid->user_data = strtoul(argv[2], RT_NULL, 10);
+        }
+        else
+        {
+            tid = rt_thread_create("usage", load_thread, RT_NULL, 256,
+                RT_THREAD_PRIORITY_MAX - 2, 20);
+            if (tid == RT_NULL)
+            {
+                rt_kprintf("create thread failed.");
+            }
+            tid->user_data = strtoul(argv[2], RT_NULL, 10);
+            rt_thread_startup(tid);
+        }
+        rt_kprintf("CPU usage adjusted to %d%c\n", tid->user_data, '%');
+    }
+    else if (argc == 1)
+    {
+        rt_kprintf("cpu: %d\n", (int)cpu_load_average());
+    }
+    else
+    {
+        rt_kprintf("%s\n", argv[0]);
+    }
+}
+MSH_CMD_EXPORT_ALIAS(cpu_usage_msh, usage, cpu usage);

+ 416 - 136
Application_cbd_apm32f1/applications/dtu_uart2.c

@@ -30,7 +30,8 @@
 #define DBG_TAG "dtu"
 #define DBG_TAG "dtu"
 #define DBG_LEVEL         DBG_LOG
 #define DBG_LEVEL         DBG_LOG
 #include <rtdbg.h> //must after of DBG_LVL, DBG_TAG or other options
 #include <rtdbg.h> //must after of DBG_LVL, DBG_TAG or other options
-
+#include <lwjson.h>
+#include "sys_monitor.h"
 
 
 #define DTU_THREAD_PRIORITY         6          //线程优先级
 #define DTU_THREAD_PRIORITY         6          //线程优先级
 #define DTU_THREAD_STACK_SIZE       4096        //线程栈空间大小
 #define DTU_THREAD_STACK_SIZE       4096        //线程栈空间大小
@@ -38,6 +39,7 @@
 
 
 
 
 Device_Status_typedef device_status;
 Device_Status_typedef device_status;
+System_stats_t system_status;
 DataTemp data_arry;
 DataTemp data_arry;
 
 
 void list_mem(void);
 void list_mem(void);
@@ -47,12 +49,12 @@ struct rx_msg
     rt_device_t dev;
     rt_device_t dev;
     rt_size_t size;
     rt_size_t size;
 };
 };
-/* 消息队列句柄 */
-static struct rt_messagequeue  rx_mq_dtu;
+
+static struct rt_semaphore rx_sem;    /* 用于接收消息的信号量 */
 rt_thread_t dtu_recv_data = RT_NULL;
 rt_thread_t dtu_recv_data = RT_NULL;
 rt_thread_t dtu_send_data = RT_NULL;
 rt_thread_t dtu_send_data = RT_NULL;
 
 
-
+static lwjson_stream_parser_t lwparser;
 rt_device_t dtuserial;   /*串口设备句柄*/
 rt_device_t dtuserial;   /*串口设备句柄*/
 struct  serial_configure dtuconfig = RT_SERIAL_CONFIG_DEFAULT;  /*初始化配置参数*/
 struct  serial_configure dtuconfig = RT_SERIAL_CONFIG_DEFAULT;  /*初始化配置参数*/
 
 
@@ -107,142 +109,66 @@ void DTU_Write(char *fmt, ...)
     if (str_length > 1024 - 1)
     if (str_length > 1024 - 1)
         str_length = 1024 - 1;
         str_length = 1024 - 1;
     rt_device_write(dtuserial, 0, dtu_str, str_length);
     rt_device_write(dtuserial, 0, dtu_str, str_length);
+    system_status.uart2_tx_bytes +=str_length;
     LOG_I("DTU_Write:%s",dtu_str);
     LOG_I("DTU_Write:%s",dtu_str);
-//    if(strstr(dtu_str,"volume")!=RT_NULL)
-//    {
-//        rt_device_write(dtuserial,0,dtu_conf,4);
-//    }
-//    else if (strstr(dtu_str,"reset")!=RT_NULL) {
-//        const char dtu_conf[4] = {7,0x00,0x00,0x00};
-//        rt_device_write(dtuserial,0,dtu_conf,4);
-//    }
+    rt_thread_delay(10);
 }
 }
 /* 接收数据回调函数 */
 /* 接收数据回调函数 */
 static rt_err_t dtu_input(rt_device_t dev, rt_size_t size)
 static rt_err_t dtu_input(rt_device_t dev, rt_size_t size)
 {
 {
-    struct rx_msg msg;
-    rt_err_t result;
-    msg.dev = dev;
-    msg.size = size;
-    result = rt_mq_send(&rx_mq_dtu,&msg, sizeof(struct rx_msg));
-    if ( result == -RT_EFULL)
-    {
-        /* 消息队列满 */
-        LOG_E("rx_mq_dtu message queue full!\n");
-        rt_mq_control(&rx_mq_dtu, RT_IPC_CMD_RESET, RT_NULL); // 清空队列
-    }
-    return result;
+    rt_sem_release(&rx_sem);
+    return RT_EOK;
 }
 }
 
 
 
 
 /* 入口函数-指令接收*/
 /* 入口函数-指令接收*/
 static void dtu_thread_entry_recv(void *parameter)
 static void dtu_thread_entry_recv(void *parameter)
 {
 {
-    struct rx_msg msg;
-    rt_memset(&msg, 0, sizeof(msg));
-    rt_err_t result;
-    rt_uint32_t rx_length;
-    static int rx_err = 0;
-    static char str_check[2]={'{','}'};
-    static char rx_buffer[512];
-    static char rx_buffer_tmp[512];
-    static char rx_buffer_tmp2[512];
+    static char accum_buf[MAX_DTU_SIZE];  // 累积缓冲区(根据实际数据量调整)
+    static size_t accum_len = 0;        // 累积缓冲区当前长度
+    char ch;
     while(1)
     while(1)
     {
     {
-        //
-        // 从消息队列中获取被回调函数放入消息队列中的内容
-        result = rt_mq_recv(&rx_mq_dtu, &msg, sizeof(struct rx_msg), 100);
-        #if 0
-        if (result != RT_EOK){
-            rx_err ++;
-            if(rx_err==15){
-                json_ctx.index = 0;
-            }
-//            if(rx_err==54000)//90分钟未接收到数据
-//            {
-//                ctr_RTU_DTU(OFF);
-//            }
-//            if (rx_err>54100&&device_status.bat_status==0)
-//            {
-//                LOG_W("通信中断,RTU重新上电");
-//                rx_err = 0;
-//                ctr_RTU_DTU(ON);
-//                ctr_photo(ON);
-//            }
-            continue;
-        }
-        // 动态分配接收缓冲区
-        char *rx_buffer = rt_malloc(msg.size + 1);
-        if (!rx_buffer) {
-            LOG_E("Memory allocation failed");
-            continue;
-        }
-        // 安全读取数据
-        int rx_length = rt_device_read(msg.dev, 0, rx_buffer, msg.size);
-        if (rx_length <= 0) {
-            rt_free(rx_buffer);
-            continue;
-        }
-        rx_err = 0;
-        rx_buffer[rx_length] = '\0';
-        // 处理数据(新增调试接口)
-        LOG_I("Raw Data:%s-%d",rx_buffer, rx_length);
-        if(strstr(rx_buffer,"{")==RT_NULL||strstr(rx_buffer,"}")==RT_NULL)
-        {
-            HMI_WRITE("sysSet.va0.txt=\"%s\"",rx_buffer);
-        }else{
-            process_uart_data(rx_buffer, rx_length);
-        }
-
-        rt_free(rx_buffer);
-        #endif
-        #if 1
-        if(result == RT_EOK)
-        {
-
-            rx_err = 0;
-            rx_length =(sizeof(rx_buffer) - 1) > msg.size ?
-                    msg.size : sizeof(rx_buffer) - 1;
-            rx_length = rt_device_read(msg.dev, 0, &rx_buffer[0], rx_length);
-            rx_buffer[rx_length] = '\0';
-            LOG_D("recv data:%s",rx_buffer);
-//            if(strstr(rx_buffer,"{")==RT_NULL||strstr(rx_buffer,"}")==RT_NULL)
-//            {
-//               HMI_WRITE("sysSet.va0.txt=\"%s\"",rx_buffer);
-//            }
-
-            //过滤异常数据
-            char str_check_head[2];
-            char str_check_end[2];
-            rt_sprintf(str_check_head, "%c",rx_buffer[0]);
-            rt_sprintf(str_check_end, "%c",rx_buffer[rx_length-1]);
-            if(str_check_end[0]==str_check[1]&&str_check_head[0]==str_check[0])
-            {
-                  parseDtu(rx_buffer);
-                  rt_memset(rx_buffer,0,sizeof(rx_buffer));
-                  rt_memset(rx_buffer_tmp,0,sizeof(rx_buffer_tmp));
-                  rt_memset(rx_buffer_tmp2,0,sizeof(rx_buffer_tmp2));
-            }
-            else {
-                   if(rx_buffer[rx_length-1]!='}')
-                   {
-                       rt_sprintf(rx_buffer_tmp, "%s",rx_buffer);
-                   }
-                   else {
-                       rt_sprintf(rx_buffer_tmp2,"%s",rx_buffer);
-                       rt_sprintf(rx_buffer, "%s%s",rx_buffer_tmp,rx_buffer_tmp2);
-                       parseDtu(rx_buffer);
-                       rt_memset(rx_buffer,0,sizeof(rx_buffer));
-                       rt_memset(rx_buffer_tmp,0,sizeof(rx_buffer_tmp));
-                       rt_memset(rx_buffer_tmp2,0,sizeof(rx_buffer_tmp2));
-                   }
-
-                 }
-            #endif
+        /* 从串口读取一个字节的数据,没有读取到则等待接收信号量 */
+       while (rt_device_read(dtuserial, -1, &ch, 1) != 1)
+       {
+           /* 阻塞等待接收信号量,等到信号量后再次读取数据 */
+           rt_sem_take(&rx_sem, RT_WAITING_FOREVER);
+       }
+       system_status.uart2_rx_bytes+=1;
+       accum_buf[accum_len++]=ch;
+       if (accum_len >= sizeof(accum_buf)) {
+           // 防止超范围
+           accum_len = 0;
+           lwjson_stream_reset(&lwparser);
+           memset(accum_buf,0,sizeof(accum_buf));
+           continue;
+       }
+       lwjsonr_t ret;
+       ret = lwjson_stream_parse(&lwparser, ch); // 把串口数据逐字节的喂给解析器去解析
+       switch(ret)
+       {
+           case lwjsonERRJSON:                  // 1, 无效的字符
+             case lwjsonSTREAMWAITFIRSTCHAR:    // 2, 等待首字符
+               LOG_W("invalid JSON byte:%s[%x]",ch,ch);
+               break;
+             case lwjsonSTREAMINPROG:           // 3, 正在解析中
+               break;
+             case lwjsonSTREAMDONE:             // 4, 解析已完成
+                parseDtu(accum_buf);
+                accum_len = 0;
+                memset(accum_buf,0,sizeof(accum_buf));
+                //rt_thread_kill(dtu_send_data, SIGUSR2);
+                lwjson_stream_reset(&lwparser);
+                break;
+             case lwjsonERRMEM:                 // 5, 嵌套的太深("LWJSON_CFG_STREAM_STACK_SIZE")
+                LOG_E("parser stack overflow (ERRMEM), resetting parser!");
+                lwjson_stream_reset(&lwparser);
+                break;
+             default: // 流式解析时, 其它的返回值, 都不应该出现
+                LOG_E("internal error, lwjson_stream_parse() returned: %d, data receive thread will exit!!!",ret);
+                break;
          }
          }
-//         else {
-//
-//
     }
     }
 }
 }
 
 
@@ -368,17 +294,10 @@ static void dtu_thread_entry_send(void *parameter)
 /* 创建线程 */
 /* 创建线程 */
 int dtu_data_play(void)
 int dtu_data_play(void)
 {
 {
-    rt_err_t rm_dtu_result;
+    lwjson_stream_init(&lwparser, NULL);
     DTU_uart2_init();
     DTU_uart2_init();
-    //初始化消息队列
-    rm_dtu_result = rt_mq_init(&rx_mq_dtu, "dtu", &data_arry.msg_pool[0], 128 - sizeof(void*), sizeof(data_arry.msg_pool), RT_IPC_FLAG_FIFO);
-    if(rm_dtu_result==RT_EOK)
-    {
-        rt_kprintf("消息队列创建成功!!");
-    }
-    else {
-        rt_kprintf("消息队列创建失败!!");
-    }
+    /* 初始化信号量 */
+    rt_sem_init(&rx_sem, "rx_sem", 0, RT_IPC_FLAG_FIFO);
     /* 设置接收回调函数 */
     /* 设置接收回调函数 */
     rt_device_set_rx_indicate(dtuserial, dtu_input);
     rt_device_set_rx_indicate(dtuserial, dtu_input);
     /*创建线程-指令发送*/
     /*创建线程-指令发送*/
@@ -694,6 +613,366 @@ char *makeJson_Cam(char * s,char *t)
     return w;
     return w;
 }
 }
 
 
+/**
+ * @brief 创建JSON-RPC 2.0请求字符串
+ * @param method 方法名(必须)
+ * @param params 参数对象(可选)
+ * @param id 请求ID(可选,NULL表示通知)
+ * @return 返回JSON字符串,需要调用者释放,失败返回NULL
+ */
+char* makeJsonRpc2_0(const char* method, cJSON* params, int id)
+{
+    // 参数检查
+    if (method == NULL || method[0] == '\0') {
+        fprintf(stderr, "Error: method cannot be NULL or empty\n");
+        return NULL;
+    }
+
+    cJSON* root = cJSON_CreateObject();
+    if (root == NULL) {
+        fprintf(stderr, "Error: Failed to create JSON object\n");
+        return NULL;
+    }
+
+    // 添加 jsonrpc 版本
+    if (!cJSON_AddStringToObject(root, "jsonrpc", "2.0")) {
+        cJSON_Delete(root);
+        return NULL;
+    }
+
+    // 添加 method
+    if (!cJSON_AddStringToObject(root, "method", method)) {
+        cJSON_Delete(root);
+        return NULL;
+    }
+
+    // 添加 params(如果有)
+    if (params != NULL) {
+        // 注意:这里不复制params,调用者需要保证params在函数调用期间有效
+        cJSON_AddItemToObject(root, "params", params);
+    }
+
+    cJSON_AddNumberToObject(root, "id", id);
+    // 生成JSON字符串
+    char* json_str = cJSON_PrintUnformatted(root);
+
+    // 清理
+    cJSON_Delete(root);
+
+    return json_str;
+}
+
+void parse_param_to_mcu(cJSON* Params)
+{
+    if(Params!=NULL)
+    {
+        cJSON* value = NULL;
+        value = cJSON_GetObjectItem(Params,"reboot_time");
+        if(value!=NULL){
+            device_status.rebootcnt = value->valueint;
+            ef_set_env_blob("reboot_time", &device_status.rebootcnt, sizeof(device_status.rebootcnt));
+        }
+
+        value = cJSON_GetObjectItem(Params,"ds");
+        if(value!=NULL){
+            device_status.ds = value->valueint;
+            ef_set_env_blob("ds", &device_status.ds, sizeof(device_status.ds));
+        }
+
+        value = cJSON_GetObjectItem(Params,"tt");
+        if(value!=NULL){
+            device_status.sunBar = value->valueint;
+            ef_set_env_blob("sunBar", &device_status.sunBar, sizeof(device_status.sunBar));
+        }
+
+        value = cJSON_GetObjectItem(Params,"st");
+        if(value!=NULL){
+            device_status.startBar = value->valueint;
+            ef_set_env_blob("sunBar", &device_status.startBar, sizeof(device_status.startBar));
+        }
+
+        value = cJSON_GetObjectItem(Params,"et");
+        if(value!=NULL){
+            device_status.stopBar = value->valueint;
+            ef_set_env_blob("stopBar", &device_status.stopBar, sizeof(device_status.stopBar));
+        }
+
+        value = cJSON_GetObjectItem(Params,"ts");
+        if(value!=NULL){
+            device_status.timeSwitch = value->valueint;
+            ef_set_env_blob("timeSwitch", &device_status.timeSwitch, sizeof(device_status.timeSwitch));
+        }
+
+        value = cJSON_GetObjectItem(Params,"tpl");
+        if(value!=NULL){
+            device_status.tpl = value->valueint;
+            ef_set_env_blob("tpl", &device_status.tpl, sizeof(device_status.tpl));
+        }
+
+        value = cJSON_GetObjectItem(Params,"tph");
+        if(value!=NULL){
+            device_status.tph = value->valueint;
+            ef_set_env_blob("tph", &device_status.tph, sizeof(device_status.tph));
+        }
+
+        value = cJSON_GetObjectItem(Params,"stime");
+        if(value!=NULL){
+            device_status.clt_time = value->valueint;
+            ef_set_env_blob("stime", &device_status.clt_time, sizeof(device_status.clt_time));
+        }
+
+        value = cJSON_GetObjectItem(Params,"jtime");
+        if(value!=NULL){
+            device_status.heattime = value->valueint;
+            ef_set_env_blob("jtime", &device_status.heattime, sizeof(device_status.heattime));
+        }
+
+        value = cJSON_GetObjectItem(Params,"hrt");
+        if(value!=NULL){
+            device_status.heatvalue = value->valueint;
+            ef_set_env_blob("jheat", &device_status.heatvalue, sizeof(device_status.heatvalue));
+        }
+
+        value = cJSON_GetObjectItem(Params,"shake_sec");
+        if(value!=NULL){
+            device_status.shake_sec = value->valueint;
+            ef_set_env_blob("shake_sec", &device_status.shake_sec, sizeof(device_status.shake_sec));
+        }
+
+        value = cJSON_GetObjectItem(Params,"shake_ws");
+        if(value!=NULL){
+            device_status.shake_ws = value->valueint;
+            ef_set_env_blob("shake_ws", &device_status.shake_ws, sizeof(device_status.shake_ws));
+        }
+
+        value = cJSON_GetObjectItem(Params,"version_type");
+        if(value!=NULL){
+            device_status.version_type = value->valueint;
+            ef_set_env_blob("version_type", &device_status.version_type, sizeof(device_status.version_type));
+        }
+
+        value = cJSON_GetObjectItem(Params,"heat_sw");
+        if(value!=NULL){
+            device_status.heat_sw = value->valueint;
+            ef_set_env_blob("heat_sw", &device_status.heat_sw, sizeof(device_status.heat_sw));
+        }
+
+        value = cJSON_GetObjectItem(Params,"dattim");
+        if(value!=NULL){
+            device_status.dattim = value->valueint;
+            ef_set_env_blob("dattim", &device_status.dattim, sizeof(device_status.dattim));
+        }
+
+        value = cJSON_GetObjectItem(Params,"deviceId");
+        if(value!=NULL){
+            rt_snprintf(device_status.deviceId, sizeof(device_status.deviceId),"%s",value->string);
+            ef_set_env_blob("deviceId", &device_status.deviceId, sizeof(device_status.deviceId));
+        }
+
+    }else{
+        LOG_E("Params is NULL!");
+    }
+}
+
+//备份MCU参数到RTU
+void backup_param_to_rtu(void)
+{
+    cJSON* proot = cJSON_CreateObject();
+    if (proot == NULL) {
+        LOG_E("Error: Failed to create JSON object\n");
+        return;
+    }
+
+    // 添加开关机
+    if (!cJSON_AddNumberToObject(proot, "reboot_time", device_status.rebootcnt)) {
+        cJSON_Delete(proot);
+        return;
+    }
+
+    // 添加开关机
+    if (!cJSON_AddNumberToObject(proot, "ds", device_status.ds)) {
+        cJSON_Delete(proot);
+        return;
+    }
+    //光控定时时长
+    if (!cJSON_AddNumberToObject(proot, "tt", device_status.sunBar)) {
+        cJSON_Delete(proot);
+        return;
+    }
+    //时控开始时间
+    if (!cJSON_AddNumberToObject(proot, "st", device_status.startBar)) {
+        cJSON_Delete(proot);
+        return;
+    }
+    //时控结束时间
+    if (!cJSON_AddNumberToObject(proot, "et", device_status.stopBar)) {
+        cJSON_Delete(proot);
+        return;
+    }
+    //时控模式
+    if (!cJSON_AddNumberToObject(proot, "ts", device_status.timeSwitch)) {
+        cJSON_Delete(proot);
+        return;
+    }
+    //低温保护值
+    if (!cJSON_AddNumberToObject(proot, "tpl", device_status.tpl)) {
+        cJSON_Delete(proot);
+        return;
+    }
+    //高温保护值
+    if (!cJSON_AddNumberToObject(proot, "tph", device_status.tph)) {
+        cJSON_Delete(proot);
+        return;
+    }
+
+    //收集时间
+    if (!cJSON_AddNumberToObject(proot, "stime", device_status.clt_time)) {
+        cJSON_Delete(proot);
+        return;
+    }
+
+    //加热时间
+    if (!cJSON_AddNumberToObject(proot, "jtime", device_status.heattime)) {
+        cJSON_Delete(proot);
+        return;
+    }
+    //加热设定温度
+    if (!cJSON_AddNumberToObject(proot, "hrt", device_status.heatvalue)) {
+        cJSON_Delete(proot);
+        return;
+    }
+
+    //震动时间
+    if (!cJSON_AddNumberToObject(proot, "shake_sec", device_status.shake_sec)) {
+        cJSON_Delete(proot);
+        return;
+    }
+
+    //震动开关
+    if (!cJSON_AddNumberToObject(proot, "shake_ws", device_status.shake_ws)) {
+        cJSON_Delete(proot);
+        return;
+    }
+
+    //版本类型
+    if (!cJSON_AddNumberToObject(proot, "version_type", device_status.version_type)) {
+        cJSON_Delete(proot);
+        return;
+    }
+    //常加热开关
+    if (!cJSON_AddNumberToObject(proot, "heat_sw", device_status.heat_sw)) {
+        cJSON_Delete(proot);
+        return;
+    }
+    //上传间隔
+    if (!cJSON_AddNumberToObject(proot, "dattim", device_status.dattim)) {
+        cJSON_Delete(proot);
+        return;
+    }
+
+    //北大荒设备ID
+    if (!cJSON_AddStringToObject(proot, "deviceId", device_status.deviceId)) {
+        cJSON_Delete(proot);
+        return;
+    }
+
+
+    char* temp = makeJsonRpc2_0("sync_param", proot, 1);
+    if(temp){
+        DTU_Write(temp);
+        free(temp);
+    }
+    //cJSON_Delete(proot);
+}
+
+void recover_param_from_rtu(void)
+{
+    char* temp1 = makeJsonRpc2_0("recover_param", NULL, 1);
+    if(temp1){
+        DTU_Write(temp1);
+        rt_free(temp1);
+    }
+}
+
+void upload_sys_monitor_info(void)
+{
+    char value_str[32];
+    cJSON* proot = cJSON_CreateObject();
+    if (proot == NULL) {
+        LOG_E("Error: Failed to create JSON object\n");
+        return;
+    }
+
+    if (!cJSON_AddNumberToObject(proot, "cpu_tempture", system_status.cpu_tempture)) {
+        cJSON_Delete(proot);
+        return;
+    }
+
+    if (!cJSON_AddNumberToObject(proot, "cpu_usage", system_status.cpu_usage)) {
+        cJSON_Delete(proot);
+        return;
+    }
+
+    if (!cJSON_AddNumberToObject(proot, "cpu_usage_max", system_status.cpu_usage_max)) {
+        cJSON_Delete(proot);
+        return;
+    }
+
+    rt_snprintf(value_str, sizeof(value_str), "%dh:%dm:%ds",system_status.system_uptime/3600,(system_status.system_uptime%3600)/60,system_status.system_uptime%60);
+    if (!cJSON_AddStringToObject(proot, "system_uptime", value_str)) {
+        cJSON_Delete(proot);
+        return;
+    }
+
+    if (!cJSON_AddNumberToObject(proot, "uart2_rx_bytes", system_status.uart2_rx_bytes)) {
+        cJSON_Delete(proot);
+        return;
+    }
+
+    if (!cJSON_AddNumberToObject(proot, "uart2_tx_bytes", system_status.uart2_tx_bytes)) {
+        cJSON_Delete(proot);
+        return;
+    }
+
+    if (!cJSON_AddNumberToObject(proot, "uart4_tx_bytes", system_status.uart4_tx_bytes)) {
+        cJSON_Delete(proot);
+        return;
+    }
+
+    if (!cJSON_AddNumberToObject(proot, "uart4_rx_bytes", system_status.uart4_rx_bytes)) {
+        cJSON_Delete(proot);
+        return;
+    }
+
+    if (!cJSON_AddNumberToObject(proot, "json_upload_count", system_status.json_upload_count)) {
+        cJSON_Delete(proot);
+        return;
+    }
+
+    if (!cJSON_AddNumberToObject(proot, "photo_taken_count", system_status.photo_taken_count)) {
+        cJSON_Delete(proot);
+        return;
+    }
+
+    if (!cJSON_AddNumberToObject(proot, "cleaning_count", system_status.cleaning_count)) {
+        cJSON_Delete(proot);
+        return;
+    }
+
+    if (!cJSON_AddNumberToObject(proot, "vibration_count", system_status.vibration_count)) {
+        cJSON_Delete(proot);
+        return;
+    }
+
+
+    char* temp = makeJsonRpc2_0("sys_monitor", proot, 1);
+    if(temp){
+        DTU_Write(temp);
+        free(temp);
+    }
+}
+
+
 char *makeJson_C01_Warn(uint16_t code,double process)
 char *makeJson_C01_Warn(uint16_t code,double process)
 {
 {
     cJSON * pJsonRoot = NULL;
     cJSON * pJsonRoot = NULL;
@@ -874,6 +1153,7 @@ char * makeJson()
     }
     }
     cJSON_Delete(pJsonRoot);
     cJSON_Delete(pJsonRoot);
     device_status.all_ycct = 0;
     device_status.all_ycct = 0;
+    system_status.json_upload_count += 1;
     return p;
     return p;
 }
 }
 
 

+ 143 - 7
Application_cbd_apm32f1/applications/hmi.c

@@ -27,6 +27,7 @@
 #include <fal.h>
 #include <fal.h>
 #include "selfcheck.h"
 #include "selfcheck.h"
 #include <user_mb_app.h>
 #include <user_mb_app.h>
+#include "sys_monitor.h"
 #define DBG_ENABLE
 #define DBG_ENABLE
 #define DBG_COLOR
 #define DBG_COLOR
 #define DBG_TAG "hmi"
 #define DBG_TAG "hmi"
@@ -45,11 +46,13 @@
 static char msg_pool[512];
 static char msg_pool[512];
 
 
 static char rx_buffer[HMI_UART_RXBUFFER_SIZE + 1];
 static char rx_buffer[HMI_UART_RXBUFFER_SIZE + 1];
+static rt_bool_t uart2_timeout_flag = RT_FALSE;
 
 
 void list_mem(void);
 void list_mem(void);
 int mb_master_samlpe();
 int mb_master_samlpe();
 /**/
 /**/
 Device_Status_typedef device_status;
 Device_Status_typedef device_status;
+System_stats_t system_status;
 
 
 extern eMBMasterReqErrCode _485_play(USHORT *Buffer,USHORT NREGS);
 extern eMBMasterReqErrCode _485_play(USHORT *Buffer,USHORT NREGS);
 
 
@@ -70,6 +73,15 @@ rt_device_t serial;   /*串口设备句柄*/
 
 
 rt_timer_t timer_uart2 = RT_NULL;
 rt_timer_t timer_uart2 = RT_NULL;
 
 
+
+static upgrade_state_t current_state = STATE_IDLE;
+uint32_t total_file_size = 0;
+static uint32_t bytes_received = 0;
+
+static uint8_t recv_buffer[RECV_BUFFER_SIZE];
+static uint32_t recv_write_pos = 0;
+
+
 /* 消息队列控制块 */
 /* 消息队列控制块 */
 static struct rt_messagequeue rx_mq;//接收数据消息队列
 static struct rt_messagequeue rx_mq;//接收数据消息队列
 static void HMI_Decode(void);
 static void HMI_Decode(void);
@@ -144,6 +156,121 @@ static rt_err_t uart_input(rt_device_t dev, rt_size_t size)
     }
     }
     return result;
     return result;
 }
 }
+// 预计算转换表
+static const int8_t hex_to_byte[256] = {
+    [0 ... 255] = -1,
+    ['0'] = 0, ['1'] = 1, ['2'] = 2, ['3'] = 3, ['4'] = 4,
+    ['5'] = 5, ['6'] = 6, ['7'] = 7, ['8'] = 8, ['9'] = 9,
+    ['A'] = 10, ['B'] = 11, ['C'] = 12, ['D'] = 13, ['E'] = 14, ['F'] = 15,
+    ['a'] = 10, ['b'] = 11, ['c'] = 12, ['d'] = 13, ['e'] = 14, ['f'] = 15
+};
+
+/**
+ * @brief 快速HEX字符串转二进制
+ * @param hex HEX字符串
+ * @param bin 输出缓冲区
+ * @param max_len 最大输出长度
+ * @return 转换的字节数,<0表示错误
+ */
+static inline int fast_hex_to_bin(const char* hex, uint8_t* bin, int max_len)
+{
+    if (!hex || !bin || max_len <= 0) {
+        return -1;
+    }
+
+    int hex_len = strlen(hex);
+    if (hex_len % 2 != 0) {
+        return -1;  // HEX长度必须是偶数
+    }
+
+    int bin_len = hex_len / 2;
+    if (bin_len > max_len) {
+        return -1;  // 输出缓冲区太小
+    }
+
+    for (int i = 0; i < bin_len; i++) {
+        int high = hex_to_byte[(unsigned char)hex[i * 2]];
+        int low = hex_to_byte[(unsigned char)hex[i * 2 + 1]];
+
+        if (high < 0 || low < 0) {
+            return -1;  // 无效HEX字符
+        }
+
+        bin[i] = (high << 4) | low;
+    }
+
+    return bin_len;
+}
+
+// 发送原始数据到HMI
+static int send_raw_to_hmi(const uint8_t* data, uint32_t size)
+{
+    if (!serial || !data || size == 0) return -1;
+
+    rt_size_t sent = rt_device_write(serial, 0, data, size);
+    return (sent == size) ? 0 : -1;
+}
+
+// 最简洁版本 - 每4096字节直接清空
+void process_hex_payload(const char* hex_str, int req_id) {
+    if (!hex_str) return;
+    current_state = STATE_RECEIVING;
+    // 转换HEX
+    uint8_t temp[JSON_CHUNK_SIZE];
+    int data_len = fast_hex_to_bin(hex_str, temp, JSON_CHUNK_SIZE);
+    if (data_len <= 0) return;
+
+    // 添加到缓冲区
+    if (recv_write_pos + data_len > sizeof(recv_buffer)) {
+        LOG_E("缓冲区溢出");
+        return;
+    }
+
+    memcpy(recv_buffer + recv_write_pos, temp, data_len);
+    recv_write_pos += data_len;
+    bytes_received += data_len;
+
+    LOG_I("收到 %d 字节,缓冲: %u/%u",
+          data_len, recv_write_pos, sizeof(recv_buffer));
+
+    // 每4096字节发送一次
+    if (recv_write_pos >= 4096) {
+        LOG_I("发送 4096 字节到HMI...");
+
+        if (send_raw_to_hmi(recv_buffer, 4096) == 0) {
+            LOG_I("发送成功");
+            // ✅ 直接清空缓冲区
+            recv_write_pos = 0;
+        } else {
+            LOG_E("发送失败");
+        }
+        return;
+    }
+
+    // 检查完成
+    if (bytes_received >= total_file_size && total_file_size > 0) {
+        if (recv_write_pos > 0) {
+            LOG_I("发送最后 %u 字节", recv_write_pos);
+            send_raw_to_hmi(recv_buffer, recv_write_pos);
+            recv_write_pos = 0;  // 清空
+        }
+        current_state = STATE_COMPLETED;
+        LOG_I("升级完成!");
+        return;
+    }
+
+    // 发送进度
+    int progress = total_file_size > 0 ?
+                  (bytes_received * 100 / total_file_size) : 0;
+
+    char progress_json[256];
+    rt_snprintf(progress_json, sizeof(progress_json),
+               "{\"jsonrpc\":\"2.0\",\"method\":\"upgradehmi\","
+               "\"params\":{\"received\":%u,\"total\":%u,\"progress\":%d},\"id\":%d}",
+               bytes_received, total_file_size, progress, req_id);
+
+    DTU_Write(progress_json);
+}
 
 
 
 
 /*入口函数*/
 /*入口函数*/
@@ -160,18 +287,26 @@ static void Hmi_thread_entry(void *parameter)
     device_status.camsta = 1;
     device_status.camsta = 1;
     while(1)
     while(1)
     {
     {
-
         rt_memset(&msg, 0, sizeof(msg));
         rt_memset(&msg, 0, sizeof(msg));
         /* 从消息队列中读取消息*/
         /* 从消息队列中读取消息*/
         result = rt_mq_recv(&rx_mq, &msg, sizeof(msg), 50);
         result = rt_mq_recv(&rx_mq, &msg, sizeof(msg), 50);
         if (result == RT_EOK)
         if (result == RT_EOK)
         {
         {
-
-                rx_length = rt_device_read(msg.dev, 0, rx_buffer, msg.size);
-                rx_buffer[rx_length] = '\0';
-                //LOG_I("%s",rx_buffer);
-                //\r 对应的hex为0x0d,0x0a,占两个字节,屏幕发送的数据都以\r结尾
-                HMI_Decode();
+            rx_length = rt_device_read(msg.dev, 0, rx_buffer, msg.size);
+            system_status.uart4_rx_bytes+=rx_length;
+            rx_buffer[rx_length] = '\0';
+            if(rx_length==1&&rx_buffer[rx_length-1]==0x05){
+               LOG_W("屏幕响应信号!");
+               if(current_state==STATE_COMPLETED) return;
+               //RTU可以发送升级文件了
+               char* upgrade_hmi = makeJsonRpc2_0("upgradehmi",NULL,1);
+               if(upgrade_hmi){
+                   DTU_Write(upgrade_hmi);
+                   free(upgrade_hmi);
+               }
+            }else {
+               HMI_Decode();
+            }
         }
         }
         /*********************************************************************************************************************/
         /*********************************************************************************************************************/
         //rt_kprintf("%04d-%02d-%02d %02d:%02d:%02d\n",tm.tm_year+1900,tm.tm_mon+1,tm.tm_mday,tm.tm_hour,tm.tm_min,tm.tm_sec);
         //rt_kprintf("%04d-%02d-%02d %02d:%02d:%02d\n",tm.tm_year+1900,tm.tm_mon+1,tm.tm_mday,tm.tm_hour,tm.tm_min,tm.tm_sec);
@@ -183,6 +318,7 @@ static void t_uart2_callback(void *parameter)
 {
 {
     HMI_WRITE("sysSet.va0.txt=\"指令超时,请重试...\"");
     HMI_WRITE("sysSet.va0.txt=\"指令超时,请重试...\"");
     LOG_E("t_uart2_callback");
     LOG_E("t_uart2_callback");
+    uart2_timeout_flag = RT_TRUE;
 }
 }
 
 
 
 

+ 59 - 0
Application_cbd_apm32f1/applications/hmi.h

@@ -22,6 +22,65 @@ extern uint8_t dbg_flag;
 extern uint8_t DBG_EN;  //是否使能调试打印
 extern uint8_t DBG_EN;  //是否使能调试打印
 
 
 extern rt_timer_t timer_uart2;
 extern rt_timer_t timer_uart2;
+
+// 常量定义
+// 数据缓冲区
+#define RECV_BUFFER_SIZE   (10 * 1024)  // 10k接收缓冲区
+#define SEND_BUFFER_SIZE   4096           // 发送到HMI的缓冲区
+#define HMI_CHUNK_SIZE          4096    // 发送到屏幕的块大小
+#define JSON_CHUNK_SIZE         512    // JSON接收的块大小
+#define HMI_DEFAULT_BAUDRATE    115200
+#define HMI_ACK_BYTE            0x05
+#define HMI_TERMINATOR          "\xFF\xFF\xFF"
+#define HMI_RESPONSE_TIMEOUT    1000    // 响应超时(ms)
+#define HMI_TRANSFER_TIMEOUT    30000   // 传输超时(ms)
+uint32_t total_file_size;
+// 升级状态
+typedef enum {
+    STATE_IDLE = 0,
+    STATE_WAIT_SIZE,
+    STATE_WAIT_HMI_ACK,
+    STATE_RECEIVING,
+    STATE_SENDING_TO_HMI,
+    STATE_COMPLETED,
+    STATE_FAILED
+} upgrade_state_t;
+
+// 数据包管理
+typedef struct {
+    uint8_t *buffer;             // 数据缓冲区
+    uint32_t size;               // 缓冲区大小
+    uint32_t write_pos;          // 写入位置
+    uint32_t read_pos;           // 读取位置
+    uint32_t chunk_size;         // 分块大小(4096字节)
+} data_buffer_t;
+
+
+// 升级控制结构
+typedef struct {
+    rt_device_t rtu_serial;      // 连接RTU的串口
+    rt_device_t hmi_serial;      // 连接HMI的串口
+    rt_mutex_t lock;             // 互斥锁
+
+    upgrade_state_t state;           // 当前状态
+    uint32_t total_file_size;    // 总文件大小
+    uint32_t bytes_received;     // 已接收字节数
+    uint32_t bytes_sent_to_hmi;  // 已发送到HMI的字节数
+    uint32_t baudrate;           // 波特率
+
+    data_buffer_t recv_buffer;   // 接收缓冲区
+    data_buffer_t send_buffer;   // 发送缓冲区
+
+    rt_tick_t start_time;        // 开始时间
+    rt_tick_t timeout;           // 超时时间
+
+    uint8_t current_chunk[4096]; // 当前发送块
+    uint32_t chunk_filled;       // 当前块已填充大小
+} hmi_upgrade_protocol_t;
+void process_hex_payload(const char* hex_str, int req_id);
+
+
+
 void Check_ParamConfig(void);
 void Check_ParamConfig(void);
 void HMI_WRITE(char *fmt,...);
 void HMI_WRITE(char *fmt,...);
 void Fresh_Hmi(void);
 void Fresh_Hmi(void);

+ 773 - 0
Application_cbd_apm32f1/applications/lwjson.c

@@ -0,0 +1,773 @@
+/**
+ * \file            lwjson.c
+ * \brief           Lightweight JSON format parser
+ */
+
+/*
+ * Copyright (c) 2024 Tilen MAJERLE
+ *
+ * Permission is hereby granted, free of charge, to any person
+ * obtaining a copy of this software and associated documentation
+ * files (the "Software"), to deal in the Software without restriction,
+ * including without limitation the rights to use, copy, modify, merge,
+ * publish, distribute, sublicense, and/or sell copies of the Software,
+ * and to permit persons to whom the Software is furnished to do so,
+ * subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
+ * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
+ * AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
+ * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
+ * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
+ * OTHER DEALINGS IN THE SOFTWARE.
+ *
+ * This file is part of LwJSON - Lightweight JSON format parser.
+ *
+ * Author:          Tilen MAJERLE <tilen@majerle.eu>
+ * Version:         v1.8.1
+ */
+#include <string.h>
+#include "lwjson.h"
+
+/**
+ * \brief           Internal string object
+ */
+typedef struct {
+    const char* start; /*!< Original pointer to beginning of JSON object */
+    size_t len;        /*!< Total length of input json string */
+    const char* p;     /*!< Current char pointer */
+} lwjson_int_str_t;
+
+/**
+ * \brief           Allocate new token for JSON block
+ * \param[in]       lwobj: LwJSON instance
+ * \return          Pointer to new token
+ */
+static lwjson_token_t*
+prv_alloc_token(lwjson_t* lwobj) {
+    if (lwobj->next_free_token_pos < lwobj->tokens_len) {
+        LWJSON_MEMSET(&lwobj->tokens[lwobj->next_free_token_pos], 0x00, sizeof(*lwobj->tokens));
+        return &lwobj->tokens[lwobj->next_free_token_pos++];
+    }
+    return NULL;
+}
+
+/**
+ * \brief           Skip all characters that are considered *blank* as per RFC4627
+ * \param[in,out]   pobj: Pointer to text that is modified on success
+ * \return          \ref lwjsonOK on success, member of \ref lwjsonr_t otherwise
+ */
+static lwjsonr_t
+prv_skip_blank(lwjson_int_str_t* pobj) {
+    while (pobj->p != NULL && (size_t)(pobj->p - pobj->start) < pobj->len && *pobj->p != '\0') {
+        if (*pobj->p == ' ' || *pobj->p == '\t' || *pobj->p == '\r' || *pobj->p == '\n' || *pobj->p == '\f') {
+            ++pobj->p;
+#if LWJSON_CFG_COMMENTS
+            /* Check for comments and remove them */
+        } else if (*pobj->p == '/') {
+            ++pobj->p;
+            if (pobj->p != NULL && (size_t)(pobj->p - pobj->start) < pobj->len && *pobj->p == '*') {
+                ++pobj->p;
+                while (pobj->p != NULL && (size_t)(pobj->p - pobj->start) < pobj->len && *pobj->p != '\0') {
+                    if (*pobj->p == '*') {
+                        ++pobj->p;
+                        if ((size_t)(pobj->p - pobj->start) < pobj->len && *pobj->p == '/') {
+                            ++pobj->p;
+                            break;
+                        }
+                    }
+                    ++pobj->p;
+                }
+            }
+#endif /* LWJSON_CFG_COMMENTS */
+        } else {
+            break;
+        }
+    }
+    if (pobj->p != NULL && (size_t)(pobj->p - pobj->start) < pobj->len && *pobj->p != '\0') {
+        return lwjsonOK;
+    }
+    return lwjsonERRJSON;
+}
+
+/**
+ * \brief           Parse JSON string that must start end end with double quotes `"` character
+ * It just parses length of characters and does not perform any decode operation
+ * \param[in,out]   pobj: Pointer to text that is modified on success
+ * \param[out]      pout: Pointer to pointer to string that is set where string starts
+ * \param[out]      poutlen: Length of string in units of characters is stored here
+ * \return          \ref lwjsonOK on success, member of \ref lwjsonr_t otherwise
+ */
+static lwjsonr_t
+prv_parse_string(lwjson_int_str_t* pobj, const char** pout, size_t* poutlen) {
+    lwjsonr_t res;
+    size_t len = 0;
+
+    res = prv_skip_blank(pobj);
+    if (res != lwjsonOK) {
+        return res;
+    }
+    if ((size_t)(pobj->p - pobj->start) < pobj->len && *pobj->p++ != '"') {
+        return lwjsonERRJSON;
+    }
+    *pout = pobj->p;
+    /* Parse string but take care of escape characters */
+    for (;; ++pobj->p, ++len) {
+        if (pobj->p == NULL || (size_t)(pobj->p - pobj->start) >= pobj->len || *pobj->p == '\0') {
+            return lwjsonERRJSON;
+        }
+        /* Check special characters */
+        if (*pobj->p == '\\') {
+            ++pobj->p;
+            ++len;
+
+            if ((size_t)(pobj->p - pobj->start) >= pobj->len) {
+                return lwjsonERRJSON;
+            }
+
+            switch (*pobj->p) {
+                case '"':  /* fallthrough */
+                case '\\': /* fallthrough */
+                case '/':  /* fallthrough */
+                case 'b':  /* fallthrough */
+                case 'f':  /* fallthrough */
+                case 'n':  /* fallthrough */
+                case 'r':  /* fallthrough */
+                case 't': break;
+                case 'u':
+                    ++pobj->p;
+                    for (size_t i = 0; i < 4; ++i, ++len) {
+                        if (!(((size_t)(pobj->p - pobj->start) < pobj->len)
+                              && ((*pobj->p >= '0' && *pobj->p <= '9') || (*pobj->p >= 'a' && *pobj->p <= 'f')
+                                  || (*pobj->p >= 'A' && *pobj->p <= 'F')))) {
+                            return lwjsonERRJSON;
+                        }
+                        if (i < 3) {
+                            ++pobj->p;
+                        }
+                    }
+                    break;
+                default: return lwjsonERRJSON;
+            }
+        } else if (*pobj->p == '"') {
+            ++pobj->p;
+            break;
+        }
+    }
+    *poutlen = len;
+    return res;
+}
+
+/**
+ * \brief           Parse property name that must comply with JSON string format as in RFC4627
+ * Property string must be followed by colon character ":"
+ * \param[in,out]   pobj: Pointer to text that is modified on success
+ * \param[out]      t: Token instance to write property name to
+ * \return          \ref lwjsonOK on success, member of \ref lwjsonr_t otherwise
+ */
+static lwjsonr_t
+prv_parse_property_name(lwjson_int_str_t* pobj, lwjson_token_t* t) {
+    lwjsonr_t res;
+
+    /* Parse property string first */
+    res = prv_parse_string(pobj, &t->token_name, &t->token_name_len);
+    if (res != lwjsonOK) {
+        return res;
+    }
+    /* Skip any spaces */
+    res = prv_skip_blank(pobj);
+    if (res != lwjsonOK) {
+        return res;
+    }
+    /* Must continue with colon */
+    if ((size_t)(pobj->p - pobj->start) >= pobj->len || *pobj->p++ != ':') {
+        return lwjsonERRJSON;
+    }
+    /* Skip any spaces */
+    res = prv_skip_blank(pobj);
+    if (res != lwjsonOK) {
+        return res;
+    }
+    return lwjsonOK;
+}
+
+/**
+ * \brief           Calculate new value for exponent 10^exponent.
+ * \param[in]       exp: Exponent.
+ * \param[in]       is_minus: Indicates whether the exponent is negative.
+ * \return          Value of 10^exponent.
+ */
+static lwjson_real_t
+prv_power10(lwjson_int_t exp, uint8_t is_minus) {
+    lwjson_real_t result = (lwjson_real_t)1;
+    lwjson_real_t base = (lwjson_real_t)10;
+
+    for (; exp > 0; base *= base, exp >>= 1) {
+        if ((exp & 1) == 1) {
+            result *= base;
+        }
+    }
+
+    return is_minus ? ((lwjson_real_t)1 / result) : result;
+}
+
+/**
+ * \brief           Parse number as described in RFC4627
+ * \param[in,out]   pobj: Pointer to text that is modified on success
+ * \param[out]      tout: Pointer to output number format
+ * \param[out]      fout: Pointer to output real-type variable. Used if type is REAL.
+ * \param[out]      iout: Pointer to output int-type variable. Used if type is INT.
+ * \return          \ref lwjsonOK on success, member of \ref lwjsonr_t otherwise
+ */
+static lwjsonr_t
+prv_parse_number(lwjson_int_str_t* pobj, lwjson_type_t* tout, lwjson_real_t* fout, lwjson_int_t* iout) {
+    lwjsonr_t res;
+    uint8_t is_minus;
+    lwjson_real_t real_num = 0;
+    lwjson_int_t int_num = 0;
+    lwjson_type_t type = LWJSON_TYPE_NUM_INT;
+
+    res = prv_skip_blank(pobj);
+    if (res != lwjsonOK) {
+        return res;
+    }
+    if ((size_t)(pobj->p - pobj->start) >= pobj->len || *pobj->p == '\0') {
+        return lwjsonERRJSON;
+    }
+    is_minus = *pobj->p == '-' ? (++pobj->p, 1) : 0;
+    if ((size_t)(pobj->p - pobj->start) >= pobj->len /* End of json input */
+        || *pobj->p == '\0'                          /* Invalid string */
+        || *pobj->p < '0' || *pobj->p > '9'          /* Character outside number range */
+        || (*pobj->p == '0' && (size_t)(pobj->p + 1 - pobj->start) < pobj->len
+            && (pobj->p[1] >= '0' && pobj->p[1] <= '9'))) { /* Number starts with 0 but not followed by dot */
+        return lwjsonERRJSON;
+    }
+
+    /* Parse number */
+    for (int_num = 0; (size_t)(pobj->p - pobj->start) < pobj->len && *pobj->p >= '0' && *pobj->p <= '9'; ++pobj->p) {
+        int_num = int_num * (lwjson_int_t)10 + (*pobj->p - '0');
+    }
+
+    real_num = (lwjson_real_t)int_num;
+
+    if (pobj->p != NULL && (size_t)(pobj->p - pobj->start) < pobj->len && *pobj->p == '.') { /* Number has exponent */
+        lwjson_real_t exp;
+        lwjson_int_t dec_num;
+
+        real_num = (lwjson_real_t)int_num;
+
+        type = LWJSON_TYPE_NUM_REAL; /* Format is real */
+        ++pobj->p;                   /* Ignore comma character */
+        if ((size_t)(pobj->p - pobj->start) >= pobj->len || *pobj->p < '0'
+            || *pobj->p > '9') { /* Must be followed by number characters */
+            return lwjsonERRJSON;
+        }
+
+        /* Get number after decimal point */
+        for (exp = (lwjson_real_t)1, dec_num = 0;
+             (size_t)(pobj->p - pobj->start) < pobj->len && *pobj->p >= '0' && *pobj->p <= '9';
+             ++pobj->p, exp *= (lwjson_real_t)10) {
+            dec_num = dec_num * (lwjson_int_t)10 + (lwjson_int_t)(*pobj->p - '0');
+        }
+
+        /* Add decimal part to number */
+        real_num += (lwjson_real_t)dec_num / exp;
+    }
+    if (pobj->p != NULL && (size_t)(pobj->p - pobj->start) < pobj->len
+        && (*pobj->p == 'e' || *pobj->p == 'E')) { /* Engineering mode */
+        uint8_t is_minus_exp;
+        lwjson_int_t exp_cnt;
+
+        type = LWJSON_TYPE_NUM_REAL; /* Format is real */
+        ++pobj->p;                   /* Ignore enginnering sing part */
+        if ((size_t)(pobj->p - pobj->start) >= pobj->len) {
+            return lwjsonERRJSON;
+        }
+        is_minus_exp = *pobj->p == '-' ? (++pobj->p, 1) : 0;                  /* Check if negative */
+        if ((size_t)(pobj->p - pobj->start) < pobj->len && *pobj->p == '+') { /* Optional '+' is possible too */
+            ++pobj->p;
+        }
+        if ((size_t)(pobj->p - pobj->start) >= pobj->len || *pobj->p < '0'
+            || *pobj->p > '9') { /* Must be followed by number characters */
+            return lwjsonERRJSON;
+        }
+
+        /* Parse exponent number */
+        for (exp_cnt = 0; (size_t)(pobj->p - pobj->start) < pobj->len && *pobj->p >= '0' && *pobj->p <= '9';
+             ++pobj->p) {
+            exp_cnt = exp_cnt * (lwjson_int_t)10 + (lwjson_int_t)(*pobj->p - '0');
+        }
+
+        /* Calculate new value for exponent 10^exponent */
+        real_num *= prv_power10(exp_cnt, is_minus_exp);
+    }
+
+    /* Write output values */
+    if (tout != NULL) {
+        *tout = type;
+    }
+    if (type == LWJSON_TYPE_NUM_INT) {
+        *iout = is_minus ? -int_num : int_num;
+    } else {
+        *fout = is_minus ? -real_num : real_num;
+    }
+    return lwjsonOK;
+}
+
+/**
+ * \brief           Create path segment from input path for search operation
+ * \param[in,out]   ppath: Pointer to pointer to input path. Pointer is modified
+ * \param[out]      opath: Pointer to pointer to write path segment
+ * \param[out]      olen: Pointer to variable to write length of segment
+ * \param[out]      is_last: Pointer to write if this is last segment
+ * \return          `1` on success, `0` otherwise
+ */
+static uint8_t
+prv_create_path_segment(const char** ppath, const char** opath, size_t* olen, uint8_t* is_last) {
+    const char* segment = *ppath;
+
+    *is_last = 0;
+    *opath = NULL;
+    *olen = 0;
+
+    /* Check input path */
+    if (segment == NULL || *segment == '\0') {
+        *is_last = 1;
+        return 0;
+    }
+
+    /*
+     * Path must be one of:
+     * - literal text
+     * - "#" followed by dot "."
+     */
+    if (*segment == '#') {
+        *opath = segment;
+        for (*olen = 0;; ++segment, ++(*olen)) {
+            if (*segment == '.') {
+                ++segment;
+                break;
+            } else if (*segment == '\0') {
+                if (*olen == 1) {
+                    return 0;
+                } else {
+                    break;
+                }
+            }
+        }
+        *ppath = segment;
+    } else {
+        *opath = segment;
+        for (*olen = 0; *segment != '\0' && *segment != '.'; ++(*olen), ++segment) {}
+        *ppath = segment + 1;
+    }
+    if (*segment == '\0') {
+        *is_last = 1;
+    }
+    return 1;
+}
+
+/**
+ * \brief           Input recursive function for find operation
+ * \param[in]       parent: Parent token of type \ref LWJSON_TYPE_ARRAY or LWJSON_TYPE_OBJECT
+ * \param[in]       path: Path to search for starting this token further
+ * \return          Found token on success, `NULL` otherwise
+ */
+static const lwjson_token_t*
+prv_find(const lwjson_token_t* parent, const char* path) {
+    const char* segment;
+    size_t segment_len;
+    uint8_t is_last, res;
+
+    /* Get path segments */
+    res = prv_create_path_segment(&path, &segment, &segment_len, &is_last);
+    if (res != 0) {
+        /* Check if detected an array request */
+        if (*segment == '#') {
+            /* Parent must be array */
+            if (parent->type != LWJSON_TYPE_ARRAY) {
+                return NULL;
+            }
+
+            /* Check if index requested */
+            if (segment_len > 1) {
+                const lwjson_token_t* tkn;
+                size_t index = 0;
+
+                /* Parse number */
+                for (size_t i = 1; i < segment_len; ++i) {
+                    if (segment[i] < '0' || segment[i] > '9') {
+                        return NULL;
+                    } else {
+                        index = index * 10 + (segment[i] - '0');
+                    }
+                }
+
+                /* Start from beginning */
+                for (tkn = parent->u.first_child; tkn != NULL && index > 0; tkn = tkn->next, --index) {}
+                if (tkn != NULL) {
+                    if (is_last) {
+                        return tkn;
+                    } else {
+                        return prv_find(tkn, path);
+                    }
+                }
+                return NULL;
+            }
+
+            /* Scan all indexes and get first match */
+            for (const lwjson_token_t* tkn = parent->u.first_child; tkn != NULL; tkn = tkn->next) {
+                const lwjson_token_t* tmp = prv_find(tkn, path);
+                if (tmp != NULL) {
+                    return tmp;
+                }
+            }
+        } else {
+            if (parent->type != LWJSON_TYPE_OBJECT) {
+                return NULL;
+            }
+            for (const lwjson_token_t* tkn = parent->u.first_child; tkn != NULL; tkn = tkn->next) {
+                if (tkn->token_name_len == segment_len && !strncmp(tkn->token_name, segment, segment_len)) {
+                    const lwjson_token_t* tmp;
+                    if (is_last) {
+                        return tkn;
+                    }
+                    tmp = prv_find(tkn, path);
+                    if (tmp != NULL) {
+                        return tmp;
+                    }
+                }
+            }
+        }
+    }
+    return NULL;
+}
+
+/**
+ * \brief           Check for character after opening bracket of array or object
+ * \param[in,out]   pobj: JSON string
+ * \param[in]       t: Token to check for type
+ * \return          \ref lwjsonOK on success, member of \ref lwjsonr_t otherwise
+ */
+static inline lwjsonr_t
+prv_check_valid_char_after_open_bracket(lwjson_int_str_t* pobj, lwjson_token_t* t) {
+    lwjsonr_t res;
+
+    /* Check next character after object open */
+    res = prv_skip_blank(pobj);
+    if (res != lwjsonOK) {
+        return res;
+    }
+    if ((size_t)(pobj->p - pobj->start) >= pobj->len || *pobj->p == '\0'
+        || (t->type == LWJSON_TYPE_OBJECT && (*pobj->p != '"' && *pobj->p != '}'))
+        || (t->type == LWJSON_TYPE_ARRAY
+            && (*pobj->p != '"' && *pobj->p != ']' && *pobj->p != '[' && *pobj->p != '{' && *pobj->p != '-'
+                && (*pobj->p < '0' || *pobj->p > '9') && *pobj->p != 't' && *pobj->p != 'n' && *pobj->p != 'f'))) {
+        res = lwjsonERRJSON;
+    }
+    return res;
+}
+
+/**
+ * \brief           Setup LwJSON instance for parsing JSON strings
+ * \param[in,out]   lwobj: LwJSON instance
+ * \param[in]       tokens: Pointer to array of tokens used for parsing
+ * \param[in]       tokens_len: Number of tokens
+ * \return          \ref lwjsonOK on success, member of \ref lwjsonr_t otherwise
+ */
+lwjsonr_t
+lwjson_init(lwjson_t* lwobj, lwjson_token_t* tokens, size_t tokens_len) {
+    LWJSON_MEMSET(lwobj, 0x00, sizeof(*lwobj));
+    LWJSON_MEMSET(tokens, 0x00, sizeof(*tokens) * tokens_len);
+    lwobj->tokens = tokens;
+    lwobj->tokens_len = tokens_len;
+    lwobj->first_token.type = LWJSON_TYPE_OBJECT;
+    return lwjsonOK;
+}
+
+/**
+ * \brief           Parse JSON data with length parameter
+ * JSON format must be complete and must comply with RFC4627
+ * \param[in,out]   lwobj: LwJSON instance
+ * \param[in]       json_data: JSON string to parse
+ * \param[in]       jsonČlen: JSON data length
+ * \return          \ref lwjsonOK on success, member of \ref lwjsonr_t otherwise
+ */
+lwjsonr_t
+lwjson_parse_ex(lwjson_t* lwobj, const void* json_data, size_t json_len) {
+    lwjsonr_t res = lwjsonOK;
+    lwjson_token_t *t, *to;
+    lwjson_int_str_t pobj = {.start = json_data, .len = json_len, .p = json_data};
+
+    /* Check input parameters */
+    if (lwobj == NULL || json_data == NULL || json_len == 0) {
+        res = lwjsonERRPAR;
+        goto ret;
+    }
+
+    /* set first token */
+    to = &lwobj->first_token;
+
+    /* values from very beginning */
+    lwobj->flags.parsed = 0;
+    lwobj->next_free_token_pos = 0;
+    LWJSON_MEMSET(to, 0x00, sizeof(*to));
+
+    /* First parse */
+    res = prv_skip_blank(&pobj);
+    if (res != lwjsonOK) {
+        goto ret;
+    }
+    if ((size_t)(pobj.p - pobj.start) >= pobj.len) {
+        res = lwjsonERRJSON;
+        goto ret;
+    }
+    if (*pobj.p == '{') {
+        to->type = LWJSON_TYPE_OBJECT;
+    } else if (*pobj.p == '[') {
+        to->type = LWJSON_TYPE_ARRAY;
+    } else {
+        res = lwjsonERRJSON;
+        goto ret;
+    }
+    ++pobj.p;
+    res = prv_check_valid_char_after_open_bracket(&pobj, to);
+    if (res != lwjsonOK) {
+        goto ret;
+    }
+
+    /* Process all characters as indicated by input user */
+    while (pobj.p != NULL && (size_t)(pobj.p - pobj.start) < pobj.len && *pobj.p != '\0') {
+        /* Filter out blanks */
+        res = prv_skip_blank(&pobj);
+        if (res != lwjsonOK) {
+            goto ret;
+        }
+        if (*pobj.p == ',') {
+            ++pobj.p;
+            continue;
+        }
+
+        /* Check if end of object or array*/
+        if (*pobj.p == (to->type == LWJSON_TYPE_OBJECT ? '}' : ']')) {
+            lwjson_token_t* parent = to->next;
+            to->next = NULL;
+            ++pobj.p;
+
+            /* End of string if to == NULL (no parent), check if properly terminated */
+            to = parent;
+            if (to == NULL) {
+                prv_skip_blank(&pobj);
+                res = (pobj.p == NULL || (size_t)(pobj.p - pobj.start) >= pobj.len || *pobj.p == '\0') ? lwjsonOK
+                                                                                                       : lwjsonERR;
+                goto ret;
+            }
+            continue;
+        }
+
+        /* Allocate new token */
+        t = prv_alloc_token(lwobj);
+        if (t == NULL) {
+            res = lwjsonERRMEM;
+            goto ret;
+        }
+
+        /* If object type is not array, first thing is property that starts with quotes */
+        if (to->type != LWJSON_TYPE_ARRAY) {
+            if (*pobj.p != '"') {
+                res = lwjsonERRJSON;
+                goto ret;
+            }
+            res = prv_parse_property_name(&pobj, t);
+            if (res != lwjsonOK) {
+                goto ret;
+            }
+        }
+
+        /* Add element to linked list */
+        if (to->u.first_child == NULL) {
+            to->u.first_child = t;
+        } else {
+            lwjson_token_t* c;
+            for (c = to->u.first_child; c->next != NULL; c = c->next) {}
+            c->next = t;
+        }
+
+        /* Check next character to process */
+        switch (*pobj.p) {
+            case '{':
+            case '[':
+                t->type = *pobj.p == '{' ? LWJSON_TYPE_OBJECT : LWJSON_TYPE_ARRAY;
+                ++pobj.p;
+
+                res = prv_check_valid_char_after_open_bracket(&pobj, t);
+                if (res != lwjsonOK) {
+                    goto ret;
+                }
+                t->next = to; /* Temporary saved as parent object */
+                to = t;
+                break;
+            case '"':
+                res = prv_parse_string(&pobj, &t->u.str.token_value, &t->u.str.token_value_len);
+                if (res == lwjsonOK) {
+                    t->type = LWJSON_TYPE_STRING;
+                } else {
+                    goto ret;
+                }
+                break;
+            case 't':
+                /* RFC4627 is lower-case only */
+                if ((size_t)(pobj.p + 3 - pobj.start) < pobj.len && strncmp(pobj.p, "true", 4) == 0) {
+                    t->type = LWJSON_TYPE_TRUE;
+                    pobj.p += 4;
+                } else {
+                    res = lwjsonERRJSON;
+                    goto ret;
+                }
+                break;
+            case 'f':
+                /* RFC4627 is lower-case only */
+                if ((size_t)(pobj.p + 4 - pobj.start) < pobj.len && strncmp(pobj.p, "false", 5) == 0) {
+                    t->type = LWJSON_TYPE_FALSE;
+                    pobj.p += 5;
+                } else {
+                    res = lwjsonERRJSON;
+                    goto ret;
+                }
+                break;
+            case 'n':
+                /* RFC4627 is lower-case only */
+                if ((size_t)(pobj.p + 3 - pobj.start) < pobj.len && strncmp(pobj.p, "null", 4) == 0) {
+                    t->type = LWJSON_TYPE_NULL;
+                    pobj.p += 4;
+                } else {
+                    res = lwjsonERRJSON;
+                    goto ret;
+                }
+                break;
+            default:
+                if (*pobj.p == '-' || (*pobj.p >= '0' && *pobj.p <= '9')) {
+                    if (prv_parse_number(&pobj, &t->type, &t->u.num_real, &t->u.num_int) != lwjsonOK) {
+                        res = lwjsonERRJSON;
+                        goto ret;
+                    }
+                } else {
+                    res = lwjsonERRJSON;
+                    goto ret;
+                }
+                break;
+        }
+
+        /* Below code is used to check characters after valid tokens */
+        if (t->type == LWJSON_TYPE_ARRAY || t->type == LWJSON_TYPE_OBJECT) {
+            continue;
+        }
+
+        /*
+         * Check what are values after the token value
+         *
+         * As per RFC4627, every token value may have one or more
+         * blank characters, followed by one of below options:
+         *  - Comma separator for next token
+         *  - End of array indication
+         *  - End of object indication
+         */
+        res = prv_skip_blank(&pobj);
+        if (res != lwjsonOK) {
+            goto ret;
+        }
+        /* Check if valid string is availabe after */
+        if (pobj.p == NULL || (size_t)(pobj.p - pobj.start) >= pobj.len || *pobj.p == '\0'
+            || (*pobj.p != ',' && *pobj.p != ']' && *pobj.p != '}')) {
+            res = lwjsonERRJSON;
+            goto ret;
+        } else if (*pobj.p == ',') { /* Check to advance to next token immediately */
+            ++pobj.p;
+        }
+    }
+    if (to != &lwobj->first_token || (to != NULL && to->next != NULL)) {
+        res = lwjsonERRJSON;
+        to = NULL;
+    }
+    if (to != NULL) {
+        if (to->type != LWJSON_TYPE_ARRAY && to->type != LWJSON_TYPE_OBJECT) {
+            res = lwjsonERRJSON;
+        }
+        to->token_name = NULL;
+        to->token_name_len = 0;
+    }
+ret:
+    if (res == lwjsonOK) {
+        lwobj->flags.parsed = 1;
+    }
+    return res;
+}
+
+/**
+ * \brief           Parse input JSON format
+ * JSON format must be complete and must comply with RFC4627
+ * \param[in,out]   lwobj: LwJSON instance
+ * \param[in]       json_str: JSON string to parse
+ * \return          \ref lwjsonOK on success, member of \ref lwjsonr_t otherwise
+ */
+lwjsonr_t
+lwjson_parse(lwjson_t* lwobj, const char* json_str) {
+    return lwjson_parse_ex(lwobj, json_str, strlen(json_str));
+}
+
+/**
+ * \brief           Free token instances (specially used in case of dynamic memory allocation)
+ * \param[in,out]   lwobj: LwJSON instance
+ * \return          \ref lwjsonOK on success, member of \ref lwjsonr_t otherwise
+ */
+lwjsonr_t
+lwjson_free(lwjson_t* lwobj) {
+    LWJSON_MEMSET(lwobj->tokens, 0x00, sizeof(*lwobj->tokens) * lwobj->tokens_len);
+    lwobj->flags.parsed = 0;
+    return lwjsonOK;
+}
+
+/**
+ * \brief           Find first match in the given path for JSON entry
+ * JSON must be valid and parsed with \ref lwjson_parse function
+ * \param[in]       lwobj: JSON instance with parsed JSON string
+ * \param[in]       path: Path with dot-separated entries to search for the JSON key to return
+ * \return          Pointer to found token on success, `NULL` if token cannot be found
+ */
+const lwjson_token_t*
+lwjson_find(lwjson_t* lwobj, const char* path) {
+    if (lwobj == NULL || !lwobj->flags.parsed || path == NULL) {
+        return NULL;
+    }
+    return prv_find(lwjson_get_first_token(lwobj), path);
+}
+
+/**
+ * \brief           Find first match in the given path for JSON path
+ * JSON must be valid and parsed with \ref lwjson_parse function
+ *
+ * \param[in]       lwobj: JSON instance with parsed JSON string
+ * \param[in]       token: Root token to start search at.
+ *                      Token must be type \ref LWJSON_TYPE_OBJECT or \ref LWJSON_TYPE_ARRAY.
+ *                      Set to `NULL` to use root token of LwJSON object
+ * \param[in]       path: path with dot-separated entries to search for JSON key
+ * \return          Pointer to found token on success, `NULL` if token cannot be found
+ */
+const lwjson_token_t*
+lwjson_find_ex(lwjson_t* lwobj, const lwjson_token_t* token, const char* path) {
+    if (lwobj == NULL || !lwobj->flags.parsed || path == NULL) {
+        return NULL;
+    }
+    if (token == NULL) {
+        token = lwjson_get_first_token(lwobj);
+    }
+    if (token == NULL || (token->type != LWJSON_TYPE_ARRAY && token->type != LWJSON_TYPE_OBJECT)) {
+        return NULL;
+    }
+    return prv_find(token, path);
+}

+ 388 - 0
Application_cbd_apm32f1/applications/lwjson.h

@@ -0,0 +1,388 @@
+/**
+ * \file            lwjson.h
+ * \brief           LwJSON - Lightweight JSON format parser
+ */
+
+/*
+ * Copyright (c) 2024 Tilen MAJERLE
+ *
+ * Permission is hereby granted, free of charge, to any person
+ * obtaining a copy of this software and associated documentation
+ * files (the "Software"), to deal in the Software without restriction,
+ * including without limitation the rights to use, copy, modify, merge,
+ * publish, distribute, sublicense, and/or sell copies of the Software,
+ * and to permit persons to whom the Software is furnished to do so,
+ * subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
+ * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
+ * AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
+ * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
+ * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
+ * OTHER DEALINGS IN THE SOFTWARE.
+ *
+ * This file is part of LwJSON - Lightweight JSON format parser.
+ *
+ * Author:          Tilen MAJERLE <tilen@majerle.eu>
+ * Version:         v1.8.1
+ */
+#ifndef LWJSON_HDR_H
+#define LWJSON_HDR_H
+
+#include <stdint.h>
+#include <string.h>
+#include "lwjson_opt.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif /* __cplusplus */
+
+/**
+ * \defgroup        LWJSON Lightweight JSON format parser
+ * \brief           LwJSON - Lightweight JSON format parser
+ * \{
+ */
+
+/**
+ * \brief           Get size of statically allocated array
+ * \param[in]       x: Object to get array size of
+ * \return          Number of elements in array
+ */
+#define LWJSON_ARRAYSIZE(x) (sizeof(x) / sizeof((x)[0]))
+
+/**
+ * \brief           List of supported JSON types
+ */
+typedef enum {
+    LWJSON_TYPE_STRING,   /*!< String/Text format. Everything that has beginning and ending quote character */
+    LWJSON_TYPE_NUM_INT,  /*!< Number type for integer */
+    LWJSON_TYPE_NUM_REAL, /*!< Number type for real number */
+    LWJSON_TYPE_OBJECT,   /*!< Object data type */
+    LWJSON_TYPE_ARRAY,    /*!< Array data type */
+    LWJSON_TYPE_TRUE,     /*!< True boolean value */
+    LWJSON_TYPE_FALSE,    /*!< False boolean value */
+    LWJSON_TYPE_NULL,     /*!< Null value */
+} lwjson_type_t;
+
+#if defined(LWJSON_DEV)
+extern const char* const lwjson_type_strings[];
+#endif
+
+/**
+ * \brief           Real data type
+ */
+typedef LWJSON_CFG_REAL_TYPE lwjson_real_t;
+
+/**
+ * \brief           Integer data type
+ */
+typedef LWJSON_CFG_INT_TYPE lwjson_int_t;
+
+/**
+ * \brief           JSON token
+ */
+typedef struct lwjson_token {
+    struct lwjson_token* next; /*!< Next token on a list */
+    lwjson_type_t type;        /*!< Token type */
+    const char* token_name;    /*!< Token name (if exists) */
+    size_t token_name_len;     /*!< Length of token name (this is needed to support const input strings to parse) */
+
+    union {
+        struct {
+            const char* token_value; /*!< Pointer to the beginning of the string */
+            size_t
+                token_value_len; /*!< Length of token value (this is needed to support const input strings to parse) */
+        } str;                   /*!< String data */
+
+        lwjson_real_t num_real;           /*!< Real number format */
+        lwjson_int_t num_int;             /*!< Int number format */
+        struct lwjson_token* first_child; /*!< First children object for object or array type */
+    } u;                                  /*!< Union with different data types */
+} lwjson_token_t;
+
+/**
+ * \brief           JSON result enumeration
+ */
+typedef enum {
+    lwjsonOK = 0x00, /*!< Function returns successfully */
+    lwjsonERR,       /*!< Generic error message */
+    lwjsonERRJSON,   /*!< Error JSON format */
+    lwjsonERRMEM,    /*!< Memory error */
+    lwjsonERRPAR,    /*!< Parameter error */
+
+    lwjsonSTREAMWAITFIRSTCHAR, /*!< Streaming parser did not yet receive first valid character
+                                    indicating start of JSON sequence */
+    lwjsonSTREAMDONE,          /*!< Streaming parser is done,
+                                    closing character matched the stream opening one */
+    lwjsonSTREAMINPROG,        /*!< Stream parsing is still in progress */
+} lwjsonr_t;
+
+/**
+ * \brief           LwJSON instance
+ */
+typedef struct {
+    lwjson_token_t* tokens;     /*!< Pointer to array of tokens */
+    size_t tokens_len;          /*!< Size of all tokens */
+    size_t next_free_token_pos; /*!< Position of next free token instance */
+    lwjson_token_t first_token; /*!< First token on a list */
+
+    struct {
+        uint8_t parsed : 1; /*!< Flag indicating JSON parsing has finished successfully */
+    } flags;                /*!< List of flags */
+} lwjson_t;
+
+lwjsonr_t lwjson_init(lwjson_t* lwobj, lwjson_token_t* tokens, size_t tokens_len);
+lwjsonr_t lwjson_parse_ex(lwjson_t* lwobj, const void* json_data, size_t len);
+lwjsonr_t lwjson_parse(lwjson_t* lwobj, const char* json_str);
+const lwjson_token_t* lwjson_find(lwjson_t* lwobj, const char* path);
+const lwjson_token_t* lwjson_find_ex(lwjson_t* lwobj, const lwjson_token_t* token, const char* path);
+lwjsonr_t lwjson_free(lwjson_t* lwobj);
+
+void lwjson_print_token(const lwjson_token_t* token);
+void lwjson_print_json(const lwjson_t* lwobj);
+
+/**
+ * \brief           Object type for streaming parser
+ */
+typedef enum {
+    LWJSON_STREAM_TYPE_NONE,       /*!< No entry - not used */
+    LWJSON_STREAM_TYPE_OBJECT,     /*!< Object indication */
+    LWJSON_STREAM_TYPE_OBJECT_END, /*!< Object end indication */
+    LWJSON_STREAM_TYPE_ARRAY,      /*!< Array indication */
+    LWJSON_STREAM_TYPE_ARRAY_END,  /*!< Array end indication */
+    LWJSON_STREAM_TYPE_KEY,        /*!< Key string */
+    LWJSON_STREAM_TYPE_STRING,     /*!< Strin type */
+    LWJSON_STREAM_TYPE_TRUE,       /*!< True primitive */
+    LWJSON_STREAM_TYPE_FALSE,      /*!< False primitive */
+    LWJSON_STREAM_TYPE_NULL,       /*!< Null primitive */
+    LWJSON_STREAM_TYPE_NUMBER,     /*!< Generic number */
+} lwjson_stream_type_t;
+
+/**
+ * \brief           Stream parsing stack object
+ */
+typedef struct {
+    lwjson_stream_type_t type; /*!< Streaming type - current value */
+
+    union {
+        char name[LWJSON_CFG_STREAM_KEY_MAX_LEN
+                  + 1]; /*!< Last known key name, used only for \ref LWJSON_STREAM_TYPE_KEY type */
+        uint16_t index; /*!< Current index when type is an array */
+    } meta;             /*!< Meta information */
+} lwjson_stream_stack_t;
+
+typedef enum {
+    LWJSON_STREAM_STATE_WAITINGFIRSTCHAR = 0x00, /*!< State to wait for very first opening character */
+    LWJSON_STREAM_STATE_PARSING,        /*!< In parsing of the first char state - detecting next character state */
+    LWJSON_STREAM_STATE_PARSING_STRING, /*!< Parse string primitive */
+    LWJSON_STREAM_STATE_PARSING_PRIMITIVE, /*!< Parse any primitive that is non-string, either "true", "false", "null" or a number */
+    LWJSON_STREAM_STATE_EXPECTING_COMMA_OR_END, /*!< Expecting ',', '}' or ']' */
+    LWJSON_STREAM_STATE_EXPECTING_COLON,        /*!< Expecting ':' */
+} lwjson_stream_state_t;
+
+/* Forward declaration */
+struct lwjson_stream_parser;
+
+/**
+ * \brief           Callback function for various events
+ * 
+ */
+typedef void (*lwjson_stream_parser_callback_fn)(struct lwjson_stream_parser* jsp, lwjson_stream_type_t type);
+
+/**
+ * \brief           LwJSON streaming structure
+ */
+typedef struct lwjson_stream_parser {
+    lwjson_stream_stack_t
+        stack[LWJSON_CFG_STREAM_STACK_SIZE]; /*!< Stack used for parsing. TODO: Add conditional compilation flag */
+    size_t stack_pos;                        /*!< Current stack position */
+
+    lwjson_stream_state_t parse_state; /*!< Parser state */
+
+    lwjson_stream_parser_callback_fn evt_fn; /*!< Event function for user */
+
+    void* user_data; /*!< User data for callback function */
+
+    /* State */
+    union {
+        struct {
+            char buff[LWJSON_CFG_STREAM_STRING_MAX_LEN
+                      + 1];        /*!< Buffer to write temporary data. TODO: Size to be variable with define */
+            size_t buff_pos;       /*!< Buffer position for next write (length of bytes in buffer) */
+            size_t buff_total_pos; /*!< Total buffer position used up to now (in several data chunks) */
+            uint8_t is_last;       /*!< Status indicates if this is the last part of the string */
+        } str;                     /*!< String structure. It is only used for keys and string objects.
+                                        Use primitive part for all other options */
+
+        struct {
+            char buff[LWJSON_CFG_STREAM_PRIMITIVE_MAX_LEN + 1]; /*!< Temporary write buffer */
+            size_t buff_pos;                                    /*!< Buffer position for next write */
+        } prim; /*!< Primitive object. Used for all types, except key or string */
+
+        /* Todo: Add other types */
+    } data; /*!< Data union used to parse various */
+
+    char prev_c; /*!< History of characters */
+} lwjson_stream_parser_t;
+
+lwjsonr_t lwjson_stream_init(lwjson_stream_parser_t* jsp, lwjson_stream_parser_callback_fn evt_fn);
+lwjsonr_t lwjson_stream_set_user_data(lwjson_stream_parser_t* jsp, void* user_data);
+void* lwjson_stream_get_user_data(lwjson_stream_parser_t* jsp);
+lwjsonr_t lwjson_stream_reset(lwjson_stream_parser_t* jsp);
+lwjsonr_t lwjson_stream_parse(lwjson_stream_parser_t* jsp, char c);
+
+/**
+ * \brief           Get number of tokens used to parse JSON
+ * \param[in]       lwobj: Pointer to LwJSON instance
+ * \return          Number of tokens used to parse JSON
+ */
+#define lwjson_get_tokens_used(lwobj) (((lwobj) != NULL) ? ((lwobj)->next_free_token_pos + 1) : 0)
+
+/**
+ * \brief           Get very first token of LwJSON instance
+ * \param[in]       lwobj: Pointer to LwJSON instance
+ * \return          Pointer to first token
+ */
+#define lwjson_get_first_token(lwobj) (((lwobj) != NULL) ? (&(lwobj)->first_token) : NULL)
+
+/**
+ * \brief           Get token value for \ref LWJSON_TYPE_NUM_INT type
+ * \param[in]       token: token with integer type
+ * \return          Int number if type is integer, `0` otherwise
+ */
+#define lwjson_get_val_int(token)                                                                                      \
+    ((lwjson_int_t)(((token) != NULL && (token)->type == LWJSON_TYPE_NUM_INT) ? (token)->u.num_int : 0))
+
+/**
+ * \brief           Get token value for \ref LWJSON_TYPE_NUM_REAL type
+ * \param[in]       token: token with real type
+ * \return          Real numbeer if type is real, `0` otherwise
+ */
+#define lwjson_get_val_real(token)                                                                                     \
+    ((lwjson_real_t)(((token) != NULL && (token)->type == LWJSON_TYPE_NUM_REAL) ? (token)->u.num_real : 0))
+
+/**
+ * \brief           Get first child token for \ref LWJSON_TYPE_OBJECT or \ref LWJSON_TYPE_ARRAY types
+ * \param[in]       token: token with integer type
+ * \return          Pointer to first child or `NULL` if parent token is not object or array
+ */
+#define lwjson_get_first_child(token)                                                                                  \
+    (const void*)(((token) != NULL && ((token)->type == LWJSON_TYPE_OBJECT || (token)->type == LWJSON_TYPE_ARRAY))     \
+                      ? (token)->u.first_child                                                                         \
+                      : NULL)
+
+/**
+ * \brief           Get string value from JSON token
+ * \param[in]       token: Token with string type
+ * \param[out]      str_len: Pointer to variable holding length of string.
+ *                      Set to `NULL` if not used
+ * \return          Pointer to string or `NULL` if invalid token type
+ */
+static inline const char*
+lwjson_get_val_string(const lwjson_token_t* token, size_t* str_len) {
+    if (token != NULL && token->type == LWJSON_TYPE_STRING) {
+        if (str_len != NULL) {
+            *str_len = token->u.str.token_value_len;
+        }
+        return token->u.str.token_value;
+    }
+    return NULL;
+}
+
+/**
+ * \brief           Get length of string for \ref LWJSON_TYPE_STRING token type
+ * \param[in]       token: token with string type
+ * \return          Length of string in units of bytes
+ */
+#define lwjson_get_val_string_length(token)                                                                            \
+    ((size_t)(((token) != NULL && (token)->type == LWJSON_TYPE_STRING) ? (token)->u.str.token_value_len : 0))
+
+/**
+ * \brief           Compare string token with user input string for a case-sensitive match
+ * \param[in]       token: Token with string type
+ * \param[in]       str: NULL-terminated string to compare
+ * \return          `1` if equal, `0` otherwise
+ */
+static inline uint8_t
+lwjson_string_compare(const lwjson_token_t* token, const char* str) {
+    if (token != NULL && token->type == LWJSON_TYPE_STRING) {
+        return strncmp(token->u.str.token_value, str, token->u.str.token_value_len) == 0;
+    }
+    return 0;
+}
+
+/**
+ * \brief           Compare string token with user input string for a case-sensitive match
+ * \param[in]       token: Token with string type
+ * \param[in]       str: NULL-terminated string to compare
+ * \param[in]       len: Length of the string in bytes
+ * \return          `1` if equal, `0` otherwise
+ */
+static inline uint8_t
+lwjson_string_compare_n(const lwjson_token_t* token, const char* str, size_t len) {
+    if (token != NULL && token->type == LWJSON_TYPE_STRING && len <= token->u.str.token_value_len) {
+        return strncmp(token->u.str.token_value, str, len) == 0;
+    }
+    return 0;
+}
+
+/**
+ * \name            LWJSON_STREAM_SEQ
+ * \brief           Helper functions for stack analysis in a callback function
+ * \note            Useful exclusively for streaming functions
+ * \{
+ */
+
+/**
+ * \brief           Check the sequence of JSON stack, starting from start_number index
+ * \note            This applies only to one sequence element. Other macros, starting with
+ *                      `lwjson_stack_seq_X` (where X is the sequence length), provide
+ *                      more parameters for longer sequences.
+ * 
+ * \param[in]       jsp: LwJSON stream instance
+ * \param[in]       start_num: Start number in the stack. Typically starts with `0`, but user may choose another
+ *                      number, if intention is to check partial sequence only
+ * \param[in]       sp0: Stream stack type. Value of \ref lwjson_stream_type_t, but only last part of the enum.
+ *                      If user is interested in the \ref LWJSON_STREAM_TYPE_OBJECT,
+ *                      you should only write `OBJECT` as parameter.
+ *                      Idea behind is to make code smaller and easier to read, especially when
+ *                      using other sequence values with more parameters.
+ * \return          `0` if sequence doesn't match, non-zero otherwise
+ */
+#define lwjson_stack_seq_1(jsp, start_num, sp0) ((jsp)->stack[(start_num)].type == LWJSON_STREAM_TYPE_##sp0)
+#define lwjson_stack_seq_2(jsp, start_num, sp0, sp1)                                                                   \
+    (lwjson_stack_seq_1((jsp), (start_num) + 0, sp0) && lwjson_stack_seq_1((jsp), (start_num) + 1, sp1))
+#define lwjson_stack_seq_3(jsp, start_num, sp0, sp1, sp2)                                                              \
+    (lwjson_stack_seq_1((jsp), (start_num) + 0, sp0) && lwjson_stack_seq_2((jsp), (start_num) + 1, sp1, sp2))
+#define lwjson_stack_seq_4(jsp, start_num, sp0, sp1, sp2, sp3)                                                         \
+    (lwjson_stack_seq_1((jsp), (start_num) + 0, sp0) && lwjson_stack_seq_3((jsp), (start_num) + 1, sp1, sp2, sp3))
+#define lwjson_stack_seq_5(jsp, start_num, sp0, sp1, sp2, sp3, sp4)                                                    \
+    (lwjson_stack_seq_1((jsp), (start_num) + 0, sp0) && lwjson_stack_seq_4((jsp), (start_num) + 1, sp1, sp2, sp3, sp4))
+#define lwjson_stack_seq_6(jsp, start_num, sp0, sp1, sp2, sp3, sp4, sp5)                                               \
+    (lwjson_stack_seq_1((jsp), (start_num) + 0, sp0)                                                                   \
+     && lwjson_stack_seq_5((jsp), (start_num) + 1, sp1, sp2, sp3, sp4, sp5))
+#define lwjson_stack_seq_7(jsp, start_num, sp0, sp1, sp2, sp3, sp4, sp5, sp6)                                          \
+    (lwjson_stack_seq_1((jsp), (start_num) + 0, sp0)                                                                   \
+     && lwjson_stack_seq_6((jsp), (start_num) + 1, sp1, sp2, sp3, sp4, sp5, sp6))
+#define lwjson_stack_seq_8(jsp, start_num, sp0, sp1, sp2, sp3, sp4, sp5, sp6, sp7)                                     \
+    (lwjson_stack_seq_1((jsp), (start_num) + 0, sp0)                                                                   \
+     && lwjson_stack_seq_7((jsp), (start_num) + 1, sp1, sp2, sp3, sp4, sp5, sp6, sp7))
+
+/**
+ * \}
+ */
+
+/**
+ * \}
+ */
+
+#ifdef __cplusplus
+}
+#endif /* __cplusplus */
+
+#endif /* LWJSON_HDR_H */

+ 133 - 0
Application_cbd_apm32f1/applications/lwjson_debug.c

@@ -0,0 +1,133 @@
+/**
+ * \file            lwjson_debug.c
+ * \brief           Debug and print function for tokens
+ */
+
+/*
+ * Copyright (c) 2024 Tilen MAJERLE
+ *
+ * Permission is hereby granted, free of charge, to any person
+ * obtaining a copy of this software and associated documentation
+ * files (the "Software"), to deal in the Software without restriction,
+ * including without limitation the rights to use, copy, modify, merge,
+ * publish, distribute, sublicense, and/or sell copies of the Software,
+ * and to permit persons to whom the Software is furnished to do so,
+ * subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
+ * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
+ * AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
+ * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
+ * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
+ * OTHER DEALINGS IN THE SOFTWARE.
+ *
+ * This file is part of LwJSON - Lightweight JSON format parser.
+ *
+ * Author:          Tilen MAJERLE <tilen@majerle.eu>
+ * Version:         v1.8.1
+ */
+#include <stdio.h>
+#include <string.h>
+#include "lwjson.h"
+
+/**
+ * \brief           Token print instance
+ */
+typedef struct {
+    size_t indent; /*!< Indent level for token print */
+} lwjson_token_print_t;
+
+/**
+ * \brief           Print token value
+ * \param[in]       prt: Token print instance
+ * \param[in]       token: Token to print
+ */
+static void
+prv_print_token(lwjson_token_print_t* prt, const lwjson_token_t* token) {
+#define print_indent() printf("%.*s", (int)((prt->indent)), "\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t");
+
+    if (token == NULL) {
+        return;
+    }
+
+    /* Check if token has a name */
+    print_indent();
+    if (token->token_name != NULL) {
+        printf("\"%.*s\":", (int)token->token_name_len, token->token_name);
+    }
+
+    /* Print different types */
+    switch (token->type) {
+        case LWJSON_TYPE_OBJECT:
+        case LWJSON_TYPE_ARRAY: {
+            printf("%c", token->type == LWJSON_TYPE_OBJECT ? '{' : '[');
+            if (token->u.first_child != NULL) {
+                printf("\n");
+                ++prt->indent;
+                for (const lwjson_token_t* t = lwjson_get_first_child(token); t != NULL; t = t->next) {
+                    prv_print_token(prt, t);
+                }
+                --prt->indent;
+                print_indent();
+            }
+            printf("%c", token->type == LWJSON_TYPE_OBJECT ? '}' : ']');
+            break;
+        }
+        case LWJSON_TYPE_STRING: {
+            printf("\"%.*s\"", (int)lwjson_get_val_string_length(token), lwjson_get_val_string(token, NULL));
+            break;
+        }
+        case LWJSON_TYPE_NUM_INT: {
+            printf("%lld", (long long)lwjson_get_val_int(token));
+            break;
+        }
+        case LWJSON_TYPE_NUM_REAL: {
+            printf("%f", (double)lwjson_get_val_real(token));
+            break;
+        }
+        case LWJSON_TYPE_TRUE: {
+            printf("true");
+            break;
+        }
+        case LWJSON_TYPE_FALSE: {
+            printf("false");
+            break;
+        }
+        case LWJSON_TYPE_NULL: {
+            printf("NULL");
+            break;
+        }
+        default: break;
+    }
+    if (token->next != NULL) {
+        printf(",");
+    }
+    printf("\n");
+}
+
+/**
+ * \brief           Prints and outputs token data to the stream output
+ * \note            This function is not re-entrant
+ * \param[in]       token: Token to print
+ */
+void
+lwjson_print_token(const lwjson_token_t* token) {
+    lwjson_token_print_t prt = {0};
+    prv_print_token(&prt, token);
+}
+
+/**
+ * \brief           Prints and outputs full parsed LwJSON instance
+ * \note            This function is not re-entrant
+ * \param[in]       lwobj: LwJSON instance to print
+ */
+void
+lwjson_print_json(const lwjson_t* lwobj) {
+    lwjson_token_print_t prt = {0};
+    prv_print_token(&prt, lwjson_get_first_token(lwobj));
+}

+ 153 - 0
Application_cbd_apm32f1/applications/lwjson_opt.h

@@ -0,0 +1,153 @@
+/**
+ * \file            lwjson_opt.h
+ * \brief           LwJSON options
+ */
+
+/*
+ * Copyright (c) 2024 Tilen MAJERLE
+ *
+ * Permission is hereby granted, free of charge, to any person
+ * obtaining a copy of this software and associated documentation
+ * files (the "Software"), to deal in the Software without restriction,
+ * including without limitation the rights to use, copy, modify, merge,
+ * publish, distribute, sublicense, and/or sell copies of the Software,
+ * and to permit persons to whom the Software is furnished to do so,
+ * subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
+ * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
+ * AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
+ * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
+ * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
+ * OTHER DEALINGS IN THE SOFTWARE.
+ *
+ * This file is part of LwJSON - Lightweight JSON format parser.
+ *
+ * Author:          Tilen MAJERLE <tilen@majerle.eu>
+ * Version:         v1.8.1
+ */
+#ifndef LWJSON_OPT_HDR_H
+#define LWJSON_OPT_HDR_H
+
+/* Uncomment to ignore user options (or set macro in compiler flags) */
+/* #define LWJSON_IGNORE_USER_OPTS */
+
+/* Include application options */
+#ifndef LWJSON_IGNORE_USER_OPTS
+#include "lwjson_opts.h"
+#endif /* LWJSON_IGNORE_USER_OPTS */
+
+#ifdef __cplusplus
+extern "C" {
+#endif /* __cplusplus */
+
+/**
+ * \defgroup        LWJSON_OPT Configuration
+ * \brief           LwJSON options
+ * \{
+ */
+
+/**
+ * \brief           Real data type used to parse numbers with floating point number
+ * \note            Data type must be signed, normally `float` or `double`
+ *
+ * This is used for numbers in \ref LWJSON_TYPE_NUM_REAL token data type.
+ */
+#ifndef LWJSON_CFG_REAL_TYPE
+#define LWJSON_CFG_REAL_TYPE float
+#endif
+
+/**
+ * \brief           Integer type used to parse numbers
+ * \note            Data type must be signed integer
+ *
+ * This is used for numbers in \ref LWJSON_TYPE_NUM_INT token data type.
+ */
+#ifndef LWJSON_CFG_INT_TYPE
+#define LWJSON_CFG_INT_TYPE long long
+#endif
+
+/**
+ * \brief           Enables `1` or disables `0` support for inline comments
+ *
+ * Default set to `0` to be JSON compliant
+ */
+#ifndef LWJSON_CFG_COMMENTS
+#define LWJSON_CFG_COMMENTS 0
+#endif
+
+/**
+ * \brief           Memory set function
+ * 
+ * \note            Function footprint is the same as \ref memset
+ */
+#ifndef LWJSON_MEMSET
+#define LWJSON_MEMSET(dst, val, len) memset((dst), (val), (len))
+#endif
+
+/**
+ * \brief           Memory copy function
+ * 
+ * \note            Function footprint is the same as \ref memcpy
+ */
+#ifndef LWJSON_MEMCPY
+#define LWJSON_MEMCPY(dst, src, len) memcpy((dst), (src), (len))
+#endif
+
+/**
+ * \defgroup        LWJSON_OPT_STREAM JSON stream
+ * \brief           JSON streaming confiuration
+ * \{
+ */
+
+/**
+ * \brief           Max length of token key (object key name) to be available for stack storage
+ * 
+ */
+#ifndef LWJSON_CFG_STREAM_KEY_MAX_LEN
+#define LWJSON_CFG_STREAM_KEY_MAX_LEN 32
+#endif
+
+/**
+ * \brief           Max stack size (depth) in units of \ref lwjson_stream_stack_t structure
+ * 
+ */
+#ifndef LWJSON_CFG_STREAM_STACK_SIZE
+#define LWJSON_CFG_STREAM_STACK_SIZE 16
+#endif
+
+/**
+ * \brief           Max size of string for single parsing in units of bytes
+ * 
+ */
+#ifndef LWJSON_CFG_STREAM_STRING_MAX_LEN
+#define LWJSON_CFG_STREAM_STRING_MAX_LEN 256
+#endif
+
+/**
+ * \brief           Max number of bytes used to parse primitive.
+ * 
+ * Primitives are all numbers and logical values (null, true, false)
+ */
+#ifndef LWJSON_CFG_STREAM_PRIMITIVE_MAX_LEN
+#define LWJSON_CFG_STREAM_PRIMITIVE_MAX_LEN 32
+#endif
+
+/**
+ * \}
+ */
+
+/**
+ * \}
+ */
+
+#ifdef __cplusplus
+}
+#endif /* __cplusplus */
+
+#endif /* LWJSON_OPT_HDR_H */

+ 44 - 0
Application_cbd_apm32f1/applications/lwjson_opts.h

@@ -0,0 +1,44 @@
+/**
+ * \file            lwjson_opts_template.h
+ * \brief           Template config file
+ */
+
+/*
+ * Copyright (c) 2024 Tilen MAJERLE
+ *
+ * Permission is hereby granted, free of charge, to any person
+ * obtaining a copy of this software and associated documentation
+ * files (the "Software"), to deal in the Software without restriction,
+ * including without limitation the rights to use, copy, modify, merge,
+ * publish, distribute, sublicense, and/or sell copies of the Software,
+ * and to permit persons to whom the Software is furnished to do so,
+ * subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
+ * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
+ * AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
+ * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
+ * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
+ * OTHER DEALINGS IN THE SOFTWARE.
+ *
+ * This file is part of LwJSON - Lightweight JSON format parser.
+ *
+ * Author:          Tilen MAJERLE <tilen@majerle.eu>
+ * Version:         v1.8.1
+ */
+#ifndef LWJSON_OPTS_HDR_H
+#define LWJSON_OPTS_HDR_H
+
+/* Rename this file to "lwjson_opts.h" for your application */
+
+/*
+ * Open "include/lwjson/lwjson_opt.h" and
+ * copy & replace here settings you want to change values
+ */
+
+#endif /* LWJSON_OPTS_HDR_H */

+ 501 - 0
Application_cbd_apm32f1/applications/lwjson_stream.c

@@ -0,0 +1,501 @@
+/**
+ * \file            lwjson_stream.c
+ * \brief           Lightweight JSON format parser
+ */
+
+/*
+ * Copyright (c) 2024 Tilen MAJERLE
+ *
+ * Permission is hereby granted, free of charge, to any person
+ * obtaining a copy of this software and associated documentation
+ * files (the "Software"), to deal in the Software without restriction,
+ * including without limitation the rights to use, copy, modify, merge,
+ * publish, distribute, sublicense, and/or sell copies of the Software,
+ * and to permit persons to whom the Software is furnished to do so,
+ * subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
+ * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
+ * AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
+ * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
+ * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
+ * OTHER DEALINGS IN THE SOFTWARE.
+ *
+ * This file is part of LwJSON - Lightweight JSON format parser.
+ *
+ * Author:          Tilen MAJERLE <tilen@majerle.eu>
+ * Version:         v1.8.1
+ */
+#include <string.h>
+#include "lwjson.h"
+
+#if defined(LWJSON_DEV)
+#include <stdio.h>
+#define DEBUG_STRING_PREFIX_SPACES                                                                                     \
+    "                                                                                                "
+#define LWJSON_DEBUG(jsp, ...)                                                                                         \
+    do {                                                                                                               \
+        if ((jsp) != NULL) {                                                                                           \
+            printf("%.*s", (int)(4 * (jsp)->stack_pos), DEBUG_STRING_PREFIX_SPACES);                                   \
+        }                                                                                                              \
+        printf(__VA_ARGS__);                                                                                           \
+    } while (0)
+
+/* Strings for debug */
+const char* const lwjson_type_strings[] = {
+    [LWJSON_STREAM_TYPE_NONE] = "none",
+    [LWJSON_STREAM_TYPE_OBJECT] = "object",
+    [LWJSON_STREAM_TYPE_OBJECT_END] = "object_end",
+    [LWJSON_STREAM_TYPE_ARRAY] = "array",
+    [LWJSON_STREAM_TYPE_ARRAY_END] = "array_end",
+    [LWJSON_STREAM_TYPE_KEY] = "key",
+    [LWJSON_STREAM_TYPE_STRING] = "string",
+    [LWJSON_STREAM_TYPE_TRUE] = "true",
+    [LWJSON_STREAM_TYPE_FALSE] = "false",
+    [LWJSON_STREAM_TYPE_NULL] = "null",
+    [LWJSON_STREAM_TYPE_NUMBER] = "number",
+};
+#else
+#define LWJSON_DEBUG(jsp, ...)
+#endif /* defined(LWJSON_DEV) */
+
+/**
+ * \brief           Sends an event to user for further processing
+ * 
+ */
+#define SEND_EVT(jsp, type)                                                                                            \
+    if ((jsp) != NULL && (jsp)->evt_fn != NULL) {                                                                      \
+        (jsp)->evt_fn((jsp), (type));                                                                                  \
+    }
+
+/**
+ * \brief           Check if character is a space character (with extended chars)
+ * \param[in]       c: Character to check
+ * \return          `1` if considered extended space, `0` otherwise
+ */
+#define prv_is_space_char_ext(c) ((c) == ' ' || (c) == '\t' || (c) == '\r' || (c) == '\n' || (c) == '\f')
+
+/**
+ * \brief           Push "parent" state to the artificial stack
+ * \param           jsp: JSON stream parser instance
+ * \param           type: Stream type to be pushed on stack
+ * \return          `1` on success, `0` otherwise
+ */
+static uint8_t
+prv_stack_push(lwjson_stream_parser_t* jsp, lwjson_stream_type_t type) {
+    if (jsp->stack_pos < LWJSON_ARRAYSIZE(jsp->stack)) {
+        jsp->stack[jsp->stack_pos].type = type;
+        jsp->stack[jsp->stack_pos].meta.index = 0;
+        LWJSON_DEBUG(jsp, "Pushed to stack: %s\r\n", lwjson_type_strings[type]);
+        jsp->stack_pos++;
+        return 1;
+    }
+    return 0;
+}
+
+/**
+ * \brief           Pop value from stack (remove it) and return its value
+ * \param           jsp: JSON stream parser instance
+ * \return          Member of \ref lwjson_stream_type_t enumeration 
+ */
+static lwjson_stream_type_t
+prv_stack_pop(lwjson_stream_parser_t* jsp) {
+    if (jsp->stack_pos > 0) {
+        lwjson_stream_type_t type = jsp->stack[--jsp->stack_pos].type;
+
+        jsp->stack[jsp->stack_pos].type = LWJSON_STREAM_TYPE_NONE;
+        LWJSON_DEBUG(jsp, "Popped from stack: %s\r\n", lwjson_type_strings[type]);
+
+        /* Take care of array to indicate number of entries */
+        if (jsp->stack_pos > 0 && jsp->stack[jsp->stack_pos - 1].type == LWJSON_STREAM_TYPE_ARRAY) {
+            jsp->stack[jsp->stack_pos - 1].meta.index++;
+        }
+        return type;
+    }
+    return LWJSON_STREAM_TYPE_NONE;
+}
+
+/**
+ * \brief           Get top type value currently on the stack
+ * \param           jsp: JSON stream parser instance
+ * \return          Member of \ref lwjson_stream_type_t enumeration 
+ */
+static lwjson_stream_type_t
+prv_stack_get_top(lwjson_stream_parser_t* jsp) {
+    if (jsp->stack_pos > 0) {
+        return jsp->stack[jsp->stack_pos - 1].type;
+    }
+    return LWJSON_STREAM_TYPE_NONE;
+}
+
+/**
+ * \brief           Initialize LwJSON stream object before parsing takes place
+ * \param[in,out]   jsp: Stream JSON structure 
+ * \return          \ref lwjsonOK on success, member of \ref lwjsonr_t otherwise
+ */
+lwjsonr_t
+lwjson_stream_init(lwjson_stream_parser_t* jsp, lwjson_stream_parser_callback_fn evt_fn) {
+    LWJSON_MEMSET(jsp, 0x00, sizeof(*jsp));
+    jsp->parse_state = LWJSON_STREAM_STATE_WAITINGFIRSTCHAR;
+    jsp->evt_fn = evt_fn;
+    jsp->user_data = NULL;
+    return lwjsonOK;
+}
+
+/**
+ * \brief           Reset LwJSON stream structure
+ * 
+ * \param[in,out]   jsp: LwJSON stream parser
+ * \return          \ref lwjsonOK on success, member of \ref lwjsonr_t otherwise
+ */
+lwjsonr_t
+lwjson_stream_reset(lwjson_stream_parser_t* jsp) {
+    jsp->parse_state = LWJSON_STREAM_STATE_WAITINGFIRSTCHAR;
+    jsp->stack_pos = 0;
+    return lwjsonOK;
+}
+
+/**
+ * \brief           Set user_data in stream parser
+ * 
+ * \param[in,out]   jsp: LwJSON stream parser
+ * \param[in]       user_data: user data
+ * \return          \ref lwjsonOK on success, member of \ref lwjsonr_t otherwise
+ */
+lwjsonr_t
+lwjson_stream_set_user_data(lwjson_stream_parser_t* jsp, void* user_data) {
+    jsp->user_data = user_data;
+    return lwjsonOK;
+}
+
+/**
+ * \brief           Get user_data in stream parser
+ * 
+ * \param[in]       jsp: LwJSON stream parser
+ * \return          pointer to user data
+ */
+void*
+lwjson_stream_get_user_data(lwjson_stream_parser_t* jsp) {
+    return jsp->user_data;
+}
+
+/**
+ * \brief           Parse JSON string in streaming mode
+ * \param[in,out]   jsp: Stream JSON structure 
+ * \param[in]       chr: Character to parse
+ * \return          \ref lwjsonSTREAMWAITFIRSTCHAR when stream did not start parsing since no valid start character has been received
+ * \return          \ref lwjsonSTREAMINPROG if parsing is in progress and no hard error detected
+ * \return          \ref lwjsonSTREAMDONE when valid JSON was detected and stack level reached back `0` level
+ * \return          \ref One of enumeration otherwise
+ */
+lwjsonr_t
+lwjson_stream_parse(lwjson_stream_parser_t* jsp, char chr) {
+    /* Get first character first */
+    if (jsp->parse_state == LWJSON_STREAM_STATE_WAITINGFIRSTCHAR && chr != '{' && chr != '[') {
+        return prv_is_space_char_ext(chr) ? lwjsonSTREAMWAITFIRSTCHAR : lwjsonERRJSON;
+    }
+
+start_over:
+    /* Determine what to do from parsing state */
+    switch (jsp->parse_state) {
+
+        /*
+         * Waiting for very first valid characters,
+         * that is used to indicate start of JSON stream
+         */
+        case LWJSON_STREAM_STATE_WAITINGFIRSTCHAR:
+        case LWJSON_STREAM_STATE_EXPECTING_COMMA_OR_END:
+        case LWJSON_STREAM_STATE_PARSING: {
+            /* Ignore whitespace chars */
+            if (prv_is_space_char_ext(chr)) {
+                break;
+
+                /* Determine value separator */
+            } else if (chr == ',') {
+                if (jsp->parse_state == LWJSON_STREAM_STATE_EXPECTING_COMMA_OR_END) {
+                    jsp->parse_state = LWJSON_STREAM_STATE_PARSING;
+                } else {
+                    LWJSON_DEBUG(jsp, "ERROR - ',' can only follow value\r\n");
+                    return lwjsonERRJSON;
+                }
+
+                /* Determine end of object or an array */
+            } else if (chr == '}' || chr == ']') {
+                lwjson_stream_type_t type = prv_stack_get_top(jsp);
+
+                /* 
+                 * If it is a key last entry on closing area,
+                 * it is an error - an example: {"key":}
+                 */
+                if (type == LWJSON_STREAM_TYPE_KEY) {
+                    LWJSON_DEBUG(jsp, "ERROR - key should not be followed by ] without value for a key\r\n");
+                    return lwjsonERRJSON;
+                }
+
+                /*
+                 * Check if closing character matches stack value
+                 * Avoid cases like: {"key":"value"] or ["v1", "v2", "v3"}
+                 */
+                if ((chr == '}' && type != LWJSON_STREAM_TYPE_OBJECT)
+                    || (chr == ']' && type != LWJSON_STREAM_TYPE_ARRAY)) {
+                    LWJSON_DEBUG(jsp, "ERROR - closing character '%c' does not match stack element \"%s\"\r\n", chr,
+                                 lwjson_type_strings[type]);
+                    return lwjsonERRJSON;
+                }
+
+                /* Now remove the array or object from stack */
+                if (prv_stack_pop(jsp) == LWJSON_STREAM_TYPE_NONE) {
+                    return lwjsonERRJSON;
+                }
+
+                SEND_EVT(jsp, chr == '}' ? LWJSON_STREAM_TYPE_OBJECT_END : LWJSON_STREAM_TYPE_ARRAY_END);
+
+                /*
+                 * Check if above is a key type
+                 * and remove it too as we finished with processing of potential case.
+                 * 
+                 * {"key":{"abc":1}} - remove "key" part
+                 */
+                if (prv_stack_get_top(jsp) == LWJSON_STREAM_TYPE_KEY) {
+                    prv_stack_pop(jsp);
+                }
+
+                /* If that is the end of JSON */
+                if (jsp->stack_pos == 0) {
+                    lwjson_stream_reset(jsp);
+                    return lwjsonSTREAMDONE;
+                }
+
+                jsp->parse_state = LWJSON_STREAM_STATE_EXPECTING_COMMA_OR_END;
+
+                /* If comma or end was expected, then it is already error here */
+            } else if (jsp->parse_state == LWJSON_STREAM_STATE_EXPECTING_COMMA_OR_END) {
+                LWJSON_DEBUG(jsp, "ERROR - ',', '}' or ']' was expected\r\n");
+                return lwjsonERRJSON;
+
+                /* Determine start of string - can be key or regular string (in array or after key) */
+            } else if (chr == '"') {
+#if defined(LWJSON_DEV)
+                lwjson_stream_type_t type = prv_stack_get_top(jsp);
+                if (type == LWJSON_STREAM_TYPE_OBJECT) {
+                    LWJSON_DEBUG(jsp, "Start of string parsing - expected key name in an object\r\n");
+                } else if (type == LWJSON_STREAM_TYPE_KEY) {
+                    LWJSON_DEBUG(jsp,
+                                 "Start of string parsing - string value associated to previous key in an object\r\n");
+                } else if (type == LWJSON_STREAM_TYPE_ARRAY) {
+                    LWJSON_DEBUG(jsp, "Start of string parsing - string entry in an array\r\n");
+                }
+#endif /* defined(LWJSON_DEV) */
+                jsp->parse_state = LWJSON_STREAM_STATE_PARSING_STRING;
+                LWJSON_MEMSET(&jsp->data.str, 0x00, sizeof(jsp->data.str));
+
+            } else if (prv_stack_get_top(jsp) == LWJSON_STREAM_TYPE_OBJECT) {
+                /* Key must be before value */
+                LWJSON_DEBUG(jsp, "ERROR - key must be before value\r\n");
+                return lwjsonERRJSON;
+
+                /* Determine start of object or an array */
+            } else if (chr == '{' || chr == '[') {
+                /* Reset stack pointer if this character came from waiting for first character */
+                if (jsp->parse_state == LWJSON_STREAM_STATE_WAITINGFIRSTCHAR) {
+                    jsp->stack_pos = 0;
+                }
+                SEND_EVT(jsp, chr == '{' ? LWJSON_STREAM_TYPE_OBJECT : LWJSON_STREAM_TYPE_ARRAY);
+                if (!prv_stack_push(jsp, chr == '{' ? LWJSON_STREAM_TYPE_OBJECT : LWJSON_STREAM_TYPE_ARRAY)) {
+                    LWJSON_DEBUG(jsp, "Cannot push object/array to stack\r\n");
+                    return lwjsonERRMEM;
+                }
+                jsp->parse_state = LWJSON_STREAM_STATE_PARSING;
+
+                /* Check if this is start of number or "true", "false" or "null" */
+            } else if (chr == '-' || (chr >= '0' && chr <= '9') || chr == 't' || chr == 'f' || chr == 'n') {
+                if (prv_stack_get_top(jsp) == LWJSON_STREAM_TYPE_OBJECT) {
+                    LWJSON_DEBUG(jsp, "ERROR - key must be before value (primitive)\r\n");
+                    /* Key must be before value */
+                    return lwjsonERRJSON;
+                }
+
+                LWJSON_DEBUG(jsp, "Start of primitive parsing parsing - %s, First char: %c\r\n",
+                             (chr == '-' || (chr >= '0' && chr <= '9')) ? "number" : "true,false,null", chr);
+                jsp->parse_state = LWJSON_STREAM_STATE_PARSING_PRIMITIVE;
+                LWJSON_MEMSET(&jsp->data.prim, 0x00, sizeof(jsp->data.prim));
+                jsp->data.prim.buff[jsp->data.prim.buff_pos++] = chr;
+
+                /* Wrong char */
+            } else {
+                LWJSON_DEBUG(jsp, "ERROR - wrong char %c\r\n", chr);
+                return lwjsonERRJSON;
+            }
+            break;
+        }
+
+        /* Check for end of key character i.e. name separator ':' */
+        case LWJSON_STREAM_STATE_EXPECTING_COLON:
+            /* Ignore whitespace chars */
+            if (prv_is_space_char_ext(chr)) {
+                break;
+            } else if (chr == ':') {
+                jsp->parse_state = LWJSON_STREAM_STATE_PARSING;
+            } else {
+                LWJSON_DEBUG(jsp, "ERROR - expecting ':'\r\n");
+                return lwjsonERRJSON;
+            }
+            break;
+
+        /*
+         * Parse any type of string in a sequence
+         *
+         * It is used for key or string in an object or an array
+         */
+        case LWJSON_STREAM_STATE_PARSING_STRING: {
+            lwjson_stream_type_t type = prv_stack_get_top(jsp);
+
+            /* 
+             * Quote character may trigger end of string, 
+             * or if backslasled before - it is part of string
+             * 
+             * TODO: Handle backslash
+             */
+            if (chr == '"' && jsp->prev_c != '\\') {
+#if defined(LWJSON_DEV)
+                if (type == LWJSON_STREAM_TYPE_OBJECT) {
+                    LWJSON_DEBUG(jsp, "End of string parsing - object key name: \"%s\"\r\n", jsp->data.str.buff);
+                } else if (type == LWJSON_STREAM_TYPE_KEY) {
+                    LWJSON_DEBUG(
+                        jsp, "End of string parsing - string value associated to previous key in an object: \"%s\"\r\n",
+                        jsp->data.str.buff);
+                } else if (type == LWJSON_STREAM_TYPE_ARRAY) {
+                    LWJSON_DEBUG(jsp, "End of string parsing - an array string entry: \"%s\"\r\n", jsp->data.str.buff);
+                }
+#endif /* defined(LWJSON_DEV) */
+
+                /* Set is_last to 1 as this is the last part of this string token */
+                jsp->data.str.is_last = 1;
+
+                /*
+                 * When top of stack is object - string is treated as a key
+                 * When top of stack is a key - string is a value for a key - notify user and pop the value for key
+                 * When top of stack is an array - string is one type - notify user and don't do anything
+                 */
+                jsp->parse_state = LWJSON_STREAM_STATE_EXPECTING_COMMA_OR_END;
+                if (type == LWJSON_STREAM_TYPE_OBJECT) {
+                    SEND_EVT(jsp, LWJSON_STREAM_TYPE_KEY);
+                    if (prv_stack_push(jsp, LWJSON_STREAM_TYPE_KEY)) {
+                        size_t len = jsp->data.str.buff_pos;
+                        if (len > (sizeof(jsp->stack[0].meta.name) - 1)) {
+                            len = sizeof(jsp->stack[0].meta.name) - 1;
+                        }
+                        LWJSON_MEMCPY(jsp->stack[jsp->stack_pos - 1].meta.name, jsp->data.str.buff, len);
+                        jsp->stack[jsp->stack_pos - 1].meta.name[len] = '\0';
+                    } else {
+                        LWJSON_DEBUG(jsp, "Cannot push key to stack\r\n");
+                        return lwjsonERRMEM;
+                    }
+                    jsp->parse_state = LWJSON_STREAM_STATE_EXPECTING_COLON;
+                } else if (type == LWJSON_STREAM_TYPE_KEY) {
+                    SEND_EVT(jsp, LWJSON_STREAM_TYPE_STRING);
+                    prv_stack_pop(jsp);
+                    /* Next character to wait for is either space or comma or end of object */
+                } else if (type == LWJSON_STREAM_TYPE_ARRAY) {
+                    SEND_EVT(jsp, LWJSON_STREAM_TYPE_STRING);
+                    jsp->stack[jsp->stack_pos - 1].meta.index++;
+                }
+            } else {
+                /* TODO: Check other backslash elements */
+                jsp->data.str.buff[jsp->data.str.buff_pos++] = chr;
+                jsp->data.str.buff_total_pos++;
+
+                /* Handle buffer "overflow" */
+                if (jsp->data.str.buff_pos >= (LWJSON_CFG_STREAM_STRING_MAX_LEN - 1)) {
+                    jsp->data.str.buff[jsp->data.str.buff_pos] = '\0';
+
+                    /* 
+                     * - For array or key types - following one is always string
+                     * - For object type - character is key
+                     */
+                    SEND_EVT(jsp, (type == LWJSON_STREAM_TYPE_KEY || type == LWJSON_STREAM_TYPE_ARRAY)
+                                      ? LWJSON_STREAM_TYPE_STRING
+                                      : LWJSON_STREAM_TYPE_KEY);
+                    jsp->data.str.buff_pos = 0;
+                }
+            }
+            break;
+        }
+
+        /*
+         * Parse any type of primitive that is not a string.
+         *
+         * true, false, null or any number primitive
+         */
+        case LWJSON_STREAM_STATE_PARSING_PRIMITIVE: {
+            /* Any character except space, comma, or end of array/object are valid */
+            if (!prv_is_space_char_ext(chr) && chr != ',' && chr != ']' && chr != '}') {
+                if (jsp->data.prim.buff_pos < sizeof(jsp->data.prim.buff) - 1) {
+                    jsp->data.prim.buff[jsp->data.prim.buff_pos++] = chr;
+                } else {
+                    LWJSON_DEBUG(jsp, "Buffer overflow for primitive\r\n");
+                    return lwjsonERRJSON;
+                }
+            } else {
+                lwjson_stream_type_t type = prv_stack_get_top(jsp);
+
+#if defined(LWJSON_DEV)
+                if (type == LWJSON_STREAM_TYPE_KEY) {
+                    LWJSON_DEBUG(
+                        jsp,
+                        "End of primitive parsing - string value associated to previous key in an object: \"%s\"\r\n",
+                        jsp->data.prim.buff);
+                } else if (type == LWJSON_STREAM_TYPE_ARRAY) {
+                    LWJSON_DEBUG(jsp, "End of primitive parsing - an array string entry: \"%s\"\r\n",
+                                 jsp->data.prim.buff);
+                }
+#endif /* defined(LWJSON_DEV) */
+
+                /*
+                 * This is the end of primitive parsing
+                 *
+                 * It is assumed that buffer for primitive can handle at least
+                 * true, false, null or all number characters (that being real or int number)
+                 */
+                if (jsp->data.prim.buff_pos == 4 && strncmp(jsp->data.prim.buff, "true", 4) == 0) {
+                    LWJSON_DEBUG(jsp, "Primitive parsed as %s\r\n", "true");
+                    SEND_EVT(jsp, LWJSON_STREAM_TYPE_TRUE);
+                } else if (jsp->data.prim.buff_pos == 4 && strncmp(jsp->data.prim.buff, "null", 4) == 0) {
+                    LWJSON_DEBUG(jsp, "Primitive parsed as %s\r\n", "null");
+                    SEND_EVT(jsp, LWJSON_STREAM_TYPE_NULL);
+                } else if (jsp->data.prim.buff_pos == 5 && strncmp(jsp->data.prim.buff, "false", 5) == 0) {
+                    LWJSON_DEBUG(jsp, "Primitive parsed as %s\r\n", "false");
+                    SEND_EVT(jsp, LWJSON_STREAM_TYPE_FALSE);
+                } else if (jsp->data.prim.buff[0] == '-'
+                           || (jsp->data.prim.buff[0] >= '0' && jsp->data.prim.buff[0] <= '9')) {
+                    LWJSON_DEBUG(jsp, "Primitive parsed - number\r\n");
+                    SEND_EVT(jsp, LWJSON_STREAM_TYPE_NUMBER);
+                } else {
+                    LWJSON_DEBUG(jsp, "Invalid primitive type. Got: %s\r\n", jsp->data.prim.buff);
+                    return lwjsonERRJSON;
+                }
+                if (type == LWJSON_STREAM_TYPE_KEY) {
+                    prv_stack_pop(jsp);
+                } else if (type == LWJSON_STREAM_TYPE_ARRAY) {
+                    jsp->stack[jsp->stack_pos - 1].meta.index++;
+                }
+
+                /* 
+                 * Received character is not part of the primitive and must be processed again
+                 */
+                jsp->parse_state = LWJSON_STREAM_STATE_EXPECTING_COMMA_OR_END;
+                goto start_over;
+            }
+            break;
+        }
+
+        default: break;
+    }
+    jsp->prev_c = chr; /* Save current c as previous for next round */
+    return lwjsonSTREAMINPROG;
+}

+ 89 - 0
Application_cbd_apm32f1/applications/sys_monitor.c

@@ -0,0 +1,89 @@
+/*
+ * Copyright (c) 2006-2021, RT-Thread Development Team
+ *
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ * Change Logs:
+ * Date           Author       Notes
+ * 2026-02-04     Administrator       the first version
+ */
+#include "sys_monitor.h"
+#include "cpu_usage.h"
+#include "control.h"
+#include "sht30_collect.h"
+#define DBG_ENABLE
+#define DBG_COLOR
+#define DBG_TAG "sysmonitor"
+#define DBG_LEVEL         DBG_LOG
+#include <rtdbg.h> //must after of DBG_LVL, DBG_TAG or other options
+
+rt_thread_t tid_sys_monitor = RT_NULL;
+
+Device_Status_typedef device_status;
+System_stats_t system_status;
+
+
+static void sys_monitor_thread_entry(void *parameter)
+{
+    uint8_t sec_t;
+    system_status.lamp_start_time = 0;
+    system_status.heat_start_time = 0;
+    while(1)
+    {
+        sec_t++;
+        system_status.cpu_usage = (int)cpu_load_average();
+        if(system_status.cpu_usage>system_status.cpu_usage_max){
+            system_status.cpu_usage_max = system_status.cpu_usage;
+        }
+        rt_tick_t tick = rt_tick_get();
+        rt_uint32_t total_sec = (rt_uint32_t)(tick / RT_TICK_PER_SECOND);
+        system_status.system_uptime = total_sec;
+        system_status.cpu_tempture = (int)Get_Temprate()/100;
+        rt_uint32_t hours   = total_sec / 3600;
+        rt_uint32_t minutes = (total_sec % 3600) / 60;
+        rt_uint32_t seconds = total_sec % 60;
+        rt_thread_delay(1000);
+        if(sec_t%10==0){
+            LOG_D("CPU温度:%d℃",system_status.cpu_tempture);
+            LOG_D("CPU利用率 :%d% Max:%d%",system_status.cpu_usage,system_status.cpu_usage_max);
+            LOG_D("系统运行时长:%d时%d分%d秒",hours,minutes,seconds);
+            LOG_D("重启次数:%d",device_status.rebootcnt);
+
+            LOG_D("串口2累计发送字节:%d",system_status.uart2_tx_bytes);
+            LOG_D("串口2累计接收字节:%d",system_status.uart2_rx_bytes);
+
+            LOG_D("串口4累计发送字节:%d",system_status.uart4_tx_bytes);
+            LOG_D("串口4累计接收字节:%d",system_status.uart4_rx_bytes);
+
+            LOG_D("累计上传数据:%d 条",system_status.json_upload_count);
+            LOG_D("累计拍照次数:%d ",system_status.photo_taken_count);
+            LOG_D("累计清扫次数:%d ",system_status.cleaning_count);
+            LOG_D("累计震动次数:%d ",system_status.vibration_count);
+
+            LOG_D("上仓门累计打开:%d ",system_status.upper_door_open_count);
+            LOG_D("上仓门累计关闭:%d ",system_status.upper_door_close_count);
+            LOG_D("下仓门累计打开:%d ",system_status.lower_door_open_count);
+            LOG_D("下仓门累计关闭:%d ",system_status.lower_door_close_count);
+
+            LOG_D("灯管累计运行:%d S",system_status.lamp_running_time/RT_TICK_PER_SECOND);
+            LOG_D("加热累计运行:%d S",system_status.heater_running_time/RT_TICK_PER_SECOND);
+
+        }
+    }
+}
+
+int Sys_Motor_Task(void)
+{
+    /* 创建线程*/
+    tid_sys_monitor = rt_thread_create("sys_monitor",
+                                sys_monitor_thread_entry, RT_NULL,
+                                1024,       //2048
+                                28,         //12
+                                5);       //5
+
+    if(tid_sys_monitor!=RT_NULL)
+    {
+        rt_thread_startup(tid_sys_monitor);
+    }
+    return 0;
+}

+ 74 - 0
Application_cbd_apm32f1/applications/sys_monitor.h

@@ -0,0 +1,74 @@
+/*
+ * Copyright (c) 2006-2021, RT-Thread Development Team
+ *
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ * Change Logs:
+ * Date           Author       Notes
+ * 2026-02-04     Administrator       the first version
+ */
+#ifndef APPLICATIONS_SYS_MONITOR_H_
+#define APPLICATIONS_SYS_MONITOR_H_
+
+#include <rtthread.h>
+
+/* 根据你的MCU字长选择合适的数据类型 */
+typedef uint32_t time_sec_t;    // 用于秒级的时间统计
+typedef uint64_t time_ms_t;     // 用于毫秒级的时间统计
+typedef uint32_t counter_t;     // 用于计数器
+typedef uint16_t small_counter_t; // 用于小计数器
+
+/* 系统运行统计结构体 */
+typedef struct
+{
+    /* 1. 系统运行时间相关 */
+    time_sec_t  system_uptime;         // 系统总运行时长(秒)
+    time_sec_t  network_connected_time; // 联网时间(秒)
+    time_sec_t  network_disconnected_time; // 断网时间(秒)
+
+    /* 2. CPU相关 */
+    uint8_t     cpu_tempture;
+    uint8_t     cpu_usage;             // CPU占用率(0-100%)
+    uint8_t     cpu_usage_max;         // 历史最大CPU占用率
+
+    /* 3. 通信统计 */
+    counter_t   uart2_rx_bytes;         // 串口接收字节数
+    counter_t   uart2_tx_bytes;         // 串口发送字节数
+    counter_t   json_upload_count;     // JSON数据上传次数
+
+    counter_t   uart4_rx_bytes;         // 串口接收字节数
+    counter_t   uart4_tx_bytes;         // 串口发送字节数
+
+    /* 4. 动作次数统计 */
+    counter_t   photo_taken_count;     // 拍照次数统计
+    counter_t   cleaning_count;         // 清扫次数统计
+    counter_t   vibration_count;        // 震动次数统计
+
+    /* 5. 仓门状态统计 */
+    counter_t   upper_door_open_count;  // 上仓门打开次数
+    counter_t   upper_door_close_count; // 上仓门关闭次数
+    counter_t   lower_door_open_count;  // 下仓门打开次数
+    counter_t   lower_door_close_count; // 下仓门关闭次数
+
+    /* 6. 传感器触发统计 */
+    counter_t   rain_control_triggers; // 雨控触发次数
+    counter_t   light_control_triggers; // 光控触发次数
+
+    /* 7. 设备运行时间统计 */
+    time_sec_t  lamp_start_time;
+    time_sec_t  lamp_running_time;     // 灯管运行时间
+    time_sec_t  heat_start_time;
+    time_sec_t  heater_running_time;  // 加热时间
+    time_sec_t  fill_light_running_time; // 补光灯运行时间
+
+    /* 8. 时间戳信息(可选) */
+    time_sec_t  last_reset_time;       // 上次重置时间戳
+    uint32_t    reset_count;           // 系统重置次数
+
+
+} System_stats_t;
+
+
+int Sys_Motor_Task(void);
+
+#endif /* APPLICATIONS_SYS_MONITOR_H_ */

+ 5 - 0
Application_cbd_apm32f1/readme.md

@@ -1,3 +1,8 @@
+# 2026-02-09 更新说明
+	版本:2.6.9
+	1. 增加lwjson库
+	2. 增加MCU参数备份到RTU
+	3. 增加系统运行状态监测
 # 2025-11-03 更新说明
 # 2025-11-03 更新说明
 	版本:2.5.9
 	版本:2.5.9
 	1. 修复屏幕设置北大荒ID的前缀类型为测报灯,修改为性诱;
 	1. 修复屏幕设置北大荒ID的前缀类型为测报灯,修改为性诱;