init
authorkyz <kyz@kyz.pub>
Fri, 28 Aug 2026 05:46:05 +0000 (13:46 +0800)
committerkyz <kyz@kyz.pub>
Fri, 28 Aug 2026 05:46:05 +0000 (13:46 +0800)
27 files changed:
.gitignore [new file with mode: 0644]
CMakeLists.txt [new file with mode: 0644]
app/CMakeLists.txt [new file with mode: 0644]
app/com.yn.ui.conf [new file with mode: 0644]
app/inc/ad_log.h [new file with mode: 0644]
app/inc/ad_version.h [new file with mode: 0644]
app/inc/agridetect.h [new file with mode: 0644]
app/inc/cJSON.h [new file with mode: 0644]
app/inc/cQueue.h [new file with mode: 0644]
app/inc/dev_info.h [new file with mode: 0644]
app/inc/maintask.h [new file with mode: 0644]
app/inc/motor.h [new file with mode: 0644]
app/inc/pipette.h [new file with mode: 0644]
app/inc/robot.h [new file with mode: 0644]
app/log4crc [new file with mode: 0644]
app/src/ad_main.c [new file with mode: 0644]
app/src/cJSON.c [new file with mode: 0644]
app/src/cQueue.c [new file with mode: 0644]
app/src/crc16.c [new file with mode: 0644]
app/src/crc16.h [new file with mode: 0644]
app/src/dev_info.c [new file with mode: 0644]
app/src/maintask.c [new file with mode: 0644]
app/src/motor.c [new file with mode: 0644]
app/src/pipette.c [new file with mode: 0644]
app/src/robot.c [new file with mode: 0644]
app/src/ui.c [new file with mode: 0644]
fs_overlay/app/agridetect_ui [new file with mode: 0755]

diff --git a/.gitignore b/.gitignore
new file mode 100644 (file)
index 0000000..b4aec0b
--- /dev/null
@@ -0,0 +1,6 @@
+build/
+*.o
+~*
+tags
+cscope.*
+
diff --git a/CMakeLists.txt b/CMakeLists.txt
new file mode 100644 (file)
index 0000000..933ec5d
--- /dev/null
@@ -0,0 +1,8 @@
+cmake_minimum_required(VERSION 3.8)
+
+project(agridetect)
+
+set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -pie -fPIE -g2 -O0")
+
+# Add the posix targets
+add_subdirectory( ${CMAKE_CURRENT_LIST_DIR}/app )
diff --git a/app/CMakeLists.txt b/app/CMakeLists.txt
new file mode 100644 (file)
index 0000000..ea61690
--- /dev/null
@@ -0,0 +1,61 @@
+cmake_minimum_required(VERSION 3.8)
+
+project(agridetect)
+
+find_package(PkgConfig REQUIRED)
+pkg_check_modules(GLIB2 glib-2.0 gio-2.0 REQUIRED)
+pkg_check_modules(DBUS  dbus-1           REQUIRED)
+
+add_definitions(-DRKAIQ)
+add_definitions(${GLIB2_CFLAGS_OTHER})
+
+aux_source_directory(common COMMON_SRCS)
+
+include_directories(
+       ${PROJECT_SOURCE_DIR}/./
+       ${PROJECT_SOURCE_DIR}/src/
+       ${PROJECT_SOURCE_DIR}/inc/
+       ${PROJECT_SOURCE_DIR}/../log/inc/
+       ${CMAKE_SYSROOT}/usr/include/
+    ${GLIB2_INCLUDE_DIRS}
+    ${DBUS_INCLUDE_DIRS}
+       )
+
+link_directories(
+       ${CMAKE_SYSROOT}/app/lib
+    ${GLIB2_LIBRARY_DIRS}
+    ${DBUS_LIBRARY_DIRS}
+       )
+
+
+
+aux_source_directory(./src/ SRCS)
+
+add_executable(${PROJECT_NAME} ${SRCS} ${COMMON_SRCS})
+
+target_link_libraries(
+       ${PROJECT_NAME}
+       PUBLIC
+       #rfjb_button
+       #rfjb_led
+       #am_log
+    #curl
+       #log4c
+       #rt
+       #modbus
+       #z
+       ${GLIB2_LIBRARIES}
+       ${DBUS_LIBRARIES}
+    #sqlite3
+    #ssl
+    #crypto
+       pthread
+ )
+
+install(TARGETS ${PROJECT_NAME} RUNTIME DESTINATION /app)
+#install(PROGRAMS ${PROJECT_SOURCE_DIR}/alarm_d DESTINATION /app)
+#install(PROGRAMS ${PROJECT_SOURCE_DIR}/update_ota.sh DESTINATION /app)
+#install(PROGRAMS ${PROJECT_SOURCE_DIR}/S99_alarmmonitor DESTINATION /etc/init.d)
+#install(FILES ${PROJECT_SOURCE_DIR}/log4crc DESTINATION /app)
+install(FILES ${PROJECT_SOURCE_DIR}/com.yn.ui.conf    DESTINATION /etc/dbus-1/system.d)
+#install(FILES ${PROJECT_SOURCE_DIR}/com.yn.ui.service DESTINATION /usr/share/dbus-1/system-services)
diff --git a/app/com.yn.ui.conf b/app/com.yn.ui.conf
new file mode 100644 (file)
index 0000000..8f3fdc9
--- /dev/null
@@ -0,0 +1,15 @@
+<!DOCTYPE busconfig PUBLIC
+ "-//freedesktop//DTD D-BUS Bus Configuration 1.0//EN"
+ "http://www.freedesktop.org/standards/dbus/1.0/busconfig.dtd">
+<busconfig>
+  <policy user="root">
+    <allow own="com.yn.ui"/>
+    <allow send_destination="com.yn.ui"/>
+    <allow receive_sender="com.yn.ui"/>
+  </policy>
+  <policy context="default">
+    <allow send_destination="com.yn.ui"/>
+    <allow receive_sender="com.yn.ui"/>
+    <allow own="com.yn.ui.client"/>
+  </policy>
+</busconfig>
\ No newline at end of file
diff --git a/app/inc/ad_log.h b/app/inc/ad_log.h
new file mode 100644 (file)
index 0000000..7bad95b
--- /dev/null
@@ -0,0 +1,30 @@
+#ifndef __AD_LOG__H__
+#define __AD_LOG__H__
+
+#include <unistd.h>
+#include "log4c.h"
+
+extern log4c_category_t *ad_log_category;
+
+#define AD_LOG_CATEGORY ad_log_category
+
+#define AD_LOGF ad_log_fatal
+#define AD_LOGE ad_log_error
+#define AD_LOGW ad_log_warning
+#define AD_LOGN ad_log_notice
+#define AD_LOGI ad_log_info
+#define AD_LOGD ad_log_debug
+
+#define ad_log_fatal(...) log4c_category_log( AD_LOG_CATEGORY, LOG4C_PRIORITY_FATAL, __VA_ARGS__)
+#define ad_log_error(...) log4c_category_log( AD_LOG_CATEGORY, LOG4C_PRIORITY_ERROR, __VA_ARGS__)
+#define ad_log_warning(...) log4c_category_log( AD_LOG_CATEGORY, LOG4C_PRIORITY_WARN, __VA_ARGS__)
+#define ad_log_notice(...) log4c_category_log( AD_LOG_CATEGORY, LOG4C_PRIORITY_NOTICE, __VA_ARGS__)
+#define ad_log_info(...)  log4c_category_log( AD_LOG_CATEGORY, LOG4C_PRIORITY_INFO, __VA_ARGS__)
+#define ad_log_debug(...) log4c_category_log( AD_LOG_CATEGORY, LOG4C_PRIORITY_DEBUG, __VA_ARGS__)
+
+
+void ad_log_init( void );
+void ad_log_deinit( void );
+
+#endif //__AD_LOG__H__
+
diff --git a/app/inc/ad_version.h b/app/inc/ad_version.h
new file mode 100644 (file)
index 0000000..041c414
--- /dev/null
@@ -0,0 +1,6 @@
+#ifndef __AD_VERSION_H__
+#define __AD_VERSION_H__
+
+#define  AD_VERSION "1.1"
+
+#endif //__AD_VERSION_H__
diff --git a/app/inc/agridetect.h b/app/inc/agridetect.h
new file mode 100644 (file)
index 0000000..4949e63
--- /dev/null
@@ -0,0 +1,160 @@
+#ifndef __AGRIDETECT_H__
+#define __AGRIDETECT_H__
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <stdint.h>
+
+#include <time.h>
+#include <pthread.h>
+#include <modbus/modbus.h>
+#include <log4c.h>
+#include <sys/wait.h>
+
+#include "cQueue.h"
+#include "cJSON.h"
+
+#include "ad_log.h"
+#include "ad_version.h"
+
+/* 自检 / 测试 / 调试 / 配置相关类型统一以 dev_info.h 中定义为准
+ *   selftest_info_t / selftest_item_t / selftest_item_state_t
+ *   test_info_t     / test_step_t    / test_step_state_t
+ *   debug_info_t    / debug_state_t
+ *   device_cfg_t    / lxj_cfg_t / ody_cfg_t / yyq_cfg_t
+ * 以及全局实例 g_dev_info
+ */
+#include "dev_info.h"
+
+#ifdef __x86_64__
+
+//ON PC for debug ........
+#define FACTORY_CFG_PATH     "./factory.cfg"
+#define DEVICE_CFG_PATH       "./device.cfg"
+
+#define READ_UUID_CMD        "echo -n pc12345678901234"
+
+#define BUTTON_DEVICE_PATH   "/dev/input/event2"
+#define LED_DEVICE_PATH_FMT  "/sys/class/leds/%s/brightness"
+
+#define IR_DEV_PATH         "/dev/infrared"
+#define TEM_SENSOR_DEV_PATH "/dev/cht11"
+#define RN8302_DEV_PATH     "/dev/rn8302"
+#define JDQ_DEV_PATH        "/dev/jdq"
+
+#define PID_FILE            "/tmp/agridetect.pid"
+#define CUSTOM_NTP_CONF     "/tmp/custom_ntp.conf"
+
+#define SPK_UART_PATH       "/dev/ttyS1"
+#define TTS_UART_PATH       "/dev/ttyS3"
+#define LCD_UART_PATH       "/tmp/ttyLCD0"
+#define RS232_TOP_PATH      "/dev/ttyS5"  //主板上顶部RS232口
+#define MB_RTU_PORT_PATH_1  "/dev/ttyS6"
+
+#define EC200_AT_PORT       "/dev/ttyUSB2"
+#else
+
+//ON BOARD
+#define FACTORY_CFG_PATH     "/userdata/factory.cfg"
+#define DEVICE_CFG_PATH      "/userdata/device.cfg"
+#define READ_UUID_CMD        "cat /proc/cpuinfo | grep Serial"
+
+#define PID_FILE            "/var/run/agridetect/agridetect.pid"
+
+#define MB_RTU_PORT_PATH_1  "/dev/ttyS6"
+#define MB_RTU_PORT_PATH_2  "/dev/ttyS8"
+#define EC200_AT_PORT       "/dev/ttyUSB2"
+#endif
+
+
+
+
+
+typedef struct{
+    int dummy;
+}dev_cfg_t;
+
+typedef struct{
+    int dummy;
+}iot_cfg_t;   //
+
+
+
+
+
+//-------------------------------------------------------------------------------------
+//am_dev
+//void ad_dev_lock( am_dev_t *dev );
+//void ad_dev_unlock( am_dev_t *dev );
+//ad_dev_t * ad_dev_get( void );
+
+
+
+typedef struct{
+    uint8_t * base;
+    uint32_t sz;
+}tx_msg_t;
+
+tx_msg_t * tx_msg_new( const char* data, size_t len );
+
+
+#if 1
+
+typedef struct{
+    char serial[32];
+    char hw_version[32];
+}factory_info_t;
+
+//测试各个动作类型定义:
+typedef enum{
+    DEV_ACT_NONE = 0,  //无动作
+    DEV_ACT_1,         //设备动作1
+    DEV_ACT_2,         //设备动作2
+    DEV_ACT_3,         //设备动作3
+    DEV_ACT_4,         //设备动作4
+    DEV_ACT_5,         //设备动作5
+    DEV_ACT_6,         //设备动作6
+    DEV_ACT_7,         //设备动作7
+    DEV_ACT_8,         //设备动作8
+    DEV_ACT_9,         //设备动作9
+    DEV_ACT_10,        //设备动作10
+    ROB_ACT_1,         //机器人动作1
+    ROB_ACT_2,         //机器人动作2
+    ROB_ACT_3,         //机器人动作3
+    ROB_ACT_4,         //机器人动作4
+    ROB_ACT_5,         //机器人动作5
+    ROB_ACT_6,         //机器人动作6
+    ROB_ACT_7,         //机器人动作7
+    ROB_ACT_8,         //机器人动作8
+    ROB_ACT_9,         //机器人动作9
+    ROB_ACT_10,        //机器人动作10
+    ACT_NUM
+}test_act_t;
+
+/* 自动测试总步骤数(与 ad_main.c 注释中"1~20 步"一致,其中设备动作 ACT_NUM≈10) */
+#ifndef AUTOTEST_ACT_NUM
+#define AUTOTEST_ACT_NUM     20
+#endif
+
+
+/* 注:pipette_cfg_t / dev_state_t 类型已统一在 dev_info.h 中定义,
+       agridetect.h 通过 `#include "dev_info.h"` 引入,避免重复声明。
+       `device_cfg_t.yyq_cfg[YYQ_NUM_MAX]` +
+       `dev_param_get_pipette() / dev_param_set_pipette()` 取代。
+       g_dev_info (dev_info.h)
+       + dev_lock() / dev_unlock()
+   线程安全地访问状态/参数。
+*/
+
+#endif
+
+
+int32_t store_device_cfg( dev_cfg_t *cfg );
+int32_t load_device_cfg( dev_cfg_t *cfg );
+
+
+int32_t store_factory_info( factory_info_t *cfg );
+int32_t load_factory_info( factory_info_t *cfg );
+
+#endif //__AGRIDETECT_H__
\ No newline at end of file
diff --git a/app/inc/cJSON.h b/app/inc/cJSON.h
new file mode 100644 (file)
index 0000000..e96b8cf
--- /dev/null
@@ -0,0 +1,293 @@
+/*
+  Copyright (c) 2009-2017 Dave Gamble and cJSON contributors
+
+  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.
+*/
+
+#ifndef cJSON__h
+#define cJSON__h
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+#if !defined(__WINDOWS__) && (defined(WIN32) || defined(WIN64) || defined(_MSC_VER) || defined(_WIN32))
+#define __WINDOWS__
+#endif
+
+#ifdef __WINDOWS__
+
+/* When compiling for windows, we specify a specific calling convention to avoid issues where we are being called from a project with a different default calling convention.  For windows you have 3 define options:
+
+CJSON_HIDE_SYMBOLS - Define this in the case where you don't want to ever dllexport symbols
+CJSON_EXPORT_SYMBOLS - Define this on library build when you want to dllexport symbols (default)
+CJSON_IMPORT_SYMBOLS - Define this if you want to dllimport symbol
+
+For *nix builds that support visibility attribute, you can define similar behavior by
+
+setting default visibility to hidden by adding
+-fvisibility=hidden (for gcc)
+or
+-xldscope=hidden (for sun cc)
+to CFLAGS
+
+then using the CJSON_API_VISIBILITY flag to "export" the same symbols the way CJSON_EXPORT_SYMBOLS does
+
+*/
+
+#define CJSON_CDECL __cdecl
+#define CJSON_STDCALL __stdcall
+
+/* export symbols by default, this is necessary for copy pasting the C and header file */
+#if !defined(CJSON_HIDE_SYMBOLS) && !defined(CJSON_IMPORT_SYMBOLS) && !defined(CJSON_EXPORT_SYMBOLS)
+#define CJSON_EXPORT_SYMBOLS
+#endif
+
+#if defined(CJSON_HIDE_SYMBOLS)
+#define CJSON_PUBLIC(type)   type CJSON_STDCALL
+#elif defined(CJSON_EXPORT_SYMBOLS)
+#define CJSON_PUBLIC(type)   __declspec(dllexport) type CJSON_STDCALL
+#elif defined(CJSON_IMPORT_SYMBOLS)
+#define CJSON_PUBLIC(type)   __declspec(dllimport) type CJSON_STDCALL
+#endif
+#else /* !__WINDOWS__ */
+#define CJSON_CDECL
+#define CJSON_STDCALL
+
+#if (defined(__GNUC__) || defined(__SUNPRO_CC) || defined (__SUNPRO_C)) && defined(CJSON_API_VISIBILITY)
+#define CJSON_PUBLIC(type)   __attribute__((visibility("default"))) type
+#else
+#define CJSON_PUBLIC(type) type
+#endif
+#endif
+
+/* project version */
+#define CJSON_VERSION_MAJOR 1
+#define CJSON_VERSION_MINOR 7
+#define CJSON_VERSION_PATCH 12
+
+#include <stddef.h>
+
+/* cJSON Types: */
+#define cJSON_Invalid (0)
+#define cJSON_False  (1 << 0)
+#define cJSON_True   (1 << 1)
+#define cJSON_NULL   (1 << 2)
+#define cJSON_Number (1 << 3)
+#define cJSON_String (1 << 4)
+#define cJSON_Array  (1 << 5)
+#define cJSON_Object (1 << 6)
+#define cJSON_Raw    (1 << 7) /* raw json */
+
+#define cJSON_IsReference 256
+#define cJSON_StringIsConst 512
+
+/* The cJSON structure: */
+typedef struct cJSON
+{
+    /* next/prev allow you to walk array/object chains. Alternatively, use GetArraySize/GetArrayItem/GetObjectItem */
+    struct cJSON *next;
+    struct cJSON *prev;
+    /* An array or object item will have a child pointer pointing to a chain of the items in the array/object. */
+    struct cJSON *child;
+
+    /* The type of the item, as above. */
+    int type;
+
+    /* The item's string, if type==cJSON_String  and type == cJSON_Raw */
+    char *valuestring;
+    /* writing to valueint is DEPRECATED, use cJSON_SetNumberValue instead */
+    int valueint;
+    /* The item's number, if type==cJSON_Number */
+    double valuedouble;
+
+    /* The item's name string, if this item is the child of, or is in the list of subitems of an object. */
+    char *string;
+} cJSON;
+
+typedef struct cJSON_Hooks
+{
+      /* malloc/free are CDECL on Windows regardless of the default calling convention of the compiler, so ensure the hooks allow passing those functions directly. */
+      void *(CJSON_CDECL *malloc_fn)(size_t sz);
+      void (CJSON_CDECL *free_fn)(void *ptr);
+} cJSON_Hooks;
+
+typedef int cJSON_bool;
+
+/* Limits how deeply nested arrays/objects can be before cJSON rejects to parse them.
+ * This is to prevent stack overflows. */
+#ifndef CJSON_NESTING_LIMIT
+#define CJSON_NESTING_LIMIT 1000
+#endif
+
+/* Precision of double variables comparison */
+#ifndef CJSON_DOUBLE_PRECISION
+#define CJSON_DOUBLE_PRECISION .0000000000000001
+#endif
+
+/* returns the version of cJSON as a string */
+CJSON_PUBLIC(const char*) cJSON_Version(void);
+
+/* Supply malloc, realloc and free functions to cJSON */
+CJSON_PUBLIC(void) cJSON_InitHooks(cJSON_Hooks* hooks);
+
+/* Memory Management: the caller is always responsible to free the results from all variants of cJSON_Parse (with cJSON_Delete) and cJSON_Print (with stdlib free, cJSON_Hooks.free_fn, or cJSON_free as appropriate). The exception is cJSON_PrintPreallocated, where the caller has full responsibility of the buffer. */
+/* Supply a block of JSON, and this returns a cJSON object you can interrogate. */
+CJSON_PUBLIC(cJSON *) cJSON_Parse(const char *value);
+/* ParseWithOpts allows you to require (and check) that the JSON is null terminated, and to retrieve the pointer to the final byte parsed. */
+/* If you supply a ptr in return_parse_end and parsing fails, then return_parse_end will contain a pointer to the error so will match cJSON_GetErrorPtr(). */
+CJSON_PUBLIC(cJSON *) cJSON_ParseWithOpts(const char *value, const char **return_parse_end, cJSON_bool require_null_terminated);
+
+/* Render a cJSON entity to text for transfer/storage. */
+CJSON_PUBLIC(char *) cJSON_Print(const cJSON *item);
+/* Render a cJSON entity to text for transfer/storage without any formatting. */
+CJSON_PUBLIC(char *) cJSON_PrintUnformatted(const cJSON *item);
+/* Render a cJSON entity to text using a buffered strategy. prebuffer is a guess at the final size. guessing well reduces reallocation. fmt=0 gives unformatted, =1 gives formatted */
+CJSON_PUBLIC(char *) cJSON_PrintBuffered(const cJSON *item, int prebuffer, cJSON_bool fmt);
+/* Render a cJSON entity to text using a buffer already allocated in memory with given length. Returns 1 on success and 0 on failure. */
+/* NOTE: cJSON is not always 100% accurate in estimating how much memory it will use, so to be safe allocate 5 bytes more than you actually need */
+CJSON_PUBLIC(cJSON_bool) cJSON_PrintPreallocated(cJSON *item, char *buffer, const int length, const cJSON_bool format);
+/* Delete a cJSON entity and all subentities. */
+CJSON_PUBLIC(void) cJSON_Delete(cJSON *item);
+
+/* Returns the number of items in an array (or object). */
+CJSON_PUBLIC(int) cJSON_GetArraySize(const cJSON *array);
+/* Retrieve item number "index" from array "array". Returns NULL if unsuccessful. */
+CJSON_PUBLIC(cJSON *) cJSON_GetArrayItem(const cJSON *array, int index);
+/* Get item "string" from object. Case insensitive. */
+CJSON_PUBLIC(cJSON *) cJSON_GetObjectItem(const cJSON * const object, const char * const string);
+CJSON_PUBLIC(cJSON *) cJSON_GetObjectItemCaseSensitive(const cJSON * const object, const char * const string);
+CJSON_PUBLIC(cJSON_bool) cJSON_HasObjectItem(const cJSON *object, const char *string);
+/* For analysing failed parses. This returns a pointer to the parse error. You'll probably need to look a few chars back to make sense of it. Defined when cJSON_Parse() returns 0. 0 when cJSON_Parse() succeeds. */
+CJSON_PUBLIC(const char *) cJSON_GetErrorPtr(void);
+
+/* Check if the item is a string and return its valuestring */
+CJSON_PUBLIC(char *) cJSON_GetStringValue(const cJSON * const item);
+
+/* These functions check the type of an item */
+CJSON_PUBLIC(cJSON_bool) cJSON_IsInvalid(const cJSON * const item);
+CJSON_PUBLIC(cJSON_bool) cJSON_IsFalse(const cJSON * const item);
+CJSON_PUBLIC(cJSON_bool) cJSON_IsTrue(const cJSON * const item);
+CJSON_PUBLIC(cJSON_bool) cJSON_IsBool(const cJSON * const item);
+CJSON_PUBLIC(cJSON_bool) cJSON_IsNull(const cJSON * const item);
+CJSON_PUBLIC(cJSON_bool) cJSON_IsNumber(const cJSON * const item);
+CJSON_PUBLIC(cJSON_bool) cJSON_IsString(const cJSON * const item);
+CJSON_PUBLIC(cJSON_bool) cJSON_IsArray(const cJSON * const item);
+CJSON_PUBLIC(cJSON_bool) cJSON_IsObject(const cJSON * const item);
+CJSON_PUBLIC(cJSON_bool) cJSON_IsRaw(const cJSON * const item);
+
+/* These calls create a cJSON item of the appropriate type. */
+CJSON_PUBLIC(cJSON *) cJSON_CreateNull(void);
+CJSON_PUBLIC(cJSON *) cJSON_CreateTrue(void);
+CJSON_PUBLIC(cJSON *) cJSON_CreateFalse(void);
+CJSON_PUBLIC(cJSON *) cJSON_CreateBool(cJSON_bool boolean);
+CJSON_PUBLIC(cJSON *) cJSON_CreateNumber(double num);
+CJSON_PUBLIC(cJSON *) cJSON_CreateString(const char *string);
+/* raw json */
+CJSON_PUBLIC(cJSON *) cJSON_CreateRaw(const char *raw);
+CJSON_PUBLIC(cJSON *) cJSON_CreateArray(void);
+CJSON_PUBLIC(cJSON *) cJSON_CreateObject(void);
+
+/* Create a string where valuestring references a string so
+ * it will not be freed by cJSON_Delete */
+CJSON_PUBLIC(cJSON *) cJSON_CreateStringReference(const char *string);
+/* Create an object/array that only references it's elements so
+ * they will not be freed by cJSON_Delete */
+CJSON_PUBLIC(cJSON *) cJSON_CreateObjectReference(const cJSON *child);
+CJSON_PUBLIC(cJSON *) cJSON_CreateArrayReference(const cJSON *child);
+
+/* These utilities create an Array of count items.
+ * The parameter count cannot be greater than the number of elements in the number array, otherwise array access will be out of bounds.*/
+CJSON_PUBLIC(cJSON *) cJSON_CreateIntArray(const int *numbers, int count);
+CJSON_PUBLIC(cJSON *) cJSON_CreateFloatArray(const float *numbers, int count);
+CJSON_PUBLIC(cJSON *) cJSON_CreateDoubleArray(const double *numbers, int count);
+CJSON_PUBLIC(cJSON *) cJSON_CreateStringArray(const char *const *strings, int count);
+
+/* Append item to the specified array/object. */
+CJSON_PUBLIC(void) cJSON_AddItemToArray(cJSON *array, cJSON *item);
+CJSON_PUBLIC(void) cJSON_AddItemToObject(cJSON *object, const char *string, cJSON *item);
+/* Use this when string is definitely const (i.e. a literal, or as good as), and will definitely survive the cJSON object.
+ * WARNING: When this function was used, make sure to always check that (item->type & cJSON_StringIsConst) is zero before
+ * writing to `item->string` */
+CJSON_PUBLIC(void) cJSON_AddItemToObjectCS(cJSON *object, const char *string, cJSON *item);
+/* Append reference to item to the specified array/object. Use this when you want to add an existing cJSON to a new cJSON, but don't want to corrupt your existing cJSON. */
+CJSON_PUBLIC(void) cJSON_AddItemReferenceToArray(cJSON *array, cJSON *item);
+CJSON_PUBLIC(void) cJSON_AddItemReferenceToObject(cJSON *object, const char *string, cJSON *item);
+
+/* Remove/Detach items from Arrays/Objects. */
+CJSON_PUBLIC(cJSON *) cJSON_DetachItemViaPointer(cJSON *parent, cJSON * const item);
+CJSON_PUBLIC(cJSON *) cJSON_DetachItemFromArray(cJSON *array, int which);
+CJSON_PUBLIC(void) cJSON_DeleteItemFromArray(cJSON *array, int which);
+CJSON_PUBLIC(cJSON *) cJSON_DetachItemFromObject(cJSON *object, const char *string);
+CJSON_PUBLIC(cJSON *) cJSON_DetachItemFromObjectCaseSensitive(cJSON *object, const char *string);
+CJSON_PUBLIC(void) cJSON_DeleteItemFromObject(cJSON *object, const char *string);
+CJSON_PUBLIC(void) cJSON_DeleteItemFromObjectCaseSensitive(cJSON *object, const char *string);
+
+/* Update array items. */
+CJSON_PUBLIC(void) cJSON_InsertItemInArray(cJSON *array, int which, cJSON *newitem); /* Shifts pre-existing items to the right. */
+CJSON_PUBLIC(cJSON_bool) cJSON_ReplaceItemViaPointer(cJSON * const parent, cJSON * const item, cJSON * replacement);
+CJSON_PUBLIC(void) cJSON_ReplaceItemInArray(cJSON *array, int which, cJSON *newitem);
+CJSON_PUBLIC(void) cJSON_ReplaceItemInObject(cJSON *object,const char *string,cJSON *newitem);
+CJSON_PUBLIC(void) cJSON_ReplaceItemInObjectCaseSensitive(cJSON *object,const char *string,cJSON *newitem);
+
+/* Duplicate a cJSON item */
+CJSON_PUBLIC(cJSON *) cJSON_Duplicate(const cJSON *item, cJSON_bool recurse);
+/* Duplicate will create a new, identical cJSON item to the one you pass, in new memory that will
+ * need to be released. With recurse!=0, it will duplicate any children connected to the item.
+ * The item->next and ->prev pointers are always zero on return from Duplicate. */
+/* Recursively compare two cJSON items for equality. If either a or b is NULL or invalid, they will be considered unequal.
+ * case_sensitive determines if object keys are treated case sensitive (1) or case insensitive (0) */
+CJSON_PUBLIC(cJSON_bool) cJSON_Compare(const cJSON * const a, const cJSON * const b, const cJSON_bool case_sensitive);
+
+/* Minify a strings, remove blank characters(such as ' ', '\t', '\r', '\n') from strings.
+ * The input pointer json cannot point to a read-only address area, such as a string constant,
+ * but should point to a readable and writable adress area. */
+CJSON_PUBLIC(void) cJSON_Minify(char *json);
+
+/* Helper functions for creating and adding items to an object at the same time.
+ * They return the added item or NULL on failure. */
+CJSON_PUBLIC(cJSON*) cJSON_AddNullToObject(cJSON * const object, const char * const name);
+CJSON_PUBLIC(cJSON*) cJSON_AddTrueToObject(cJSON * const object, const char * const name);
+CJSON_PUBLIC(cJSON*) cJSON_AddFalseToObject(cJSON * const object, const char * const name);
+CJSON_PUBLIC(cJSON*) cJSON_AddBoolToObject(cJSON * const object, const char * const name, const cJSON_bool boolean);
+CJSON_PUBLIC(cJSON*) cJSON_AddNumberToObject(cJSON * const object, const char * const name, const double number);
+CJSON_PUBLIC(cJSON*) cJSON_AddStringToObject(cJSON * const object, const char * const name, const char * const string);
+CJSON_PUBLIC(cJSON*) cJSON_AddRawToObject(cJSON * const object, const char * const name, const char * const raw);
+CJSON_PUBLIC(cJSON*) cJSON_AddObjectToObject(cJSON * const object, const char * const name);
+CJSON_PUBLIC(cJSON*) cJSON_AddArrayToObject(cJSON * const object, const char * const name);
+
+/* When assigning an integer value, it needs to be propagated to valuedouble too. */
+#define cJSON_SetIntValue(object, number) ((object) ? (object)->valueint = (object)->valuedouble = (number) : (number))
+/* helper for the cJSON_SetNumberValue macro */
+CJSON_PUBLIC(double) cJSON_SetNumberHelper(cJSON *object, double number);
+#define cJSON_SetNumberValue(object, number) ((object != NULL) ? cJSON_SetNumberHelper(object, (double)number) : (number))
+
+/* Macro for iterating over an array or object */
+#define cJSON_ArrayForEach(element, array) for(element = (array != NULL) ? (array)->child : NULL; element != NULL; element = element->next)
+
+/* malloc/free objects using the malloc/free functions that have been set with cJSON_InitHooks */
+CJSON_PUBLIC(void *) cJSON_malloc(size_t size);
+CJSON_PUBLIC(void) cJSON_free(void *object);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/app/inc/cQueue.h b/app/inc/cQueue.h
new file mode 100644 (file)
index 0000000..8b02a3f
--- /dev/null
@@ -0,0 +1,39 @@
+#ifndef cQUEUE_H
+#define cQUEUE_H
+
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+#define cQueue_API_DECL extern
+
+/*------------------------------------------------------------------------------------------------*/
+typedef struct cQueue{          /* Queue control block  */
+    void            **QMemory;  /* pointer to message queue storage area                          */
+    void            **QStart;   /* pointer to start of queue data                                 */
+    void            **QEnd;     /* pointer to end   of queue data                                 */
+    void            **QIn;      /* pointer to where next message will be inserted in the queue    */
+    void            **QOut;     /* pointer to where next message will be extracted from the queue */
+    int             QSize;      /* size of queue -- max number of entries                         */
+    int             QEntries;   /* current number of entries in the queue                         */
+} cQueue_t;
+
+#define ERR_Q_NONE      0
+#define ERR_Q_FULL      1
+#define ERR_Q_EMPTY     2
+
+cQueue_API_DECL cQueue_t *cQcreate(int size);
+cQueue_API_DECL void cQDelete(cQueue_t *pq);
+cQueue_API_DECL void cQFlush(cQueue_t *pq);
+cQueue_API_DECL void *cQRcv(cQueue_t *pq, char *perr);
+cQueue_API_DECL int cQPost(cQueue_t *pq, void *pmsg);
+cQueue_API_DECL int cQPostFront(cQueue_t *pq, void *pmsg);
+
+/*--------------------------------------------------------*/
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/app/inc/dev_info.h b/app/inc/dev_info.h
new file mode 100644 (file)
index 0000000..88d0eff
--- /dev/null
@@ -0,0 +1,202 @@
+#ifndef __DEV_INFO_H__
+#define __DEV_INFO_H__
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <stdint.h>
+#include <time.h>
+#include <pthread.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#define SELFTEST_ITEM_MAX      10
+#define TEST_STEP_MAX          10
+#define DEVICE_NAME_LEN        32
+#define FAULT_MSG_LEN          64
+#define YYQ_NUM_MAX            4
+
+/* UI 层顶层状态机(取代原 agridetect_t.state) */
+typedef enum {
+    DEV_INIT = 0,
+    DEV_SELFTESTING,
+    DEV_SELFTEST_FAILED,
+    DEV_READY,
+    DEV_TESTING,
+    DEV_TEST_PAUSED,
+    DEV_TEST_ERROR,
+    DEV_TEST_COMPLETED,
+    DEV_MANUAL_DEBUG,
+    DEV_STATE_NUM
+} dev_state_t;
+
+
+
+typedef enum {
+    ST_ITEM_PENDING = 0,
+    ST_ITEM_TESTING,
+    ST_ITEM_PASS,
+    ST_ITEM_FAIL
+} selftest_item_state_t;
+
+typedef struct {
+    int                     id;
+    char                    name[DEVICE_NAME_LEN];
+    selftest_item_state_t   state;
+    int32_t                 fault_code;
+    char                    fault_msg[FAULT_MSG_LEN];
+    time_t                  start_time;
+    time_t                  end_time;
+    uint32_t                duration_ms;
+} selftest_item_t;
+
+typedef struct {
+    selftest_item_t         items[SELFTEST_ITEM_MAX];
+    int                     item_count;
+    int                     current_idx;
+    int32_t                 total_fault_code;
+    time_t                  start_time;
+    time_t                  end_time;
+    uint32_t                total_duration_ms;
+} selftest_info_t;
+
+typedef enum {
+    TEST_STEP_IDLE = 0,
+    TEST_STEP_RUNNING = 2,
+    TEST_STEP_PASS = 1,
+    TEST_STEP_FAIL = -1
+} test_step_state_t;
+
+typedef struct {
+    int                     step_id;
+    char                    name[DEVICE_NAME_LEN];
+    test_step_state_t       state;
+    int32_t                 fault_code;
+    char                    fault_msg[FAULT_MSG_LEN];
+    time_t                  start_time;
+    time_t                  end_time;
+    uint32_t                duration_ms;
+    int32_t                 remain_time_s;
+    int32_t                 total_time_s;
+} test_step_t;
+
+typedef struct {
+    test_step_t             steps[TEST_STEP_MAX];
+    int                     step_count;
+    int                     current_step;
+    int32_t                 total_fault_code;
+    time_t                  start_time;
+    time_t                  end_time;
+    uint32_t                total_duration_ms;
+} test_info_t;
+
+typedef enum {
+    DEBUG_IDLE = 0,
+    DEBUG_RUNNING,
+    DEBUG_DONE,
+    DEBUG_FAULT
+} debug_state_t;
+
+typedef struct {
+    int                     cmd_id;
+    char                    cmd_name[DEVICE_NAME_LEN];
+    debug_state_t           state;
+    int32_t                 fault_code;
+    char                    fault_msg[FAULT_MSG_LEN];
+    time_t                  start_time;
+    time_t                  end_time;
+    uint32_t                duration_ms;
+} debug_info_t;
+
+typedef struct {
+    int                     lxj_work_time_s;
+    int                     lxj_speed_rpm;
+} lxj_cfg_t;
+
+typedef struct {
+    int                     ody_work_time_s;
+    int                     ody_speed_rpm;
+} ody_cfg_t;
+
+typedef struct {
+    int                     x1;
+    int                     y1;
+    int                     z1;
+    int                     x2;
+    int                     y2;
+    int                     z2;
+} yyq_cfg_t;
+typedef yyq_cfg_t pipette_cfg_t; /* agridetect.h 里的名字 */
+
+typedef struct {
+    int                     selftest_item_number;
+    int                     test_step_number;
+    lxj_cfg_t               lxj_cfg;
+    ody_cfg_t               ody_cfg;
+    yyq_cfg_t               yyq_cfg[YYQ_NUM_MAX];
+} device_cfg_t;
+
+typedef struct {
+    dev_state_t             state;       /* 统一的顶层状态机(UI/业务层共用) */
+    selftest_info_t         selftest;
+    test_info_t             test;
+    debug_info_t            debug;
+    device_cfg_t            cfg;
+    pthread_mutex_t         lock;
+} dev_info_t;
+
+extern dev_info_t g_dev_info;
+
+/* 对外暴露的加锁 / 解锁(原 dev_info.c 内部 static,现已公开) */
+void        dev_lock(void);
+void        dev_unlock(void);
+
+int         dev_info_init(void);
+int         dev_info_deinit(void);
+
+/* 顶层状态机访问:线程安全(UI/D-Bus/业务层统一使用) */
+dev_state_t dev_get_state(void);
+int         dev_set_state(dev_state_t s);
+
+/* param (移液器配置) 访问:pip_id ∈ [1, YYQ_NUM_MAX] */
+int         dev_param_get_pipette(int pip_id, pipette_cfg_t *out);
+int         dev_param_set_pipette(int pip_id, const pipette_cfg_t *cfg);
+
+int         dev_selftest_set_item_name(int idx, const char *name);
+int         dev_selftest_start_item(int idx);
+int         dev_selftest_pass_item(int idx);
+int         dev_selftest_fail_item(int idx, int32_t fault_code, const char *fault_msg);
+int         dev_selftest_start_all(void);
+int         dev_selftest_finish_all(int32_t total_fault);
+int         dev_selftest_get_item(int idx, selftest_item_t *out);
+int         dev_selftest_get_info(selftest_info_t *out);
+
+int         dev_test_set_step_name(int idx, const char *name);
+int         dev_test_set_step_timing(int idx, int32_t total_time_s);
+int         dev_test_start_step(int step_idx);
+int         dev_test_update_remain(int step_idx, int32_t remain_s);
+int         dev_test_pass_step(int step_idx);
+int         dev_test_fail_step(int step_idx, int32_t fault_code, const char *fault_msg);
+int         dev_test_start_all(void);
+int         dev_test_finish_all(int32_t total_fault);
+int         dev_test_get_step(int idx, test_step_t *out);
+int         dev_test_get_info(test_info_t *out);
+
+int         dev_debug_start(int cmd_id, const char *cmd_name);
+int         dev_debug_finish(int32_t fault_code, const char *fault_msg);
+int         dev_debug_get_info(debug_info_t *out);
+
+int         dev_cfg_set_lxj(int work_time_s, int speed_rpm);
+int         dev_cfg_set_ody(int work_time_s, int speed_rpm);
+int         dev_cfg_set_yyq(int idx, int x1, int y1, int z1, int x2, int y2, int z2);
+int         dev_cfg_get(device_cfg_t *out);
+
+int         dev_reset_to_normal(void);
+int         dev_get_snapshot(dev_info_t *out);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
\ No newline at end of file
diff --git a/app/inc/maintask.h b/app/inc/maintask.h
new file mode 100644 (file)
index 0000000..c9be8f8
--- /dev/null
@@ -0,0 +1,94 @@
+#ifndef __MAINTASK_H__
+#define __MAINTASK_H__
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#include <stdint.h>
+#include "agridetect.h"
+#include "dev_info.h"
+
+/*=============================================================================
+ * 主任务模块 (main task / FSM)
+ *  架构:
+ *   - 启动一个 "main_task_thread" 串行化执行所有设备业务 (初始化/自检/测试/调试)
+ *   - D-Bus UI 线程接收命令后,通过 cmd_queue 将命令投递到主任务线程
+ *   - 主任务 FSM 每个可取消点 (每个步骤之间 / 每个延时内部) 检查暂停/停止请求
+ *   - 状态/自检项/测试步统一写入 g_dev_info (dev_info.h)
+ *   - UI 通过 query_state D-Bus 接口读取,或通过 ui_srv_send_event signal 推送
+ *
+ * UI (触摸屏) cmd -> dbus -> ui.c weak ad_cmd_xxx() -> maintask_cmd_post()
+ *                                                            |
+ *                                                            v
+ *                                                main_task_thread loop
+ *                                                - 解 cmd
+ *                                                - 执行 自检 / 自动测试 / 调试步
+ *                                                - 更新 dev state
+ *                                                - 发 state_changed signal
+ *===========================================================================*/
+
+/* 主任务支持的命令 (与 ui.c 中 dbus 的 cmd 对齐) */
+typedef enum {
+    MT_CMD_NONE = 0,
+    MT_CMD_START_AUTOTEST,
+    MT_CMD_PAUSE_AUTOTEST,
+    MT_CMD_RESUME_AUTOTEST,
+    MT_CMD_STOP_AUTOTEST,
+    MT_CMD_ENTER_DEBUG,
+    MT_CMD_EXIT_DEBUG,
+    MT_CMD_DEBUG_ACTION,
+    MT_CMD_FAULT_RESET,
+    MT_CMD_EXIT_SELFTEST_FAILED,
+    MT_CMD_CHANGE_MODE,
+} mt_cmd_type_t;
+
+typedef struct {
+    mt_cmd_type_t   type;
+    int             int_arg0;       /* debug_action 的 act_id,或 change_mode 的 mode 等 */
+    void           *ptr_arg;
+} mt_cmd_t;
+
+/*==== 生命周期 ====*/
+int  maintask_init(void);        /* 创建线程/队列;自动进入 DEV_INIT -> DEV_SELFTESTING -> DEV_READY */
+void maintask_deinit(void);      /* 停止线程 释放资源 */
+
+/*==== 命令投递 (D-Bus/UI 回调调用,非阻塞) ====*/
+int  maintask_cmd_post(const mt_cmd_t *cmd);
+
+/*==== 便捷封装,给 ui.c weak 函数直接调用 ====*/
+static inline int mt_cmd_start_autotest(void)       { mt_cmd_t c={MT_CMD_START_AUTOTEST}; return maintask_cmd_post(&c); }
+static inline int mt_cmd_pause_autotest(void)       { mt_cmd_t c={MT_CMD_PAUSE_AUTOTEST}; return maintask_cmd_post(&c); }
+static inline int mt_cmd_resume_autotest(void)      { mt_cmd_t c={MT_CMD_RESUME_AUTOTEST};return maintask_cmd_post(&c); }
+static inline int mt_cmd_stop_autotest(void)        { mt_cmd_t c={MT_CMD_STOP_AUTOTEST};  return maintask_cmd_post(&c); }
+static inline int mt_cmd_enter_debug(void)          { mt_cmd_t c={MT_CMD_ENTER_DEBUG};    return maintask_cmd_post(&c); }
+static inline int mt_cmd_exit_debug(void)           { mt_cmd_t c={MT_CMD_EXIT_DEBUG};     return maintask_cmd_post(&c); }
+static inline int mt_cmd_debug_action(int act_id)   { mt_cmd_t c={MT_CMD_DEBUG_ACTION,.int_arg0=act_id}; return maintask_cmd_post(&c); }
+static inline int mt_cmd_fault_reset(void)          { mt_cmd_t c={MT_CMD_FAULT_RESET};    return maintask_cmd_post(&c); }
+static inline int mt_cmd_exit_selftest_failed(void) { mt_cmd_t c={MT_CMD_EXIT_SELFTEST_FAILED}; return maintask_cmd_post(&c); }
+static inline int mt_cmd_change_mode(int mode)      { mt_cmd_t c={MT_CMD_CHANGE_MODE,.int_arg0=mode}; return maintask_cmd_post(&c); }
+
+/*==== 任务协作接口:自动测试 / 调试动作可实现文件使用 ====*/
+
+/* 检测当前是否请求了暂停或停止:
+ * 返回:  0 继续
+ *        1 已暂停 (进入阻塞式等恢复)
+ *       -1 已请求停止
+ * 注意:测试动作每一步前必须调用,一旦返回 -1 要立刻清理资源并退出当前测试函数
+ */
+int  maintask_should_stop(void);
+int  maintask_breakpoint(void);    /* 在步骤之间调用:处理暂停+检查停止。返回 0 继续,-1 停止 */
+
+/* 可取消的 sleep:暂停时会挂起计时,停止时立即返回 -1 */
+int  maintask_cancellable_sleep_ms(int ms_total);
+
+/* 测试步骤进度 / 状态变更时主动通知 UI */
+void maintask_notify_state_changed(const char *extra_json);
+
+/* 对外查询主任务是否运行中 (线程存活) */
+int  maintask_is_running(void);
+
+#ifdef __cplusplus
+}
+#endif
+#endif /* __MAINTASK_H__ */
\ No newline at end of file
diff --git a/app/inc/motor.h b/app/inc/motor.h
new file mode 100644 (file)
index 0000000..968eb46
--- /dev/null
@@ -0,0 +1,138 @@
+#ifndef __MOTOR_H__
+#define __MOTOR_H__
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#include <stdint.h>
+
+/*===========================================================================
+ * 雷赛 DM2B 系列驱控一体步进驱动器 (RS485 Modbus RTU) 高层控制接口
+ * 控制范式:PR 路径模式
+ *   - 每个驱动器最多支持 16 段路径 (PR0 ~ PR15)
+ *   - 主机先将某段路径的参数 (模式/位置/速度/加减速度) 通过 Modbus 写入驱动器
+ *   - 之后仅需写"触发寄存器",驱动器即自动执行该段路径
+ *   - 运行过程中主机可轮询 0x1003 状态寄存器直到 Bit5(路径完成) 置位
+ *=========================================================================*/
+
+#define MOTOR_PATH_MAX          16      /* PR 路径数量上限 PR0~PR15 */
+#define MOTOR_DEF_RS485_PORT    "/dev/ttyS4"
+#define MOTOR_DEF_BAUD          115200
+#define MOTOR_DEF_MOVE_TIMEOUT  30000   /* 单段路径默认超时 (ms) */
+
+/* ---- 返回值 / 错误码 ---- */
+enum {
+    MOTOR_OK = 0,
+    MOTOR_ERR_PARAM = -1000,
+    MOTOR_ERR_COMM,
+    MOTOR_ERR_NOT_INIT,
+    MOTOR_ERR_TIMEOUT,
+    MOTOR_ERR_FAULT,
+    MOTOR_ERR_PATH_NO,
+};
+
+/* ---- PR 路径运行模式 (写 0x62n0) ---- */
+typedef enum {
+    PR_MODE_ABS_POS = 1,        /* 绝对位置 */
+    PR_MODE_REL_POS = 2,        /* 相对位置 */
+    PR_MODE_HOME    = 8,        /* 回零模式 (只在需要走 PR 式回零时用) */
+} pr_mode_t;
+
+/* ---- 0x1003 运行状态寄存器位定义 ---- */
+#define MOTOR_ST_FAULT          (1u << 0)
+#define MOTOR_ST_ENABLE         (1u << 1)
+#define MOTOR_ST_RUNNING        (1u << 2)
+/* Bit3 保留 */
+#define MOTOR_ST_INSN_DONE      (1u << 4)   /* 指令完成 */
+#define MOTOR_ST_PATH_DONE      (1u << 5)   /* 路径完成 (主要等待位) */
+#define MOTOR_ST_HOME_DONE      (1u << 6)   /* 回零完成 */
+
+/* ---- 0x2203 故障代码 ---- */
+#define MOTOR_ALM_OVERCURRENT       0x001
+#define MOTOR_ALM_OVERVOLTAGE       0x002
+#define MOTOR_ALM_ADC_FAULT         0x040
+#define MOTOR_ALM_PHASE_LOSS        0x080
+#define MOTOR_ALM_EEPROM            0x200
+#define MOTOR_ALM_AUTO_TUNE         0x100
+#define MOTOR_ALM_IO_CFG_REPEAT     0x009
+
+/* ------------------------------------------------------------------------- */
+/*  总线 / 生命周期                                                          */
+/* ------------------------------------------------------------------------- */
+int  motor_bus_init(const char *port, int baud);
+void motor_bus_deinit(void);
+
+/* ------------------------------------------------------------------------- */
+/*  单个驱动器基础操作                                                       */
+/* ------------------------------------------------------------------------- */
+int  motor_ping(uint8_t slave);
+int  motor_enable(uint8_t slave, int on);
+int  motor_clear_alarm(uint8_t slave);
+int  motor_stop_emergency(uint8_t slave);
+int  motor_read_state(uint8_t slave, uint16_t *out_state);
+int  motor_read_alarm(uint8_t slave, uint16_t *out_alarm);
+int  motor_read_curpos(uint8_t slave, int32_t *out_pos);
+
+/* ------------------------------------------------------------------------- */
+/*  PR 路径模式接口                                                          */
+/* ------------------------------------------------------------------------- */
+
+/**
+ * @brief 配置指定驱动器的某一段 PR 路径参数
+ *
+ * @param slave      驱动器从站地址 (1~247)
+ * @param path_no    路径编号 (0 ~ MOTOR_PATH_MAX-1)
+ * @param mode       PR_MODE_ABS_POS / PR_MODE_REL_POS
+ * @param pos        目标位置 (脉冲数,32bit)
+ * @param speed_rpm  运行速度 (rpm)
+ * @param accel      加速度
+ * @param decel      减速度
+ * @return int       MOTOR_OK or 错误码
+ */
+int  motor_setup_path(uint8_t slave, uint8_t path_no,
+                      pr_mode_t mode, int32_t pos,
+                      uint16_t speed_rpm, uint16_t accel, uint16_t decel);
+
+/**
+ * @brief 触发驱动器执行指定 PR 路径,并阻塞等待路径完成
+ *
+ * @param slave      驱动器从站地址
+ * @param path_no    路径编号 (0~15)
+ * @param timeout_ms 超时毫秒
+ * @param out_alarm  非 NULL 时,若发生故障回传报警码
+ * @return int       MOTOR_OK or 错误码
+ */
+int  motor_trigger_path_wait(uint8_t slave, uint8_t path_no,
+                             int timeout_ms, uint16_t *out_alarm);
+
+/**
+ * @brief 触发驱动器执行指定 PR 路径 (不等待,立即返回)
+ */
+int  motor_trigger_path_async(uint8_t slave, uint8_t path_no);
+
+/**
+ * @brief 等待当前运动路径完成 / 故障 / 超时
+ */
+int  motor_wait_path_done(uint8_t slave, int timeout_ms, uint16_t *out_alarm);
+
+/**
+ * @brief 执行回零 (通过触发 HOME 专用流程)
+ *        等价于 setup home 参数 + 触发 + 等待 HOME_DONE 标志
+ * @return MOTOR_OK or 错误码
+ */
+int  motor_home(uint8_t slave, int timeout_ms);
+
+/* ------------------------------------------------------------------------- */
+/*  从站地址帮助: 4 移液器 × 3 轴 共 12 轴,从站号 1~12 依次分配             */
+/* ------------------------------------------------------------------------- */
+static inline int motor_slave_of(int pip_id, int axis)
+{
+    /* pip_id 从 1 开始;axis 0=X,1=Y,2=Z */
+    return (pip_id - 1) * 3 + axis + 1;
+}
+
+#ifdef __cplusplus
+}
+#endif
+#endif /* __MOTOR_H__ */
\ No newline at end of file
diff --git a/app/inc/pipette.h b/app/inc/pipette.h
new file mode 100644 (file)
index 0000000..ab6d13d
--- /dev/null
@@ -0,0 +1,92 @@
+#ifndef __PIPETTE_H__
+#define __PIPETTE_H__
+
+#include <stdio.h>
+#include <stdint.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#define PIPETTE_ID_MIN            1
+#define PIPETTE_ID_MAX            4
+#define PIPETTE_NUM               (PIPETTE_ID_MAX)
+
+#define PIPETTE_OK                0
+#define PIPETTE_ERR_COMM         -1
+#define PIPETTE_ERR_ID           -2
+#define PIPETTE_ERR_NO_ACT       -3
+#define PIPETTE_ERR_AXIS         -4
+#define PIPETTE_ERR_MOVE         -5
+#define PIPETTE_ERR_TIMEOUT      -6
+#define PIPETTE_ERR_NOT_INIT     -7
+#define PIPETTE_ERR_PARAM        -8
+
+#define PIPETTE_AXIS_X            0
+#define PIPETTE_AXIS_Y            1
+#define PIPETTE_AXIS_Z            2
+#define PIPETTE_AXIS_NUM          3
+
+#define PIPETTE_ACT_TABLE_SIZE    16
+#define PIPETTE_STEP_MAX          32
+
+#define PIPETTE_DEF_RS485_PORT    "/dev/ttyS6"
+#define PIPETTE_DEF_BAUD          115200
+#define PIPETTE_DEF_MOVE_TIMEOUT  15000
+
+#define PIPETTE_STATE_IDLE        0
+#define PIPETTE_STATE_BUSY        1
+#define PIPETTE_STATE_FAULT       2
+#define PIPETTE_STATE_NOINIT      3
+
+typedef struct {
+    int         axis;
+    int         pos_from;
+    int         pos_to;
+    int         delay_ms;
+} pipette_step_t;
+
+typedef struct {
+    int             act_id;
+    const char     *name;
+    int             step_num;
+    pipette_step_t  step[PIPETTE_STEP_MAX];
+} pipette_act_t;
+
+typedef struct {
+    int x_origin;
+    int x_pos1;
+    int x_pos2;
+    int y_origin;
+    int y_pos1;
+    int y_pos2;
+    int z_origin;
+    int z_pos1;
+    int z_pos2;
+} pipette_pos_t;
+
+int  pipette_init(int id);
+int  pipette_deinit(int id);
+int  pipette_init_all(void);
+void pipette_deinit_all(void);
+
+int  pipette_is_inited(int id);
+
+int  pipette_act(int id, int act_id);
+
+int  pipette_axis_move(int id, int axis, int pos, int timeout_ms);
+int  pipette_axis_home(int id, int axis);
+int  pipette_get_axis_pos(int id, int axis, int *out_pos);
+
+int  pipette_get_state(int id);
+int  pipette_get_last_error(int id, char *buf, int buf_len);
+
+int  pipette_set_act_table(int id, const pipette_act_t *table, int count);
+int  pipette_get_positions(int id, pipette_pos_t *out);
+int  pipette_set_positions(int id, const pipette_pos_t *cfg);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
\ No newline at end of file
diff --git a/app/inc/robot.h b/app/inc/robot.h
new file mode 100644 (file)
index 0000000..a03ca32
--- /dev/null
@@ -0,0 +1,65 @@
+#ifndef __ROBOT_H__
+#define __ROBOT_H__
+
+#include <stdio.h>
+#include <stdint.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#define ROBOT_OK               0
+#define ROBOT_ERR_COMM        -1
+#define ROBOT_ERR_NO_SAMPLE   -2
+#define ROBOT_ERR_NO_ACT      -3
+#define ROBOT_ERR_TIMEOUT     -4
+#define ROBOT_ERR_EXEC        -5
+#define ROBOT_ERR_NOT_CONN    -6
+#define ROBOT_ERR_PARAM       -7
+
+#define ROBOT_ACT_RESET        0
+#define ROBOT_ACT_1_2          1
+#define ROBOT_ACT_2_3          2
+#define ROBOT_ACT_3_4          3
+#define ROBOT_ACT_4_5          4
+#define ROBOT_ACT_5_8          5
+#define ROBOT_ACT_9_5          6
+#define ROBOT_ACT_5_6          7
+#define ROBOT_ACT_6_3          8
+#define ROBOT_ACT_3_7          9
+#define ROBOT_ACT_7_8          10
+#define ROBOT_ACT_PHOTO        11
+#define ROBOT_ACT_HOME         12
+#define ROBOT_ACT_NUM_MAX      13
+
+#define ROBOT_STATE_IDLE       0
+#define ROBOT_STATE_FAULT      1
+#define ROBOT_STATE_BUSY       2
+#define ROBOT_STATE_NO_CONN    3
+
+#define ROBOT_DEFAULT_IP       "127.0.0.1"
+#define ROBOT_DEFAULT_PORT     9000
+#define ROBOT_DEFAULT_TIMEOUT  30
+
+typedef struct {
+    int         act_id;
+    const char *name;
+    const char *cmd_str;
+    int         def_timeout_s;
+} robot_act_def_t;
+
+int  robot_connect(void);
+void robot_disconnect(void);
+int  robot_is_connected(void);
+
+int  robot_act(int act_id, int timeout_s);
+int  robot_state(void);
+
+int  robot_set_server(const char *ip, int port);
+int  robot_get_last_error(char *buf, int buf_len);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
\ No newline at end of file
diff --git a/app/log4crc b/app/log4crc
new file mode 100644 (file)
index 0000000..8f28c9d
--- /dev/null
@@ -0,0 +1,33 @@
+<?xml version="1.0" encoding="ISO-8859-1"?>
+<!DOCTYPE log4c SYSTEM "">
+
+<log4c>
+
+    <config>
+        <bufsize>0</bufsize>
+        <debug level="0"/>
+        <nocleanup>0</nocleanup>
+    </config>
+
+    <!-- root category ========================================= -->
+    <category name="root" priority="notice"/>
+
+    <!-- 输出到文件console -->
+    <category name="AM" priority="debug" appender = "stdout"/>
+
+    <!-- 输出到文件mylogfilename.x ========================================= -->
+    <!-- category name="app" priority="debug" appender = "stdout"/ -->
+    <category name="XAM" priority="debug" appender = "myrollingappender"/>
+    <appender name="myrollingappender" type="rollingfile" logdir="./" prefix="am-log" layout="dated" rollingpolicy="myrollingpolicy" />
+    <rollingpolicy name="myrollingpolicy" type="sizewin" maxsize="102400" maxnum="3" />
+
+    <!-- default appenders ===================================== -->
+    <appender name="stdout" type="stream" layout="basic"/>
+    <appender name="stderr" type="stream" layout="dated"/>
+    <appender name="syslog" type="syslog" layout="basic"/>
+
+    <!-- default layouts ======================================= -->
+    <layout name="basic" type="basic"/>
+    <layout name="dated" type="dated"/>
+</log4c>
+
diff --git a/app/src/ad_main.c b/app/src/ad_main.c
new file mode 100644 (file)
index 0000000..006b29b
--- /dev/null
@@ -0,0 +1,299 @@
+#include <stdio.h>
+#include <stdint.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+#include <pthread.h>
+#include <ctype.h>
+#include <signal.h>
+
+#include "agridetect.h"
+#include "maintask.h"
+
+char *ad_version = "app_v" AD_VERSION;
+
+extern int ui_srv_start(void);
+extern int ui_srv_stop(void);
+
+static volatile int s_app_quit = 0;
+static void sigint_handler(int sig)
+{
+    (void)sig;
+    s_app_quit = 1;
+}
+
+/*-----------------------------------------------------------------------------
+自动检测流水线工位步骤
+
+工位 :
+工位1: 进样工位        (试管架)
+工位2: 加提取液工位    (移液器1)
+工位3: 涡动仪工位      (涡动仪)
+工位4: 离心机工位      (离心机)
+工位5: 提取样本液工位  (移液器2)
+工位6: 二次加提取液    (移液器3)
+工位7: 检测工位        (移液器4+试纸)
+工位8: 废液仓          (试管架)
+工位9: 新离心管         (试管架)
+
+测试步骤:
+1  工作人员将含有样本的离心管,放置在工位1,点击屏幕按钮,启动检测。
+2  机器臂将离心管从工位1(试管架)移动到工位2(加提取液)。
+3  主控用移液器1,将提取液加入到离心管中。
+4  机器臂将离心管从工位2(移液器1)移动到工位3(涡动仪)中。
+5  启动涡动仪,定时关闭。
+6  机器臂将离心管从工位3(涡动仪) 移动到工位4(离心机)。
+7  启动离心机,定时关闭。
+8  机器臂将离心管从工位4(涡动仪) 移动到工位5(移液器2)。
+9  使用移液枪从离心管中吸取样本液
+10 机器臂将离心管移入工位8(废液仓)
+11 机器臂将新的离心管从工位9(试管架)移动到工位5(移液器2)。
+12 移液枪将样本液放入新离心管
+13 机器臂将离心管移动到工位6(移液器3)。
+14 控制移液器将提取液加入离心管
+15 机器臂将新的离心管从工位6(移液器3)移动到工位3(涡动仪)。
+16 启动涡动仪,定时关闭。
+17 机器臂将离心管从工位3(涡动仪)移动到工位7(移液器4)。
+18 移液枪吸取样本,滴入试纸。
+19 机器臂将离心管从工位7(移液器4)移动到工位8(废液仓),等待8分钟。
+20 机器臂移动到工位7(移液器4)试纸上方,拍照,报告结果。
+
+机械臂动作:
+动作1  - 机器臂将离心管从工位1(试管架)移动到工位2(移液器)。
+动作2  - 机器臂将离心管从工位2(移液器)移动到工位3(涡动仪)。
+动作3  - 机器臂将离心管从工位3(涡动仪)移动到工位4(离心机)。
+动作4  - 机器臂将离心管从工位4(离心机)移动到工位5(移液器)。
+动作5  - 机器臂将离心管从工位5(移液器)移动到工位8(废液仓)。
+动作6  - 机器臂将离心管从工位9(试管架)移动到工位5(移液器)。
+动作7  - 机器臂将离心管从工位5(移液器)移动到工位6(移液器)。
+动作8  - 机器臂将离心管从工位6(移液器)移动到工位3(涡动仪)。
+动作9  - 机器臂将离心管从工位3(涡动仪)移动到工位7(移液器)。
+动作10 - 机器臂将离心管从工位7(移液器)移动到工位8(废气仓)。
+动作11 - 机器臂移动到工位7, 拍照,报告结果,上传图片。
+动作12 - 机器臂回到原位
+
+主控动作:
+动作1 - 移液器1控制,移动到容器位置,吸取提取液,移动到离心管位置,注入到样本离心管中,回原位。
+动作2 - 启动涡动仪,定时自动关闭。
+动作3 - 启动离心机,定时自动关闭。
+动作4 - 移液器2控制,移动到离心管位置,从离心管吸取样本液,回原位。
+动作5 - 移液器2控制,移动到离心管位置,将样本液注入离心管,回原位。
+动作6 - 移液器3控制,从容器中吸取提取液,移动到离心管位置,注入到样本离心管中,回原位。
+动作7 - 移液器4控制,移动到离心管位置,吸取样本液,移动到试纸位置,将样本液滴入试纸,回原位。
+*/
+
+int robot_act_sync( void )
+{
+    // 重试3次
+    //发送tcp指令,等待回复
+    //等待10秒,若未收到回复,重试
+    //若3次均失败,返回-1
+    //回复失败处理
+    //循环等待回应时增加强制退出事件判断
+    
+    return 0;
+}
+
+int device_act_sync( int act, int wait, int *resp )
+{
+    // 重试3次
+    //涡动仪控制命令,RS485 发送到控制板,定时关闭,等待时间到关闭, 如果发现强制退出,立即关闭
+
+    //离心机命令,控制通涡动仪
+    //移液器控制, 单独函数实现,管理三路电机和限位开关
+
+}
+
+/*******************************************
+ui 通信协议
+
+使用gdbus实现通信, 
+1 设备状态json数据, 主控定时发送设备状态到UI,
+2 设备事件报告数据, 主控实时发送到UI
+3 UI用户指令,      
+
+主控注册dbus接口,监听用户指令
+
+UI定时发送查询指令,主控返回状态信息signal到UI,UI显示状态
+主控发送事件是,通过signal通知UI, UI发送读取指令获取当前状态
+
+接口1 查询设备状态信息
+接口2 查询设备参数信息
+接口3 设置设备参数
+接口4 执行设备动作
+事件通知,设备状态变化或事件产生,主控通过signal发送事件到UI
+
+查询状态  { "cmd":"qurery_state" },   response  { device_status  }
+查询参数  { "cmd":"query_parameter" }, response  { device_parameter  }
+设置参数  { "cmd":"set_parameter" },   response  { device_parameter  }
+执行动作  { "cmd":"execute_action" },  response  { device_action  }
+event    { device_event  } 状态改变通知  { device_status }
+
+状态内容
+{
+    "device_state":{
+        "state":"init", // init, selftest, selftest_failed, ready, autotest, autotest_failed
+        "result":{
+        }
+
+    }
+
+}
+1 主动上报状态内容:
+a 工作状态:
+开机初始化   (进度)
+开机自检中   (进度)
+开机自检失败 (故障信息)
+就绪
+检测中  ( 当前检测步骤,检测总进度,检测步骤进度)
+检测异常退出 (故障信息)
+调试中   (调试步骤,调试总进度,调试步骤进度)
+
+显示:
+1  开机显示开机画面,开机进度
+2  显示自检中,自检进度,如故障,显示故障信息
+3  显示主画面
+4  主画面,或点击调试按钮,进入调试画面,显示多个按钮,用户点击,执行单步动作,点击退出调试,返回主画面
+5  主画面,点击开始检测,开始自动测试,显示检测进度
+6  检测中,点击暂停按钮,完成当前动作后,停止动作,显示暂停信息
+7  检测暂停中,点击恢复按钮,继续检测,
+8  检测中故障,显示故障信息,按退出按钮,返回主画面
+9  检测完成,显示检测结果,按返回按钮,返回主画面
+
+工作状态:
+设备开机后有以下状态:
+开机初始化、开机自检中、开机自检失败、就绪、检测中、检测异常退出、调试中
+
+1 开机初始化:上电开机中,显示开机画面,开机进度
+"device_state":{
+    "device_state":{ 
+        "state":"init"
+        } 
+}
+
+2 开机自检中:开机完成后,显示自检中,自检进度
+"device_state":{
+    "state":"selftest",
+    "result":{
+        "dev1": 1,  //涡动仪, 检测通过
+        "dev2": 1,  //离心机, 检测通过
+        "dev3": -1, //移液器1,检测失败
+        "dev4": 1,  //移液器2,检测通过
+        "dev5": 0,  //移液器3,未检测
+        "dev6": 0,  //移液器4,未检测
+        "dev7": 0  //机械臂, 未检测
+    }
+}
+
+3 开机自检失败:自检失败,显示故障信息,等待用户点击退出按钮
+"device_state":{
+    "state":"selftest_failed",
+    "result":{
+        "dev1": 1,  //涡动仪, 检测通过
+        "dev2": 1,  //离心机, 检测通过
+        "dev3": -1, //移液器1,检测失败
+        "dev4": 1,  //移液器2,检测通过
+        "dev5": 0,  //移液器3,未检测
+        "dev6": 0,  //移液器4,未检测
+        "dev7": 0,  //机械臂, 未检测
+    }
+}
+
+4 就绪:自检通过,显示主画面
+"device_state":{
+     "state":"ready"
+}
+
+5 检测中:用户点击开始检测,显示检测进度
+"device_state":{
+    "state":"autotest",
+    "result":{
+        "act1": 2,  //动作1 完成, 0: 未开始,1: 进行中,2: 完成, -1: 异常退出
+        "act2": 2,  //动作2 完成
+        "act3": 2,  //动作3 完成
+        "act4": 1,  //动作4 测试中
+        "act5": 0,  //动作5 未开始
+        "act6": 0,  //动作6 未开始
+        "act7": 0,  //动作7 未开始
+        "act8": 0,  //动作8 未开始
+    }
+}
+
+6 检测暂停:用户点击开始检测,显示检测进度
+"device_state":{
+    "state":"autotest_pause",
+    "result":{
+        "act1": 2,  //动作1 完成, 0: 未开始,1: 进行中,2: 完成, -1: 异常退出
+        "act2": 2,  //动作2 完成
+        "act3": 2,  //动作3 完成
+        "act4": 1,  //动作4 测试中
+        "act5": 0,  //动作5 未开始
+        "act6": 0,  //动作6 未开始
+        "act7": 0,  //动作7 未开始
+        "act8": 0,  //动作8 未开始
+    }
+}
+
+7 检测异常退出:检测中故障,显示故障信息,等待用户点击退出按钮
+"device_state":{
+    "state":"autotest_fault",
+     "result":{
+        "act1": 2,  //动作1 完成, 0: 未开始,1: 进行中,2: 完成, -1: 异常退出
+        "act2": 2,  //动作2 完成
+        "act3": 2,  //动作3 完成
+        "act4": 1,  //动作4 测试中
+        "act5": 0,  //动作5 未开始
+        "act6": 0,  //动作6 未开始
+        "act7": 0,  //动作7 未开始
+        "act8": 0,  //动作8 未开始
+    },
+    "fault": //故障信息
+}
+
+8 调试模式:用户点击调试按钮,显示调试画面,显示多个按钮,用户点击,执行单步动作,点击退出调试,返回主画面
+"device_state":{
+    "state":"debug", //manual 手动调试
+    "result":{
+        "act":0, //0: 未开始,1--10:动作1--10
+        "status": 0, //0: 未开始,1: 进行中,2: 完成, 小于0:故障( -1:机器臂通信故障,-2: 移液器控制故障,-3:涡动仪控制故障,-4:离心机控制故障,-5:样本未就绪,-6:样本放置目的地失败,-7:其他故障)
+    }
+}
+
+9 检测完成:检测完成,显示检测结果,按返回按钮,返回主画面
+"device_state":{
+    "state":"autotest_finished",
+    "test":"ok" //ok , failed
+}
+
+*******************************************/
+
+int main( int argc, char ** argv )
+{
+    printf( "\n\nagridetect version: %s\n\n", ad_version);
+
+    //todo:检查程序是否已经运行,如果已经运行,打印提示信息然后退出
+
+    /* 全局 dev_info_t:自检 / 测试步骤 / 调试 / UI 状态机 / param 配置 统一存在这里 */
+    dev_info_init();
+    dev_set_state(DEV_INIT);
+
+    /* UI D-Bus 服务: 处理 query_state 和触摸屏命令回调 (会调 ad_cmd_xxx) */
+    ui_srv_start();
+
+    /* 主任务线程: 串行处理初始化 / 自检 / 自动测试 / 调试 */
+    maintask_init();
+
+    /* 主程序:前台挂住,等待 Ctrl+C / SIGTERM 退出 */
+    signal(SIGINT,  sigint_handler);
+    signal(SIGTERM, sigint_handler);
+    while (!s_app_quit) {
+        sleep(1);
+    }
+
+    printf("app quit signaled, shutting down...\n");
+    maintask_deinit();
+    ui_srv_stop();
+    dev_info_deinit();
+
+    return 0;
+}
\ No newline at end of file
diff --git a/app/src/cJSON.c b/app/src/cJSON.c
new file mode 100644 (file)
index 0000000..bc95cde
--- /dev/null
@@ -0,0 +1,2979 @@
+/*
+  Copyright (c) 2009-2017 Dave Gamble and cJSON contributors
+
+  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.
+*/
+
+/* cJSON */
+/* JSON parser in C. */
+
+/* disable warnings about old C89 functions in MSVC */
+#if !defined(_CRT_SECURE_NO_DEPRECATE) && defined(_MSC_VER)
+#define _CRT_SECURE_NO_DEPRECATE
+#endif
+
+#ifdef __GNUC__
+#pragma GCC visibility push(default)
+#endif
+#if defined(_MSC_VER)
+#pragma warning (push)
+/* disable warning about single line comments in system headers */
+#pragma warning (disable : 4001)
+#endif
+
+#include <string.h>
+#include <stdio.h>
+#include <math.h>
+#include <stdlib.h>
+#include <limits.h>
+#include <ctype.h>
+
+#ifdef ENABLE_LOCALES
+#include <locale.h>
+#endif
+
+#if defined(_MSC_VER)
+#pragma warning (pop)
+#endif
+#ifdef __GNUC__
+#pragma GCC visibility pop
+#endif
+
+#include "cJSON.h"
+
+/* define our own boolean type */
+#ifdef true
+#undef true
+#endif
+#define true ((cJSON_bool)1)
+
+#ifdef false
+#undef false
+#endif
+#define false ((cJSON_bool)0)
+
+typedef struct {
+    const unsigned char *json;
+    size_t position;
+} error;
+static error global_error = { NULL, 0 };
+
+CJSON_PUBLIC(const char *) cJSON_GetErrorPtr(void)
+{
+    return (const char*) (global_error.json + global_error.position);
+}
+
+CJSON_PUBLIC(char *) cJSON_GetStringValue(const cJSON * const item) {
+    if (!cJSON_IsString(item)) {
+        return NULL;
+    }
+
+    return item->valuestring;
+}
+
+/* This is a safeguard to prevent copy-pasters from using incompatible C and header files */
+#if (CJSON_VERSION_MAJOR != 1) || (CJSON_VERSION_MINOR != 7) || (CJSON_VERSION_PATCH != 12)
+    #error cJSON.h and cJSON.c have different versions. Make sure that both have the same.
+#endif
+
+CJSON_PUBLIC(const char*) cJSON_Version(void)
+{
+    static char version[15];
+    sprintf(version, "%i.%i.%i", CJSON_VERSION_MAJOR, CJSON_VERSION_MINOR, CJSON_VERSION_PATCH);
+
+    return version;
+}
+
+/* Case insensitive string comparison, doesn't consider two NULL pointers equal though */
+static int case_insensitive_strcmp(const unsigned char *string1, const unsigned char *string2)
+{
+    if ((string1 == NULL) || (string2 == NULL))
+    {
+        return 1;
+    }
+
+    if (string1 == string2)
+    {
+        return 0;
+    }
+
+    for(; tolower(*string1) == tolower(*string2); (void)string1++, string2++)
+    {
+        if (*string1 == '\0')
+        {
+            return 0;
+        }
+    }
+
+    return tolower(*string1) - tolower(*string2);
+}
+
+typedef struct internal_hooks
+{
+    void *(CJSON_CDECL *allocate)(size_t size);
+    void (CJSON_CDECL *deallocate)(void *pointer);
+    void *(CJSON_CDECL *reallocate)(void *pointer, size_t size);
+} internal_hooks;
+
+#if defined(_MSC_VER)
+/* work around MSVC error C2322: '...' address of dllimport '...' is not static */
+static void * CJSON_CDECL internal_malloc(size_t size)
+{
+    return malloc(size);
+}
+static void CJSON_CDECL internal_free(void *pointer)
+{
+    free(pointer);
+}
+static void * CJSON_CDECL internal_realloc(void *pointer, size_t size)
+{
+    return realloc(pointer, size);
+}
+#else
+#define internal_malloc malloc
+#define internal_free free
+#define internal_realloc realloc
+#endif
+
+/* strlen of character literals resolved at compile time */
+#define static_strlen(string_literal) (sizeof(string_literal) - sizeof(""))
+
+static internal_hooks global_hooks = { internal_malloc, internal_free, internal_realloc };
+
+static unsigned char* cJSON_strdup(const unsigned char* string, const internal_hooks * const hooks)
+{
+    size_t length = 0;
+    unsigned char *copy = NULL;
+
+    if (string == NULL)
+    {
+        return NULL;
+    }
+
+    length = strlen((const char*)string) + sizeof("");
+    copy = (unsigned char*)hooks->allocate(length);
+    if (copy == NULL)
+    {
+        return NULL;
+    }
+    memcpy(copy, string, length);
+
+    return copy;
+}
+
+CJSON_PUBLIC(void) cJSON_InitHooks(cJSON_Hooks* hooks)
+{
+    if (hooks == NULL)
+    {
+        /* Reset hooks */
+        global_hooks.allocate = malloc;
+        global_hooks.deallocate = free;
+        global_hooks.reallocate = realloc;
+        return;
+    }
+
+    global_hooks.allocate = malloc;
+    if (hooks->malloc_fn != NULL)
+    {
+        global_hooks.allocate = hooks->malloc_fn;
+    }
+
+    global_hooks.deallocate = free;
+    if (hooks->free_fn != NULL)
+    {
+        global_hooks.deallocate = hooks->free_fn;
+    }
+
+    /* use realloc only if both free and malloc are used */
+    global_hooks.reallocate = NULL;
+    if ((global_hooks.allocate == malloc) && (global_hooks.deallocate == free))
+    {
+        global_hooks.reallocate = realloc;
+    }
+}
+
+/* Internal constructor. */
+static cJSON *cJSON_New_Item(const internal_hooks * const hooks)
+{
+    cJSON* node = (cJSON*)hooks->allocate(sizeof(cJSON));
+    if (node)
+    {
+        memset(node, '\0', sizeof(cJSON));
+    }
+
+    return node;
+}
+
+/* Delete a cJSON structure. */
+CJSON_PUBLIC(void) cJSON_Delete(cJSON *item)
+{
+    cJSON *next = NULL;
+    while (item != NULL)
+    {
+        next = item->next;
+        if (!(item->type & cJSON_IsReference) && (item->child != NULL))
+        {
+            cJSON_Delete(item->child);
+        }
+        if (!(item->type & cJSON_IsReference) && (item->valuestring != NULL))
+        {
+            global_hooks.deallocate(item->valuestring);
+        }
+        if (!(item->type & cJSON_StringIsConst) && (item->string != NULL))
+        {
+            global_hooks.deallocate(item->string);
+        }
+        global_hooks.deallocate(item);
+        item = next;
+    }
+}
+
+/* get the decimal point character of the current locale */
+static unsigned char get_decimal_point(void)
+{
+#ifdef ENABLE_LOCALES
+    struct lconv *lconv = localeconv();
+    return (unsigned char) lconv->decimal_point[0];
+#else
+    return '.';
+#endif
+}
+
+typedef struct
+{
+    const unsigned char *content;
+    size_t length;
+    size_t offset;
+    size_t depth; /* How deeply nested (in arrays/objects) is the input at the current offset. */
+    internal_hooks hooks;
+} parse_buffer;
+
+/* check if the given size is left to read in a given parse buffer (starting with 1) */
+#define can_read(buffer, size) ((buffer != NULL) && (((buffer)->offset + size) <= (buffer)->length))
+/* check if the buffer can be accessed at the given index (starting with 0) */
+#define can_access_at_index(buffer, index) ((buffer != NULL) && (((buffer)->offset + index) < (buffer)->length))
+#define cannot_access_at_index(buffer, index) (!can_access_at_index(buffer, index))
+/* get a pointer to the buffer at the position */
+#define buffer_at_offset(buffer) ((buffer)->content + (buffer)->offset)
+
+/* Parse the input text to generate a number, and populate the result into item. */
+static cJSON_bool parse_number(cJSON * const item, parse_buffer * const input_buffer)
+{
+    double number = 0;
+    unsigned char *after_end = NULL;
+    unsigned char number_c_string[64];
+    unsigned char decimal_point = get_decimal_point();
+    size_t i = 0;
+
+    if ((input_buffer == NULL) || (input_buffer->content == NULL))
+    {
+        return false;
+    }
+
+    /* copy the number into a temporary buffer and replace '.' with the decimal point
+     * of the current locale (for strtod)
+     * This also takes care of '\0' not necessarily being available for marking the end of the input */
+    for (i = 0; (i < (sizeof(number_c_string) - 1)) && can_access_at_index(input_buffer, i); i++)
+    {
+        switch (buffer_at_offset(input_buffer)[i])
+        {
+            case '0':
+            case '1':
+            case '2':
+            case '3':
+            case '4':
+            case '5':
+            case '6':
+            case '7':
+            case '8':
+            case '9':
+            case '+':
+            case '-':
+            case 'e':
+            case 'E':
+                number_c_string[i] = buffer_at_offset(input_buffer)[i];
+                break;
+
+            case '.':
+                number_c_string[i] = decimal_point;
+                break;
+
+            default:
+                goto loop_end;
+        }
+    }
+loop_end:
+    number_c_string[i] = '\0';
+
+    number = strtod((const char*)number_c_string, (char**)&after_end);
+    if (number_c_string == after_end)
+    {
+        return false; /* parse_error */
+    }
+
+    item->valuedouble = number;
+
+    /* use saturation in case of overflow */
+    if (number >= INT_MAX)
+    {
+        item->valueint = INT_MAX;
+    }
+    else if (number <= (double)INT_MIN)
+    {
+        item->valueint = INT_MIN;
+    }
+    else
+    {
+        item->valueint = (int)number;
+    }
+
+    item->type = cJSON_Number;
+
+    input_buffer->offset += (size_t)(after_end - number_c_string);
+    return true;
+}
+
+/* don't ask me, but the original cJSON_SetNumberValue returns an integer or double */
+CJSON_PUBLIC(double) cJSON_SetNumberHelper(cJSON *object, double number)
+{
+    if (number >= INT_MAX)
+    {
+        object->valueint = INT_MAX;
+    }
+    else if (number <= (double)INT_MIN)
+    {
+        object->valueint = INT_MIN;
+    }
+    else
+    {
+        object->valueint = (int)number;
+    }
+
+    return object->valuedouble = number;
+}
+
+typedef struct
+{
+    unsigned char *buffer;
+    size_t length;
+    size_t offset;
+    size_t depth; /* current nesting depth (for formatted printing) */
+    cJSON_bool noalloc;
+    cJSON_bool format; /* is this print a formatted print */
+    internal_hooks hooks;
+} printbuffer;
+
+/* realloc printbuffer if necessary to have at least "needed" bytes more */
+static unsigned char* ensure(printbuffer * const p, size_t needed)
+{
+    unsigned char *newbuffer = NULL;
+    size_t newsize = 0;
+
+    if ((p == NULL) || (p->buffer == NULL))
+    {
+        return NULL;
+    }
+
+    if ((p->length > 0) && (p->offset >= p->length))
+    {
+        /* make sure that offset is valid */
+        return NULL;
+    }
+
+    if (needed > INT_MAX)
+    {
+        /* sizes bigger than INT_MAX are currently not supported */
+        return NULL;
+    }
+
+    needed += p->offset + 1;
+    if (needed <= p->length)
+    {
+        return p->buffer + p->offset;
+    }
+
+    if (p->noalloc) {
+        return NULL;
+    }
+
+    /* calculate new buffer size */
+    if (needed > (INT_MAX / 2))
+    {
+        /* overflow of int, use INT_MAX if possible */
+        if (needed <= INT_MAX)
+        {
+            newsize = INT_MAX;
+        }
+        else
+        {
+            return NULL;
+        }
+    }
+    else
+    {
+        newsize = needed * 2;
+    }
+
+    if (p->hooks.reallocate != NULL)
+    {
+        /* reallocate with realloc if available */
+        newbuffer = (unsigned char*)p->hooks.reallocate(p->buffer, newsize);
+        if (newbuffer == NULL)
+        {
+            p->hooks.deallocate(p->buffer);
+            p->length = 0;
+            p->buffer = NULL;
+
+            return NULL;
+        }
+    }
+    else
+    {
+        /* otherwise reallocate manually */
+        newbuffer = (unsigned char*)p->hooks.allocate(newsize);
+        if (!newbuffer)
+        {
+            p->hooks.deallocate(p->buffer);
+            p->length = 0;
+            p->buffer = NULL;
+
+            return NULL;
+        }
+        if (newbuffer)
+        {
+            memcpy(newbuffer, p->buffer, p->offset + 1);
+        }
+        p->hooks.deallocate(p->buffer);
+    }
+    p->length = newsize;
+    p->buffer = newbuffer;
+
+    return newbuffer + p->offset;
+}
+
+/* calculate the new length of the string in a printbuffer and update the offset */
+static void update_offset(printbuffer * const buffer)
+{
+    const unsigned char *buffer_pointer = NULL;
+    if ((buffer == NULL) || (buffer->buffer == NULL))
+    {
+        return;
+    }
+    buffer_pointer = buffer->buffer + buffer->offset;
+
+    buffer->offset += strlen((const char*)buffer_pointer);
+}
+
+/* securely comparison of floating-point variables */
+static cJSON_bool compare_double(double a, double b)
+{
+    return (fabs(a - b) <= CJSON_DOUBLE_PRECISION);
+}
+
+/* Render the number nicely from the given item into a string. */
+static cJSON_bool print_number(const cJSON * const item, printbuffer * const output_buffer)
+{
+    unsigned char *output_pointer = NULL;
+    double d = item->valuedouble;
+    int length = 0;
+    size_t i = 0;
+    unsigned char number_buffer[26] = {0}; /* temporary buffer to print the number into */
+    unsigned char decimal_point = get_decimal_point();
+    double test = 0.0;
+
+    if (output_buffer == NULL)
+    {
+        return false;
+    }
+
+    /* This checks for NaN and Infinity */
+    if ((d * 0) != 0)
+    {
+        length = sprintf((char*)number_buffer, "null");
+    }
+    else
+    {
+        /* Try 15 decimal places of precision to avoid nonsignificant nonzero digits */
+        length = sprintf((char*)number_buffer, "%1.15g", d);
+
+        /* Check whether the original double can be recovered */
+        if ((sscanf((char*)number_buffer, "%lg", &test) != 1) || !compare_double((double)test, d))
+        {
+            /* If not, print with 17 decimal places of precision */
+            length = sprintf((char*)number_buffer, "%1.17g", d);
+        }
+    }
+
+    /* sprintf failed or buffer overrun occurred */
+    if ((length < 0) || (length > (int)(sizeof(number_buffer) - 1)))
+    {
+        return false;
+    }
+
+    /* reserve appropriate space in the output */
+    output_pointer = ensure(output_buffer, (size_t)length + sizeof(""));
+    if (output_pointer == NULL)
+    {
+        return false;
+    }
+
+    /* copy the printed number to the output and replace locale
+     * dependent decimal point with '.' */
+    for (i = 0; i < ((size_t)length); i++)
+    {
+        if (number_buffer[i] == decimal_point)
+        {
+            output_pointer[i] = '.';
+            continue;
+        }
+
+        output_pointer[i] = number_buffer[i];
+    }
+    output_pointer[i] = '\0';
+
+    output_buffer->offset += (size_t)length;
+
+    return true;
+}
+
+/* parse 4 digit hexadecimal number */
+static unsigned parse_hex4(const unsigned char * const input)
+{
+    unsigned int h = 0;
+    size_t i = 0;
+
+    for (i = 0; i < 4; i++)
+    {
+        /* parse digit */
+        if ((input[i] >= '0') && (input[i] <= '9'))
+        {
+            h += (unsigned int) input[i] - '0';
+        }
+        else if ((input[i] >= 'A') && (input[i] <= 'F'))
+        {
+            h += (unsigned int) 10 + input[i] - 'A';
+        }
+        else if ((input[i] >= 'a') && (input[i] <= 'f'))
+        {
+            h += (unsigned int) 10 + input[i] - 'a';
+        }
+        else /* invalid */
+        {
+            return 0;
+        }
+
+        if (i < 3)
+        {
+            /* shift left to make place for the next nibble */
+            h = h << 4;
+        }
+    }
+
+    return h;
+}
+
+/* converts a UTF-16 literal to UTF-8
+ * A literal can be one or two sequences of the form \uXXXX */
+static unsigned char utf16_literal_to_utf8(const unsigned char * const input_pointer, const unsigned char * const input_end, unsigned char **output_pointer)
+{
+    long unsigned int codepoint = 0;
+    unsigned int first_code = 0;
+    const unsigned char *first_sequence = input_pointer;
+    unsigned char utf8_length = 0;
+    unsigned char utf8_position = 0;
+    unsigned char sequence_length = 0;
+    unsigned char first_byte_mark = 0;
+
+    if ((input_end - first_sequence) < 6)
+    {
+        /* input ends unexpectedly */
+        goto fail;
+    }
+
+    /* get the first utf16 sequence */
+    first_code = parse_hex4(first_sequence + 2);
+
+    /* check that the code is valid */
+    if (((first_code >= 0xDC00) && (first_code <= 0xDFFF)))
+    {
+        goto fail;
+    }
+
+    /* UTF16 surrogate pair */
+    if ((first_code >= 0xD800) && (first_code <= 0xDBFF))
+    {
+        const unsigned char *second_sequence = first_sequence + 6;
+        unsigned int second_code = 0;
+        sequence_length = 12; /* \uXXXX\uXXXX */
+
+        if ((input_end - second_sequence) < 6)
+        {
+            /* input ends unexpectedly */
+            goto fail;
+        }
+
+        if ((second_sequence[0] != '\\') || (second_sequence[1] != 'u'))
+        {
+            /* missing second half of the surrogate pair */
+            goto fail;
+        }
+
+        /* get the second utf16 sequence */
+        second_code = parse_hex4(second_sequence + 2);
+        /* check that the code is valid */
+        if ((second_code < 0xDC00) || (second_code > 0xDFFF))
+        {
+            /* invalid second half of the surrogate pair */
+            goto fail;
+        }
+
+
+        /* calculate the unicode codepoint from the surrogate pair */
+        codepoint = 0x10000 + (((first_code & 0x3FF) << 10) | (second_code & 0x3FF));
+    }
+    else
+    {
+        sequence_length = 6; /* \uXXXX */
+        codepoint = first_code;
+    }
+
+    /* encode as UTF-8
+     * takes at maximum 4 bytes to encode:
+     * 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx */
+    if (codepoint < 0x80)
+    {
+        /* normal ascii, encoding 0xxxxxxx */
+        utf8_length = 1;
+    }
+    else if (codepoint < 0x800)
+    {
+        /* two bytes, encoding 110xxxxx 10xxxxxx */
+        utf8_length = 2;
+        first_byte_mark = 0xC0; /* 11000000 */
+    }
+    else if (codepoint < 0x10000)
+    {
+        /* three bytes, encoding 1110xxxx 10xxxxxx 10xxxxxx */
+        utf8_length = 3;
+        first_byte_mark = 0xE0; /* 11100000 */
+    }
+    else if (codepoint <= 0x10FFFF)
+    {
+        /* four bytes, encoding 1110xxxx 10xxxxxx 10xxxxxx 10xxxxxx */
+        utf8_length = 4;
+        first_byte_mark = 0xF0; /* 11110000 */
+    }
+    else
+    {
+        /* invalid unicode codepoint */
+        goto fail;
+    }
+
+    /* encode as utf8 */
+    for (utf8_position = (unsigned char)(utf8_length - 1); utf8_position > 0; utf8_position--)
+    {
+        /* 10xxxxxx */
+        (*output_pointer)[utf8_position] = (unsigned char)((codepoint | 0x80) & 0xBF);
+        codepoint >>= 6;
+    }
+    /* encode first byte */
+    if (utf8_length > 1)
+    {
+        (*output_pointer)[0] = (unsigned char)((codepoint | first_byte_mark) & 0xFF);
+    }
+    else
+    {
+        (*output_pointer)[0] = (unsigned char)(codepoint & 0x7F);
+    }
+
+    *output_pointer += utf8_length;
+
+    return sequence_length;
+
+fail:
+    return 0;
+}
+
+/* Parse the input text into an unescaped cinput, and populate item. */
+static cJSON_bool parse_string(cJSON * const item, parse_buffer * const input_buffer)
+{
+    const unsigned char *input_pointer = buffer_at_offset(input_buffer) + 1;
+    const unsigned char *input_end = buffer_at_offset(input_buffer) + 1;
+    unsigned char *output_pointer = NULL;
+    unsigned char *output = NULL;
+
+    /* not a string */
+    if (buffer_at_offset(input_buffer)[0] != '\"')
+    {
+        goto fail;
+    }
+
+    {
+        /* calculate approximate size of the output (overestimate) */
+        size_t allocation_length = 0;
+        size_t skipped_bytes = 0;
+        while (((size_t)(input_end - input_buffer->content) < input_buffer->length) && (*input_end != '\"'))
+        {
+            /* is escape sequence */
+            if (input_end[0] == '\\')
+            {
+                if ((size_t)(input_end + 1 - input_buffer->content) >= input_buffer->length)
+                {
+                    /* prevent buffer overflow when last input character is a backslash */
+                    goto fail;
+                }
+                skipped_bytes++;
+                input_end++;
+            }
+            input_end++;
+        }
+        if (((size_t)(input_end - input_buffer->content) >= input_buffer->length) || (*input_end != '\"'))
+        {
+            goto fail; /* string ended unexpectedly */
+        }
+
+        /* This is at most how much we need for the output */
+        allocation_length = (size_t) (input_end - buffer_at_offset(input_buffer)) - skipped_bytes;
+        output = (unsigned char*)input_buffer->hooks.allocate(allocation_length + sizeof(""));
+        if (output == NULL)
+        {
+            goto fail; /* allocation failure */
+        }
+    }
+
+    output_pointer = output;
+    /* loop through the string literal */
+    while (input_pointer < input_end)
+    {
+        if (*input_pointer != '\\')
+        {
+            *output_pointer++ = *input_pointer++;
+        }
+        /* escape sequence */
+        else
+        {
+            unsigned char sequence_length = 2;
+            if ((input_end - input_pointer) < 1)
+            {
+                goto fail;
+            }
+
+            switch (input_pointer[1])
+            {
+                case 'b':
+                    *output_pointer++ = '\b';
+                    break;
+                case 'f':
+                    *output_pointer++ = '\f';
+                    break;
+                case 'n':
+                    *output_pointer++ = '\n';
+                    break;
+                case 'r':
+                    *output_pointer++ = '\r';
+                    break;
+                case 't':
+                    *output_pointer++ = '\t';
+                    break;
+                case '\"':
+                case '\\':
+                case '/':
+                    *output_pointer++ = input_pointer[1];
+                    break;
+
+                /* UTF-16 literal */
+                case 'u':
+                    sequence_length = utf16_literal_to_utf8(input_pointer, input_end, &output_pointer);
+                    if (sequence_length == 0)
+                    {
+                        /* failed to convert UTF16-literal to UTF-8 */
+                        goto fail;
+                    }
+                    break;
+
+                default:
+                    goto fail;
+            }
+            input_pointer += sequence_length;
+        }
+    }
+
+    /* zero terminate the output */
+    *output_pointer = '\0';
+
+    item->type = cJSON_String;
+    item->valuestring = (char*)output;
+
+    input_buffer->offset = (size_t) (input_end - input_buffer->content);
+    input_buffer->offset++;
+
+    return true;
+
+fail:
+    if (output != NULL)
+    {
+        input_buffer->hooks.deallocate(output);
+    }
+
+    if (input_pointer != NULL)
+    {
+        input_buffer->offset = (size_t)(input_pointer - input_buffer->content);
+    }
+
+    return false;
+}
+
+/* Render the cstring provided to an escaped version that can be printed. */
+static cJSON_bool print_string_ptr(const unsigned char * const input, printbuffer * const output_buffer)
+{
+    const unsigned char *input_pointer = NULL;
+    unsigned char *output = NULL;
+    unsigned char *output_pointer = NULL;
+    size_t output_length = 0;
+    /* numbers of additional characters needed for escaping */
+    size_t escape_characters = 0;
+
+    if (output_buffer == NULL)
+    {
+        return false;
+    }
+
+    /* empty string */
+    if (input == NULL)
+    {
+        output = ensure(output_buffer, sizeof("\"\""));
+        if (output == NULL)
+        {
+            return false;
+        }
+        strcpy((char*)output, "\"\"");
+
+        return true;
+    }
+
+    /* set "flag" to 1 if something needs to be escaped */
+    for (input_pointer = input; *input_pointer; input_pointer++)
+    {
+        switch (*input_pointer)
+        {
+            case '\"':
+            case '\\':
+            case '\b':
+            case '\f':
+            case '\n':
+            case '\r':
+            case '\t':
+                /* one character escape sequence */
+                escape_characters++;
+                break;
+            default:
+                if (*input_pointer < 32)
+                {
+                    /* UTF-16 escape sequence uXXXX */
+                    escape_characters += 5;
+                }
+                break;
+        }
+    }
+    output_length = (size_t)(input_pointer - input) + escape_characters;
+
+    output = ensure(output_buffer, output_length + sizeof("\"\""));
+    if (output == NULL)
+    {
+        return false;
+    }
+
+    /* no characters have to be escaped */
+    if (escape_characters == 0)
+    {
+        output[0] = '\"';
+        memcpy(output + 1, input, output_length);
+        output[output_length + 1] = '\"';
+        output[output_length + 2] = '\0';
+
+        return true;
+    }
+
+    output[0] = '\"';
+    output_pointer = output + 1;
+    /* copy the string */
+    for (input_pointer = input; *input_pointer != '\0'; (void)input_pointer++, output_pointer++)
+    {
+        if ((*input_pointer > 31) && (*input_pointer != '\"') && (*input_pointer != '\\'))
+        {
+            /* normal character, copy */
+            *output_pointer = *input_pointer;
+        }
+        else
+        {
+            /* character needs to be escaped */
+            *output_pointer++ = '\\';
+            switch (*input_pointer)
+            {
+                case '\\':
+                    *output_pointer = '\\';
+                    break;
+                case '\"':
+                    *output_pointer = '\"';
+                    break;
+                case '\b':
+                    *output_pointer = 'b';
+                    break;
+                case '\f':
+                    *output_pointer = 'f';
+                    break;
+                case '\n':
+                    *output_pointer = 'n';
+                    break;
+                case '\r':
+                    *output_pointer = 'r';
+                    break;
+                case '\t':
+                    *output_pointer = 't';
+                    break;
+                default:
+                    /* escape and print as unicode codepoint */
+                    sprintf((char*)output_pointer, "u%04x", *input_pointer);
+                    output_pointer += 4;
+                    break;
+            }
+        }
+    }
+    output[output_length + 1] = '\"';
+    output[output_length + 2] = '\0';
+
+    return true;
+}
+
+/* Invoke print_string_ptr (which is useful) on an item. */
+static cJSON_bool print_string(const cJSON * const item, printbuffer * const p)
+{
+    return print_string_ptr((unsigned char*)item->valuestring, p);
+}
+
+/* Predeclare these prototypes. */
+static cJSON_bool parse_value(cJSON * const item, parse_buffer * const input_buffer);
+static cJSON_bool print_value(const cJSON * const item, printbuffer * const output_buffer);
+static cJSON_bool parse_array(cJSON * const item, parse_buffer * const input_buffer);
+static cJSON_bool print_array(const cJSON * const item, printbuffer * const output_buffer);
+static cJSON_bool parse_object(cJSON * const item, parse_buffer * const input_buffer);
+static cJSON_bool print_object(const cJSON * const item, printbuffer * const output_buffer);
+
+/* Utility to jump whitespace and cr/lf */
+static parse_buffer *buffer_skip_whitespace(parse_buffer * const buffer)
+{
+    if ((buffer == NULL) || (buffer->content == NULL))
+    {
+        return NULL;
+    }
+
+    while (can_access_at_index(buffer, 0) && (buffer_at_offset(buffer)[0] <= 32))
+    {
+       buffer->offset++;
+    }
+
+    if (buffer->offset == buffer->length)
+    {
+        buffer->offset--;
+    }
+
+    return buffer;
+}
+
+/* skip the UTF-8 BOM (byte order mark) if it is at the beginning of a buffer */
+static parse_buffer *skip_utf8_bom(parse_buffer * const buffer)
+{
+    if ((buffer == NULL) || (buffer->content == NULL) || (buffer->offset != 0))
+    {
+        return NULL;
+    }
+
+    if (can_access_at_index(buffer, 4) && (strncmp((const char*)buffer_at_offset(buffer), "\xEF\xBB\xBF", 3) == 0))
+    {
+        buffer->offset += 3;
+    }
+
+    return buffer;
+}
+
+/* Parse an object - create a new root, and populate. */
+CJSON_PUBLIC(cJSON *) cJSON_ParseWithOpts(const char *value, const char **return_parse_end, cJSON_bool require_null_terminated)
+{
+    parse_buffer buffer = { 0, 0, 0, 0, { 0, 0, 0 } };
+    cJSON *item = NULL;
+
+    /* reset error position */
+    global_error.json = NULL;
+    global_error.position = 0;
+
+    if (value == NULL)
+    {
+        goto fail;
+    }
+
+    buffer.content = (const unsigned char*)value;
+    buffer.length = strlen((const char*)value) + sizeof("");
+    buffer.offset = 0;
+    buffer.hooks = global_hooks;
+
+    item = cJSON_New_Item(&global_hooks);
+    if (item == NULL) /* memory fail */
+    {
+        goto fail;
+    }
+
+    if (!parse_value(item, buffer_skip_whitespace(skip_utf8_bom(&buffer))))
+    {
+        /* parse failure. ep is set. */
+        goto fail;
+    }
+
+    /* if we require null-terminated JSON without appended garbage, skip and then check for a null terminator */
+    if (require_null_terminated)
+    {
+        buffer_skip_whitespace(&buffer);
+        if ((buffer.offset >= buffer.length) || buffer_at_offset(&buffer)[0] != '\0')
+        {
+            goto fail;
+        }
+    }
+    if (return_parse_end)
+    {
+        *return_parse_end = (const char*)buffer_at_offset(&buffer);
+    }
+
+    return item;
+
+fail:
+    if (item != NULL)
+    {
+        cJSON_Delete(item);
+    }
+
+    if (value != NULL)
+    {
+        error local_error;
+        local_error.json = (const unsigned char*)value;
+        local_error.position = 0;
+
+        if (buffer.offset < buffer.length)
+        {
+            local_error.position = buffer.offset;
+        }
+        else if (buffer.length > 0)
+        {
+            local_error.position = buffer.length - 1;
+        }
+
+        if (return_parse_end != NULL)
+        {
+            *return_parse_end = (const char*)local_error.json + local_error.position;
+        }
+
+        global_error = local_error;
+    }
+
+    return NULL;
+}
+
+/* Default options for cJSON_Parse */
+CJSON_PUBLIC(cJSON *) cJSON_Parse(const char *value)
+{
+    return cJSON_ParseWithOpts(value, 0, 0);
+}
+
+#define cjson_min(a, b) ((a < b) ? a : b)
+
+static unsigned char *print(const cJSON * const item, cJSON_bool format, const internal_hooks * const hooks)
+{
+    static const size_t default_buffer_size = 256;
+    printbuffer buffer[1];
+    unsigned char *printed = NULL;
+
+    memset(buffer, 0, sizeof(buffer));
+
+    /* create buffer */
+    buffer->buffer = (unsigned char*) hooks->allocate(default_buffer_size);
+    buffer->length = default_buffer_size;
+    buffer->format = format;
+    buffer->hooks = *hooks;
+    if (buffer->buffer == NULL)
+    {
+        goto fail;
+    }
+
+    /* print the value */
+    if (!print_value(item, buffer))
+    {
+        goto fail;
+    }
+    update_offset(buffer);
+
+    /* check if reallocate is available */
+    if (hooks->reallocate != NULL)
+    {
+        printed = (unsigned char*) hooks->reallocate(buffer->buffer, buffer->offset + 1);
+        if (printed == NULL) {
+            goto fail;
+        }
+        buffer->buffer = NULL;
+    }
+    else /* otherwise copy the JSON over to a new buffer */
+    {
+        printed = (unsigned char*) hooks->allocate(buffer->offset + 1);
+        if (printed == NULL)
+        {
+            goto fail;
+        }
+        memcpy(printed, buffer->buffer, cjson_min(buffer->length, buffer->offset + 1));
+        printed[buffer->offset] = '\0'; /* just to be sure */
+
+        /* free the buffer */
+        hooks->deallocate(buffer->buffer);
+    }
+
+    return printed;
+
+fail:
+    if (buffer->buffer != NULL)
+    {
+        hooks->deallocate(buffer->buffer);
+    }
+
+    if (printed != NULL)
+    {
+        hooks->deallocate(printed);
+    }
+
+    return NULL;
+}
+
+/* Render a cJSON item/entity/structure to text. */
+CJSON_PUBLIC(char *) cJSON_Print(const cJSON *item)
+{
+    return (char*)print(item, true, &global_hooks);
+}
+
+CJSON_PUBLIC(char *) cJSON_PrintUnformatted(const cJSON *item)
+{
+    return (char*)print(item, false, &global_hooks);
+}
+
+CJSON_PUBLIC(char *) cJSON_PrintBuffered(const cJSON *item, int prebuffer, cJSON_bool fmt)
+{
+    printbuffer p = { 0, 0, 0, 0, 0, 0, { 0, 0, 0 } };
+
+    if (prebuffer < 0)
+    {
+        return NULL;
+    }
+
+    p.buffer = (unsigned char*)global_hooks.allocate((size_t)prebuffer);
+    if (!p.buffer)
+    {
+        return NULL;
+    }
+
+    p.length = (size_t)prebuffer;
+    p.offset = 0;
+    p.noalloc = false;
+    p.format = fmt;
+    p.hooks = global_hooks;
+
+    if (!print_value(item, &p))
+    {
+        global_hooks.deallocate(p.buffer);
+        return NULL;
+    }
+
+    return (char*)p.buffer;
+}
+
+CJSON_PUBLIC(cJSON_bool) cJSON_PrintPreallocated(cJSON *item, char *buffer, const int length, const cJSON_bool format)
+{
+    printbuffer p = { 0, 0, 0, 0, 0, 0, { 0, 0, 0 } };
+
+    if ((length < 0) || (buffer == NULL))
+    {
+        return false;
+    }
+
+    p.buffer = (unsigned char*)buffer;
+    p.length = (size_t)length;
+    p.offset = 0;
+    p.noalloc = true;
+    p.format = format;
+    p.hooks = global_hooks;
+
+    return print_value(item, &p);
+}
+
+/* Parser core - when encountering text, process appropriately. */
+static cJSON_bool parse_value(cJSON * const item, parse_buffer * const input_buffer)
+{
+    if ((input_buffer == NULL) || (input_buffer->content == NULL))
+    {
+        return false; /* no input */
+    }
+
+    /* parse the different types of values */
+    /* null */
+    if (can_read(input_buffer, 4) && (strncmp((const char*)buffer_at_offset(input_buffer), "null", 4) == 0))
+    {
+        item->type = cJSON_NULL;
+        input_buffer->offset += 4;
+        return true;
+    }
+    /* false */
+    if (can_read(input_buffer, 5) && (strncmp((const char*)buffer_at_offset(input_buffer), "false", 5) == 0))
+    {
+        item->type = cJSON_False;
+        input_buffer->offset += 5;
+        return true;
+    }
+    /* true */
+    if (can_read(input_buffer, 4) && (strncmp((const char*)buffer_at_offset(input_buffer), "true", 4) == 0))
+    {
+        item->type = cJSON_True;
+        item->valueint = 1;
+        input_buffer->offset += 4;
+        return true;
+    }
+    /* string */
+    if (can_access_at_index(input_buffer, 0) && (buffer_at_offset(input_buffer)[0] == '\"'))
+    {
+        return parse_string(item, input_buffer);
+    }
+    /* number */
+    if (can_access_at_index(input_buffer, 0) && ((buffer_at_offset(input_buffer)[0] == '-') || ((buffer_at_offset(input_buffer)[0] >= '0') && (buffer_at_offset(input_buffer)[0] <= '9'))))
+    {
+        return parse_number(item, input_buffer);
+    }
+    /* array */
+    if (can_access_at_index(input_buffer, 0) && (buffer_at_offset(input_buffer)[0] == '['))
+    {
+        return parse_array(item, input_buffer);
+    }
+    /* object */
+    if (can_access_at_index(input_buffer, 0) && (buffer_at_offset(input_buffer)[0] == '{'))
+    {
+        return parse_object(item, input_buffer);
+    }
+
+    return false;
+}
+
+/* Render a value to text. */
+static cJSON_bool print_value(const cJSON * const item, printbuffer * const output_buffer)
+{
+    unsigned char *output = NULL;
+
+    if ((item == NULL) || (output_buffer == NULL))
+    {
+        return false;
+    }
+
+    switch ((item->type) & 0xFF)
+    {
+        case cJSON_NULL:
+            output = ensure(output_buffer, 5);
+            if (output == NULL)
+            {
+                return false;
+            }
+            strcpy((char*)output, "null");
+            return true;
+
+        case cJSON_False:
+            output = ensure(output_buffer, 6);
+            if (output == NULL)
+            {
+                return false;
+            }
+            strcpy((char*)output, "false");
+            return true;
+
+        case cJSON_True:
+            output = ensure(output_buffer, 5);
+            if (output == NULL)
+            {
+                return false;
+            }
+            strcpy((char*)output, "true");
+            return true;
+
+        case cJSON_Number:
+            return print_number(item, output_buffer);
+
+        case cJSON_Raw:
+        {
+            size_t raw_length = 0;
+            if (item->valuestring == NULL)
+            {
+                return false;
+            }
+
+            raw_length = strlen(item->valuestring) + sizeof("");
+            output = ensure(output_buffer, raw_length);
+            if (output == NULL)
+            {
+                return false;
+            }
+            memcpy(output, item->valuestring, raw_length);
+            return true;
+        }
+
+        case cJSON_String:
+            return print_string(item, output_buffer);
+
+        case cJSON_Array:
+            return print_array(item, output_buffer);
+
+        case cJSON_Object:
+            return print_object(item, output_buffer);
+
+        default:
+            return false;
+    }
+}
+
+/* Build an array from input text. */
+static cJSON_bool parse_array(cJSON * const item, parse_buffer * const input_buffer)
+{
+    cJSON *head = NULL; /* head of the linked list */
+    cJSON *current_item = NULL;
+
+    if (input_buffer->depth >= CJSON_NESTING_LIMIT)
+    {
+        return false; /* to deeply nested */
+    }
+    input_buffer->depth++;
+
+    if (buffer_at_offset(input_buffer)[0] != '[')
+    {
+        /* not an array */
+        goto fail;
+    }
+
+    input_buffer->offset++;
+    buffer_skip_whitespace(input_buffer);
+    if (can_access_at_index(input_buffer, 0) && (buffer_at_offset(input_buffer)[0] == ']'))
+    {
+        /* empty array */
+        goto success;
+    }
+
+    /* check if we skipped to the end of the buffer */
+    if (cannot_access_at_index(input_buffer, 0))
+    {
+        input_buffer->offset--;
+        goto fail;
+    }
+
+    /* step back to character in front of the first element */
+    input_buffer->offset--;
+    /* loop through the comma separated array elements */
+    do
+    {
+        /* allocate next item */
+        cJSON *new_item = cJSON_New_Item(&(input_buffer->hooks));
+        if (new_item == NULL)
+        {
+            goto fail; /* allocation failure */
+        }
+
+        /* attach next item to list */
+        if (head == NULL)
+        {
+            /* start the linked list */
+            current_item = head = new_item;
+        }
+        else
+        {
+            /* add to the end and advance */
+            current_item->next = new_item;
+            new_item->prev = current_item;
+            current_item = new_item;
+        }
+
+        /* parse next value */
+        input_buffer->offset++;
+        buffer_skip_whitespace(input_buffer);
+        if (!parse_value(current_item, input_buffer))
+        {
+            goto fail; /* failed to parse value */
+        }
+        buffer_skip_whitespace(input_buffer);
+    }
+    while (can_access_at_index(input_buffer, 0) && (buffer_at_offset(input_buffer)[0] == ','));
+
+    if (cannot_access_at_index(input_buffer, 0) || buffer_at_offset(input_buffer)[0] != ']')
+    {
+        goto fail; /* expected end of array */
+    }
+
+success:
+    input_buffer->depth--;
+
+    item->type = cJSON_Array;
+    item->child = head;
+
+    input_buffer->offset++;
+
+    return true;
+
+fail:
+    if (head != NULL)
+    {
+        cJSON_Delete(head);
+    }
+
+    return false;
+}
+
+/* Render an array to text */
+static cJSON_bool print_array(const cJSON * const item, printbuffer * const output_buffer)
+{
+    unsigned char *output_pointer = NULL;
+    size_t length = 0;
+    cJSON *current_element = item->child;
+
+    if (output_buffer == NULL)
+    {
+        return false;
+    }
+
+    /* Compose the output array. */
+    /* opening square bracket */
+    output_pointer = ensure(output_buffer, 1);
+    if (output_pointer == NULL)
+    {
+        return false;
+    }
+
+    *output_pointer = '[';
+    output_buffer->offset++;
+    output_buffer->depth++;
+
+    while (current_element != NULL)
+    {
+        if (!print_value(current_element, output_buffer))
+        {
+            return false;
+        }
+        update_offset(output_buffer);
+        if (current_element->next)
+        {
+            length = (size_t) (output_buffer->format ? 2 : 1);
+            output_pointer = ensure(output_buffer, length + 1);
+            if (output_pointer == NULL)
+            {
+                return false;
+            }
+            *output_pointer++ = ',';
+            if(output_buffer->format)
+            {
+                *output_pointer++ = ' ';
+            }
+            *output_pointer = '\0';
+            output_buffer->offset += length;
+        }
+        current_element = current_element->next;
+    }
+
+    output_pointer = ensure(output_buffer, 2);
+    if (output_pointer == NULL)
+    {
+        return false;
+    }
+    *output_pointer++ = ']';
+    *output_pointer = '\0';
+    output_buffer->depth--;
+
+    return true;
+}
+
+/* Build an object from the text. */
+static cJSON_bool parse_object(cJSON * const item, parse_buffer * const input_buffer)
+{
+    cJSON *head = NULL; /* linked list head */
+    cJSON *current_item = NULL;
+
+    if (input_buffer->depth >= CJSON_NESTING_LIMIT)
+    {
+        return false; /* to deeply nested */
+    }
+    input_buffer->depth++;
+
+    if (cannot_access_at_index(input_buffer, 0) || (buffer_at_offset(input_buffer)[0] != '{'))
+    {
+        goto fail; /* not an object */
+    }
+
+    input_buffer->offset++;
+    buffer_skip_whitespace(input_buffer);
+    if (can_access_at_index(input_buffer, 0) && (buffer_at_offset(input_buffer)[0] == '}'))
+    {
+        goto success; /* empty object */
+    }
+
+    /* check if we skipped to the end of the buffer */
+    if (cannot_access_at_index(input_buffer, 0))
+    {
+        input_buffer->offset--;
+        goto fail;
+    }
+
+    /* step back to character in front of the first element */
+    input_buffer->offset--;
+    /* loop through the comma separated array elements */
+    do
+    {
+        /* allocate next item */
+        cJSON *new_item = cJSON_New_Item(&(input_buffer->hooks));
+        if (new_item == NULL)
+        {
+            goto fail; /* allocation failure */
+        }
+
+        /* attach next item to list */
+        if (head == NULL)
+        {
+            /* start the linked list */
+            current_item = head = new_item;
+        }
+        else
+        {
+            /* add to the end and advance */
+            current_item->next = new_item;
+            new_item->prev = current_item;
+            current_item = new_item;
+        }
+
+        /* parse the name of the child */
+        input_buffer->offset++;
+        buffer_skip_whitespace(input_buffer);
+        if (!parse_string(current_item, input_buffer))
+        {
+            goto fail; /* failed to parse name */
+        }
+        buffer_skip_whitespace(input_buffer);
+
+        /* swap valuestring and string, because we parsed the name */
+        current_item->string = current_item->valuestring;
+        current_item->valuestring = NULL;
+
+        if (cannot_access_at_index(input_buffer, 0) || (buffer_at_offset(input_buffer)[0] != ':'))
+        {
+            goto fail; /* invalid object */
+        }
+
+        /* parse the value */
+        input_buffer->offset++;
+        buffer_skip_whitespace(input_buffer);
+        if (!parse_value(current_item, input_buffer))
+        {
+            goto fail; /* failed to parse value */
+        }
+        buffer_skip_whitespace(input_buffer);
+    }
+    while (can_access_at_index(input_buffer, 0) && (buffer_at_offset(input_buffer)[0] == ','));
+
+    if (cannot_access_at_index(input_buffer, 0) || (buffer_at_offset(input_buffer)[0] != '}'))
+    {
+        goto fail; /* expected end of object */
+    }
+
+success:
+    input_buffer->depth--;
+
+    item->type = cJSON_Object;
+    item->child = head;
+
+    input_buffer->offset++;
+    return true;
+
+fail:
+    if (head != NULL)
+    {
+        cJSON_Delete(head);
+    }
+
+    return false;
+}
+
+/* Render an object to text. */
+static cJSON_bool print_object(const cJSON * const item, printbuffer * const output_buffer)
+{
+    unsigned char *output_pointer = NULL;
+    size_t length = 0;
+    cJSON *current_item = item->child;
+
+    if (output_buffer == NULL)
+    {
+        return false;
+    }
+
+    /* Compose the output: */
+    length = (size_t) (output_buffer->format ? 2 : 1); /* fmt: {\n */
+    output_pointer = ensure(output_buffer, length + 1);
+    if (output_pointer == NULL)
+    {
+        return false;
+    }
+
+    *output_pointer++ = '{';
+    output_buffer->depth++;
+    if (output_buffer->format)
+    {
+        *output_pointer++ = '\n';
+    }
+    output_buffer->offset += length;
+
+    while (current_item)
+    {
+        if (output_buffer->format)
+        {
+            size_t i;
+            output_pointer = ensure(output_buffer, output_buffer->depth);
+            if (output_pointer == NULL)
+            {
+                return false;
+            }
+            for (i = 0; i < output_buffer->depth; i++)
+            {
+                *output_pointer++ = '\t';
+            }
+            output_buffer->offset += output_buffer->depth;
+        }
+
+        /* print key */
+        if (!print_string_ptr((unsigned char*)current_item->string, output_buffer))
+        {
+            return false;
+        }
+        update_offset(output_buffer);
+
+        length = (size_t) (output_buffer->format ? 2 : 1);
+        output_pointer = ensure(output_buffer, length);
+        if (output_pointer == NULL)
+        {
+            return false;
+        }
+        *output_pointer++ = ':';
+        if (output_buffer->format)
+        {
+            *output_pointer++ = '\t';
+        }
+        output_buffer->offset += length;
+
+        /* print value */
+        if (!print_value(current_item, output_buffer))
+        {
+            return false;
+        }
+        update_offset(output_buffer);
+
+        /* print comma if not last */
+        length = ((size_t)(output_buffer->format ? 1 : 0) + (size_t)(current_item->next ? 1 : 0));
+        output_pointer = ensure(output_buffer, length + 1);
+        if (output_pointer == NULL)
+        {
+            return false;
+        }
+        if (current_item->next)
+        {
+            *output_pointer++ = ',';
+        }
+
+        if (output_buffer->format)
+        {
+            *output_pointer++ = '\n';
+        }
+        *output_pointer = '\0';
+        output_buffer->offset += length;
+
+        current_item = current_item->next;
+    }
+
+    output_pointer = ensure(output_buffer, output_buffer->format ? (output_buffer->depth + 1) : 2);
+    if (output_pointer == NULL)
+    {
+        return false;
+    }
+    if (output_buffer->format)
+    {
+        size_t i;
+        for (i = 0; i < (output_buffer->depth - 1); i++)
+        {
+            *output_pointer++ = '\t';
+        }
+    }
+    *output_pointer++ = '}';
+    *output_pointer = '\0';
+    output_buffer->depth--;
+
+    return true;
+}
+
+/* Get Array size/item / object item. */
+CJSON_PUBLIC(int) cJSON_GetArraySize(const cJSON *array)
+{
+    cJSON *child = NULL;
+    size_t size = 0;
+
+    if (array == NULL)
+    {
+        return 0;
+    }
+
+    child = array->child;
+
+    while(child != NULL)
+    {
+        size++;
+        child = child->next;
+    }
+
+    /* FIXME: Can overflow here. Cannot be fixed without breaking the API */
+
+    return (int)size;
+}
+
+static cJSON* get_array_item(const cJSON *array, size_t index)
+{
+    cJSON *current_child = NULL;
+
+    if (array == NULL)
+    {
+        return NULL;
+    }
+
+    current_child = array->child;
+    while ((current_child != NULL) && (index > 0))
+    {
+        index--;
+        current_child = current_child->next;
+    }
+
+    return current_child;
+}
+
+CJSON_PUBLIC(cJSON *) cJSON_GetArrayItem(const cJSON *array, int index)
+{
+    if (index < 0)
+    {
+        return NULL;
+    }
+
+    return get_array_item(array, (size_t)index);
+}
+
+static cJSON *get_object_item(const cJSON * const object, const char * const name, const cJSON_bool case_sensitive)
+{
+    cJSON *current_element = NULL;
+
+    if ((object == NULL) || (name == NULL))
+    {
+        return NULL;
+    }
+
+    current_element = object->child;
+    if (case_sensitive)
+    {
+        while ((current_element != NULL) && (current_element->string != NULL) && (strcmp(name, current_element->string) != 0))
+        {
+            current_element = current_element->next;
+        }
+    }
+    else
+    {
+        while ((current_element != NULL) && (case_insensitive_strcmp((const unsigned char*)name, (const unsigned char*)(current_element->string)) != 0))
+        {
+            current_element = current_element->next;
+        }
+    }
+
+    if ((current_element == NULL) || (current_element->string == NULL)) {
+        return NULL;
+    }
+
+    return current_element;
+}
+
+CJSON_PUBLIC(cJSON *) cJSON_GetObjectItem(const cJSON * const object, const char * const string)
+{
+    return get_object_item(object, string, false);
+}
+
+CJSON_PUBLIC(cJSON *) cJSON_GetObjectItemCaseSensitive(const cJSON * const object, const char * const string)
+{
+    return get_object_item(object, string, true);
+}
+
+CJSON_PUBLIC(cJSON_bool) cJSON_HasObjectItem(const cJSON *object, const char *string)
+{
+    return cJSON_GetObjectItem(object, string) ? 1 : 0;
+}
+
+/* Utility for array list handling. */
+static void suffix_object(cJSON *prev, cJSON *item)
+{
+    prev->next = item;
+    item->prev = prev;
+}
+
+/* Utility for handling references. */
+static cJSON *create_reference(const cJSON *item, const internal_hooks * const hooks)
+{
+    cJSON *reference = NULL;
+    if (item == NULL)
+    {
+        return NULL;
+    }
+
+    reference = cJSON_New_Item(hooks);
+    if (reference == NULL)
+    {
+        return NULL;
+    }
+
+    memcpy(reference, item, sizeof(cJSON));
+    reference->string = NULL;
+    reference->type |= cJSON_IsReference;
+    reference->next = reference->prev = NULL;
+    return reference;
+}
+
+static cJSON_bool add_item_to_array(cJSON *array, cJSON *item)
+{
+    cJSON *child = NULL;
+
+    if ((item == NULL) || (array == NULL))
+    {
+        return false;
+    }
+
+    child = array->child;
+
+    if (child == NULL)
+    {
+        /* list is empty, start new one */
+        array->child = item;
+    }
+    else
+    {
+        /* append to the end */
+        while (child->next)
+        {
+            child = child->next;
+        }
+        suffix_object(child, item);
+    }
+
+    return true;
+}
+
+/* Add item to array/object. */
+CJSON_PUBLIC(void) cJSON_AddItemToArray(cJSON *array, cJSON *item)
+{
+    add_item_to_array(array, item);
+}
+
+#if defined(__clang__) || (defined(__GNUC__)  && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 5))))
+    #pragma GCC diagnostic push
+#endif
+#ifdef __GNUC__
+#pragma GCC diagnostic ignored "-Wcast-qual"
+#endif
+/* helper function to cast away const */
+static void* cast_away_const(const void* string)
+{
+    return (void*)string;
+}
+#if defined(__clang__) || (defined(__GNUC__)  && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 5))))
+    #pragma GCC diagnostic pop
+#endif
+
+
+static cJSON_bool add_item_to_object(cJSON * const object, const char * const string, cJSON * const item, const internal_hooks * const hooks, const cJSON_bool constant_key)
+{
+    char *new_key = NULL;
+    int new_type = cJSON_Invalid;
+
+    if ((object == NULL) || (string == NULL) || (item == NULL))
+    {
+        return false;
+    }
+
+    if (constant_key)
+    {
+        new_key = (char*)cast_away_const(string);
+        new_type = item->type | cJSON_StringIsConst;
+    }
+    else
+    {
+        new_key = (char*)cJSON_strdup((const unsigned char*)string, hooks);
+        if (new_key == NULL)
+        {
+            return false;
+        }
+
+        new_type = item->type & ~cJSON_StringIsConst;
+    }
+
+    if (!(item->type & cJSON_StringIsConst) && (item->string != NULL))
+    {
+        hooks->deallocate(item->string);
+    }
+
+    item->string = new_key;
+    item->type = new_type;
+
+    return add_item_to_array(object, item);
+}
+
+CJSON_PUBLIC(void) cJSON_AddItemToObject(cJSON *object, const char *string, cJSON *item)
+{
+    add_item_to_object(object, string, item, &global_hooks, false);
+}
+
+/* Add an item to an object with constant string as key */
+CJSON_PUBLIC(void) cJSON_AddItemToObjectCS(cJSON *object, const char *string, cJSON *item)
+{
+    add_item_to_object(object, string, item, &global_hooks, true);
+}
+
+CJSON_PUBLIC(void) cJSON_AddItemReferenceToArray(cJSON *array, cJSON *item)
+{
+    if (array == NULL)
+    {
+        return;
+    }
+
+    add_item_to_array(array, create_reference(item, &global_hooks));
+}
+
+CJSON_PUBLIC(void) cJSON_AddItemReferenceToObject(cJSON *object, const char *string, cJSON *item)
+{
+    if ((object == NULL) || (string == NULL))
+    {
+        return;
+    }
+
+    add_item_to_object(object, string, create_reference(item, &global_hooks), &global_hooks, false);
+}
+
+CJSON_PUBLIC(cJSON*) cJSON_AddNullToObject(cJSON * const object, const char * const name)
+{
+    cJSON *null = cJSON_CreateNull();
+    if (add_item_to_object(object, name, null, &global_hooks, false))
+    {
+        return null;
+    }
+
+    cJSON_Delete(null);
+    return NULL;
+}
+
+CJSON_PUBLIC(cJSON*) cJSON_AddTrueToObject(cJSON * const object, const char * const name)
+{
+    cJSON *true_item = cJSON_CreateTrue();
+    if (add_item_to_object(object, name, true_item, &global_hooks, false))
+    {
+        return true_item;
+    }
+
+    cJSON_Delete(true_item);
+    return NULL;
+}
+
+CJSON_PUBLIC(cJSON*) cJSON_AddFalseToObject(cJSON * const object, const char * const name)
+{
+    cJSON *false_item = cJSON_CreateFalse();
+    if (add_item_to_object(object, name, false_item, &global_hooks, false))
+    {
+        return false_item;
+    }
+
+    cJSON_Delete(false_item);
+    return NULL;
+}
+
+CJSON_PUBLIC(cJSON*) cJSON_AddBoolToObject(cJSON * const object, const char * const name, const cJSON_bool boolean)
+{
+    cJSON *bool_item = cJSON_CreateBool(boolean);
+    if (add_item_to_object(object, name, bool_item, &global_hooks, false))
+    {
+        return bool_item;
+    }
+
+    cJSON_Delete(bool_item);
+    return NULL;
+}
+
+CJSON_PUBLIC(cJSON*) cJSON_AddNumberToObject(cJSON * const object, const char * const name, const double number)
+{
+    cJSON *number_item = cJSON_CreateNumber(number);
+    if (add_item_to_object(object, name, number_item, &global_hooks, false))
+    {
+        return number_item;
+    }
+
+    cJSON_Delete(number_item);
+    return NULL;
+}
+
+CJSON_PUBLIC(cJSON*) cJSON_AddStringToObject(cJSON * const object, const char * const name, const char * const string)
+{
+    cJSON *string_item = cJSON_CreateString(string);
+    if (add_item_to_object(object, name, string_item, &global_hooks, false))
+    {
+        return string_item;
+    }
+
+    cJSON_Delete(string_item);
+    return NULL;
+}
+
+CJSON_PUBLIC(cJSON*) cJSON_AddRawToObject(cJSON * const object, const char * const name, const char * const raw)
+{
+    cJSON *raw_item = cJSON_CreateRaw(raw);
+    if (add_item_to_object(object, name, raw_item, &global_hooks, false))
+    {
+        return raw_item;
+    }
+
+    cJSON_Delete(raw_item);
+    return NULL;
+}
+
+CJSON_PUBLIC(cJSON*) cJSON_AddObjectToObject(cJSON * const object, const char * const name)
+{
+    cJSON *object_item = cJSON_CreateObject();
+    if (add_item_to_object(object, name, object_item, &global_hooks, false))
+    {
+        return object_item;
+    }
+
+    cJSON_Delete(object_item);
+    return NULL;
+}
+
+CJSON_PUBLIC(cJSON*) cJSON_AddArrayToObject(cJSON * const object, const char * const name)
+{
+    cJSON *array = cJSON_CreateArray();
+    if (add_item_to_object(object, name, array, &global_hooks, false))
+    {
+        return array;
+    }
+
+    cJSON_Delete(array);
+    return NULL;
+}
+
+CJSON_PUBLIC(cJSON *) cJSON_DetachItemViaPointer(cJSON *parent, cJSON * const item)
+{
+    if ((parent == NULL) || (item == NULL))
+    {
+        return NULL;
+    }
+
+    if (item->prev != NULL)
+    {
+        /* not the first element */
+        item->prev->next = item->next;
+    }
+    if (item->next != NULL)
+    {
+        /* not the last element */
+        item->next->prev = item->prev;
+    }
+
+    if (item == parent->child)
+    {
+        /* first element */
+        parent->child = item->next;
+    }
+    /* make sure the detached item doesn't point anywhere anymore */
+    item->prev = NULL;
+    item->next = NULL;
+
+    return item;
+}
+
+CJSON_PUBLIC(cJSON *) cJSON_DetachItemFromArray(cJSON *array, int which)
+{
+    if (which < 0)
+    {
+        return NULL;
+    }
+
+    return cJSON_DetachItemViaPointer(array, get_array_item(array, (size_t)which));
+}
+
+CJSON_PUBLIC(void) cJSON_DeleteItemFromArray(cJSON *array, int which)
+{
+    cJSON_Delete(cJSON_DetachItemFromArray(array, which));
+}
+
+CJSON_PUBLIC(cJSON *) cJSON_DetachItemFromObject(cJSON *object, const char *string)
+{
+    cJSON *to_detach = cJSON_GetObjectItem(object, string);
+
+    return cJSON_DetachItemViaPointer(object, to_detach);
+}
+
+CJSON_PUBLIC(cJSON *) cJSON_DetachItemFromObjectCaseSensitive(cJSON *object, const char *string)
+{
+    cJSON *to_detach = cJSON_GetObjectItemCaseSensitive(object, string);
+
+    return cJSON_DetachItemViaPointer(object, to_detach);
+}
+
+CJSON_PUBLIC(void) cJSON_DeleteItemFromObject(cJSON *object, const char *string)
+{
+    cJSON_Delete(cJSON_DetachItemFromObject(object, string));
+}
+
+CJSON_PUBLIC(void) cJSON_DeleteItemFromObjectCaseSensitive(cJSON *object, const char *string)
+{
+    cJSON_Delete(cJSON_DetachItemFromObjectCaseSensitive(object, string));
+}
+
+/* Replace array/object items with new ones. */
+CJSON_PUBLIC(void) cJSON_InsertItemInArray(cJSON *array, int which, cJSON *newitem)
+{
+    cJSON *after_inserted = NULL;
+
+    if (which < 0)
+    {
+        return;
+    }
+
+    after_inserted = get_array_item(array, (size_t)which);
+    if (after_inserted == NULL)
+    {
+        add_item_to_array(array, newitem);
+        return;
+    }
+
+    newitem->next = after_inserted;
+    newitem->prev = after_inserted->prev;
+    after_inserted->prev = newitem;
+    if (after_inserted == array->child)
+    {
+        array->child = newitem;
+    }
+    else
+    {
+        newitem->prev->next = newitem;
+    }
+}
+
+CJSON_PUBLIC(cJSON_bool) cJSON_ReplaceItemViaPointer(cJSON * const parent, cJSON * const item, cJSON * replacement)
+{
+    if ((parent == NULL) || (replacement == NULL) || (item == NULL))
+    {
+        return false;
+    }
+
+    if (replacement == item)
+    {
+        return true;
+    }
+
+    replacement->next = item->next;
+    replacement->prev = item->prev;
+
+    if (replacement->next != NULL)
+    {
+        replacement->next->prev = replacement;
+    }
+    if (replacement->prev != NULL)
+    {
+        replacement->prev->next = replacement;
+    }
+    if (parent->child == item)
+    {
+        parent->child = replacement;
+    }
+
+    item->next = NULL;
+    item->prev = NULL;
+    cJSON_Delete(item);
+
+    return true;
+}
+
+CJSON_PUBLIC(void) cJSON_ReplaceItemInArray(cJSON *array, int which, cJSON *newitem)
+{
+    if (which < 0)
+    {
+        return;
+    }
+
+    cJSON_ReplaceItemViaPointer(array, get_array_item(array, (size_t)which), newitem);
+}
+
+static cJSON_bool replace_item_in_object(cJSON *object, const char *string, cJSON *replacement, cJSON_bool case_sensitive)
+{
+    if ((replacement == NULL) || (string == NULL))
+    {
+        return false;
+    }
+
+    /* replace the name in the replacement */
+    if (!(replacement->type & cJSON_StringIsConst) && (replacement->string != NULL))
+    {
+        cJSON_free(replacement->string);
+    }
+    replacement->string = (char*)cJSON_strdup((const unsigned char*)string, &global_hooks);
+    replacement->type &= ~cJSON_StringIsConst;
+
+    cJSON_ReplaceItemViaPointer(object, get_object_item(object, string, case_sensitive), replacement);
+
+    return true;
+}
+
+CJSON_PUBLIC(void) cJSON_ReplaceItemInObject(cJSON *object, const char *string, cJSON *newitem)
+{
+    replace_item_in_object(object, string, newitem, false);
+}
+
+CJSON_PUBLIC(void) cJSON_ReplaceItemInObjectCaseSensitive(cJSON *object, const char *string, cJSON *newitem)
+{
+    replace_item_in_object(object, string, newitem, true);
+}
+
+/* Create basic types: */
+CJSON_PUBLIC(cJSON *) cJSON_CreateNull(void)
+{
+    cJSON *item = cJSON_New_Item(&global_hooks);
+    if(item)
+    {
+        item->type = cJSON_NULL;
+    }
+
+    return item;
+}
+
+CJSON_PUBLIC(cJSON *) cJSON_CreateTrue(void)
+{
+    cJSON *item = cJSON_New_Item(&global_hooks);
+    if(item)
+    {
+        item->type = cJSON_True;
+    }
+
+    return item;
+}
+
+CJSON_PUBLIC(cJSON *) cJSON_CreateFalse(void)
+{
+    cJSON *item = cJSON_New_Item(&global_hooks);
+    if(item)
+    {
+        item->type = cJSON_False;
+    }
+
+    return item;
+}
+
+CJSON_PUBLIC(cJSON *) cJSON_CreateBool(cJSON_bool boolean)
+{
+    cJSON *item = cJSON_New_Item(&global_hooks);
+    if(item)
+    {
+        item->type = boolean ? cJSON_True : cJSON_False;
+    }
+
+    return item;
+}
+
+CJSON_PUBLIC(cJSON *) cJSON_CreateNumber(double num)
+{
+    cJSON *item = cJSON_New_Item(&global_hooks);
+    if(item)
+    {
+        item->type = cJSON_Number;
+        item->valuedouble = num;
+
+        /* use saturation in case of overflow */
+        if (num >= INT_MAX)
+        {
+            item->valueint = INT_MAX;
+        }
+        else if (num <= (double)INT_MIN)
+        {
+            item->valueint = INT_MIN;
+        }
+        else
+        {
+            item->valueint = (int)num;
+        }
+    }
+
+    return item;
+}
+
+CJSON_PUBLIC(cJSON *) cJSON_CreateString(const char *string)
+{
+    cJSON *item = cJSON_New_Item(&global_hooks);
+    if(item)
+    {
+        item->type = cJSON_String;
+        item->valuestring = (char*)cJSON_strdup((const unsigned char*)string, &global_hooks);
+        if(!item->valuestring)
+        {
+            cJSON_Delete(item);
+            return NULL;
+        }
+    }
+
+    return item;
+}
+
+CJSON_PUBLIC(cJSON *) cJSON_CreateStringReference(const char *string)
+{
+    cJSON *item = cJSON_New_Item(&global_hooks);
+    if (item != NULL)
+    {
+        item->type = cJSON_String | cJSON_IsReference;
+        item->valuestring = (char*)cast_away_const(string);
+    }
+
+    return item;
+}
+
+CJSON_PUBLIC(cJSON *) cJSON_CreateObjectReference(const cJSON *child)
+{
+    cJSON *item = cJSON_New_Item(&global_hooks);
+    if (item != NULL) {
+        item->type = cJSON_Object | cJSON_IsReference;
+        item->child = (cJSON*)cast_away_const(child);
+    }
+
+    return item;
+}
+
+CJSON_PUBLIC(cJSON *) cJSON_CreateArrayReference(const cJSON *child) {
+    cJSON *item = cJSON_New_Item(&global_hooks);
+    if (item != NULL) {
+        item->type = cJSON_Array | cJSON_IsReference;
+        item->child = (cJSON*)cast_away_const(child);
+    }
+
+    return item;
+}
+
+CJSON_PUBLIC(cJSON *) cJSON_CreateRaw(const char *raw)
+{
+    cJSON *item = cJSON_New_Item(&global_hooks);
+    if(item)
+    {
+        item->type = cJSON_Raw;
+        item->valuestring = (char*)cJSON_strdup((const unsigned char*)raw, &global_hooks);
+        if(!item->valuestring)
+        {
+            cJSON_Delete(item);
+            return NULL;
+        }
+    }
+
+    return item;
+}
+
+CJSON_PUBLIC(cJSON *) cJSON_CreateArray(void)
+{
+    cJSON *item = cJSON_New_Item(&global_hooks);
+    if(item)
+    {
+        item->type=cJSON_Array;
+    }
+
+    return item;
+}
+
+CJSON_PUBLIC(cJSON *) cJSON_CreateObject(void)
+{
+    cJSON *item = cJSON_New_Item(&global_hooks);
+    if (item)
+    {
+        item->type = cJSON_Object;
+    }
+
+    return item;
+}
+
+/* Create Arrays: */
+CJSON_PUBLIC(cJSON *) cJSON_CreateIntArray(const int *numbers, int count)
+{
+    size_t i = 0;
+    cJSON *n = NULL;
+    cJSON *p = NULL;
+    cJSON *a = NULL;
+
+    if ((count < 0) || (numbers == NULL))
+    {
+        return NULL;
+    }
+
+    a = cJSON_CreateArray();
+    for(i = 0; a && (i < (size_t)count); i++)
+    {
+        n = cJSON_CreateNumber(numbers[i]);
+        if (!n)
+        {
+            cJSON_Delete(a);
+            return NULL;
+        }
+        if(!i)
+        {
+            a->child = n;
+        }
+        else
+        {
+            suffix_object(p, n);
+        }
+        p = n;
+    }
+
+    return a;
+}
+
+CJSON_PUBLIC(cJSON *) cJSON_CreateFloatArray(const float *numbers, int count)
+{
+    size_t i = 0;
+    cJSON *n = NULL;
+    cJSON *p = NULL;
+    cJSON *a = NULL;
+
+    if ((count < 0) || (numbers == NULL))
+    {
+        return NULL;
+    }
+
+    a = cJSON_CreateArray();
+
+    for(i = 0; a && (i < (size_t)count); i++)
+    {
+        n = cJSON_CreateNumber((double)numbers[i]);
+        if(!n)
+        {
+            cJSON_Delete(a);
+            return NULL;
+        }
+        if(!i)
+        {
+            a->child = n;
+        }
+        else
+        {
+            suffix_object(p, n);
+        }
+        p = n;
+    }
+
+    return a;
+}
+
+CJSON_PUBLIC(cJSON *) cJSON_CreateDoubleArray(const double *numbers, int count)
+{
+    size_t i = 0;
+    cJSON *n = NULL;
+    cJSON *p = NULL;
+    cJSON *a = NULL;
+
+    if ((count < 0) || (numbers == NULL))
+    {
+        return NULL;
+    }
+
+    a = cJSON_CreateArray();
+
+    for(i = 0;a && (i < (size_t)count); i++)
+    {
+        n = cJSON_CreateNumber(numbers[i]);
+        if(!n)
+        {
+            cJSON_Delete(a);
+            return NULL;
+        }
+        if(!i)
+        {
+            a->child = n;
+        }
+        else
+        {
+            suffix_object(p, n);
+        }
+        p = n;
+    }
+
+    return a;
+}
+
+CJSON_PUBLIC(cJSON *) cJSON_CreateStringArray(const char *const *strings, int count)
+{
+    size_t i = 0;
+    cJSON *n = NULL;
+    cJSON *p = NULL;
+    cJSON *a = NULL;
+
+    if ((count < 0) || (strings == NULL))
+    {
+        return NULL;
+    }
+
+    a = cJSON_CreateArray();
+
+    for (i = 0; a && (i < (size_t)count); i++)
+    {
+        n = cJSON_CreateString(strings[i]);
+        if(!n)
+        {
+            cJSON_Delete(a);
+            return NULL;
+        }
+        if(!i)
+        {
+            a->child = n;
+        }
+        else
+        {
+            suffix_object(p,n);
+        }
+        p = n;
+    }
+
+    return a;
+}
+
+/* Duplication */
+CJSON_PUBLIC(cJSON *) cJSON_Duplicate(const cJSON *item, cJSON_bool recurse)
+{
+    cJSON *newitem = NULL;
+    cJSON *child = NULL;
+    cJSON *next = NULL;
+    cJSON *newchild = NULL;
+
+    /* Bail on bad ptr */
+    if (!item)
+    {
+        goto fail;
+    }
+    /* Create new item */
+    newitem = cJSON_New_Item(&global_hooks);
+    if (!newitem)
+    {
+        goto fail;
+    }
+    /* Copy over all vars */
+    newitem->type = item->type & (~cJSON_IsReference);
+    newitem->valueint = item->valueint;
+    newitem->valuedouble = item->valuedouble;
+    if (item->valuestring)
+    {
+        newitem->valuestring = (char*)cJSON_strdup((unsigned char*)item->valuestring, &global_hooks);
+        if (!newitem->valuestring)
+        {
+            goto fail;
+        }
+    }
+    if (item->string)
+    {
+        newitem->string = (item->type&cJSON_StringIsConst) ? item->string : (char*)cJSON_strdup((unsigned char*)item->string, &global_hooks);
+        if (!newitem->string)
+        {
+            goto fail;
+        }
+    }
+    /* If non-recursive, then we're done! */
+    if (!recurse)
+    {
+        return newitem;
+    }
+    /* Walk the ->next chain for the child. */
+    child = item->child;
+    while (child != NULL)
+    {
+        newchild = cJSON_Duplicate(child, true); /* Duplicate (with recurse) each item in the ->next chain */
+        if (!newchild)
+        {
+            goto fail;
+        }
+        if (next != NULL)
+        {
+            /* If newitem->child already set, then crosswire ->prev and ->next and move on */
+            next->next = newchild;
+            newchild->prev = next;
+            next = newchild;
+        }
+        else
+        {
+            /* Set newitem->child and move to it */
+            newitem->child = newchild;
+            next = newchild;
+        }
+        child = child->next;
+    }
+
+    return newitem;
+
+fail:
+    if (newitem != NULL)
+    {
+        cJSON_Delete(newitem);
+    }
+
+    return NULL;
+}
+
+static void skip_oneline_comment(char **input)
+{
+    *input += static_strlen("//");
+
+    for (; (*input)[0] != '\0'; ++(*input))
+    {
+        if ((*input)[0] == '\n') {
+            *input += static_strlen("\n");
+            return;
+        }
+    }
+}
+
+static void skip_multiline_comment(char **input)
+{
+    *input += static_strlen("/*");
+
+    for (; (*input)[0] != '\0'; ++(*input))
+    {
+        if (((*input)[0] == '*') && ((*input)[1] == '/'))
+        {
+            *input += static_strlen("*/");
+            return;
+        }
+    }
+}
+
+static void minify_string(char **input, char **output) {
+    (*output)[0] = (*input)[0];
+    *input += static_strlen("\"");
+    *output += static_strlen("\"");
+
+
+    for (; (*input)[0] != '\0'; (void)++(*input), ++(*output)) {
+        (*output)[0] = (*input)[0];
+
+        if ((*input)[0] == '\"') {
+            (*output)[0] = '\"';
+            *input += static_strlen("\"");
+            *output += static_strlen("\"");
+            return;
+        } else if (((*input)[0] == '\\') && ((*input)[1] == '\"')) {
+            (*output)[1] = (*input)[1];
+            *input += static_strlen("\"");
+            *output += static_strlen("\"");
+        }
+    }
+}
+
+CJSON_PUBLIC(void) cJSON_Minify(char *json)
+{
+    char *into = json;
+
+    if (json == NULL)
+    {
+        return;
+    }
+
+    while (json[0] != '\0')
+    {
+        switch (json[0])
+        {
+            case ' ':
+            case '\t':
+            case '\r':
+            case '\n':
+                json++;
+                break;
+
+            case '/':
+                if (json[1] == '/')
+                {
+                    skip_oneline_comment(&json);
+                }
+                else if (json[1] == '*')
+                {
+                    skip_multiline_comment(&json);
+                } else {
+                    json++;
+                }
+                break;
+
+            case '\"':
+                minify_string(&json, (char**)&into);
+                break;
+
+            default:
+                into[0] = json[0];
+                json++;
+                into++;
+        }
+    }
+
+    /* and null-terminate. */
+    *into = '\0';
+}
+
+CJSON_PUBLIC(cJSON_bool) cJSON_IsInvalid(const cJSON * const item)
+{
+    if (item == NULL)
+    {
+        return false;
+    }
+
+    return (item->type & 0xFF) == cJSON_Invalid;
+}
+
+CJSON_PUBLIC(cJSON_bool) cJSON_IsFalse(const cJSON * const item)
+{
+    if (item == NULL)
+    {
+        return false;
+    }
+
+    return (item->type & 0xFF) == cJSON_False;
+}
+
+CJSON_PUBLIC(cJSON_bool) cJSON_IsTrue(const cJSON * const item)
+{
+    if (item == NULL)
+    {
+        return false;
+    }
+
+    return (item->type & 0xff) == cJSON_True;
+}
+
+
+CJSON_PUBLIC(cJSON_bool) cJSON_IsBool(const cJSON * const item)
+{
+    if (item == NULL)
+    {
+        return false;
+    }
+
+    return (item->type & (cJSON_True | cJSON_False)) != 0;
+}
+CJSON_PUBLIC(cJSON_bool) cJSON_IsNull(const cJSON * const item)
+{
+    if (item == NULL)
+    {
+        return false;
+    }
+
+    return (item->type & 0xFF) == cJSON_NULL;
+}
+
+CJSON_PUBLIC(cJSON_bool) cJSON_IsNumber(const cJSON * const item)
+{
+    if (item == NULL)
+    {
+        return false;
+    }
+
+    return (item->type & 0xFF) == cJSON_Number;
+}
+
+CJSON_PUBLIC(cJSON_bool) cJSON_IsString(const cJSON * const item)
+{
+    if (item == NULL)
+    {
+        return false;
+    }
+
+    return (item->type & 0xFF) == cJSON_String;
+}
+
+CJSON_PUBLIC(cJSON_bool) cJSON_IsArray(const cJSON * const item)
+{
+    if (item == NULL)
+    {
+        return false;
+    }
+
+    return (item->type & 0xFF) == cJSON_Array;
+}
+
+CJSON_PUBLIC(cJSON_bool) cJSON_IsObject(const cJSON * const item)
+{
+    if (item == NULL)
+    {
+        return false;
+    }
+
+    return (item->type & 0xFF) == cJSON_Object;
+}
+
+CJSON_PUBLIC(cJSON_bool) cJSON_IsRaw(const cJSON * const item)
+{
+    if (item == NULL)
+    {
+        return false;
+    }
+
+    return (item->type & 0xFF) == cJSON_Raw;
+}
+
+CJSON_PUBLIC(cJSON_bool) cJSON_Compare(const cJSON * const a, const cJSON * const b, const cJSON_bool case_sensitive)
+{
+    if ((a == NULL) || (b == NULL) || ((a->type & 0xFF) != (b->type & 0xFF)) || cJSON_IsInvalid(a))
+    {
+        return false;
+    }
+
+    /* check if type is valid */
+    switch (a->type & 0xFF)
+    {
+        case cJSON_False:
+        case cJSON_True:
+        case cJSON_NULL:
+        case cJSON_Number:
+        case cJSON_String:
+        case cJSON_Raw:
+        case cJSON_Array:
+        case cJSON_Object:
+            break;
+
+        default:
+            return false;
+    }
+
+    /* identical objects are equal */
+    if (a == b)
+    {
+        return true;
+    }
+
+    switch (a->type & 0xFF)
+    {
+        /* in these cases and equal type is enough */
+        case cJSON_False:
+        case cJSON_True:
+        case cJSON_NULL:
+            return true;
+
+        case cJSON_Number:
+            if (compare_double(a->valuedouble, b->valuedouble))
+            {
+                return true;
+            }
+            return false;
+
+        case cJSON_String:
+        case cJSON_Raw:
+            if ((a->valuestring == NULL) || (b->valuestring == NULL))
+            {
+                return false;
+            }
+            if (strcmp(a->valuestring, b->valuestring) == 0)
+            {
+                return true;
+            }
+
+            return false;
+
+        case cJSON_Array:
+        {
+            cJSON *a_element = a->child;
+            cJSON *b_element = b->child;
+
+            for (; (a_element != NULL) && (b_element != NULL);)
+            {
+                if (!cJSON_Compare(a_element, b_element, case_sensitive))
+                {
+                    return false;
+                }
+
+                a_element = a_element->next;
+                b_element = b_element->next;
+            }
+
+            /* one of the arrays is longer than the other */
+            if (a_element != b_element) {
+                return false;
+            }
+
+            return true;
+        }
+
+        case cJSON_Object:
+        {
+            cJSON *a_element = NULL;
+            cJSON *b_element = NULL;
+            cJSON_ArrayForEach(a_element, a)
+            {
+                /* TODO This has O(n^2) runtime, which is horrible! */
+                b_element = get_object_item(b, a_element->string, case_sensitive);
+                if (b_element == NULL)
+                {
+                    return false;
+                }
+
+                if (!cJSON_Compare(a_element, b_element, case_sensitive))
+                {
+                    return false;
+                }
+            }
+
+            /* doing this twice, once on a and b to prevent true comparison if a subset of b
+             * TODO: Do this the proper way, this is just a fix for now */
+            cJSON_ArrayForEach(b_element, b)
+            {
+                a_element = get_object_item(a, b_element->string, case_sensitive);
+                if (a_element == NULL)
+                {
+                    return false;
+                }
+
+                if (!cJSON_Compare(b_element, a_element, case_sensitive))
+                {
+                    return false;
+                }
+            }
+
+            return true;
+        }
+
+        default:
+            return false;
+    }
+}
+
+CJSON_PUBLIC(void *) cJSON_malloc(size_t size)
+{
+    return global_hooks.allocate(size);
+}
+
+CJSON_PUBLIC(void) cJSON_free(void *object)
+{
+    global_hooks.deallocate(object);
+}
diff --git a/app/src/cQueue.c b/app/src/cQueue.c
new file mode 100644 (file)
index 0000000..a7f01cd
--- /dev/null
@@ -0,0 +1,143 @@
+#include <stdlib.h>
+#include <ctype.h>
+#include "cQueue.h"
+
+
+/*
+ * Description  :   create and init the queue.
+ *
+ * @para[in]    :   start   is a pointer to the base address of the message queue
+ *                          storage area,the stroage area MUST be declare as an array
+ *                          of pointers to 'void' as follows
+ *
+ *                          void *messageStroage[size]
+ *
+ * @para[in]    :   size    is the number of elements in the storage area
+ *
+ * @return      :   the pointer to the new queue
+ */
+cQueue_t *cQcreate(int size)
+{
+    cQueue_t *pq = NULL;
+    pq = (cQueue_t *)malloc(sizeof(cQueue_t));
+    if(pq != NULL){             /*      Initialize the queue    */
+        pq->QMemory = (void **)malloc(size*sizeof(void *));
+        pq->QStart      = pq->QMemory;
+        pq->QEnd        = &pq->QMemory[size];
+        pq->QIn         = pq->QMemory;
+        pq->QOut        = pq->QMemory;
+        pq->QSize       = size;
+        pq->QEntries    = 0;
+    }
+    return pq;
+}
+
+/*
+ * Description  :   delete the queue, and free the stroage area
+ *
+ * @para[in]    :   pq      is the pointer to the queue
+ *
+ * @return      :   NULL
+ */
+void cQDelete(cQueue_t *pq)
+{
+       free(pq->QMemory);
+    free(pq);
+}
+
+/*
+ * Description  :   flush the queue, the queue is like the new create state
+ *
+ * @para[in]    :   pq      is the pointer to the queue
+ *
+ * @return      :   NULL
+ */
+void cQFlush(cQueue_t *pq)
+{
+    pq->QIn = pq->QStart;
+    pq->QOut = pq->QStart;
+    pq->QEntries = 0;
+}
+
+
+/*
+ * Description  :   receive msg from queue, if queue is empty,return NULL
+ *
+ * @para[in]    :   pq      is the pointer to the queue
+ *
+ * @para[out]   :   perr    is the pointer to error return
+ *
+ * @return      : the pointer to the receive msg.
+ */
+void *cQRcv(cQueue_t *pq, char *perr)
+{
+    void *pmsg = NULL;
+
+    if(pq->QEntries > 0){                   /* See if any messages in the queue                   */
+       pmsg = *pq->QOut++;                  /* Yes, extract oldest message from the queue         */
+        pq->QEntries--;                     /* Update the number of entries in the queue          */
+        if(pq->QOut == pq->QEnd){           /* Wrap OUT pointer if we are at the end of the queue */
+            pq->QOut = pq->QStart;
+        }
+        *perr = ERR_Q_NONE;
+    }else{
+        *perr = ERR_Q_EMPTY;                /* Queue is empty                                     */
+    }
+
+    return (pmsg);
+}
+
+/*
+ * Description  :   send a message to the queue
+ *
+ * @para[in]    :   pq      is the pointer to the queue
+ *
+ * @para[in]    :   pmsg    is the pointer to new message to send
+ *
+ * @return      :   ERR_Q_NONE      The call was successful and the message was sent
+ *                  ERR_Q_FULL      If the queue cannot accept any more messages because it is full.
+ */
+int cQPost(cQueue_t *pq, void *pmsg)
+{
+    if(pq->QEntries >= pq->QSize){             /* Make sure queue is not full                   */
+        return ERR_Q_FULL;
+    }
+
+    *pq->QIn++ = pmsg;
+
+       pq->QEntries++;
+
+    if(pq->QIn == pq->QEnd){
+        pq->QIn = pq->QStart;
+    }
+
+    return ERR_Q_NONE;
+}
+
+/*
+ * Description  :   send a message to the queue,the message is posted at the FRONT instead of
+ *                  the end of the queue. Using cQPostFront() alllows you to send 'priority'
+ *                  message.
+ *
+ * @para[in]    :   pq      is the pointer to the queue
+ *
+ * @para[in]    :   pmsg    is the pointer to new message to send
+ *
+ * @return      :   ERR_Q_NONE      The call was successful and the message was sent
+ *                  ERR_Q_FULL      If the queue cannot accept any more messages because it is full.
+ */
+int cQPostFront(cQueue_t *pq, void *pmsg)
+{
+    if(pq->QEntries >= pq->QSize){      /* Make sure queue is not full                   */
+        return ERR_Q_FULL;
+    }
+
+    if(pq->QOut == pq->QStart){         /* Wrap OUT ptr if we are at the 1st queue entry */
+        pq->QOut = pq->QEnd;
+    }
+
+    pq->QOut--;
+    *pq->QOut = pmsg;                   /* Insert message into queue                     */
+    pq->QEntries++;                     /* Update the nbr of entries in the queue        */
+    return ERR_Q_NONE;
+}
diff --git a/app/src/crc16.c b/app/src/crc16.c
new file mode 100644 (file)
index 0000000..8f134e6
--- /dev/null
@@ -0,0 +1,133 @@
+/**
+ *
+ *   _  _|  \/  |___  __| | |__ _  _ __|  \/  |__ _ __| |_ ___ _ _
+ *  | || | |\/| / _ \/ _` | '_ \ || (_-< |\/| / _` (_-<  _/ -_) '_|
+ *   \_,_|_|  |_\___/\__,_|_.__/\_,_/__/_|  |_\__,_/__/\__\___|_|
+ *
+ * File      : mbmCRC16.c
+ *  Copyright (C) <2018>  <FlandreUNX>
+ *
+ *  This program is free software: you can redistribute it and/or modify
+ *  it under the terms of the GNU Affero General Public License as
+ *  published by the Free Software Foundation, either version 3 of the
+ *  License, or (at your option) any later version.
+ *
+ *  This program is distributed in the hope that it will be useful,
+ *  but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *  GNU Affero General Public License for more details.
+ *
+ *  You should have received a copy of the GNU Affero General Public License
+ *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
+ */
+
+/* ----------------------- ANSI-C include files -----------------------------*/
+#include <stdbool.h>
+#include <stdint.h>
+/* ----------------------- Modbus core include files -----------------------------*/
+/**
+ * @addtogroup CRC16 const define
+ * @note Private
+ */
+
+/*@{*/
+
+static const uint8_t CRC16_HI[] = {
+  0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41,
+  0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40,
+  0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41,
+  0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41,
+  0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41,
+  0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40,
+  0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40,
+  0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40,
+  0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41,
+  0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40,
+  0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41,
+  0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41,
+  0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41,
+  0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41,
+  0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41,
+  0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41,
+  0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41,
+  0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40,
+  0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41,
+  0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41,
+  0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41,
+  0x00, 0xC1, 0x81, 0x40
+};
+
+static const uint8_t CRC16_LO[] = {
+  0x00, 0xC0, 0xC1, 0x01, 0xC3, 0x03, 0x02, 0xC2, 0xC6, 0x06, 0x07, 0xC7,
+  0x05, 0xC5, 0xC4, 0x04, 0xCC, 0x0C, 0x0D, 0xCD, 0x0F, 0xCF, 0xCE, 0x0E,
+  0x0A, 0xCA, 0xCB, 0x0B, 0xC9, 0x09, 0x08, 0xC8, 0xD8, 0x18, 0x19, 0xD9,
+  0x1B, 0xDB, 0xDA, 0x1A, 0x1E, 0xDE, 0xDF, 0x1F, 0xDD, 0x1D, 0x1C, 0xDC,
+  0x14, 0xD4, 0xD5, 0x15, 0xD7, 0x17, 0x16, 0xD6, 0xD2, 0x12, 0x13, 0xD3,
+  0x11, 0xD1, 0xD0, 0x10, 0xF0, 0x30, 0x31, 0xF1, 0x33, 0xF3, 0xF2, 0x32,
+  0x36, 0xF6, 0xF7, 0x37, 0xF5, 0x35, 0x34, 0xF4, 0x3C, 0xFC, 0xFD, 0x3D,
+  0xFF, 0x3F, 0x3E, 0xFE, 0xFA, 0x3A, 0x3B, 0xFB, 0x39, 0xF9, 0xF8, 0x38,
+  0x28, 0xE8, 0xE9, 0x29, 0xEB, 0x2B, 0x2A, 0xEA, 0xEE, 0x2E, 0x2F, 0xEF,
+  0x2D, 0xED, 0xEC, 0x2C, 0xE4, 0x24, 0x25, 0xE5, 0x27, 0xE7, 0xE6, 0x26,
+  0x22, 0xE2, 0xE3, 0x23, 0xE1, 0x21, 0x20, 0xE0, 0xA0, 0x60, 0x61, 0xA1,
+  0x63, 0xA3, 0xA2, 0x62, 0x66, 0xA6, 0xA7, 0x67, 0xA5, 0x65, 0x64, 0xA4,
+  0x6C, 0xAC, 0xAD, 0x6D, 0xAF, 0x6F, 0x6E, 0xAE, 0xAA, 0x6A, 0x6B, 0xAB,
+  0x69, 0xA9, 0xA8, 0x68, 0x78, 0xB8, 0xB9, 0x79, 0xBB, 0x7B, 0x7A, 0xBA,
+  0xBE, 0x7E, 0x7F, 0xBF, 0x7D, 0xBD, 0xBC, 0x7C, 0xB4, 0x74, 0x75, 0xB5,
+  0x77, 0xB7, 0xB6, 0x76, 0x72, 0xB2, 0xB3, 0x73, 0xB1, 0x71, 0x70, 0xB0,
+  0x50, 0x90, 0x91, 0x51, 0x93, 0x53, 0x52, 0x92, 0x96, 0x56, 0x57, 0x97,
+  0x55, 0x95, 0x94, 0x54, 0x9C, 0x5C, 0x5D, 0x9D, 0x5F, 0x9F, 0x9E, 0x5E,
+  0x5A, 0x9A, 0x9B, 0x5B, 0x99, 0x59, 0x58, 0x98, 0x88, 0x48, 0x49, 0x89,
+  0x4B, 0x8B, 0x8A, 0x4A, 0x4E, 0x8E, 0x8F, 0x4F, 0x8D, 0x4D, 0x4C, 0x8C,
+  0x44, 0x84, 0x85, 0x45, 0x87, 0x47, 0x46, 0x86, 0x82, 0x42, 0x43, 0x83,
+  0x41, 0x81, 0x80, 0x40
+};
+
+/*@}*/
+
+/**
+ * @addtogroup CRC16 functions
+ * @note Private
+ */
+
+/*@{*/
+
+/**
+ * 计算一定长度数据的CRC16值
+ * @note [Rev.1]
+ *
+ * @param *data, 数据
+ * @param length, 长度
+ *
+ * @return uint16_t, 计算结果
+ */
+uint16_t mbm_CRC16Calc(uint8_t *data, uint32_t length)
+{
+  uint8_t crcHI = 0xFF;
+  uint8_t crcLO = 0xFF;
+  int32_t index;
+
+  while (length--) {
+    index = crcLO ^ *(data++);
+    crcLO = (uint8_t) (crcHI ^ CRC16_HI[index]);
+    crcHI = CRC16_LO[index];
+  }
+
+  return (uint16_t) (crcHI << 8 | crcLO);
+}
+
+uint16_t mbm_crc16( uint16_t init, uint8_t *data, uint32_t length)
+{
+  uint8_t crcHI = (init>>8)&0xFF;
+  uint8_t crcLO = init&0xFF;
+  int32_t index;
+
+  while (length--) {
+    index = crcLO ^ *(data++);
+    crcLO = (uint8_t) (crcHI ^ CRC16_HI[index]);
+    crcHI = CRC16_LO[index];
+  }
+
+  return (uint16_t) (crcHI << 8 | crcLO);
+}
+
+/*@}*/
diff --git a/app/src/crc16.h b/app/src/crc16.h
new file mode 100644 (file)
index 0000000..b149a05
--- /dev/null
@@ -0,0 +1,42 @@
+/**
+ *        __  __         _ _            __  __         _
+ *   _  _|  \/  |___  __| | |__ _  _ __|  \/  |__ _ __| |_ ___ _ _
+ *  | || | |\/| / _ \/ _` | '_ \ || (_-< |\/| / _` (_-<  _/ -_) '_|
+ *   \_,_|_|  |_\___/\__,_|_.__/\_,_/__/_|  |_\__,_/__/\__\___|_|
+ *
+ * File      : mbmCRC16.h
+ *  Copyright (C) <2018>  <FlandreUNX>
+ *
+ *  This program is free software: you can redistribute it and/or modify
+ *  it under the terms of the GNU Affero General Public License as
+ *  published by the Free Software Foundation, either version 3 of the
+ *  License, or (at your option) any later version.
+ *
+ *  This program is distributed in the hope that it will be useful,
+ *  but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *  GNU Affero General Public License for more details.
+ *
+ *  You should have received a copy of the GNU Affero General Public License
+ *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
+ */
+
+#ifndef MBMCRC16_H_
+#define MBMCRC16_H_
+
+/* ----------------------- ANSI-C include files -----------------------------*/
+#include <stdbool.h>
+#include <stdint.h>
+
+/**
+ * @addtogroup CRC16 functions
+ * @note Private
+ */
+
+/*@{*/
+
+extern uint16_t mbm_CRC16Calc(uint8_t *data, uint16_t length);
+
+/*@}*/
+
+#endif
diff --git a/app/src/dev_info.c b/app/src/dev_info.c
new file mode 100644 (file)
index 0000000..159910b
--- /dev/null
@@ -0,0 +1,482 @@
+#include <stdio.h>
+#include <stdint.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+#include <time.h>
+#include <sys/time.h>
+#include <pthread.h>
+
+#include "dev_info.h"
+
+dev_info_t g_dev_info;
+
+static inline uint32_t get_time_ms(void)
+{
+    struct timeval tv;
+    gettimeofday(&tv, NULL);
+    return (uint32_t)(tv.tv_sec * 1000 + tv.tv_usec / 1000);
+}
+
+/* 公开的加锁/解锁(所有 UI/D-Bus/主任务状态更新统一使用同一把锁) */
+void dev_lock(void)
+{
+    pthread_mutex_lock(&g_dev_info.lock);
+}
+
+void dev_unlock(void)
+{
+    pthread_mutex_unlock(&g_dev_info.lock);
+}
+
+int dev_info_init(void)
+{
+    int i;
+    memset(&g_dev_info, 0, sizeof(g_dev_info));
+
+    pthread_mutex_init(&g_dev_info.lock, NULL);
+
+    g_dev_info.state = DEV_INIT;
+
+    g_dev_info.selftest.item_count = SELFTEST_ITEM_MAX;
+    for (i = 0; i < SELFTEST_ITEM_MAX; i++) {
+        g_dev_info.selftest.items[i].id = i + 1;
+        g_dev_info.selftest.items[i].state = ST_ITEM_PENDING;
+        g_dev_info.selftest.items[i].fault_code = 0;
+    }
+
+    g_dev_info.test.step_count = TEST_STEP_MAX;
+    for (i = 0; i < TEST_STEP_MAX; i++) {
+        g_dev_info.test.steps[i].step_id = i + 1;
+        g_dev_info.test.steps[i].state = TEST_STEP_IDLE;
+        g_dev_info.test.steps[i].fault_code = 0;
+    }
+
+    g_dev_info.debug.state = DEBUG_IDLE;
+    g_dev_info.debug.fault_code = 0;
+
+    g_dev_info.cfg.selftest_item_number = SELFTEST_ITEM_MAX;
+    g_dev_info.cfg.test_step_number = TEST_STEP_MAX;
+
+    return 0;
+}
+
+int dev_info_deinit(void)
+{
+    pthread_mutex_destroy(&g_dev_info.lock);
+    return 0;
+}
+
+dev_state_t dev_get_state(void)
+{
+    dev_state_t s;
+    dev_lock();
+    s = g_dev_info.state;
+    dev_unlock();
+    return s;
+}
+
+int dev_set_state(dev_state_t s)
+{
+    if (s < 0 || s >= DEV_STATE_NUM) {
+        return -1;
+    }
+    dev_lock();
+    g_dev_info.state = s;
+    dev_unlock();
+    return 0;
+}
+
+int dev_selftest_set_item_name(int idx, const char *name)
+{
+    if (idx < 0 || idx >= SELFTEST_ITEM_MAX || name == NULL) {
+        return -1;
+    }
+    dev_lock();
+    strncpy(g_dev_info.selftest.items[idx].name, name, DEVICE_NAME_LEN - 1);
+    dev_unlock();
+    return 0;
+}
+
+int dev_selftest_start_item(int idx)
+{
+    if (idx < 0 || idx >= SELFTEST_ITEM_MAX) {
+        return -1;
+    }
+    dev_lock();
+    g_dev_info.selftest.current_idx = idx;
+    g_dev_info.selftest.items[idx].state = ST_ITEM_TESTING;
+    g_dev_info.selftest.items[idx].fault_code = 0;
+    g_dev_info.selftest.items[idx].fault_msg[0] = '\0';
+    g_dev_info.selftest.items[idx].start_time = time(NULL);
+    g_dev_info.selftest.items[idx].duration_ms = 0;
+    dev_unlock();
+    return 0;
+}
+
+int dev_selftest_pass_item(int idx)
+{
+    if (idx < 0 || idx >= SELFTEST_ITEM_MAX) {
+        return -1;
+    }
+    dev_lock();
+    g_dev_info.selftest.items[idx].state = ST_ITEM_PASS;
+    g_dev_info.selftest.items[idx].fault_code = 0;
+    g_dev_info.selftest.items[idx].end_time = time(NULL);
+    g_dev_info.selftest.items[idx].duration_ms = get_time_ms() -
+        (uint32_t)(g_dev_info.selftest.items[idx].start_time * 1000);
+    dev_unlock();
+    return 0;
+}
+
+int dev_selftest_fail_item(int idx, int32_t fault_code, const char *fault_msg)
+{
+    if (idx < 0 || idx >= SELFTEST_ITEM_MAX) {
+        return -1;
+    }
+    dev_lock();
+    g_dev_info.selftest.items[idx].state = ST_ITEM_FAIL;
+    g_dev_info.selftest.items[idx].fault_code = fault_code;
+    if (fault_msg != NULL) {
+        strncpy(g_dev_info.selftest.items[idx].fault_msg, fault_msg, FAULT_MSG_LEN - 1);
+    }
+    g_dev_info.selftest.items[idx].end_time = time(NULL);
+    g_dev_info.selftest.items[idx].duration_ms = get_time_ms() -
+        (uint32_t)(g_dev_info.selftest.items[idx].start_time * 1000);
+    dev_unlock();
+    return 0;
+}
+
+int dev_selftest_start_all(void)
+{
+    int i;
+    dev_lock();
+    g_dev_info.state = DEV_SELFTESTING;
+    g_dev_info.selftest.current_idx = -1;
+    g_dev_info.selftest.total_fault_code = 0;
+    g_dev_info.selftest.start_time = time(NULL);
+    g_dev_info.selftest.total_duration_ms = 0;
+    for (i = 0; i < SELFTEST_ITEM_MAX; i++) {
+        g_dev_info.selftest.items[i].state = ST_ITEM_PENDING;
+        g_dev_info.selftest.items[i].fault_code = 0;
+        g_dev_info.selftest.items[i].fault_msg[0] = '\0';
+        g_dev_info.selftest.items[i].duration_ms = 0;
+    }
+    dev_unlock();
+    return 0;
+}
+
+int dev_selftest_finish_all(int32_t total_fault)
+{
+    dev_lock();
+    g_dev_info.selftest.total_fault_code = total_fault;
+    g_dev_info.selftest.end_time = time(NULL);
+    g_dev_info.selftest.total_duration_ms = get_time_ms() -
+        (uint32_t)(g_dev_info.selftest.start_time * 1000);
+    if (total_fault == 0) {
+        g_dev_info.state = DEV_READY;
+    } else {
+        g_dev_info.state = DEV_SELFTEST_FAILED;
+    }
+    dev_unlock();
+    return 0;
+}
+
+int dev_selftest_get_item(int idx, selftest_item_t *out)
+{
+    if (idx < 0 || idx >= SELFTEST_ITEM_MAX || out == NULL) {
+        return -1;
+    }
+    dev_lock();
+    memcpy(out, &g_dev_info.selftest.items[idx], sizeof(selftest_item_t));
+    dev_unlock();
+    return 0;
+}
+
+int dev_selftest_get_info(selftest_info_t *out)
+{
+    if (out == NULL) {
+        return -1;
+    }
+    dev_lock();
+    memcpy(out, &g_dev_info.selftest, sizeof(selftest_info_t));
+    dev_unlock();
+    return 0;
+}
+
+int dev_test_set_step_name(int idx, const char *name)
+{
+    if (idx < 0 || idx >= TEST_STEP_MAX || name == NULL) {
+        return -1;
+    }
+    dev_lock();
+    strncpy(g_dev_info.test.steps[idx].name, name, DEVICE_NAME_LEN - 1);
+    dev_unlock();
+    return 0;
+}
+
+int dev_test_set_step_timing(int idx, int32_t total_time_s)
+{
+    if (idx < 0 || idx >= TEST_STEP_MAX) {
+        return -1;
+    }
+    dev_lock();
+    g_dev_info.test.steps[idx].total_time_s = total_time_s;
+    g_dev_info.test.steps[idx].remain_time_s = total_time_s;
+    dev_unlock();
+    return 0;
+}
+
+int dev_test_start_step(int step_idx)
+{
+    if (step_idx < 0 || step_idx >= TEST_STEP_MAX) {
+        return -1;
+    }
+    dev_lock();
+    g_dev_info.state = DEV_TESTING;
+    g_dev_info.test.current_step = step_idx;
+    g_dev_info.test.steps[step_idx].state = TEST_STEP_RUNNING;
+    g_dev_info.test.steps[step_idx].fault_code = 0;
+    g_dev_info.test.steps[step_idx].fault_msg[0] = '\0';
+    g_dev_info.test.steps[step_idx].start_time = time(NULL);
+    g_dev_info.test.steps[step_idx].duration_ms = 0;
+    g_dev_info.test.steps[step_idx].remain_time_s = g_dev_info.test.steps[step_idx].total_time_s;
+    dev_unlock();
+    return 0;
+}
+
+int dev_test_update_remain(int step_idx, int32_t remain_s)
+{
+    if (step_idx < 0 || step_idx >= TEST_STEP_MAX) {
+        return -1;
+    }
+    dev_lock();
+    g_dev_info.test.steps[step_idx].remain_time_s = remain_s;
+    dev_unlock();
+    return 0;
+}
+
+int dev_test_pass_step(int step_idx)
+{
+    if (step_idx < 0 || step_idx >= TEST_STEP_MAX) {
+        return -1;
+    }
+    dev_lock();
+    g_dev_info.test.steps[step_idx].state = TEST_STEP_PASS;
+    g_dev_info.test.steps[step_idx].fault_code = 0;
+    g_dev_info.test.steps[step_idx].remain_time_s = 0;
+    g_dev_info.test.steps[step_idx].end_time = time(NULL);
+    g_dev_info.test.steps[step_idx].duration_ms = get_time_ms() -
+        (uint32_t)(g_dev_info.test.steps[step_idx].start_time * 1000);
+    dev_unlock();
+    return 0;
+}
+
+int dev_test_fail_step(int step_idx, int32_t fault_code, const char *fault_msg)
+{
+    if (step_idx < 0 || step_idx >= TEST_STEP_MAX) {
+        return -1;
+    }
+    dev_lock();
+    g_dev_info.test.steps[step_idx].state = TEST_STEP_FAIL;
+    g_dev_info.test.steps[step_idx].fault_code = fault_code;
+    if (fault_msg != NULL) {
+        strncpy(g_dev_info.test.steps[step_idx].fault_msg, fault_msg, FAULT_MSG_LEN - 1);
+    }
+    g_dev_info.test.steps[step_idx].remain_time_s = 0;
+    g_dev_info.test.steps[step_idx].end_time = time(NULL);
+    g_dev_info.test.steps[step_idx].duration_ms = get_time_ms() -
+        (uint32_t)(g_dev_info.test.steps[step_idx].start_time * 1000);
+    g_dev_info.test.total_fault_code = fault_code;
+    dev_unlock();
+    return 0;
+}
+
+int dev_test_start_all(void)
+{
+    int i;
+    dev_lock();
+    g_dev_info.state = DEV_TESTING;
+    g_dev_info.test.current_step = -1;
+    g_dev_info.test.total_fault_code = 0;
+    g_dev_info.test.start_time = time(NULL);
+    g_dev_info.test.total_duration_ms = 0;
+    for (i = 0; i < TEST_STEP_MAX; i++) {
+        g_dev_info.test.steps[i].state = TEST_STEP_IDLE;
+        g_dev_info.test.steps[i].fault_code = 0;
+        g_dev_info.test.steps[i].fault_msg[0] = '\0';
+        g_dev_info.test.steps[i].duration_ms = 0;
+        g_dev_info.test.steps[i].remain_time_s = g_dev_info.test.steps[i].total_time_s;
+    }
+    dev_unlock();
+    return 0;
+}
+
+int dev_test_finish_all(int32_t total_fault)
+{
+    dev_lock();
+    g_dev_info.test.total_fault_code = total_fault;
+    g_dev_info.test.end_time = time(NULL);
+    g_dev_info.test.total_duration_ms = get_time_ms() -
+        (uint32_t)(g_dev_info.test.start_time * 1000);
+    /* 最终状态 (DEV_TEST_COMPLETED / DEV_TEST_ERROR) 由调用方显式设置 */
+    dev_unlock();
+    return 0;
+}
+
+int dev_test_get_step(int idx, test_step_t *out)
+{
+    if (idx < 0 || idx >= TEST_STEP_MAX || out == NULL) {
+        return -1;
+    }
+    dev_lock();
+    memcpy(out, &g_dev_info.test.steps[idx], sizeof(test_step_t));
+    dev_unlock();
+    return 0;
+}
+
+int dev_test_get_info(test_info_t *out)
+{
+    if (out == NULL) {
+        return -1;
+    }
+    dev_lock();
+    memcpy(out, &g_dev_info.test, sizeof(test_info_t));
+    dev_unlock();
+    return 0;
+}
+
+int dev_debug_start(int cmd_id, const char *cmd_name)
+{
+    dev_lock();
+    g_dev_info.state = DEV_MANUAL_DEBUG;
+    g_dev_info.debug.cmd_id = cmd_id;
+    if (cmd_name != NULL) {
+        strncpy(g_dev_info.debug.cmd_name, cmd_name, DEVICE_NAME_LEN - 1);
+    }
+    g_dev_info.debug.state = DEBUG_RUNNING;
+    g_dev_info.debug.fault_code = 0;
+    g_dev_info.debug.fault_msg[0] = '\0';
+    g_dev_info.debug.start_time = time(NULL);
+    g_dev_info.debug.duration_ms = 0;
+    dev_unlock();
+    return 0;
+}
+
+int dev_debug_finish(int32_t fault_code, const char *fault_msg)
+{
+    dev_lock();
+    g_dev_info.debug.fault_code = fault_code;
+    if (fault_msg != NULL) {
+        strncpy(g_dev_info.debug.fault_msg, fault_msg, FAULT_MSG_LEN - 1);
+    }
+    g_dev_info.debug.end_time = time(NULL);
+    g_dev_info.debug.duration_ms = get_time_ms() -
+        (uint32_t)(g_dev_info.debug.start_time * 1000);
+    if (fault_code == 0) {
+        g_dev_info.debug.state = DEBUG_DONE;
+    } else {
+        g_dev_info.debug.state = DEBUG_FAULT;
+    }
+    /* 保持 DEV_MANUAL_DEBUG,直到用户显式退出调试模式 */
+    g_dev_info.state = DEV_MANUAL_DEBUG;
+    dev_unlock();
+    return 0;
+}
+
+int dev_debug_get_info(debug_info_t *out)
+{
+    if (out == NULL) {
+        return -1;
+    }
+    dev_lock();
+    memcpy(out, &g_dev_info.debug, sizeof(debug_info_t));
+    dev_unlock();
+    return 0;
+}
+
+int dev_cfg_set_lxj(int work_time_s, int speed_rpm)
+{
+    dev_lock();
+    g_dev_info.cfg.lxj_cfg.lxj_work_time_s = work_time_s;
+    g_dev_info.cfg.lxj_cfg.lxj_speed_rpm = speed_rpm;
+    dev_unlock();
+    return 0;
+}
+
+int dev_cfg_set_ody(int work_time_s, int speed_rpm)
+{
+    dev_lock();
+    g_dev_info.cfg.ody_cfg.ody_work_time_s = work_time_s;
+    g_dev_info.cfg.ody_cfg.ody_speed_rpm = speed_rpm;
+    dev_unlock();
+    return 0;
+}
+
+int dev_cfg_set_yyq(int idx, int x1, int y1, int z1, int x2, int y2, int z2)
+{
+    if (idx < 0 || idx >= YYQ_NUM_MAX) {
+        return -1;
+    }
+    dev_lock();
+    g_dev_info.cfg.yyq_cfg[idx].x1 = x1;
+    g_dev_info.cfg.yyq_cfg[idx].y1 = y1;
+    g_dev_info.cfg.yyq_cfg[idx].z1 = z1;
+    g_dev_info.cfg.yyq_cfg[idx].x2 = x2;
+    g_dev_info.cfg.yyq_cfg[idx].y2 = y2;
+    g_dev_info.cfg.yyq_cfg[idx].z2 = z2;
+    dev_unlock();
+    return 0;
+}
+
+int dev_cfg_get(device_cfg_t *out)
+{
+    if (out == NULL) {
+        return -1;
+    }
+    dev_lock();
+    memcpy(out, &g_dev_info.cfg, sizeof(device_cfg_t));
+    dev_unlock();
+    return 0;
+}
+
+int dev_reset_to_normal(void)
+{
+    dev_lock();
+    g_dev_info.state = DEV_READY;
+    dev_unlock();
+    return 0;
+}
+
+int dev_get_snapshot(dev_info_t *out)
+{
+    if (out == NULL) {
+        return -1;
+    }
+    dev_lock();
+    memcpy(out, &g_dev_info, sizeof(dev_info_t));
+    dev_unlock();
+    return 0;
+}
+
+/*============================================================================
+ * 移液器参数 param.pipette[] 的线程安全访问
+ *  pip_id: 1..YYQ_NUM_MAX  (对应内部 index: pip_id-1)
+ *==========================================================================*/
+int dev_param_get_pipette(int pip_id, pipette_cfg_t *out)
+{
+    if (!out || pip_id < 1 || pip_id > YYQ_NUM_MAX) return -1;
+    dev_lock();
+    memcpy(out, &g_dev_info.cfg.yyq_cfg[pip_id - 1], sizeof(pipette_cfg_t));
+    dev_unlock();
+    return 0;
+}
+
+int dev_param_set_pipette(int pip_id, const pipette_cfg_t *cfg)
+{
+    if (!cfg || pip_id < 1 || pip_id > YYQ_NUM_MAX) return -1;
+    dev_lock();
+    memcpy(&g_dev_info.cfg.yyq_cfg[pip_id - 1], cfg, sizeof(pipette_cfg_t));
+    dev_unlock();
+    return 0;
+}
\ No newline at end of file
diff --git a/app/src/maintask.c b/app/src/maintask.c
new file mode 100644 (file)
index 0000000..fdab0cf
--- /dev/null
@@ -0,0 +1,738 @@
+#include <stdio.h>
+#include <stdint.h>
+#include <stdlib.h>
+#include <stdarg.h>
+#include <string.h>
+#include <unistd.h>
+#include <errno.h>
+#include <pthread.h>
+
+#include "maintask.h"
+#include "dev_info.h"
+#include "motor.h"
+#include "pipette.h"
+#include "robot.h"
+#include "ad_log.h"
+#include "cQueue.h"
+
+/* ui.c 中暴露给业务层发状态变化事件 */
+extern int ui_srv_send_event(const char *json_payload);
+
+#ifndef LOG_INFO
+#define LOG_INFO(fmt, args...)   do { printf("[MT ][INFO ] " fmt, ##args); } while(0)
+#define LOG_ERROR(fmt, args...)  do { printf("[MT ][ERROR] " fmt, ##args); } while(0)
+#endif
+
+/*============================================================================
+ * 模块内部变量
+ *==========================================================================*/
+static pthread_t      s_tid;
+static volatile int   s_running;
+static volatile int   s_thread_inited;
+
+static cQueue_t      *s_cmd_q;            /* UI -> 主任务 的命令队列 */
+static pthread_mutex_t s_cmd_lock;        /* 防止命令并发 enqueue,其实 cQPost 自处理,加一层保险 */
+static pthread_cond_t  s_cancel_cond;     /* 用于暂停/恢复、停止的通知 */
+static pthread_mutex_t s_cancel_lock;
+
+/* 协作式控制请求标志 (test loop 定期检查) */
+static volatile int   s_req_stop;        /* 1 = 用户要求停止当前测试/调试 */
+static volatile int   s_req_pause;       /* 1 = 用户要求暂停 */
+static volatile int   s_paused;          /* 1 = 当前确实处于暂停中 */
+static volatile int   s_debugging;       /* 1 = 正在手动调试模式 */
+
+/* 自动测试完成结果: 0 未开始, 1 成功, -1 失败/被停止  保存给 DEV_TEST_COMPLETED/ERROR 状态 */
+static volatile int   s_last_test_result;
+static char           s_last_fault_msg[128];
+
+/*============================================================================
+ * 工具/宏
+ *==========================================================================*/
+#define SELFTEST_ITEM_DEF_NUM       7   /* 按 agridetect.h 注释: 涡动/离心/移液1~4/机械臂 共7项 */
+#define AUTOTEST_ACT_NUM           20   /* 注释中自动检测动作 1~20 */
+
+static int sleep_ms_(int ms)
+{
+    struct timespec ts;
+    if (ms <= 0) return 0;
+    ts.tv_sec  = ms / 1000;
+    ts.tv_nsec = (long)(ms % 1000) * 1000000L;
+    return nanosleep(&ts, NULL);
+}
+
+static void set_state_and_notify(dev_state_t s, const char *extra_json)
+{
+    dev_set_state(s);
+
+    char payload[256];
+    if (extra_json && *extra_json) {
+        snprintf(payload, sizeof(payload),
+                 "{\"event\":\"state_changed\",\"state\":%d,%s}",
+                 (int)s, extra_json);
+    } else {
+        snprintf(payload, sizeof(payload),
+                 "{\"event\":\"state_changed\",\"state\":%d}",
+                 (int)s);
+    }
+    ui_srv_send_event(payload);
+}
+
+void maintask_notify_state_changed(const char *extra_json)
+{
+    set_state_and_notify(dev_get_state(), extra_json);
+}
+
+/*============================================================================
+ * 对外 API:命令投递
+ *==========================================================================*/
+int maintask_cmd_post(const mt_cmd_t *cmd)
+{
+    if (cmd == NULL) return -1;
+    if (!s_thread_inited) return -1;
+
+    mt_cmd_t *copy = (mt_cmd_t *)calloc(1, sizeof(mt_cmd_t));
+    if (copy == NULL) return -1;
+    memcpy(copy, cmd, sizeof(mt_cmd_t));
+
+    pthread_mutex_lock(&s_cmd_lock);
+    int rc = cQPost(s_cmd_q, copy);
+    pthread_mutex_unlock(&s_cmd_lock);
+
+    /* 唤醒主任务阻塞在 cancel_cond (暂停中) 的情况,让它去取命令 */
+    pthread_mutex_lock(&s_cancel_lock);
+    s_req_stop  = s_req_stop; /* no-op */
+    pthread_cond_broadcast(&s_cancel_cond);
+    pthread_mutex_unlock(&s_cancel_lock);
+
+    if (rc != ERR_Q_NONE) {
+        free(copy);
+        return -1;
+    }
+    return 0;
+}
+
+int maintask_should_stop(void)
+{
+    return s_req_stop ? -1 : 0;
+}
+
+/* 每一步骤之间的协作断点:处理暂停(阻塞等到恢复) + 返回是否要求停止 */
+int maintask_breakpoint(void)
+{
+    if (s_req_stop) return -1;
+
+    /* 暂停请求 -> 进入暂停,阻塞直到 resume 或 stop */
+    if (s_req_pause && !s_paused) {
+        s_paused = 1;
+        set_state_and_notify(DEV_TEST_PAUSED, "\"paused\":1");
+        LOG_INFO("autotest paused\n");
+    }
+
+    while (s_paused) {
+        if (s_req_stop) {
+            s_paused = 0;
+            s_req_pause = 0;
+            return -1;
+        }
+        pthread_mutex_lock(&s_cancel_lock);
+        pthread_cond_wait(&s_cancel_cond, &s_cancel_lock);
+        pthread_mutex_unlock(&s_cancel_lock);
+    }
+    return 0;
+}
+
+/* 可取消 sleep:每 20ms 检查一次停止/暂停 */
+int maintask_cancellable_sleep_ms(int ms_total)
+{
+    int remain = ms_total;
+    while (remain > 0) {
+        int step = (remain > 20) ? 20 : remain;
+        sleep_ms_(step);
+        remain -= step;
+        if (s_req_stop) return -1;
+        if (s_req_pause) {
+            int br = maintask_breakpoint();
+            if (br < 0) return -1;
+        }
+    }
+    return 0;
+}
+
+int maintask_is_running(void) { return s_thread_inited && s_running; }
+
+/*============================================================================
+ * 子系统自检 (设备自检 7 项 对应 SELFTEST_ITEM_DEF_NUM)
+ *==========================================================================*/
+static const char *const s_st_name[SELFTEST_ITEM_DEF_NUM] = {
+    "涡动仪",      /* 0 */
+    "离心机",      /* 1 */
+    "移液器1",     /* 2 */
+    "移液器2",     /* 3 */
+    "移液器3",     /* 4 */
+    "移液器4",     /* 5 */
+    "机械臂"       /* 6 */
+};
+
+/* 返回 0 全部通过,非0表示有几项失败 */
+static int run_selftest_sequence(void)
+{
+    int i, fail_cnt = 0;
+
+    dev_selftest_start_all();
+    for (i = 0; i < SELFTEST_ITEM_DEF_NUM; i++) {
+        dev_selftest_set_item_name(i, s_st_name[i]);
+        dev_selftest_start_item(i);
+    }
+    set_state_and_notify(DEV_SELFTESTING, NULL);
+#if 1
+    // 模拟自检通过,调试用
+    for( i=0; i<SELFTEST_ITEM_DEF_NUM; i++)
+    {
+        dev_selftest_pass_item(i);
+        usleep(500*1000);
+    }
+    dev_selftest_fail_item(3, -1, "移液器2-通信故障");
+    dev_selftest_fail_item(5, -1, "移液器4-通信故障");
+    fail_cnt = 2;
+
+#else
+    /* 1. 涡动仪/离心机/IO: 占位 (实际硬件到位后接入 485/GPIO)
+     *    由于硬件可能未就绪,这里保持 PASS 不阻塞启动,调试时再改为实测 */
+    for (i = 0; i < 2; i++) {
+        (void)maintask_cancellable_sleep_ms(300);
+        if (s_req_stop) { dev_selftest_fail_item(i, -200, "aborted"); fail_cnt++; continue; }
+        dev_selftest_pass_item(i);
+    }
+
+    /* 2. 移液器 1~4: 调用 pipette_init 做回零,作为自检 */
+    for (i = 2; i <= 5; i++) {
+        int yyq_id = i - 1;   /* 移液器 1..4 */
+        int ok = pipette_init(yyq_id);
+        (void)maintask_cancellable_sleep_ms(100);
+        if (ok == PIPETTE_OK) {
+            dev_selftest_pass_item(i);
+        } else {
+            char msg[64];
+            snprintf(msg, sizeof(msg), "移液器%d init fail=%d", yyq_id, ok);
+            LOG_ERROR("%s\n", msg);
+            dev_selftest_fail_item(i, ok, msg);
+            fail_cnt++;
+        }
+    }
+
+    /* 3. 机械臂:调用 robot_connect 做 socket PING + 机器人状态查询 */
+    {
+        int ok = robot_connect();
+        if (ok == ROBOT_OK) {
+            dev_selftest_pass_item(6);
+        } else {
+            char msg[64];
+            snprintf(msg, sizeof(msg), "机械臂 connect fail=%d", ok);
+            LOG_ERROR("%s\n", msg);
+            dev_selftest_fail_item(6, ok, msg);
+            fail_cnt++;
+        }
+    }
+#endif
+    dev_selftest_finish_all(fail_cnt ? -1 : 0);
+
+    /* selftest 数据统一存储在 g_dev_info.selftest (dev_info.h),
+       ui.c query_state 直接从那里读取,无需同步到 agridetect_t */
+
+    return fail_cnt;
+}
+
+/*============================================================================
+ * 自动测试流程 (agridetect.h 主注释的 1..20 步)
+ *  每个动作调用一次 maintask_breakpoint() 检查暂停/停止
+ *  正常返回 0;用户停止返回 -1;动作故障返回 -2~
+ *  步骤状态统一写入 g_dev_info.test (dev_info.h)  通过 dev_test_*() API
+ *==========================================================================*/
+
+/* --- 辅助:把单个自动测试动作的结果写入 g_dev_info.test.steps[step_idx] --- */
+static int commit_step_result(int step_idx, int ret, int fail_fault_code, const char *fail_msg)
+{
+    if (step_idx < 0 || step_idx >= TEST_STEP_MAX) {
+        maintask_notify_state_changed(NULL);
+        return (ret == 0) ? 0 : -1;
+    }
+    if (ret == 0) {
+        dev_test_pass_step(step_idx);
+    } else {
+        char msg[128];
+        if (fail_msg && *fail_msg) snprintf(msg, sizeof(msg), "%s(ret=%d)", fail_msg, ret);
+        else                       snprintf(msg, sizeof(msg), "step%d fail(ret=%d)", step_idx + 1, ret);
+        dev_test_fail_step(step_idx, fail_fault_code, msg);
+    }
+    maintask_notify_state_changed(NULL);
+    return (ret == 0) ? 0 : (fail_fault_code >= -8 && fail_fault_code < 0) ? fail_fault_code : -1;
+}
+
+static int robot_move_to_(int step_idx, int act_id, const char *name)
+{
+    LOG_INFO("[step%d] robot act %d:%s start\n", step_idx + 1, act_id, name ? name : "");
+    if (step_idx >= 0 && step_idx < TEST_STEP_MAX) dev_test_start_step(step_idx);
+    int ret = robot_act(act_id, 15);
+    /* ROBOT_OK(0) -> pass; 否则故障码 ACT_FAULT_2 = -2 */
+    return commit_step_result(step_idx, ret, -2, "机器人通信/动作失败");
+}
+
+static int pipette_act_(int step_idx, int pip_id, int act_id)
+{
+    LOG_INFO("[step%d] pipette%d act %d start\n", step_idx + 1, pip_id, act_id);
+    if (step_idx >= 0 && step_idx < TEST_STEP_MAX) dev_test_start_step(step_idx);
+    int ret = pipette_act(pip_id, act_id);
+    return commit_step_result(step_idx, ret, -3, "移液器动作失败");
+}
+
+static int timed_device_wait_(int step_idx, const char *name, int sec)
+{
+    LOG_INFO("[step%d] %s run %ds timer\n", step_idx + 1, name ? name : "device", sec);
+    if (step_idx >= 0 && step_idx < TEST_STEP_MAX) dev_test_start_step(step_idx);
+    int ret = maintask_cancellable_sleep_ms(sec * 1000);
+    return commit_step_result(step_idx, ret, -4, "设备定时等待被中止");
+}
+
+static int set_step_running(int step_idx)
+{
+    if (step_idx < 0 || step_idx >= TEST_STEP_MAX) return -1;
+    dev_test_start_step(step_idx);
+    maintask_notify_state_changed(NULL);
+    return 0;
+}
+
+static int run_autotest_sequence(void)
+{
+    int ret, step_idx;
+    s_last_test_result = 0;
+    s_last_fault_msg[0] = 0;
+
+    /* 先把 test step 的 name/timing 初始化 (可选),这里让 start_all 走默认即可 */
+    dev_test_start_all();
+    set_state_and_notify(DEV_TESTING, NULL);
+
+#define SET_RUNNING(_idx)  set_step_running(_idx)
+
+    /* 步骤1: 用户已在工位1放好样本 -> 直接进下一步 */
+    step_idx = 0; dev_test_start_step(step_idx);
+
+    /* 步骤2: 机械臂 工1->工2 */
+    if (maintask_breakpoint() < 0) goto user_stop;
+    SET_RUNNING(step_idx);
+    if (robot_move_to_(step_idx, 1, "工位1->工位2") < 0) goto fault;
+    dev_test_pass_step(step_idx);
+
+    /* 步骤3: 移液器1加提取液 pipette_act(1,1)  */
+    step_idx = 1;
+    if (maintask_breakpoint() < 0) goto user_stop;
+    SET_RUNNING(step_idx);
+    if (pipette_act_(step_idx, 1, 1) < 0) goto fault;
+
+    /* 步骤4: 机械臂 工2->工3 */
+    step_idx = 2;
+    if (maintask_breakpoint() < 0) goto user_stop;
+    if (robot_move_to_(step_idx, 2, "工位2->工位3") < 0) goto fault;
+
+    /* 步骤5: 启动涡动仪 定时关闭 */
+    step_idx = 3;
+    if (maintask_breakpoint() < 0) goto user_stop;
+    SET_RUNNING(step_idx);
+    if (timed_device_wait_(step_idx, "涡动仪", 5) < 0) goto user_stop;
+
+    /* 步骤6: 机械臂 工3->工4 */
+    step_idx = 4;
+    if (maintask_breakpoint() < 0) goto user_stop;
+    if (robot_move_to_(step_idx, 3, "工位3->工位4") < 0) goto fault;
+
+    /* 步骤7: 启动离心机 定时关闭 */
+    step_idx = 5;
+    if (maintask_breakpoint() < 0) goto user_stop;
+    SET_RUNNING(step_idx);
+    if (timed_device_wait_(step_idx, "离心机", 8) < 0) goto user_stop;
+
+    /* 步骤8: 机械臂 工4->工5 */
+    step_idx = 6;
+    if (maintask_breakpoint() < 0) goto user_stop;
+    if (robot_move_to_(step_idx, 4, "工位4->工位5") < 0) goto fault;
+
+    /* 步骤9: 移液器2 吸样本液 pipette_act(2,1) */
+    step_idx = 7;
+    if (maintask_breakpoint() < 0) goto user_stop;
+    SET_RUNNING(step_idx);
+    if (pipette_act_(step_idx, 2, 1) < 0) goto fault;
+
+    /* 步骤10: 机械臂 工5->工8(废液仓)  (超出 TEST_STEP_MAX=10, 不写入 steps[],仅执行动作) */
+    if (maintask_breakpoint() < 0) goto user_stop;
+    if (robot_move_to_(TEST_STEP_MAX, 5, "工位5->废液仓") < 0) goto fault;
+
+    /* 步骤11: 机械臂 工9->工5 拿新离心管 */
+    if (maintask_breakpoint() < 0) goto user_stop;
+    if (robot_move_to_(TEST_STEP_MAX, 6, "工位9->工位5(新管)") < 0) goto fault;
+
+    /* 步骤12: 移液器2 注样本液 pipette_act(2,2)  -> step_idx=7 同槽共用 */
+    step_idx = 7;
+    if (maintask_breakpoint() < 0) goto user_stop;
+    SET_RUNNING(step_idx);
+    if (pipette_act_(step_idx, 2, 2) < 0) goto fault;
+
+    /* 步骤13: 机械臂 工5->工6 */
+    if (maintask_breakpoint() < 0) goto user_stop;
+    if (robot_move_to_(TEST_STEP_MAX, 7, "工位5->工位6") < 0) goto fault;
+
+    /* 步骤14: 移液器3 二次加提取液 pipette_act(3,1)  -> 复用 step_idx=8 */
+    step_idx = 8;
+    if (maintask_breakpoint() < 0) goto user_stop;
+    SET_RUNNING(step_idx);
+    if (pipette_act_(step_idx, 3, 1) < 0) goto fault;
+
+    /* 步骤15: 机械臂 工6->工3 */
+    if (maintask_breakpoint() < 0) goto user_stop;
+    if (robot_move_to_(TEST_STEP_MAX, 8, "工位6->工位3") < 0) goto fault;
+
+    /* 步骤16: 再涡动 */
+    step_idx = 9; /* 最后一个 step 槽 */
+    if (maintask_breakpoint() < 0) goto user_stop;
+    SET_RUNNING(step_idx);
+    if (timed_device_wait_(step_idx, "涡动仪(二次)", 5) < 0) goto user_stop;
+
+    /* 步骤17: 机械臂 工3->工7 */
+    if (maintask_breakpoint() < 0) goto user_stop;
+    if (robot_move_to_(TEST_STEP_MAX, 9, "工位3->工位7") < 0) goto fault;
+
+    /* 步骤18: 移液器4 吸样滴试纸 pipette_act(4,1)  复用 step_idx=8 */
+    step_idx = 8;
+    if (maintask_breakpoint() < 0) goto user_stop;
+    SET_RUNNING(step_idx);
+    if (pipette_act_(step_idx, 4, 1) < 0) goto fault;
+
+    /* 步骤19: 机械臂 工7->工8(废液仓) + 等待 8 分钟 (演示用缩短到 8 秒) */
+    if (maintask_breakpoint() < 0) goto user_stop;
+    if (robot_move_to_(TEST_STEP_MAX, 10, "工位7->废液仓") < 0) goto fault;
+    if (maintask_breakpoint() < 0) goto user_stop;
+    step_idx = 9;
+    SET_RUNNING(step_idx);
+    if (timed_device_wait_(step_idx, "等待显色", 8) < 0) goto user_stop;
+
+    /* 步骤20: 拍照、报告结果、上传 (ROB_ACT_11) */
+    if (maintask_breakpoint() < 0) goto user_stop;
+    step_idx = 9;
+    SET_RUNNING(step_idx);
+    if (robot_move_to_(step_idx, 11, "拍照+报告") < 0) goto fault;
+
+    /* 机械臂回原位 ROB_ACT_12 (不占用 step 槽) */
+    if (maintask_breakpoint() < 0) goto user_stop;
+    (void)robot_move_to_(TEST_STEP_MAX, 12, "回原位");
+
+    /* 成功完成 */
+    dev_test_finish_all(0);
+    s_last_test_result = 1;
+    set_state_and_notify(DEV_TEST_COMPLETED, "\"test\":\"ok\"");
+    return 0;
+
+user_stop:
+    LOG_INFO("autotest stopped by user\n");
+    s_last_test_result = -1;
+    snprintf(s_last_fault_msg, sizeof(s_last_fault_msg), "%s", "用户停止");
+    dev_test_finish_all(-900);
+    set_state_and_notify(DEV_TEST_ERROR, "\"test\":\"stopped\",\"fault\":\"用户停止\"");
+    return -1;
+
+fault:
+    ret = -2;
+    s_last_test_result = -2;
+    snprintf(s_last_fault_msg, sizeof(s_last_fault_msg), "%s", "自动测试动作失败");
+    dev_test_finish_all(-901);
+    set_state_and_notify(DEV_TEST_ERROR, "\"test\":\"failed\",\"fault\":\"动作故障\"");
+    return ret;
+}
+
+/*============================================================================
+ * 调试模式执行单步动作 (act_id 1~20 = 自动测试里的每一步)
+ *==========================================================================*/
+static int run_debug_action(int act_id)
+{
+    if (act_id <= 0 || act_id > AUTOTEST_ACT_NUM) return -1;
+    s_debugging = 1;
+    set_state_and_notify(DEV_MANUAL_DEBUG, NULL);
+
+    char name[40];
+    snprintf(name, sizeof(name), "debug_act_%d", act_id);
+    dev_debug_start(act_id, name);
+
+    /* act_id 1..20 按前表映射(调试模式 step_idx 统一用 TEST_STEP_MAX 表示不写入 steps[]) */
+    int ret = 0;
+    switch (act_id) {
+    case 2:  ret = robot_move_to_(TEST_STEP_MAX, 1,  "调试 工1->工2"); break;
+    case 3:  ret = pipette_act_(TEST_STEP_MAX, 1, 1); break;
+    case 4:  ret = robot_move_to_(TEST_STEP_MAX, 2,  "调试 工2->工3"); break;
+    case 5:  ret = timed_device_wait_(TEST_STEP_MAX, "涡动仪", 3); break;
+    case 6:  ret = robot_move_to_(TEST_STEP_MAX, 3,  "调试 工3->工4"); break;
+    case 7:  ret = timed_device_wait_(TEST_STEP_MAX, "离心机", 3); break;
+    case 8:  ret = robot_move_to_(TEST_STEP_MAX, 4,  "调试 工4->工5"); break;
+    case 9:  ret = pipette_act_(TEST_STEP_MAX, 2, 1); break;
+    case 10: ret = robot_move_to_(TEST_STEP_MAX, 5,  "调试 工5->废液仓"); break;
+    case 11: ret = robot_move_to_(TEST_STEP_MAX, 6,  "调试 工9->工5"); break;
+    case 12: ret = pipette_act_(TEST_STEP_MAX, 2, 2); break;
+    case 13: ret = robot_move_to_(TEST_STEP_MAX, 7,  "调试 工5->工6"); break;
+    case 14: ret = pipette_act_(TEST_STEP_MAX, 3, 1); break;
+    case 15: ret = robot_move_to_(TEST_STEP_MAX, 8,  "调试 工6->工3"); break;
+    case 16: ret = timed_device_wait_(TEST_STEP_MAX, "涡动仪(二)", 3); break;
+    case 17: ret = robot_move_to_(TEST_STEP_MAX, 9,  "调试 工3->工7"); break;
+    case 18: ret = pipette_act_(TEST_STEP_MAX, 4, 1); break;
+    case 19: ret = robot_move_to_(TEST_STEP_MAX, 10, "调试 工7->废液仓"); break;
+    case 20: ret = robot_move_to_(TEST_STEP_MAX, 11, "调试 拍照报告"); break;
+    case 1:
+    default:
+        LOG_INFO("debug act %d: idle / noop\n", act_id);
+        ret = 0;
+        break;
+    }
+    dev_debug_finish(ret < 0 ? ret : 0, ret < 0 ? "动作失败" : NULL);
+    set_state_and_notify(DEV_MANUAL_DEBUG, NULL);
+    return ret;
+}
+
+/*============================================================================
+ * 命令处理 (由主任务线程调用)
+ *==========================================================================*/
+static void proc_cmd_start_autotest(void)
+{
+    dev_state_t ws = dev_get_state();
+    if (ws != DEV_READY && ws != DEV_TEST_COMPLETED && ws != DEV_TEST_ERROR) {
+        LOG_ERROR("start_autotest: not ready, ws=%d\n", ws);
+        return;
+    }
+    s_req_stop = 0; s_req_pause = 0; s_paused = 0;
+    (void)run_autotest_sequence();
+    /* 结束后留在 DEV_TEST_COMPLETED/ERROR -> 用户点击 fault_reset 才回就绪 */
+}
+
+static void proc_cmd_stop_autotest(void)
+{
+    if (dev_get_state() == DEV_TESTING ||
+        dev_get_state() == DEV_MANUAL_DEBUG) {
+        pthread_mutex_lock(&s_cancel_lock);
+        s_req_stop = 1;
+        s_req_pause = 0;
+        pthread_cond_broadcast(&s_cancel_cond);
+        pthread_mutex_unlock(&s_cancel_lock);
+    }
+}
+
+static void proc_cmd_pause_autotest(void)
+{
+    if (dev_get_state() == DEV_TESTING) {
+        pthread_mutex_lock(&s_cancel_lock);
+        s_req_pause = 1;
+        pthread_cond_broadcast(&s_cancel_cond);
+        pthread_mutex_unlock(&s_cancel_lock);
+    }
+}
+
+static void proc_cmd_resume_autotest(void)
+{
+    if (s_paused) {
+        pthread_mutex_lock(&s_cancel_lock);
+        s_req_pause = 0;
+        s_paused = 0;
+        pthread_cond_broadcast(&s_cancel_cond);
+        pthread_mutex_unlock(&s_cancel_lock);
+        set_state_and_notify(DEV_TESTING, "\"paused\":0");
+    }
+}
+
+static void proc_cmd_enter_debug(void)
+{
+    if (dev_get_state() != DEV_READY) return;
+    s_debugging = 1;
+    set_state_and_notify(DEV_MANUAL_DEBUG, NULL);
+}
+
+static void proc_cmd_exit_debug(void)
+{
+    if (dev_get_state() == DEV_MANUAL_DEBUG ||
+        dev_get_state() == DEV_MANUAL_DEBUG) {
+        s_debugging = 0;
+        set_state_and_notify(DEV_READY, NULL);
+    }
+}
+
+static void proc_cmd_debug_action(int act_id)
+{
+    if (dev_get_state() != DEV_MANUAL_DEBUG &&
+        dev_get_state() != DEV_MANUAL_DEBUG) return;
+    s_req_stop = 0;
+    (void)run_debug_action(act_id);
+}
+
+static void proc_cmd_fault_reset(void)
+{
+    /* 从 autotest_fault / autotest_completed / selftest_failed 均可手动复位回 READY */
+    s_req_stop = 0; s_req_pause = 0; s_paused = 0;
+    s_last_test_result = 0;
+    dev_reset_to_normal();
+    set_state_and_notify(DEV_READY, NULL);
+}
+
+static void proc_cmd_exit_selftest_failed(void)
+{
+    /* 自检失败后的"重新自检"按钮:先清故障标志,然后强制回到 DEV_INIT,
+       主循环会重新 run_selftest_sequence() 重跑自检整套流程。
+       (不再走 proc_cmd_fault_reset,它会把机器直接塞到 DEV_READY,无法"再自检") */
+    s_req_stop = 0; s_req_pause = 0; s_paused = 0;
+    s_last_test_result = 0;
+    /* 用带通知的版本:把 DEV_INIT 推到 D-Bus,让 UI 立刻刷新按钮为禁用,并显示"初始化中…" */
+    set_state_and_notify(DEV_INIT, NULL);
+}
+
+static void proc_cmd_change_mode(int mode)
+{
+    /* 模式切换:简化处理,mode=0 强制回到 INIT 重跑自检 */
+    if (mode == 0) {
+        dev_set_state(DEV_INIT);
+        /* 让主循环下一轮跳到自检 */
+    }
+}
+
+/*============================================================================
+ * 主任务线程入口
+ *==========================================================================*/
+static void *main_task_thread(void *arg)
+{
+    (void)arg;
+    LOG_INFO("main_task_thread start\n");
+
+    /* ---- 阶段 1: 初始化 ---- */
+    dev_info_init();
+    set_state_and_notify(DEV_INIT, NULL);
+    (void)maintask_cancellable_sleep_ms(800);  /* 开机画面停留 */
+
+    int fail = run_selftest_sequence();
+    /* ---- 阶段 2: 自检 ---- */
+    if (fail != 0) {
+        LOG_ERROR("selftest %d item(s) failed, go to selftest_fault\n", fail);
+        set_state_and_notify(DEV_SELFTEST_FAILED, NULL);
+    } else {
+        LOG_INFO("selftest all pass, go to READY\n");
+        set_state_and_notify(DEV_READY, NULL);
+    }
+
+    /* ---- 阶段 3: 命令主循环 ---- */
+    while (s_running) {
+        /* 如果 mode=0 的复位触发了 (INIT),重跑自检 */
+        if (dev_get_state() == DEV_INIT) {
+            int f = run_selftest_sequence();
+            if (f != 0) set_state_and_notify(DEV_SELFTEST_FAILED, NULL);
+            else        set_state_and_notify(DEV_READY, NULL);
+        }
+
+        /* 从队列里取一条命令 (非队列式等待:每 20ms 轮询一次以便处理退出标志) */
+        char perr = ERR_Q_NONE;
+        void *pmsg = cQRcv(s_cmd_q, &perr);
+        if (pmsg != NULL) {
+            mt_cmd_t *cmd = (mt_cmd_t *)pmsg;
+            LOG_INFO("recv cmd type=%d arg=%d\n", (int)cmd->type, cmd->int_arg0);
+            switch (cmd->type) {
+            case MT_CMD_START_AUTOTEST:       proc_cmd_start_autotest(); break;
+            case MT_CMD_PAUSE_AUTOTEST:       proc_cmd_pause_autotest(); break;
+            case MT_CMD_RESUME_AUTOTEST:      proc_cmd_resume_autotest(); break;
+            case MT_CMD_STOP_AUTOTEST:        proc_cmd_stop_autotest(); break;
+            case MT_CMD_ENTER_DEBUG:          proc_cmd_enter_debug(); break;
+            case MT_CMD_EXIT_DEBUG:           proc_cmd_exit_debug(); break;
+            case MT_CMD_DEBUG_ACTION:         proc_cmd_debug_action(cmd->int_arg0); break;
+            case MT_CMD_FAULT_RESET:          proc_cmd_fault_reset(); break;
+            case MT_CMD_EXIT_SELFTEST_FAILED: proc_cmd_exit_selftest_failed(); break;
+            case MT_CMD_CHANGE_MODE:          proc_cmd_change_mode(cmd->int_arg0); break;
+            default: break;
+            }
+            free(cmd);
+            continue;
+        }
+
+        sleep_ms_(20);
+    }
+
+    /* ---- 清理 ---- */
+    pipette_deinit_all();
+    dev_info_deinit();
+
+    LOG_INFO("main_task_thread exit\n");
+    return NULL;
+}
+
+/*============================================================================
+ * 生命周期对外 API
+ *==========================================================================*/
+int maintask_init(void)
+{
+    if (s_thread_inited) return 0;
+
+    s_cmd_q = cQcreate(32);
+    if (s_cmd_q == NULL) return -1;
+    pthread_mutex_init(&s_cmd_lock, NULL);
+    pthread_mutex_init(&s_cancel_lock, NULL);
+    pthread_cond_init(&s_cancel_cond, NULL);
+
+    s_req_stop = 0;
+    s_req_pause = 0;
+    s_paused = 0;
+    s_debugging = 0;
+    s_last_test_result = 0;
+
+    s_running = 1;
+    int rc = pthread_create(&s_tid, NULL, main_task_thread, NULL);
+    if (rc != 0) {
+        s_running = 0;
+        cQDelete(s_cmd_q); s_cmd_q = NULL;
+        pthread_mutex_destroy(&s_cmd_lock);
+        pthread_mutex_destroy(&s_cancel_lock);
+        pthread_cond_destroy(&s_cancel_cond);
+        return -1;
+    }
+    s_thread_inited = 1;
+    return 0;
+}
+
+void maintask_deinit(void)
+{
+    if (!s_thread_inited) return;
+    s_running = 0;
+
+    /* 唤醒可能的等待 */
+    pthread_mutex_lock(&s_cancel_lock);
+    s_req_stop = 1;
+    pthread_cond_broadcast(&s_cancel_cond);
+    pthread_mutex_unlock(&s_cancel_lock);
+
+    pthread_join(s_tid, NULL);
+
+    /* 排空队列剩余命令 */
+    if (s_cmd_q) {
+        char perr;
+        for (;;) {
+            void *m = cQRcv(s_cmd_q, &perr);
+            if (m == NULL) break;
+            free(m);
+        }
+        cQDelete(s_cmd_q);
+        s_cmd_q = NULL;
+    }
+    pthread_mutex_destroy(&s_cmd_lock);
+    pthread_mutex_destroy(&s_cancel_lock);
+    pthread_cond_destroy(&s_cancel_cond);
+    s_thread_inited = 0;
+}
+
+/*============================================================================
+ * 覆盖 ui.c 中 weak 的 ad_cmd_xxx() 钩子,将 dbus 命令翻译成主任务命令
+ *==========================================================================*/
+int ad_cmd_start_autotest(void)       { return mt_cmd_start_autotest(); }
+int ad_cmd_pause_autotest(void)       { return mt_cmd_pause_autotest(); }
+int ad_cmd_resume_autotest(void)      { return mt_cmd_resume_autotest(); }
+int ad_cmd_stop_autotest(void)        { return mt_cmd_stop_autotest(); }
+int ad_cmd_enter_debug(void)          { return mt_cmd_enter_debug(); }
+int ad_cmd_exit_debug(void)           { return mt_cmd_exit_debug(); }
+int ad_cmd_debug_action(int act_id)   { return mt_cmd_debug_action(act_id); }
+int ad_cmd_fault_reset(void)          { return mt_cmd_fault_reset(); }
+int ad_cmd_exit_selftest_failed(void) { return mt_cmd_exit_selftest_failed(); }
+int ad_change_mode(int mode)          { return mt_cmd_change_mode(mode); }
\ No newline at end of file
diff --git a/app/src/motor.c b/app/src/motor.c
new file mode 100644 (file)
index 0000000..837d315
--- /dev/null
@@ -0,0 +1,555 @@
+#include <stdio.h>
+#include <stdint.h>
+#include <stdlib.h>
+#include <stdarg.h>
+#include <string.h>
+#include <unistd.h>
+#include <errno.h>
+#include <fcntl.h>
+#include <termios.h>
+#include <sys/time.h>
+#include <pthread.h>
+
+#include "motor.h"
+#include "ad_log.h"
+
+#ifndef LOG_INFO
+#define LOG_INFO(fmt, args...)   do { printf("[MOT][INFO ] " fmt, ##args); } while(0)
+#define LOG_ERROR(fmt, args...)  do { printf("[MOT][ERROR] " fmt, ##args); } while(0)
+#endif
+
+/*==========================================================================
+ * 雷赛 DM2B 系列 Modbus RTU 寄存器定义
+ *   完全基于用户手册示例帧 + 状态寄存器说明:
+ *   - 状态  0x1003 (bit0~bit6)
+ *   - 报警  0x2203
+ *   - PR 段 0x6200 + path_no*0x10 :  模式/位置高/位置低/速度/加速/减速 共 6 个
+ *   - PR 选择 0x6001 (写路径号 0~15)
+ *   - PR 命令 0x6002 (bit4 START, bit6 ESTOP)
+ *   - 控制字 0x6000 (bit0 使能, bit8 清报警)
+ *   - 当前位置 0x1001(高) 0x1002(低)
+ *   如与实际型号有细微差异,仅需改下面宏值
+ *========================================================================*/
+
+/* ---- Modbus 功能码 ---- */
+#define MB_FC_READ_HR           0x03
+#define MB_FC_WRITE_ONE         0x06
+#define MB_FC_WRITE_MULTI       0x10
+
+/* ---- 控制字区 ---- */
+#define DM2B_REG_CTRL_WORD      0x6000      /* 控制字 W
+                                             *  bit0 : 1=使能 0=去使能
+                                             *  bit8 : 0->1 清报警
+                                             */
+#define DM2B_REG_PATH_SEL       0x6001      /* PR 路径选择 W (0~15) */
+#define DM2B_REG_CMD_TRIG       0x6002      /* 命令触发 W
+                                             *  bit4 : 0->1 启动当前路径
+                                             *  bit6 : 1 急停
+                                             */
+#define DM2B_CTRL_SERVO_ON_BIT  (1u << 0)
+#define DM2B_CTRL_CLR_ALM_BIT   (1u << 8)
+#define DM2B_CMD_START_BIT      (1u << 4)
+#define DM2B_CMD_ESTOP_BIT      (1u << 6)
+
+/* ---- PR 段寄存器 ----
+ * PRk 的基址 = 0x6200 + k * 0x10
+ *   +0 模式        (1=绝对 2=相对 8=回零等)
+ *   +1 位置 高16
+ *   +2 位置 低16
+ *   +3 速度 rpm
+ *   +4 加速度
+ *   +5 减速度
+ */
+#define DM2B_PR_BASE            0x6200
+#define DM2B_PR_STRIDE          0x10        /* 每段占用 16 个寄存器地址 */
+#define DM2B_OFFS_MODE          0
+#define DM2B_OFFS_POS_HI        1
+#define DM2B_OFFS_POS_LO        2
+#define DM2B_OFFS_SPEED         3
+#define DM2B_OFFS_ACCEL         4
+#define DM2B_OFFS_DECEL         5
+
+/* ---- 状态 / 报警 / 位置 (只读区) ---- */
+#define DM2B_REG_RUN_STATE      0x1003      /* 运行状态 R  */
+#define DM2B_REG_CUR_POS_HI     0x1001      /* 当前位置高 R */
+#define DM2B_REG_CUR_POS_LO     0x1002      /* 当前位置低 R */
+#define DM2B_REG_ALARM_CODE     0x2203      /* 当前报警 R  */
+
+/*================== 模块变量 ==================*/
+static int            s_fd = -1;
+static char           s_port[128] = MOTOR_DEF_RS485_PORT;
+static int            s_baud = MOTOR_DEF_BAUD;
+static pthread_mutex_t s_lock;
+static int            s_inited = 0;
+
+static inline void mot_lock(void)   { pthread_mutex_lock(&s_lock); }
+static inline void mot_unlock(void) { pthread_mutex_unlock(&s_lock); }
+
+static int sleep_ms(int ms)
+{
+    if (ms <= 0) return 0;
+    struct timespec ts;
+    ts.tv_sec  = ms / 1000;
+    ts.tv_nsec = (long)(ms % 1000) * 1000000L;
+    nanosleep(&ts, NULL);
+    return 0;
+}
+
+/*================== CRC16 Modbus ==================*/
+static uint16_t crc16_modbus(const uint8_t *data, int len)
+{
+    uint16_t crc = 0xFFFF;
+    int i, j;
+    for (i = 0; i < len; i++) {
+        crc ^= (uint16_t)data[i];
+        for (j = 0; j < 8; j++) {
+            if (crc & 0x0001) crc = (crc >> 1) ^ 0xA001;
+            else              crc >>= 1;
+        }
+    }
+    return crc;
+}
+
+/*================== 串口 ==================*/
+static speed_t baud_to_speed(int baud)
+{
+    switch (baud) {
+        case 9600:   return B9600;
+        case 19200:  return B19200;
+        case 38400:  return B38400;
+        case 57600:  return B57600;
+        case 115200: return B115200;
+        case 230400: return B230400;
+        default:     return B115200;
+    }
+}
+
+static int rs485_open_locked(void)
+{
+    int fd;
+    struct termios tio;
+
+    if (s_fd >= 0) return 0;
+    fd = open(s_port, O_RDWR | O_NOCTTY);
+    if (fd < 0) {
+        LOG_ERROR("open %s failed: %s\n", s_port, strerror(errno));
+        return -1;
+    }
+    memset(&tio, 0, sizeof(tio));
+    cfmakeraw(&tio);
+    cfsetispeed(&tio, baud_to_speed(s_baud));
+    cfsetospeed(&tio, baud_to_speed(s_baud));
+    tio.c_cflag |= (CLOCAL | CREAD);
+    tio.c_cflag &= ~CSIZE;
+    tio.c_cflag |= CS8;
+    tio.c_cflag &= ~PARENB;
+    tio.c_cflag &= ~CSTOPB;
+    tio.c_cc[VTIME] = 2;
+    tio.c_cc[VMIN]  = 0;
+    tcsetattr(fd, TCSANOW, &tio);
+    tcflush(fd, TCIOFLUSH);
+    s_fd = fd;
+    LOG_INFO("DM2B rs485 %s @%d opened, fd=%d\n", s_port, s_baud, fd);
+    return 0;
+}
+
+static void rs485_close_locked(void)
+{
+    if (s_fd >= 0) {
+        close(s_fd);
+        s_fd = -1;
+    }
+}
+
+static int rs485_xchg_locked(const uint8_t *tx, int tx_len,
+                             uint8_t *rx, int rx_max, int timeout_ms)
+{
+    int ret, n;
+    fd_set rfds;
+    struct timeval tv;
+    int total = 0;
+    int remain = timeout_ms;
+
+    if (s_fd < 0 && rs485_open_locked() < 0) return -1;
+
+    tcflush(s_fd, TCIOFLUSH);
+    ret = write(s_fd, tx, tx_len);
+    if (ret != tx_len) return -1;
+    tcdrain(s_fd);
+
+    while (remain > 0 && total < rx_max) {
+        FD_ZERO(&rfds);
+        FD_SET(s_fd, &rfds);
+        tv.tv_sec  = 0;
+        tv.tv_usec = (remain > 20 ? 20 : remain) * 1000;
+        ret = select(s_fd + 1, &rfds, NULL, NULL, &tv);
+        if (ret < 0) return -1;
+        if (ret == 0) { remain -= 20; continue; }
+        n = read(s_fd, rx + total, rx_max - total);
+        if (n > 0) {
+            total += n;
+            if (total >= 5) break;
+        }
+        remain -= 20;
+    }
+    return total;
+}
+
+/*================== Modbus RTU 主站 ==================*/
+static int mb_check_resp(const uint8_t *rx, int rx_len,
+                         uint8_t slave, uint8_t fc)
+{
+    uint16_t crc_calc, crc_rx;
+    if (rx_len < 5) return -1;
+    if (rx[0] != slave) return -2;
+    if ((rx[1] & 0x7F) != fc) return -3;
+    if (rx[1] & 0x80) {
+        /* Modbus 异常响应:异常码在 rx[2] */
+        return -100 - rx[2];
+    }
+    crc_calc = crc16_modbus(rx, rx_len - 2);
+    crc_rx   = (uint16_t)rx[rx_len - 1] << 8 | rx[rx_len - 2];
+    if (crc_calc != crc_rx) return -4;
+    return 0;
+}
+
+static int mb_read_regs(uint8_t slave, uint16_t reg, int cnt,
+                        uint16_t *out_regs, int timeout_ms)
+{
+    uint8_t tx[8], rx[256];
+    int rx_len, i, err;
+
+    tx[0] = slave;
+    tx[1] = MB_FC_READ_HR;
+    tx[2] = (reg >> 8) & 0xFF;
+    tx[3] = reg & 0xFF;
+    tx[4] = (cnt >> 8) & 0xFF;
+    tx[5] = cnt & 0xFF;
+    uint16_t crc = crc16_modbus(tx, 6);
+    tx[6] = crc & 0xFF;
+    tx[7] = (crc >> 8) & 0xFF;
+
+    rx_len = rs485_xchg_locked(tx, 8, rx, sizeof(rx), timeout_ms);
+    if (rx_len < 0) return MOTOR_ERR_COMM;
+    err = mb_check_resp(rx, rx_len, slave, MB_FC_READ_HR);
+    if (err < 0) return MOTOR_ERR_COMM;
+    if (rx[2] != cnt * 2) return MOTOR_ERR_COMM;
+    for (i = 0; i < cnt; i++) {
+        out_regs[i] = (uint16_t)rx[3 + i * 2] << 8 | rx[4 + i * 2];
+    }
+    return 0;
+}
+
+static int mb_write_reg(uint8_t slave, uint16_t reg, uint16_t val,
+                        int timeout_ms)
+{
+    uint8_t tx[8], rx[16];
+    int rx_len, err;
+
+    tx[0] = slave;
+    tx[1] = MB_FC_WRITE_ONE;
+    tx[2] = (reg >> 8) & 0xFF;
+    tx[3] = reg & 0xFF;
+    tx[4] = (val >> 8) & 0xFF;
+    tx[5] = val & 0xFF;
+    uint16_t crc = crc16_modbus(tx, 6);
+    tx[6] = crc & 0xFF;
+    tx[7] = (crc >> 8) & 0xFF;
+
+    rx_len = rs485_xchg_locked(tx, 8, rx, sizeof(rx), timeout_ms);
+    if (rx_len < 0) return MOTOR_ERR_COMM;
+    err = mb_check_resp(rx, rx_len, slave, MB_FC_WRITE_ONE);
+    if (err < 0) return MOTOR_ERR_COMM;
+    return 0;
+}
+
+static int mb_write_regs(uint8_t slave, uint16_t start_reg,
+                         const uint16_t *vals, int cnt,
+                         int timeout_ms)
+{
+    uint8_t tx[256], rx[16];
+    int rx_len, i, pos = 0, err;
+
+    tx[pos++] = slave;
+    tx[pos++] = MB_FC_WRITE_MULTI;
+    tx[pos++] = (start_reg >> 8) & 0xFF;
+    tx[pos++] = start_reg & 0xFF;
+    tx[pos++] = (cnt >> 8) & 0xFF;
+    tx[pos++] = cnt & 0xFF;
+    tx[pos++] = (uint8_t)(cnt * 2);
+    for (i = 0; i < cnt; i++) {
+        tx[pos++] = (vals[i] >> 8) & 0xFF;
+        tx[pos++] = vals[i] & 0xFF;
+    }
+    uint16_t crc = crc16_modbus(tx, pos);
+    tx[pos++] = crc & 0xFF;
+    tx[pos++] = (crc >> 8) & 0xFF;
+
+    rx_len = rs485_xchg_locked(tx, pos, rx, sizeof(rx), timeout_ms);
+    if (rx_len < 0) return MOTOR_ERR_COMM;
+    err = mb_check_resp(rx, rx_len, slave, MB_FC_WRITE_MULTI);
+    if (err < 0) return MOTOR_ERR_COMM;
+    return 0;
+}
+
+/*================== 总线 / 生命周期 ==================*/
+int motor_bus_init(const char *port, int baud)
+{
+    pthread_mutex_init(&s_lock, NULL);
+    mot_lock();
+    if (port != NULL) {
+        strncpy(s_port, port, sizeof(s_port) - 1);
+        s_port[sizeof(s_port) - 1] = '\0';
+    }
+    if (baud > 0) s_baud = baud;
+    int ret = rs485_open_locked();
+    if (ret == 0) s_inited = 1;
+    mot_unlock();
+    return ret == 0 ? MOTOR_OK : MOTOR_ERR_COMM;
+}
+
+void motor_bus_deinit(void)
+{
+    mot_lock();
+    rs485_close_locked();
+    s_inited = 0;
+    mot_unlock();
+    pthread_mutex_destroy(&s_lock);
+}
+
+/*================== 单驱动器基础操作 ==================*/
+int motor_ping(uint8_t slave)
+{
+    uint16_t st = 0;
+    int ret;
+    if (!s_inited) return MOTOR_ERR_NOT_INIT;
+    mot_lock();
+    ret = mb_read_regs(slave, DM2B_REG_RUN_STATE, 1, &st, 500);
+    mot_unlock();
+    return ret;
+}
+
+int motor_read_state(uint8_t slave, uint16_t *out_state)
+{
+    int ret;
+    if (out_state == NULL) return MOTOR_ERR_PARAM;
+    if (!s_inited) return MOTOR_ERR_NOT_INIT;
+    mot_lock();
+    ret = mb_read_regs(slave, DM2B_REG_RUN_STATE, 1, out_state, 500);
+    mot_unlock();
+    return ret;
+}
+
+int motor_read_alarm(uint8_t slave, uint16_t *out_alarm)
+{
+    int ret;
+    if (out_alarm == NULL) return MOTOR_ERR_PARAM;
+    if (!s_inited) return MOTOR_ERR_NOT_INIT;
+    mot_lock();
+    ret = mb_read_regs(slave, DM2B_REG_ALARM_CODE, 1, out_alarm, 500);
+    mot_unlock();
+    return ret;
+}
+
+int motor_read_curpos(uint8_t slave, int32_t *out_pos)
+{
+    uint16_t r[2];
+    int ret;
+    if (out_pos == NULL) return MOTOR_ERR_PARAM;
+    if (!s_inited) return MOTOR_ERR_NOT_INIT;
+    mot_lock();
+    ret = mb_read_regs(slave, DM2B_REG_CUR_POS_HI, 2, r, 500);
+    mot_unlock();
+    if (ret != 0) return ret;
+    *out_pos = (int32_t)((uint32_t)r[0] << 16 | r[1]);
+    return MOTOR_OK;
+}
+
+/* 读-改-写 0x6000 控制字某一位 (锁内调用) */
+static int ctrl_word_set_bit_locked(uint8_t slave, uint16_t bitmask, int onoff,
+                                    int timeout_ms)
+{
+    uint16_t cur = 0;
+    int ret = mb_read_regs(slave, DM2B_REG_CTRL_WORD, 1, &cur, timeout_ms);
+    if (ret != 0) return ret;
+    uint16_t next = onoff ? (cur | bitmask) : (cur & ~bitmask);
+    if (next == cur) return 0;
+    return mb_write_reg(slave, DM2B_REG_CTRL_WORD, next, timeout_ms);
+}
+
+int motor_enable(uint8_t slave, int on)
+{
+    int ret;
+    if (!s_inited) return MOTOR_ERR_NOT_INIT;
+    mot_lock();
+    ret = ctrl_word_set_bit_locked(slave, DM2B_CTRL_SERVO_ON_BIT, on ? 1 : 0, 500);
+    mot_unlock();
+    return ret;
+}
+
+int motor_clear_alarm(uint8_t slave)
+{
+    int ret;
+    if (!s_inited) return MOTOR_ERR_NOT_INIT;
+    mot_lock();
+    ret = ctrl_word_set_bit_locked(slave, DM2B_CTRL_CLR_ALM_BIT, 0, 500);
+    if (ret == 0) ret = ctrl_word_set_bit_locked(slave, DM2B_CTRL_CLR_ALM_BIT, 1, 500);
+    if (ret == 0) (void)ctrl_word_set_bit_locked(slave, DM2B_CTRL_CLR_ALM_BIT, 0, 500);
+    mot_unlock();
+    sleep_ms(100);
+    return ret == 0 ? MOTOR_OK : MOTOR_ERR_COMM;
+}
+
+int motor_stop_emergency(uint8_t slave)
+{
+    int ret;
+    if (!s_inited) return MOTOR_ERR_NOT_INIT;
+    mot_lock();
+    /* 先置 ESTOP=1 然后清 START */
+    (void)mb_write_reg(slave, DM2B_REG_CMD_TRIG, DM2B_CMD_ESTOP_BIT, 500);
+    ret = mb_write_reg(slave, DM2B_REG_CMD_TRIG, 0x0000, 500);
+    mot_unlock();
+    return ret == 0 ? MOTOR_OK : MOTOR_ERR_COMM;
+}
+
+/*================== PR 路径模式 ==================*/
+int motor_setup_path(uint8_t slave, uint8_t path_no,
+                     pr_mode_t mode, int32_t pos,
+                     uint16_t speed_rpm, uint16_t accel, uint16_t decel)
+{
+    uint16_t base, v[6];
+    int ret;
+    if (!s_inited) return MOTOR_ERR_NOT_INIT;
+    if (path_no >= MOTOR_PATH_MAX) return MOTOR_ERR_PATH_NO;
+
+    base = (uint16_t)(DM2B_PR_BASE + (uint16_t)path_no * DM2B_PR_STRIDE);
+    v[DM2B_OFFS_MODE   ] = (uint16_t)mode;
+    v[DM2B_OFFS_POS_HI ] = (uint16_t)((uint32_t)pos >> 16);
+    v[DM2B_OFFS_POS_LO ] = (uint16_t)((uint32_t)pos & 0xFFFF);
+    v[DM2B_OFFS_SPEED  ] = speed_rpm;
+    v[DM2B_OFFS_ACCEL  ] = accel;
+    v[DM2B_OFFS_DECEL  ] = decel;
+
+    mot_lock();
+    ret = mb_write_regs(slave, base, v, 6, 800);
+    mot_unlock();
+    return ret == 0 ? MOTOR_OK : MOTOR_ERR_COMM;
+}
+
+int motor_trigger_path_async(uint8_t slave, uint8_t path_no)
+{
+    int ret;
+    if (!s_inited) return MOTOR_ERR_NOT_INIT;
+    if (path_no >= MOTOR_PATH_MAX) return MOTOR_ERR_PATH_NO;
+
+    mot_lock();
+    /* 步骤:
+     * 1) 选路径号到 0x6001
+     * 2) 清 0x6002
+     * 3) 写 START 位到 0x6002
+     */
+    ret = mb_write_reg(slave, DM2B_REG_PATH_SEL, (uint16_t)path_no, 500);
+    if (ret != 0) goto out;
+    ret = mb_write_reg(slave, DM2B_REG_CMD_TRIG, 0x0000, 500);
+    if (ret != 0) goto out;
+    ret = mb_write_reg(slave, DM2B_REG_CMD_TRIG, DM2B_CMD_START_BIT, 500);
+out:
+    mot_unlock();
+    return ret == 0 ? MOTOR_OK : MOTOR_ERR_COMM;
+}
+
+int motor_wait_path_done(uint8_t slave, int timeout_ms, uint16_t *out_alarm)
+{
+    uint16_t sta = 0;
+    int64_t start_ms;
+    struct timeval tv;
+
+    if (!s_inited) return MOTOR_ERR_NOT_INIT;
+    if (timeout_ms <= 0) timeout_ms = MOTOR_DEF_MOVE_TIMEOUT;
+
+    gettimeofday(&tv, NULL);
+    start_ms = (int64_t)tv.tv_sec * 1000 + tv.tv_usec / 1000;
+
+    while (1) {
+        int ret = motor_read_state(slave, &sta);
+        if (ret != 0) return ret;
+
+        if (sta & MOTOR_ST_FAULT) {
+            uint16_t alm = 0;
+            (void)motor_read_alarm(slave, &alm);
+            if (out_alarm) *out_alarm = alm;
+            return MOTOR_ERR_FAULT;
+        }
+        if (sta & MOTOR_ST_PATH_DONE) {
+            return MOTOR_OK;
+        }
+        struct timeval tv2;
+        gettimeofday(&tv2, NULL);
+        int64_t now = (int64_t)tv2.tv_sec * 1000 + tv2.tv_usec / 1000;
+        if ((int)(now - start_ms) > timeout_ms) {
+            return MOTOR_ERR_TIMEOUT;
+        }
+        sleep_ms(20);
+    }
+}
+
+int motor_trigger_path_wait(uint8_t slave, uint8_t path_no,
+                            int timeout_ms, uint16_t *out_alarm)
+{
+    int ret;
+    ret = motor_trigger_path_async(slave, path_no);
+    if (ret != 0) return ret;
+    ret = motor_wait_path_done(slave, timeout_ms, out_alarm);
+    if (ret != 0) {
+        (void)motor_stop_emergency(slave);
+    }
+    return ret;
+}
+
+int motor_home(uint8_t slave, int timeout_ms)
+{
+    /* 方案:用 PR0 配置成回零模式,触发 PR0 并等待 HOME_DONE 标志
+     * 这样不依赖额外回零寄存器地址,完全符合手册 PR 模式思路。
+     * 若驱动器另外支持专用回零命令,可在此替换实现。
+     */
+    int ret;
+    uint16_t alm = 0, sta = 0;
+    struct timeval tv;
+    int64_t start_ms;
+    if (!s_inited) return MOTOR_ERR_NOT_INIT;
+    if (timeout_ms <= 0) timeout_ms = MOTOR_DEF_MOVE_TIMEOUT;
+
+    (void)motor_clear_alarm(slave);
+    ret = motor_enable(slave, 1);
+    if (ret != 0) return ret;
+    sleep_ms(50);
+
+    ret = motor_setup_path(slave, 0, PR_MODE_HOME, 0, 300, 100, 100);
+    if (ret != 0) return ret;
+    ret = motor_trigger_path_async(slave, 0);
+    if (ret != 0) return ret;
+
+    gettimeofday(&tv, NULL);
+    start_ms = (int64_t)tv.tv_sec * 1000 + tv.tv_usec / 1000;
+
+    while (1) {
+        ret = motor_read_state(slave, &sta);
+        if (ret != 0) return ret;
+        if (sta & MOTOR_ST_FAULT) {
+            (void)motor_read_alarm(slave, &alm);
+            (void)motor_stop_emergency(slave);
+            return MOTOR_ERR_FAULT;
+        }
+        if (sta & MOTOR_ST_HOME_DONE) {
+            return MOTOR_OK;
+        }
+        struct timeval tv2;
+        gettimeofday(&tv2, NULL);
+        int64_t now = (int64_t)tv2.tv_sec * 1000 + tv2.tv_usec / 1000;
+        if ((int)(now - start_ms) > timeout_ms) {
+            (void)motor_stop_emergency(slave);
+            return MOTOR_ERR_TIMEOUT;
+        }
+        sleep_ms(20);
+    }
+}
\ No newline at end of file
diff --git a/app/src/pipette.c b/app/src/pipette.c
new file mode 100644 (file)
index 0000000..1bd1cd8
--- /dev/null
@@ -0,0 +1,510 @@
+#include <stdio.h>
+#include <stdint.h>
+#include <stdlib.h>
+#include <stdarg.h>
+#include <string.h>
+#include <unistd.h>
+#include <pthread.h>
+
+#include "pipette.h"
+#include "motor.h"
+#include "ad_log.h"
+
+#ifndef LOG_INFO
+#define LOG_INFO(fmt, args...)   do { printf("[PIP][INFO ] " fmt, ##args); } while(0)
+#define LOG_ERROR(fmt, args...)  do { printf("[PIP][ERROR] " fmt, ##args); } while(0)
+#endif
+
+/*===========================================================================
+ * 移液器控制层 (基于 DM2B PR 路径模式的 motor.c 接口)
+ *
+ * 策略:
+ *  - 每个驱动器自带 16 段 PR 路径 (PR0~PR15)
+ *  - 本层将 PR15 用作"即时指令段" (on-the-fly 临时路径):
+ *      pipette_axis_move() / 动作表每一步,先写 PR15 段寄存器
+ *      (模式/位置/速度/加减速度),再触发该段,等待路径完成。
+ *  - 将来如果要提升性能,可把常用动作预存到 PR0~PR14,触发时零配置开销。
+ *  - 上电初始化:每轴依次执行 motor_home() 回零,作为绝对位置参考点。
+ *=========================================================================*/
+
+/* PR 段分配 */
+#define PIPETTE_PR_ON_THE_FLY    15      /* 即时指令段号 PR15 */
+#define PIPETTE_PR_IMMEDIATE     PIPETTE_PR_ON_THE_FLY
+
+/* 默认运动参数 (若用户未通过接口覆盖则使用) */
+#define PIPETTE_DEF_SPEED_RPM    600
+#define PIPETTE_DEF_ACCEL        50
+#define PIPETTE_DEF_DECEL        50
+
+static inline uint8_t SLAVE_OF(int pip_id, int axis)
+{
+    return (uint8_t)motor_slave_of(pip_id, axis);
+}
+
+#define AXXIS(axis)  ((axis)==PIPETTE_AXIS_X)?"X":((axis)==PIPETTE_AXIS_Y)?"Y":"Z"
+
+/*================== 结构定义 ==================*/
+typedef struct {
+    int                 inited;
+    int                 state;
+    int                 cur_pos[PIPETTE_AXIS_NUM];
+    int                 speed[PIPETTE_AXIS_NUM];   /* rpm    */
+    int                 accel[PIPETTE_AXIS_NUM];
+    int                 decel[PIPETTE_AXIS_NUM];
+    int                 last_err;
+    char                last_err_msg[256];
+    pipette_pos_t       pos_cfg;
+    const pipette_act_t *act_table;
+    int                 act_table_cnt;
+} pipette_inst_t;
+
+static pipette_inst_t s_inst[PIPETTE_NUM];
+static pthread_mutex_t s_lock;
+static int            s_bus_inited = 0;
+
+static inline void pip_lock(void)   { pthread_mutex_lock(&s_lock); }
+static inline void pip_unlock(void) { pthread_mutex_unlock(&s_lock); }
+
+/*================== 工具函数 ==================*/
+static pipette_inst_t *get_inst(int id)
+{
+    if (id < PIPETTE_ID_MIN || id > PIPETTE_ID_MAX) return NULL;
+    return &s_inst[id - PIPETTE_ID_MIN];
+}
+
+static void set_err(pipette_inst_t *p, int code, const char *fmt, ...)
+{
+    va_list ap;
+    if (p == NULL) return;
+    p->last_err = code;
+    if (fmt != NULL) {
+        va_start(ap, fmt);
+        vsnprintf(p->last_err_msg, sizeof(p->last_err_msg) - 1, fmt, ap);
+        va_end(ap);
+    } else {
+        p->last_err_msg[0] = '\0';
+    }
+}
+
+static int motor_to_pip_err(int motor_err)
+{
+    switch (motor_err) {
+        case MOTOR_OK:         return PIPETTE_OK;
+        case MOTOR_ERR_PARAM:  return PIPETTE_ERR_PARAM;
+        case MOTOR_ERR_COMM:   return PIPETTE_ERR_COMM;
+        case MOTOR_ERR_NOT_INIT:return PIPETTE_ERR_NOT_INIT;
+        case MOTOR_ERR_TIMEOUT:return PIPETTE_ERR_TIMEOUT;
+        case MOTOR_ERR_FAULT:  return PIPETTE_ERR_MOVE;
+        case MOTOR_ERR_PATH_NO:return PIPETTE_ERR_PARAM;
+        default:               return (motor_err < 0) ? motor_err : PIPETTE_ERR_COMM;
+    }
+}
+
+/*================== 默认动作表/位置表 ==================*/
+static void init_default_pos_cfg(void)
+{
+    int i;
+    for (i = 0; i < PIPETTE_NUM; i++) {
+        s_inst[i].pos_cfg = (pipette_pos_t){
+            0, 100, 200,  0, 200, 100,  0, 200, 220
+        };
+        s_inst[i].speed[0] = s_inst[i].speed[1] = s_inst[i].speed[2] = PIPETTE_DEF_SPEED_RPM;
+        s_inst[i].accel[0] = s_inst[i].accel[1] = s_inst[i].accel[2] = PIPETTE_DEF_ACCEL;
+        s_inst[i].decel[0] = s_inst[i].decel[1] = s_inst[i].decel[2] = PIPETTE_DEF_DECEL;
+    }
+    s_inst[1].pos_cfg = (pipette_pos_t){
+        0,   0,   0,  0, 100, 100,  0, 200, 220
+    };
+    s_inst[3].pos_cfg = (pipette_pos_t){
+        0, 100, 200,  0, 100, 200,  0, 200, 220
+    };
+}
+
+static const pipette_act_t s_yyq1_acts[] = {
+    { .act_id = 1, .name = "加提取液", .step_num = 10, .step = {
+        { PIPETTE_AXIS_X, 0,   100,   0 },
+        { PIPETTE_AXIS_Z, 0,   150, 100 },
+        { PIPETTE_AXIS_Y, 0,   200,   0 },
+        { PIPETTE_AXIS_Z, 150,   0, 200 },
+        { PIPETTE_AXIS_Y, 200,   0,   0 },
+        { PIPETTE_AXIS_X, 100, 200,   0 },
+        { PIPETTE_AXIS_Y, 0,   100,   0 },
+        { PIPETTE_AXIS_Z, 0,   200, 200 },
+        { PIPETTE_AXIS_Y, 100,   0,   0 },
+        { PIPETTE_AXIS_X, 200,   0,   0 },
+    } }
+};
+static const pipette_act_t s_yyq2_acts[] = {
+    { .act_id = 1, .name = "吸取样本液", .step_num = 4, .step = {
+        { PIPETTE_AXIS_Z, 0,   150, 100 },
+        { PIPETTE_AXIS_Y, 0,   100,   0 },
+        { PIPETTE_AXIS_Z, 150,   0, 300 },
+        { PIPETTE_AXIS_Y, 100,   0,   0 },
+    } },
+    { .act_id = 2, .name = "注入样本液", .step_num = 4, .step = {
+        { PIPETTE_AXIS_Y, 0,   100,   0 },
+        { PIPETTE_AXIS_Z, 0,   200, 300 },
+        { PIPETTE_AXIS_Z, 200,   0,   0 },
+        { PIPETTE_AXIS_Y, 100,   0,   0 },
+    } }
+};
+static const pipette_act_t s_yyq3_acts[] = {
+    { .act_id = 1, .name = "二次加提取液", .step_num = 10, .step = {
+        { PIPETTE_AXIS_X, 0,   100,   0 },
+        { PIPETTE_AXIS_Z, 0,   150, 100 },
+        { PIPETTE_AXIS_Y, 0,   200,   0 },
+        { PIPETTE_AXIS_Z, 150,   0, 200 },
+        { PIPETTE_AXIS_Y, 200,   0,   0 },
+        { PIPETTE_AXIS_X, 100, 200,   0 },
+        { PIPETTE_AXIS_Y, 0,   100,   0 },
+        { PIPETTE_AXIS_Z, 0,   200, 200 },
+        { PIPETTE_AXIS_Y, 100,   0,   0 },
+        { PIPETTE_AXIS_X, 200,   0,   0 },
+    } }
+};
+static const pipette_act_t s_yyq4_acts[] = {
+    { .act_id = 1, .name = "吸样本滴试纸", .step_num = 9, .step = {
+        { PIPETTE_AXIS_X, 0,   100,   0 },
+        { PIPETTE_AXIS_Y, 0,   100,   0 },
+        { PIPETTE_AXIS_Z, 0,   200, 200 },
+        { PIPETTE_AXIS_Y, 100,   0,   0 },
+        { PIPETTE_AXIS_X, 100, 200,   0 },
+        { PIPETTE_AXIS_Y, 0,   200,   0 },
+        { PIPETTE_AXIS_Z, 200, 220, 500 },
+        { PIPETTE_AXIS_Y, 200,   0,   0 },
+        { PIPETTE_AXIS_X, 200,   0,   0 },
+    } }
+};
+static void init_default_act_table(void)
+{
+    s_inst[0].act_table     = s_yyq1_acts;
+    s_inst[0].act_table_cnt = (int)(sizeof(s_yyq1_acts)/sizeof(s_yyq1_acts[0]));
+    s_inst[1].act_table     = s_yyq2_acts;
+    s_inst[1].act_table_cnt = (int)(sizeof(s_yyq2_acts)/sizeof(s_yyq2_acts[0]));
+    s_inst[2].act_table     = s_yyq3_acts;
+    s_inst[2].act_table_cnt = (int)(sizeof(s_yyq3_acts)/sizeof(s_yyq3_acts[0]));
+    s_inst[3].act_table     = s_yyq4_acts;
+    s_inst[3].act_table_cnt = (int)(sizeof(s_yyq4_acts)/sizeof(s_yyq4_acts[0]));
+}
+
+static const pipette_act_t *find_act(pipette_inst_t *p, int act_id)
+{
+    int i;
+    if (p == NULL || p->act_table == NULL) return NULL;
+    for (i = 0; i < p->act_table_cnt; i++) {
+        if (p->act_table[i].act_id == act_id) return &p->act_table[i];
+    }
+    return NULL;
+}
+
+/*================== 轴命令封装 (调用 motor.c PR 接口) ==================*/
+
+/* 执行一步移动:setup PR15(即时段) + 触发并等待 */
+static int axis_move_via_pr(int pip_id, int axis, int32_t pos, int timeout_ms)
+{
+    pipette_inst_t *p = get_inst(pip_id);
+    uint8_t slave = SLAVE_OF(pip_id, axis);
+    uint16_t alm = 0;
+    int speed = PIPETTE_DEF_SPEED_RPM, acc = PIPETTE_DEF_ACCEL, dec = PIPETTE_DEF_DECEL;
+    int ret;
+
+    if (p != NULL) {
+        speed = p->speed[axis] > 0 ? p->speed[axis] : PIPETTE_DEF_SPEED_RPM;
+        acc   = p->accel[axis] > 0 ? p->accel[axis] : PIPETTE_DEF_ACCEL;
+        dec   = p->decel[axis] > 0 ? p->decel[axis] : PIPETTE_DEF_DECEL;
+    }
+
+    ret = motor_setup_path(slave, PIPETTE_PR_IMMEDIATE,
+                           PR_MODE_ABS_POS, pos,
+                           (uint16_t)speed, (uint16_t)acc, (uint16_t)dec);
+    if (ret != 0) return motor_to_pip_err(ret);
+
+    ret = motor_trigger_path_wait(slave, PIPETTE_PR_IMMEDIATE, timeout_ms, &alm);
+    return motor_to_pip_err(ret);
+}
+
+static int axis_home_via_motor(int pip_id, int axis, int timeout_ms)
+{
+    uint8_t slave = SLAVE_OF(pip_id, axis);
+    int ret = motor_home(slave, timeout_ms);
+    return motor_to_pip_err(ret);
+}
+
+static int axis_ping_via_motor(int pip_id, int axis)
+{
+    return motor_to_pip_err(motor_ping(SLAVE_OF(pip_id, axis)));
+}
+
+static int axis_read_pos_via_motor(int pip_id, int axis, int *out_pos)
+{
+    uint8_t slave = SLAVE_OF(pip_id, axis);
+    int32_t p32 = 0;
+    int ret = motor_read_curpos(slave, &p32);
+    if (ret != 0) return motor_to_pip_err(ret);
+    if (out_pos) *out_pos = (int)p32;
+    return PIPETTE_OK;
+}
+
+/*================== 公共接口 ==================*/
+int pipette_init(int id)
+{
+    pipette_inst_t *p = get_inst(id);
+    int ax, ret;
+    if (p == NULL) return PIPETTE_ERR_ID;
+
+    pip_lock();
+    if (!s_bus_inited) {
+        int r = motor_bus_init(PIPETTE_DEF_RS485_PORT, PIPETTE_DEF_BAUD);
+        if (r != MOTOR_OK) {
+            set_err(p, PIPETTE_ERR_COMM, "motor_bus_init failed");
+            pip_unlock();
+            return PIPETTE_ERR_COMM;
+        }
+        s_bus_inited = 1;
+    }
+
+    /* 1. 所有轴 PING 通信检查 */
+    for (ax = 0; ax < PIPETTE_AXIS_NUM; ax++) {
+        ret = axis_ping_via_motor(id, ax);
+        if (ret != PIPETTE_OK) {
+            p->state = PIPETTE_STATE_FAULT;
+            set_err(p, PIPETTE_ERR_COMM,
+                    "yyq%d %c-axis(slave=%d) DM2B ping fail",
+                    id, AXXIS(ax), SLAVE_OF(id, ax));
+            pip_unlock();
+            return PIPETTE_ERR_COMM;
+        }
+        (void)motor_clear_alarm(SLAVE_OF(id, ax));
+    }
+
+    /* 2. 上电逐轴回零点 */
+    for (ax = 0; ax < PIPETTE_AXIS_NUM; ax++) {
+        LOG_INFO("pipette %d %c-axis home start (slave=%d)\n",
+                 id, AXXIS(ax), SLAVE_OF(id, ax));
+        ret = axis_home_via_motor(id, ax, MOTOR_DEF_MOVE_TIMEOUT);
+        if (ret != PIPETTE_OK) {
+            p->state = PIPETTE_STATE_FAULT;
+            set_err(p, ret, "yyq%d %c-axis home fail", id, AXXIS(ax));
+            pip_unlock();
+            return ret;
+        }
+        p->cur_pos[ax] = 0;
+    }
+
+    p->inited = 1;
+    p->state  = PIPETTE_STATE_IDLE;
+    set_err(p, PIPETTE_OK, NULL);
+    pip_unlock();
+    LOG_INFO("pipette %d init ok (X/Y/Z servo home done)\n", id);
+    return PIPETTE_OK;
+}
+
+int pipette_deinit(int id)
+{
+    pipette_inst_t *p = get_inst(id);
+    int ax;
+    if (p == NULL) return PIPETTE_ERR_ID;
+    pip_lock();
+    if (p->inited) {
+        for (ax = 0; ax < PIPETTE_AXIS_NUM; ax++) {
+            (void)motor_enable(SLAVE_OF(id, ax), 0);
+        }
+    }
+    p->inited = 0;
+    p->state  = PIPETTE_STATE_NOINIT;
+    pip_unlock();
+    return PIPETTE_OK;
+}
+
+int pipette_init_all(void)
+{
+    int i, ret;
+    pthread_mutex_init(&s_lock, NULL);
+    memset(s_inst, 0, sizeof(s_inst));
+    for (i = 0; i < PIPETTE_NUM; i++) s_inst[i].state = PIPETTE_STATE_NOINIT;
+    init_default_pos_cfg();
+    init_default_act_table();
+    for (i = PIPETTE_ID_MIN; i <= PIPETTE_ID_MAX; i++) {
+        ret = pipette_init(i);
+        if (ret != PIPETTE_OK) {
+            LOG_ERROR("pipette %d init fail=%d\n", i, ret);
+        }
+    }
+    return PIPETTE_OK;
+}
+
+void pipette_deinit_all(void)
+{
+    int i;
+    for (i = PIPETTE_ID_MIN; i <= PIPETTE_ID_MAX; i++) {
+        (void)pipette_deinit(i);
+    }
+    motor_bus_deinit();
+    s_bus_inited = 0;
+    pthread_mutex_destroy(&s_lock);
+}
+
+int pipette_is_inited(int id)
+{
+    pipette_inst_t *p = get_inst(id);
+    return (p != NULL) ? p->inited : 0;
+}
+
+int pipette_axis_move(int id, int axis, int pos, int timeout_ms)
+{
+    pipette_inst_t *p = get_inst(id);
+    int ret;
+    if (p == NULL) return PIPETTE_ERR_ID;
+    if (axis < 0 || axis >= PIPETTE_AXIS_NUM) return PIPETTE_ERR_AXIS;
+    if (!p->inited) return PIPETTE_ERR_NOT_INIT;
+    if (timeout_ms <= 0) timeout_ms = PIPETTE_DEF_MOVE_TIMEOUT;
+
+    pip_lock();
+    p->state = PIPETTE_STATE_BUSY;
+    ret = axis_move_via_pr(id, axis, pos, timeout_ms);
+    if (ret == PIPETTE_OK) {
+        int rp = 0;
+        if (axis_read_pos_via_motor(id, axis, &rp) == 0) p->cur_pos[axis] = rp;
+        else                                             p->cur_pos[axis] = pos;
+        p->state = PIPETTE_STATE_IDLE;
+        set_err(p, PIPETTE_OK, NULL);
+    } else {
+        p->state = PIPETTE_STATE_FAULT;
+        set_err(p, ret, "yyq%d %c-axis move to %d fail", id, AXXIS(axis), pos);
+    }
+    pip_unlock();
+    return ret;
+}
+
+int pipette_axis_home(int id, int axis)
+{
+    pipette_inst_t *p = get_inst(id);
+    int ret;
+    if (p == NULL) return PIPETTE_ERR_ID;
+    if (axis < 0 || axis >= PIPETTE_AXIS_NUM) return PIPETTE_ERR_AXIS;
+    if (!p->inited) return PIPETTE_ERR_NOT_INIT;
+
+    pip_lock();
+    p->state = PIPETTE_STATE_BUSY;
+    ret = axis_home_via_motor(id, axis, MOTOR_DEF_MOVE_TIMEOUT);
+    if (ret == PIPETTE_OK) {
+        p->cur_pos[axis] = 0;
+        p->state = PIPETTE_STATE_IDLE;
+        set_err(p, PIPETTE_OK, NULL);
+    } else {
+        p->state = PIPETTE_STATE_FAULT;
+        set_err(p, ret, "yyq%d %c-axis home fail", id, AXXIS(axis));
+    }
+    pip_unlock();
+    return ret;
+}
+
+int pipette_get_axis_pos(int id, int axis, int *out_pos)
+{
+    pipette_inst_t *p = get_inst(id);
+    if (p == NULL) return PIPETTE_ERR_ID;
+    if (axis < 0 || axis >= PIPETTE_AXIS_NUM || out_pos == NULL) return PIPETTE_ERR_PARAM;
+    pip_lock();
+    *out_pos = p->cur_pos[axis];
+    pip_unlock();
+    return PIPETTE_OK;
+}
+
+int pipette_act(int id, int act_id)
+{
+    pipette_inst_t *p = get_inst(id);
+    const pipette_act_t *act;
+    int i, ret;
+
+    if (p == NULL) return PIPETTE_ERR_ID;
+    if (!p->inited) return PIPETTE_ERR_NOT_INIT;
+    act = find_act(p, act_id);
+    if (act == NULL) return PIPETTE_ERR_NO_ACT;
+
+    LOG_INFO("pipette %d start act=%d(%s) steps=%d\n",
+             id, act_id, act->name, act->step_num);
+
+    pip_lock();
+    p->state = PIPETTE_STATE_BUSY;
+    for (i = 0; i < act->step_num; i++) {
+        const pipette_step_t *st = &act->step[i];
+        pip_unlock();
+        LOG_INFO("  step %2d/%d: %c %d -> %d  delay=%dms\n",
+                 i + 1, act->step_num, AXXIS(st->axis),
+                 st->pos_from, st->pos_to, st->delay_ms);
+
+        ret = axis_move_via_pr(id, st->axis, st->pos_to, PIPETTE_DEF_MOVE_TIMEOUT);
+        pip_lock();
+        if (ret != PIPETTE_OK) {
+            p->state = PIPETTE_STATE_FAULT;
+            set_err(p, ret, "act %d step %d(%c) fail", act_id, i + 1, AXXIS(st->axis));
+            pip_unlock();
+            return ret;
+        }
+        int rp = 0;
+        if (axis_read_pos_via_motor(id, st->axis, &rp) == 0)
+            p->cur_pos[st->axis] = rp;
+        else
+            p->cur_pos[st->axis] = st->pos_to;
+        if (st->delay_ms > 0) {
+            pip_unlock();
+            struct timespec ts;
+            ts.tv_sec  = st->delay_ms / 1000;
+            ts.tv_nsec = (long)(st->delay_ms % 1000) * 1000000L;
+            nanosleep(&ts, NULL);
+            pip_lock();
+        }
+    }
+    p->state = PIPETTE_STATE_IDLE;
+    set_err(p, PIPETTE_OK, NULL);
+    pip_unlock();
+    LOG_INFO("pipette %d act %d done\n", id, act_id);
+    return PIPETTE_OK;
+}
+
+int pipette_get_state(int id)
+{
+    pipette_inst_t *p = get_inst(id);
+    return (p != NULL) ? p->state : PIPETTE_STATE_NOINIT;
+}
+
+int pipette_get_last_error(int id, char *buf, int buf_len)
+{
+    pipette_inst_t *p = get_inst(id);
+    int code;
+    if (p == NULL || buf == NULL || buf_len <= 0) return PIPETTE_ERR_PARAM;
+    pip_lock();
+    code = p->last_err;
+    strncpy(buf, p->last_err_msg, buf_len - 1);
+    buf[buf_len - 1] = '\0';
+    pip_unlock();
+    return code;
+}
+
+int pipette_set_act_table(int id, const pipette_act_t *table, int count)
+{
+    pipette_inst_t *p = get_inst(id);
+    if (p == NULL) return PIPETTE_ERR_ID;
+    if (table == NULL || count <= 0 || count > PIPETTE_ACT_TABLE_SIZE) return PIPETTE_ERR_PARAM;
+    pip_lock();
+    p->act_table     = table;
+    p->act_table_cnt = count;
+    pip_unlock();
+    return PIPETTE_OK;
+}
+
+int pipette_get_positions(int id, pipette_pos_t *out)
+{
+    pipette_inst_t *p = get_inst(id);
+    if (p == NULL || out == NULL) return PIPETTE_ERR_PARAM;
+    pip_lock(); *out = p->pos_cfg; pip_unlock();
+    return PIPETTE_OK;
+}
+
+int pipette_set_positions(int id, const pipette_pos_t *cfg)
+{
+    pipette_inst_t *p = get_inst(id);
+    if (p == NULL || cfg == NULL) return PIPETTE_ERR_PARAM;
+    pip_lock(); p->pos_cfg = *cfg; pip_unlock();
+    return PIPETTE_OK;
+}
\ No newline at end of file
diff --git a/app/src/robot.c b/app/src/robot.c
new file mode 100644 (file)
index 0000000..c265cd8
--- /dev/null
@@ -0,0 +1,435 @@
+#include <stdio.h>
+#include <stdint.h>
+#include <stdlib.h>
+#include <stdarg.h>
+#include <string.h>
+#include <unistd.h>
+#include <errno.h>
+#include <fcntl.h>
+#include <time.h>
+#include <sys/types.h>
+#include <sys/socket.h>
+#include <sys/select.h>
+#include <netinet/in.h>
+#include <arpa/inet.h>
+#include <netdb.h>
+#include <pthread.h>
+
+#include "robot.h"
+#include "ad_log.h"
+
+#ifndef LOG_INFO
+#define LOG_INFO(fmt, args...)   do { printf("[ROBOT][INFO ] " fmt, ##args); } while(0)
+#define LOG_ERROR(fmt, args...)  do { printf("[ROBOT][ERROR] " fmt, ##args); } while(0)
+#endif
+
+static int          s_sockfd = -1;
+static char         s_server_ip[64] = ROBOT_DEFAULT_IP;
+static int          s_server_port = ROBOT_DEFAULT_PORT;
+static int          s_cur_state = ROBOT_STATE_NO_CONN;
+static int          s_last_err = ROBOT_OK;
+static char         s_last_err_msg[256] = {0};
+static pthread_mutex_t s_lock;
+
+static const robot_act_def_t s_act_table[ROBOT_ACT_NUM_MAX] = {
+    { ROBOT_ACT_RESET,  "复位回原点",         "ROBOT:RESET",     15 },
+    { ROBOT_ACT_1_2,    "工位1->移液器1",     "ROBOT:ACT:1_2",   10 },
+    { ROBOT_ACT_2_3,    "移液器1->涡动仪",    "ROBOT:ACT:2_3",   10 },
+    { ROBOT_ACT_3_4,    "涡动仪->离心机",     "ROBOT:ACT:3_4",   10 },
+    { ROBOT_ACT_4_5,    "离心机->移液器2",    "ROBOT:ACT:4_5",   10 },
+    { ROBOT_ACT_5_8,    "移液器2->废液仓",    "ROBOT:ACT:5_8",   10 },
+    { ROBOT_ACT_9_5,    "新管工位9->移液器2", "ROBOT:ACT:9_5",   10 },
+    { ROBOT_ACT_5_6,    "移液器2->移液器3",   "ROBOT:ACT:5_6",   10 },
+    { ROBOT_ACT_6_3,    "移液器3->涡动仪",    "ROBOT:ACT:6_3",   10 },
+    { ROBOT_ACT_3_7,    "涡动仪->移液器4",    "ROBOT:ACT:3_7",   10 },
+    { ROBOT_ACT_7_8,    "移液器4->废液仓",    "ROBOT:ACT:7_8",   10 },
+    { ROBOT_ACT_PHOTO,  "拍照上报结果",       "ROBOT:ACT:PHOTO", 60 },
+    { ROBOT_ACT_HOME,   "回到原位",           "ROBOT:ACT:HOME",  10 },
+};
+
+static inline void robot_lock(void)   { pthread_mutex_lock(&s_lock); }
+static inline void robot_unlock(void) { pthread_mutex_unlock(&s_lock); }
+
+static void set_error(int code, const char *fmt, ...)
+{
+    va_list ap;
+    s_last_err = code;
+    if (fmt != NULL) {
+        va_start(ap, fmt);
+        vsnprintf(s_last_err_msg, sizeof(s_last_err_msg) - 1, fmt, ap);
+        va_end(ap);
+    } else {
+        s_last_err_msg[0] = '\0';
+    }
+}
+
+static int sock_set_nonblock(int fd, int nonblock)
+{
+    int flags;
+    flags = fcntl(fd, F_GETFL, 0);
+    if (flags < 0) return -1;
+    if (nonblock) flags |= O_NONBLOCK;
+    else          flags &= ~O_NONBLOCK;
+    return fcntl(fd, F_SETFL, flags);
+}
+
+static int sock_wait_writable(int fd, int timeout_ms)
+{
+    fd_set wfds;
+    struct timeval tv;
+    FD_ZERO(&wfds);
+    FD_SET(fd, &wfds);
+    tv.tv_sec  = timeout_ms / 1000;
+    tv.tv_usec = (timeout_ms % 1000) * 1000;
+    return select(fd + 1, NULL, &wfds, NULL, &tv);
+}
+
+static int sock_wait_readable(int fd, int timeout_ms)
+{
+    fd_set rfds;
+    struct timeval tv;
+    FD_ZERO(&rfds);
+    FD_SET(fd, &rfds);
+    tv.tv_sec  = timeout_ms / 1000;
+    tv.tv_usec = (timeout_ms % 1000) * 1000;
+    return select(fd + 1, &rfds, NULL, NULL, &tv);
+}
+
+static int sock_connected_check(int fd)
+{
+    int err = 0;
+    socklen_t len = sizeof(err);
+    if (getsockopt(fd, SOL_SOCKET, SO_ERROR, &err, &len) < 0) return -1;
+    return err == 0 ? 0 : -1;
+}
+
+static int robot_do_connect(void)
+{
+    int fd, ret;
+    struct sockaddr_in addr;
+
+    fd = socket(AF_INET, SOCK_STREAM, 0);
+    if (fd < 0) {
+        set_error(ROBOT_ERR_COMM, "socket create failed: %s", strerror(errno));
+        return -1;
+    }
+    sock_set_nonblock(fd, 1);
+    memset(&addr, 0, sizeof(addr));
+    addr.sin_family = AF_INET;
+    addr.sin_port   = htons(s_server_port);
+    inet_pton(AF_INET, s_server_ip, &addr.sin_addr);
+
+    ret = connect(fd, (struct sockaddr *)&addr, sizeof(addr));
+    if (ret < 0 && errno != EINPROGRESS) {
+        close(fd);
+        set_error(ROBOT_ERR_COMM, "connect failed: %s", strerror(errno));
+        return -1;
+    }
+    if (ret == 0) goto connected;
+
+    ret = sock_wait_writable(fd, 3000);
+    if (ret <= 0) {
+        close(fd);
+        set_error(ROBOT_ERR_TIMEOUT, "connect timeout");
+        return -1;
+    }
+    if (sock_connected_check(fd) < 0) {
+        close(fd);
+        set_error(ROBOT_ERR_COMM, "connect refused");
+        return -1;
+    }
+connected:
+    sock_set_nonblock(fd, 0);
+    s_sockfd = fd;
+    s_cur_state = ROBOT_STATE_IDLE;
+    set_error(ROBOT_OK, NULL);
+    LOG_INFO("robot connected to %s:%d, fd=%d\n", s_server_ip, s_server_port, fd);
+    return 0;
+}
+
+static int robot_do_send(const char *data, int len, int timeout_s)
+{
+    int sent = 0, ret;
+    int remain = len;
+    int deadline_ms = timeout_s * 1000;
+    int start_ms = (int)(time(NULL) * 1000);
+
+    while (remain > 0) {
+        sock_set_nonblock(s_sockfd, 1);
+        ret = send(s_sockfd, data + sent, remain, 0);
+        sock_set_nonblock(s_sockfd, 0);
+        if (ret > 0) {
+            sent   += ret;
+            remain -= ret;
+        } else if (ret == 0) {
+            set_error(ROBOT_ERR_COMM, "send peer closed");
+            return -1;
+        } else {
+            if (errno != EAGAIN && errno != EWOULDBLOCK) {
+                set_error(ROBOT_ERR_COMM, "send error: %s", strerror(errno));
+                return -1;
+            }
+            int elapsed = (int)(time(NULL) * 1000) - start_ms;
+            int left = deadline_ms - elapsed;
+            if (left <= 0) {
+                set_error(ROBOT_ERR_TIMEOUT, "send timeout");
+                return -1;
+            }
+            ret = sock_wait_writable(s_sockfd, left > 100 ? 100 : left);
+            if (ret < 0) {
+                set_error(ROBOT_ERR_COMM, "send select error");
+                return -1;
+            }
+        }
+    }
+    return sent;
+}
+
+static int robot_do_recv(char *buf, int buf_len, int timeout_s, int *has_line)
+{
+    int total = 0, ret;
+    int deadline_ms = timeout_s * 1000;
+    int start_ms = (int)(time(NULL) * 1000);
+    *has_line = 0;
+
+    while (total < buf_len - 1) {
+        sock_set_nonblock(s_sockfd, 1);
+        ret = recv(s_sockfd, buf + total, buf_len - 1 - total, 0);
+        sock_set_nonblock(s_sockfd, 0);
+        if (ret > 0) {
+            total += ret;
+            buf[total] = '\0';
+            if (strchr(buf, '\n') != NULL) {
+                *has_line = 1;
+                break;
+            }
+        } else if (ret == 0) {
+            set_error(ROBOT_ERR_COMM, "recv peer closed");
+            return -1;
+        } else {
+            if (errno != EAGAIN && errno != EWOULDBLOCK) {
+                set_error(ROBOT_ERR_COMM, "recv error: %s", strerror(errno));
+                return -1;
+            }
+            int elapsed = (int)(time(NULL) * 1000) - start_ms;
+            int left = deadline_ms - elapsed;
+            if (left <= 0) {
+                break;
+            }
+            ret = sock_wait_readable(s_sockfd, left > 200 ? 200 : left);
+            if (ret < 0) {
+                set_error(ROBOT_ERR_COMM, "recv select error");
+                return -1;
+            }
+        }
+    }
+    return total;
+}
+
+static int parse_resp_code(const char *resp)
+{
+    int code = ROBOT_ERR_EXEC;
+    char tmp[16];
+    const char *p;
+
+    if (resp == NULL) return ROBOT_ERR_EXEC;
+    p = strstr(resp, "OK");
+    if (p != NULL) return 0;
+    p = strstr(resp, "ERR:");
+    if (p != NULL) {
+        if (sscanf(p + 4, "%15s", tmp) == 1) {
+            if (strstr(tmp, "NO_SAMPLE") != NULL) return ROBOT_ERR_NO_SAMPLE;
+            if (strstr(tmp, "NO_ACT")    != NULL) return ROBOT_ERR_NO_ACT;
+            if (strstr(tmp, "TIMEOUT")   != NULL) return ROBOT_ERR_TIMEOUT;
+            if (strstr(tmp, "COMM")      != NULL) return ROBOT_ERR_COMM;
+            return ROBOT_ERR_EXEC;
+        }
+    }
+    p = strstr(resp, "RESULT:");
+    if (p != NULL && sscanf(p + 7, "%d", &code) == 1) {
+        return code;
+    }
+    if (strncmp(resp, "0", 1) == 0) return 0;
+    return code;
+}
+
+static void robot_close_locked(void)
+{
+    if (s_sockfd >= 0) {
+        close(s_sockfd);
+        s_sockfd = -1;
+    }
+    s_cur_state = ROBOT_STATE_NO_CONN;
+}
+
+int robot_connect(void)
+{
+    int ret;
+    pthread_mutex_init(&s_lock, NULL);
+    robot_lock();
+    robot_close_locked();
+    ret = robot_do_connect();
+    if (ret < 0) {
+        robot_close_locked();
+        robot_unlock();
+        return s_last_err;
+    }
+    robot_unlock();
+    return ROBOT_OK;
+}
+
+void robot_disconnect(void)
+{
+    robot_lock();
+    robot_close_locked();
+    pthread_mutex_destroy(&s_lock);
+}
+
+int robot_is_connected(void)
+{
+    int r;
+    robot_lock();
+    r = (s_sockfd >= 0) ? 1 : 0;
+    robot_unlock();
+    return r;
+}
+
+int robot_set_server(const char *ip, int port)
+{
+    if (ip == NULL || port <= 0 || port > 65535) {
+        set_error(ROBOT_ERR_PARAM, "invalid param");
+        return -1;
+    }
+    robot_lock();
+    strncpy(s_server_ip, ip, sizeof(s_server_ip) - 1);
+    s_server_port = port;
+    robot_unlock();
+    return 0;
+}
+
+int robot_get_last_error(char *buf, int buf_len)
+{
+    if (buf == NULL || buf_len <= 0) return -1;
+    robot_lock();
+    int code = s_last_err;
+    strncpy(buf, s_last_err_msg, buf_len - 1);
+    buf[buf_len - 1] = '\0';
+    robot_unlock();
+    return code;
+}
+
+int robot_act(int act_id, int timeout_s)
+{
+    int ret, n, code, has_line;
+    char send_buf[128];
+    char recv_buf[512];
+    const robot_act_def_t *def = NULL;
+    int i, effective_timeout;
+
+    if (act_id < 0 || act_id >= ROBOT_ACT_NUM_MAX) {
+        set_error(ROBOT_ERR_NO_ACT, "act_id=%d invalid", act_id);
+        return ROBOT_ERR_NO_ACT;
+    }
+    def = &s_act_table[act_id];
+    effective_timeout = (timeout_s > 0) ? timeout_s : def->def_timeout_s;
+
+    robot_lock();
+    if (s_sockfd < 0) {
+        ret = robot_do_connect();
+        if (ret < 0) {
+            robot_unlock();
+            return ROBOT_ERR_NOT_CONN;
+        }
+    }
+
+    s_cur_state = ROBOT_STATE_BUSY;
+    snprintf(send_buf, sizeof(send_buf), "%s\n", def->cmd_str);
+    LOG_INFO("robot_act send: %s", send_buf);
+
+    n = robot_do_send(send_buf, (int)strlen(send_buf), effective_timeout);
+    if (n <= 0) {
+        s_cur_state = ROBOT_STATE_FAULT;
+        robot_close_locked();
+        robot_unlock();
+        return s_last_err != ROBOT_OK ? s_last_err : ROBOT_ERR_COMM;
+    }
+
+    memset(recv_buf, 0, sizeof(recv_buf));
+    n = robot_do_recv(recv_buf, sizeof(recv_buf), effective_timeout, &has_line);
+    if (n <= 0) {
+        s_cur_state = ROBOT_STATE_FAULT;
+        if (s_last_err == ROBOT_OK) set_error(ROBOT_ERR_TIMEOUT, "act resp timeout");
+        robot_close_locked();
+        robot_unlock();
+        return s_last_err;
+    }
+    recv_buf[n] = '\0';
+    LOG_INFO("robot_act recv: %s", recv_buf);
+
+    code = parse_resp_code(recv_buf);
+    if (code == 0) {
+        s_cur_state = ROBOT_STATE_IDLE;
+        set_error(ROBOT_OK, NULL);
+        ret = ROBOT_OK;
+    } else {
+        s_cur_state = ROBOT_STATE_FAULT;
+        if (s_last_err == ROBOT_OK) {
+            set_error(code, "act failed: %s", recv_buf);
+        }
+        ret = code;
+    }
+    robot_unlock();
+    return ret;
+}
+
+int robot_state(void)
+{
+    int ret, n, has_line;
+    char send_buf[64];
+    char recv_buf[512];
+
+    robot_lock();
+    if (s_cur_state == ROBOT_STATE_BUSY) {
+        ret = ROBOT_STATE_BUSY;
+        robot_unlock();
+        return ret;
+    }
+    if (s_sockfd < 0) {
+        ret = robot_do_connect();
+        if (ret < 0) {
+            s_cur_state = ROBOT_STATE_NO_CONN;
+            robot_unlock();
+            return ROBOT_STATE_NO_CONN;
+        }
+    }
+
+    snprintf(send_buf, sizeof(send_buf), "ROBOT:STATE?\n");
+    n = robot_do_send(send_buf, (int)strlen(send_buf), 3);
+    if (n <= 0) {
+        s_cur_state = ROBOT_STATE_NO_CONN;
+        robot_close_locked();
+        robot_unlock();
+        return ROBOT_STATE_NO_CONN;
+    }
+    memset(recv_buf, 0, sizeof(recv_buf));
+    n = robot_do_recv(recv_buf, sizeof(recv_buf), 3, &has_line);
+    if (n <= 0) {
+        s_cur_state = ROBOT_STATE_NO_CONN;
+        robot_close_locked();
+        robot_unlock();
+        return ROBOT_STATE_NO_CONN;
+    }
+    recv_buf[n] = '\0';
+    if (strstr(recv_buf, "IDLE")  != NULL) s_cur_state = ROBOT_STATE_IDLE;
+    else if (strstr(recv_buf, "BUSY")  != NULL) s_cur_state = ROBOT_STATE_BUSY;
+    else if (strstr(recv_buf, "FAULT") != NULL) s_cur_state = ROBOT_STATE_FAULT;
+    else {
+        int code = ROBOT_STATE_IDLE;
+        if (sscanf(recv_buf, "%d", &code) == 1) {
+            s_cur_state = code;
+        }
+    }
+    ret = s_cur_state;
+    robot_unlock();
+    return ret;
+}
\ No newline at end of file
diff --git a/app/src/ui.c b/app/src/ui.c
new file mode 100644 (file)
index 0000000..fc4f93a
--- /dev/null
@@ -0,0 +1,869 @@
+#include <gio/gio.h>
+#include <glib.h>
+#include "cJSON.h"
+#include "agridetect.h"
+#include <time.h>
+
+#define SERVICE_NAME          "com.yn.ui"
+#define OBJECT_PATH           "/com/yn/ui"
+#define INTERFACE_NAME        "com.yn.ui.interface"
+
+//dbus method
+#define API_QUERY_STATE        "query_state"
+#define API_QUERY_PARAMS       "query_parameters"
+#define API_UPDATE_PARAMS      "update_parameters"
+#define API_USER_CMD           "user_cmd"
+
+//---API_QUERY_STATE----------------------------
+//定时查询状态  
+#define CMD_QUERY_STATE        "query_state"
+//---API_USER_CMD----------------------------
+//用户点击按钮执行指令
+#define CMD_TEST_START         "test_start"
+#define CMD_TEST_PAUSE         "test_pause"
+#define CMD_TEST_STOP          "test_stop"
+#define CMD_LOGIN              "login"
+#define CMD_LOGOUT             "logout"
+#define CMD_DEBUG              "debug"
+#define CMD_RESET              "reset"      //故障页面点击复位
+//---API_QUERY_PARAMS----------------------------
+//用户点击按钮读参数
+#define CMD_QUERY_PARAMS       "query_params"
+//---API_UPDATE_PARAMS----------------------------
+//用户点击按钮写参数
+#define CMD_UPDATE_PARAMS      "update_params"
+//-------------------------------------------------
+
+/* -------------------------------------------------------------
+ * 协议中 state / msg 对应表(与 doc/dbus.md 保持一致)
+ *   code   msg                 agridetect.h 中 dev_state_t
+ *   0      init                DEV_INIT
+ *   1      selftest            DEV_SELFTESTING
+ *   2      selftest_failed     DEV_SELFTEST_FAILED
+ *   3      ready               DEV_READY
+ *   4      test                DEV_TESTING
+ *   5      test_pause          DEV_TEST_PAUSE
+ *   6      test_fault          DEV_TEST_ERROR
+ *   7      debug               DEV_MANUAL_DEBUG
+ * ------------------------------------------------------------- */
+typedef struct {
+    dev_state_t state;
+    const char *name;
+} state_map_t;
+
+static const char * g_devstate_name[ DEV_STATE_NUM] = {
+    "init",            //DEV_INIT
+    "selftest",        //DEV_SELFTESTING
+    "selftest_failed", //DEV_SELFTEST_FAILED
+    "ready",           //DEV_READY
+    "testing",         //DEV_TESTING
+    "test_paused",      //DEV_TEST_PAUSED
+    "test_fault",      //DEV_TEST_ERROR
+    "test_finish",     //DEV_TEST_COMPLETED
+    "debug"           //DEV_MANUAL_DEBUG
+};
+
+/* 故障码与中文描述 */
+typedef struct {
+    int         code;
+    const char *message;
+} fault_msg_t;
+
+static const fault_msg_t g_fault_msgs[] = {
+    { -1, "机械臂通信故障" },
+    { -2, "移液器控制故障" },
+    { -3, "涡动仪控制故障" },
+    { -4, "离心机控制故障" },
+    { -5, "样本未就绪" },
+    { -6, "样本放置目的地失败" },
+    { -7, "未知/其他故障" },
+};
+#define FAULT_MSG_ENTRIES (sizeof(g_fault_msgs)/sizeof(g_fault_msgs[0]))
+
+static const char *fault_code_to_msg(int code)
+{
+    for (guint i = 0; i < DEV_STATE_NUM; i++) {
+        if (g_fault_msgs[i].code == code) return g_fault_msgs[i].message;
+    }
+    return "未知故障";
+}
+
+/* agridetect.h dev_state_t -> 协议 code/msg 查询 */
+static const char *get_devstate_name(dev_state_t ds)
+{
+    if( ds < DEV_STATE_NUM)
+        return g_devstate_name[ds];
+    else
+        return "unkonwn_state";
+}
+
+static GDBusNodeInfo *g_introspect_info = NULL;
+
+typedef char *(*api_handler_t)(const char *json_in);
+
+static char *api_query_state(const char *json_in);
+static char *api_query_params(const char *json_in);
+static char *api_update_params(const char *json_in);
+static char *api_user_cmd(const char *json_in);
+
+/* =============================================================
+ *  通用响应包装:{ "cmd": "...", "code": N, "msg": "...", "data": {} }
+ * ============================================================= */
+static char *make_response(const char *cmd, int code, const char *msg, cJSON *data_obj)
+{
+    cJSON *root = cJSON_CreateObject();
+    cJSON_AddStringToObject(root, "cmd", cmd ? cmd : "");
+    cJSON_AddNumberToObject(root, "code", code);
+    if (msg) cJSON_AddStringToObject(root, "msg", msg);
+    else     cJSON_AddStringToObject(root, "msg", code == 0 ? "ok" : "error");
+
+    if (data_obj) cJSON_AddItemToObject(root, "data", data_obj);
+    else          cJSON_AddItemToObject(root, "data", cJSON_CreateObject());
+
+    char *out = cJSON_PrintUnformatted(root);
+    cJSON_Delete(root);
+
+    return out;
+}
+
+static char *make_ok_response(const char *cmd, cJSON *data_obj)
+{
+printf( "------mk ok resp, cmd:%s\n", cmd );
+    return make_response(cmd, 0, "ok", data_obj);
+}
+
+static char *make_err_response(const char *cmd, int code, const char *fmt, ...)
+{
+    char msg[256];
+    va_list ap;
+    va_start(ap, fmt);
+    vsnprintf(msg, sizeof(msg), fmt, ap);
+    va_end(ap);
+    return make_response(cmd, code, msg, NULL);
+}
+
+/* 安全读取 cJSON 字符串 */
+static const char *cj_str(const cJSON *obj, const char *key, const char *def)
+{
+    cJSON *v = cJSON_GetObjectItem(obj, key);
+    if (v && cJSON_IsString(v)) return v->valuestring;
+    return def;
+}
+static int cj_int(const cJSON *obj, const char *key, int def)
+{
+    cJSON *v = cJSON_GetObjectItem(obj, key);
+    if (v && cJSON_IsNumber(v)) return v->valueint;
+    return def;
+}
+
+/* =============================================================
+ *  query_state 数据构造:统一通过 dev_info.h 公开 API 获取快照
+ * ============================================================= */
+
+/* dev_info.h selftest_item_state_t -> UI 协议结果
+   PENDING(0) / TESTING(2) / PASS(1) / FAIL(-1) */
+static int map_selftest_state(selftest_item_state_t s)
+{
+    switch (s) {
+        case ST_ITEM_TESTING: return 2;
+        case ST_ITEM_PASS:    return 1;
+        case ST_ITEM_FAIL:    return -1;
+        default:              return 0; /* PENDING / unknown */
+    }
+}
+
+/* 自检结果按 name 匹配兜底(使用 dev_info.h 中 selftest_info_t) */
+static int selftest_result_by_name(const selftest_info_t *s, const char *key)
+{
+    if (!s || !key) return 0;
+    for (int i = 0; i < s->item_count && i < SELFTEST_ITEM_MAX; i++) {
+        if (s->items[i].name[0] && g_strcmp0(s->items[i].name, key) == 0) {
+            return map_selftest_state(s->items[i].state);
+        }
+    }
+    return 0;
+}
+
+static cJSON *build_selftest_result_array(const selftest_info_t *s)
+{
+    cJSON *arr = cJSON_CreateArray();
+    if (!s) return arr;
+    int n = (s->item_count > SELFTEST_ITEM_MAX) ? SELFTEST_ITEM_MAX : s->item_count;
+    for (int k = 0; k < n; k++) {
+        cJSON_AddItemToArray(arr, cJSON_CreateNumber(map_selftest_state(s->items[k].state)));
+    }
+    return arr;
+}
+
+/* 自动检测中:基于 dev_info.h 的 test_info_t / test_step_t */
+static void collect_test_info(const test_info_t *ti,
+                                  int *out_total, int *out_current,
+                                  cJSON **out_steps_array)
+{
+    int total = 0, current = 0;
+    cJSON *arr = cJSON_CreateArray();
+    if (ti) {
+        total = (ti->step_count > TEST_STEP_MAX) ? TEST_STEP_MAX : ti->step_count;
+        for (int i = 0; i < total; i++) {
+            int s = ti->steps[i].state;
+            cJSON_AddItemToArray(arr, cJSON_CreateNumber(s));
+            if (s == TEST_STEP_RUNNING && current == 0) current = i + 1;
+        }
+        current = ti->current_step;
+    }
+    *out_total   = total;
+    *out_current = current;
+    if (out_steps_array) *out_steps_array = arr;
+    else cJSON_Delete(arr);
+}
+
+/* 自动检测出错时:取第一个异常动作的 fault 码(使用 dev_info.h test_info_t) */
+static int detect_test_fault(const test_info_t *ti)
+{
+    if (!ti) return 5;
+    int n = (ti->step_count > TEST_STEP_MAX) ? TEST_STEP_MAX : ti->step_count;
+    for (int i = 0; i < n; i++) {
+        if (ti->steps[i].state == TEST_STEP_FAIL) {
+            if (ti->steps[i].fault_code > 0) return (int)ti->steps[i].fault_code;
+            return 5;
+        }
+    }
+    return 5;
+}
+
+/* dev_info.h debug_state_t -> UI 调试结果
+   IDLE(0) / RUNNING(1) / DONE(2) / FAULT(-1) */
+static int map_debug_state_to_res(debug_state_t s)
+{
+    switch (s) {
+        case DEBUG_RUNNING: return 1;
+        case DEBUG_DONE:    return 2;
+        case DEBUG_FAULT:   return -1;
+        default:            return 0; /* IDLE / unknown */
+    }
+}
+
+/* 主查询处理 */
+static char *api_query_state(const char *json_in)
+{
+    (void)json_in;
+    const char *cmd = "query_state";
+
+    /* 1. 拿整机工作态(ui_state)线程安全读取 */
+    dev_state_t curr = dev_get_state();
+
+    const char *proto_msg;
+
+    /* 2. 拿 dev_info 一致快照(内部已加锁,dev_get_snapshot 是 dev_info.h 公开 API) */
+    dev_info_t snap;
+    memset(&snap, 0, sizeof(snap));
+    (void)dev_get_snapshot(&snap);
+
+    cJSON *data = cJSON_CreateObject();
+    cJSON_AddNumberToObject(data, "state", curr );
+    cJSON_AddStringToObject(data, "msg",   get_devstate_name(curr));
+    switch (curr) {
+        case DEV_INIT: {
+            break;
+        }
+        case DEV_SELFTESTING:
+        case DEV_SELFTEST_FAILED: {
+            selftest_info_t st;
+            memset(&st, 0, sizeof(st));
+            (void)dev_selftest_get_info(&st);
+            cJSON *arr = build_selftest_result_array(&st);
+            cJSON_AddItemToObject(data, "res", arr);
+            break;
+        }
+        case DEV_READY: {
+            break;
+        }
+        case DEV_TESTING:
+        case DEV_TEST_PAUSED:
+        case DEV_TEST_ERROR:
+        case DEV_TEST_COMPLETED: {
+            test_info_t ti;
+            memset(&ti, 0, sizeof(ti));
+            (void)dev_test_get_info(&ti);
+
+            int total = 0, current = 0;
+            cJSON *steps = NULL;
+            collect_test_info(&ti, &total, &current, &steps);
+            cJSON_AddNumberToObject(data, "step", (current > 0) ? current : 0);
+
+            cJSON *timer = cJSON_CreateObject();
+            int total_time = 0, remain = 0;
+            if (total > 0 && ti.current_step >= 0 && ti.current_step < TEST_STEP_MAX) {
+                total_time = ti.steps[ti.current_step].total_time_s;
+                remain     = ti.steps[ti.current_step].remain_time_s;
+            }
+            cJSON_AddNumberToObject(timer, "total",  total_time);
+            cJSON_AddNumberToObject(timer, "remain", remain);
+            cJSON_AddItemToObject(data, "timer", timer);
+
+            if (steps) cJSON_AddItemToObject(data, "steps", steps);
+
+            if (curr == DEV_TEST_ERROR) {
+                int fc = detect_test_fault(&ti);
+                cJSON_AddNumberToObject(data, "fault", fc);
+            }
+            break;
+        }
+        case DEV_MANUAL_DEBUG: {
+            debug_info_t dbg;
+            memset(&dbg, 0, sizeof(dbg));
+            (void)dev_debug_get_info(&dbg);
+            cJSON *dbg_json = cJSON_CreateObject();
+            cJSON_AddNumberToObject(dbg_json, "id",  dbg.cmd_id);
+            cJSON_AddNumberToObject(dbg_json, "res", map_debug_state_to_res(dbg.state));
+            cJSON_AddItemToObject(data, "dbg_act", dbg_json);
+            break;
+        }
+        default:
+            break;
+    }
+
+    cJSON_AddNumberToObject(data, "timestamp", (int)time(NULL));
+
+    (void)selftest_result_by_name; /* 保留函数引用,避免未使用警告 */
+    return make_ok_response(cmd, data);
+}
+
+/* =============================================================
+ *  参数查询 / 更新(移液器 4 路配置,读取自 g_dev_info.cfg.yyq_cfg[])
+ * ============================================================= */
+static cJSON *build_param_data(void)
+{
+    cJSON *data = cJSON_CreateObject();
+    cJSON *pips = cJSON_CreateArray();
+    for (int i = 0; i < YYQ_NUM_MAX; i++) {
+        pipette_cfg_t cfg;
+        memset(&cfg, 0, sizeof(cfg));
+        (void)dev_param_get_pipette(i + 1, &cfg); /* pip_id 从 1 开始 */
+        cJSON *p = cJSON_CreateObject();
+        cJSON_AddNumberToObject(p, "x1", cfg.x1);
+        cJSON_AddNumberToObject(p, "y1", cfg.y1);
+        cJSON_AddNumberToObject(p, "z1", cfg.z1);
+        cJSON_AddNumberToObject(p, "x2", cfg.x2);
+        cJSON_AddNumberToObject(p, "y2", cfg.y2);
+        cJSON_AddNumberToObject(p, "z2", cfg.z2);
+        cJSON_AddItemToArray(pips, p);
+    }
+    cJSON_AddItemToObject(data, "pipette", pips);
+    return data;
+}
+
+static char *api_query_params(const char *json_in)
+{
+    (void)json_in;
+    cJSON *data = build_param_data();
+    return make_ok_response("query_params", data);
+}
+
+static char *api_update_params(const char *json_in)
+{
+    cJSON *root = cJSON_Parse(json_in ? json_in : "");
+    if (!root) return make_err_response("update_params", 400, "参数 JSON 解析失败");
+    cJSON *data = cJSON_GetObjectItem(root, "data");
+    int updated = 0;
+    if (data) {
+        cJSON *pips = cJSON_GetObjectItem(data, "pipette");
+        if (pips && cJSON_IsArray(pips)) {
+            int n = cJSON_GetArraySize(pips);
+            for (int i = 0; i < n && i < YYQ_NUM_MAX; i++) {
+                cJSON *p = cJSON_GetArrayItem(pips, i);
+                if (!p) continue;
+                pipette_cfg_t cfg;
+                if (dev_param_get_pipette(i + 1, &cfg) < 0) memset(&cfg, 0, sizeof(cfg));
+                cfg.x1 = cj_int(p, "x1", cfg.x1);
+                cfg.y1 = cj_int(p, "y1", cfg.y1);
+                cfg.z1 = cj_int(p, "z1", cfg.z1);
+                cfg.x2 = cj_int(p, "x2", cfg.x2);
+                cfg.y2 = cj_int(p, "y2", cfg.y2);
+                cfg.z2 = cj_int(p, "z2", cfg.z2);
+                (void)dev_param_set_pipette(i + 1, &cfg);
+            }
+            updated = 1;
+        }
+    }
+    cJSON_Delete(root);
+    if (!updated) return make_err_response("update_params", 400, "缺少 pipette 参数");
+    return make_ok_response("update_params", NULL);
+}
+
+/* =============================================================
+ *  user_cmd / cmd 指令分发 (与 dbus.md 3.3 命令定义一致)
+ * ============================================================= */
+
+/* 对外全局声明 —— 这些函数应由主控状态机模块实现,此处做弱引用占位 */
+__attribute__((weak)) int ad_cmd_start_test(void)      { return 501; }
+__attribute__((weak)) int ad_cmd_pause_test(void)      { return 501; }
+__attribute__((weak)) int ad_cmd_resume_test(void)     { return 501; }
+__attribute__((weak)) int ad_cmd_stop_test(void)       { return 501; }
+__attribute__((weak)) int ad_cmd_enter_debug(void)         { return 501; }
+__attribute__((weak)) int ad_cmd_exit_debug(void)          { return 501; }
+__attribute__((weak)) int ad_cmd_debug_action(int act_id)  { (void)act_id; return 501; }
+__attribute__((weak)) int ad_cmd_fault_reset(void)         { return 501; }
+__attribute__((weak)) int ad_cmd_exit_selftest_failed(void){ return 501; }
+__attribute__((weak)) int ad_change_mode(int mode)            { return 501;}
+
+/* 状态机合法性校验(与 dbus.md 第 7 节一致) */
+static gboolean cmd_is_allowed( dev_state_t st, const char *cmd)
+{
+    if (!cmd) return FALSE;
+    if (g_strcmp0(cmd, "query_state") == 0) return TRUE;
+
+    switch (st) {
+    case DEV_INIT: /* init */
+    case DEV_SELFTESTING: /* selftest */
+        return FALSE;
+    case DEV_SELFTEST_FAILED: /* selftest_failed */
+        return (g_strcmp0(cmd, "exit_selftest_failed") == 0);
+    case DEV_READY: /* ready */
+        return  (g_strcmp0(cmd, "change_mode") == 0 ||
+                g_strcmp0(cmd, "start_test") == 0 ||
+                g_strcmp0(cmd, "enter_debug")    == 0);
+    case DEV_TESTING: /* test */
+        return (g_strcmp0(cmd, "pause_test") == 0 ||
+                g_strcmp0(cmd, "stop_test")  == 0);
+    case DEV_TEST_PAUSED: /* test_pause */
+        return (g_strcmp0(cmd, "resume_test") == 0 ||
+                g_strcmp0(cmd, "stop_test")   == 0);
+    case DEV_TEST_ERROR: /* test_fault */
+        return (g_strcmp0(cmd, "fault_reset") == 0);
+    case DEV_MANUAL_DEBUG: /* debug */
+        return (g_strcmp0(cmd, "debug_action") == 0 ||
+                g_strcmp0(cmd, "exit_debug")   == 0);
+    default:
+        return FALSE;
+    }
+}
+
+static char *api_user_cmd(const char *json_in)
+{
+    cJSON *root = cJSON_Parse(json_in ? json_in : "");
+    if (!root) return make_err_response("execute_action", 400, "JSON 解析失败");
+    char resp_cmd[64];
+    const char * cmd = cj_str(root, "cmd", "");
+    if (!cmd || !*cmd) {
+        cJSON_Delete(root);
+        return make_err_response("execute_action", 400, "缺少 cmd 字段");
+    }
+
+    strcpy( resp_cmd, cmd );
+
+    /* 1) 状态合法性 */
+    dev_state_t curr = dev_get_state();
+
+    if (!cmd_is_allowed( curr, cmd)) {
+        cJSON_Delete(root);
+        return make_err_response(resp_cmd, 405, "当前状态不允许此操作: %s", get_devstate_name(curr));
+    }
+
+    /* 2) 分发执行 */
+    int rc = 501;
+    if (g_strcmp0(cmd, CMD_TEST_START ) == 0) {
+        rc = ad_cmd_start_test();
+    } else if (g_strcmp0(cmd, CMD_TEST_PAUSE ) == 0) {
+        rc = ad_cmd_pause_test();
+    } else if (g_strcmp0(cmd, CMD_TEST_START ) == 0) {
+        rc = ad_cmd_resume_test();
+    } else if (g_strcmp0(cmd, CMD_TEST_STOP ) == 0) {
+        rc = ad_cmd_stop_test();
+    } else if (g_strcmp0(cmd, CMD_DEBUG ) == 0) {
+        cJSON *data = cJSON_GetObjectItem(root, "data");
+        int act_id = cj_int(data, "action", 0);
+        if (act_id <= 0) {
+            cJSON_Delete(root);
+            return make_err_response(resp_cmd, 400, "调试动作 action 无效");
+        }
+        rc = ad_cmd_debug_action(act_id);
+    } else if (g_strcmp0(cmd, "fault_reset") == 0) {
+        rc = ad_cmd_fault_reset();
+    } else if (g_strcmp0(cmd, "exit_selftest_failed") == 0) {
+        rc = ad_cmd_exit_selftest_failed();
+    } else if (g_strcmp0(cmd, "change_mode") == 0) {
+        int mode = cj_int(root, "data", 99);
+        printf( "-----Change mode %d\n", mode );
+        rc = ad_change_mode( mode );
+        if( mode == 0 ){
+            dev_set_state(DEV_INIT);
+            rc = 0;
+        }
+    } else {
+        cJSON_Delete(root);
+        return make_err_response(resp_cmd, 404, "未知命令: %s", cmd);
+    }
+
+    cJSON_Delete(root);
+
+    if (rc == 0)   return make_ok_response(resp_cmd, NULL);
+    if (rc == 501) return make_err_response(resp_cmd, 501, "功能未实现");
+    if (rc == 405) return make_err_response(resp_cmd, 405, "当前状态不允许该操作");
+    return make_err_response(resp_cmd, rc, "操作失败(%d)", rc);
+}
+
+/* =============================================================
+ *  DBus method 统一入口
+ * ============================================================= */
+static void handle_method_call(GDBusConnection *conn,
+                               const gchar *sender,
+                               const gchar *object_path,
+                               const gchar *interface_name,
+                               const gchar *method_name,
+                               GVariant *parameters,
+                               GDBusMethodInvocation *invocation,
+                               gpointer user_data)
+{
+    (void)sender;(void)object_path;(void)interface_name;(void)user_data;(void)conn;
+
+    gchar *json_in = NULL;
+    g_variant_get(parameters, "(s)", &json_in);
+    g_print("[Srv-GDBus] recv method[%s] json: %s\n", method_name, json_in ? json_in : "(null)");
+
+    char *json_out = NULL;
+    api_handler_t handler = NULL;
+
+    if (g_strcmp0(method_name, API_QUERY_STATE) == 0) {
+        handler = api_query_state;
+    } else if (g_strcmp0(method_name, API_QUERY_PARAMS) == 0) {
+        handler = api_query_params;
+    } else if (g_strcmp0(method_name, API_UPDATE_PARAMS) == 0) {
+        handler = api_update_params;
+    } else if (g_strcmp0(method_name, API_USER_CMD ) == 0) {
+        handler = api_user_cmd;
+    } else {
+        g_printerr("[Srv-GDBus] method %s not found\n", method_name);
+    }
+
+    if (handler) {
+        json_out = handler(json_in ? json_in : "{}");
+    }
+    if (!json_out) {
+        json_out = make_err_response(method_name, 500, "内部错误");
+    }
+
+    GVariant *reply = g_variant_new("(s)", json_out);
+printf( "----------reply, json_out: %s\n", json_out );
+    g_dbus_method_invocation_return_value(invocation, reply);
+    g_free(json_out);
+    g_free(json_in);
+}
+
+/* =============================================================
+ *  DBus XML 接口描述(按实际对外 method 对齐)
+ * ============================================================= */
+static const gchar *introspect_xml =
+"<node>"
+"  <interface name='com.yn.ui.interface'>"
+"    <method name='query_state'>"
+"      <arg type='s' name='json_in'  direction='in'/>"
+"      <arg type='s' name='json_out' direction='out'/>"
+"    </method>"
+"    <method name='query_parameters'>"
+"      <arg type='s' name='json_in'  direction='in'/>"
+"      <arg type='s' name='json_out' direction='out'/>"
+"    </method>"
+"    <method name='update_parameters'>"
+"      <arg type='s' name='json_in'  direction='in'/>"
+"      <arg type='s' name='json_out' direction='out'/>"
+"    </method>"
+"    <method name='user_cmd'>"
+"      <arg type='s' name='json_in'  direction='in'/>"
+"      <arg type='s' name='json_out' direction='out'/>"
+"    </method>"
+"    <signal name='EventNotify'>"
+"      <arg type='s' name='json_payload'/>"
+"    </signal>"
+"  </interface>"
+"</node>";
+
+/* =============================================================
+ *  单测 main(可独立编译调试)
+ * ============================================================= */
+__attribute__((unused))
+static int test_main_unused(int argc, char **argv)
+{
+    (void)argc; (void)argv;
+    GMainLoop *loop;
+    GDBusConnection *conn = NULL;
+    GError *err = NULL;
+    guint obj_reg_id, name_owner_id;
+
+    g_introspect_info = g_dbus_node_info_new_for_xml(introspect_xml, &err);
+    if (err) {
+        g_printerr("parse xml fail: %s\n", err->message);
+        g_error_free(err);
+        return -1;
+    }
+    conn = g_bus_get_sync(G_BUS_TYPE_SYSTEM, NULL, &err);
+    if (err) {
+        g_printerr("connect system bus fail: %s\n", err->message);
+        g_error_free(err);
+        return -1;
+    }
+    obj_reg_id = g_dbus_connection_register_object(conn,
+        OBJECT_PATH,
+        g_introspect_info->interfaces[0],
+        &(GDBusInterfaceVTable){.method_call = handle_method_call},
+        NULL, NULL, &err);
+    if (err) {
+        g_printerr("register object fail %s\n", err->message);
+        g_error_free(err);
+        return -1;
+    }
+    name_owner_id = g_bus_own_name(G_BUS_TYPE_SYSTEM,
+        SERVICE_NAME, G_BUS_NAME_OWNER_FLAGS_NONE,
+        NULL, NULL, NULL, NULL, NULL);
+
+    g_print("[Srv-GDBus] service ready\n");
+    loop = g_main_loop_new(NULL, FALSE);
+    g_main_loop_run(loop);
+
+    g_main_loop_unref(loop);
+    g_bus_unown_name(name_owner_id);
+    g_dbus_connection_unregister_object(conn, obj_reg_id);
+    g_dbus_node_info_unref(g_introspect_info);
+    g_object_unref(conn);
+    return 0;
+}
+
+/* =============================================================
+ *  线程化 GDBus 服务接口(对外公共 API)
+ * ============================================================= */
+#include <pthread.h>
+#include <unistd.h>
+
+static GMainLoop       *g_srv_loop    = NULL;
+static GMainContext    *g_srv_ctx     = NULL;
+static GDBusConnection *g_srv_conn    = NULL;
+static guint            g_srv_obj_id  = 0;
+static guint            g_srv_name_id = 0;
+static pthread_t        g_srv_tid     = 0;
+static volatile gint    g_srv_ready   = 0;
+static volatile gint    g_srv_name_fail = 0;
+
+typedef struct {
+    gchar *json;
+} emit_task_t;
+
+static gboolean _emit_signal_idle(gpointer user_data)
+{
+    emit_task_t *task = (emit_task_t *)user_data;
+    if (task && task->json && g_srv_conn) {
+        g_dbus_connection_emit_signal(g_srv_conn,
+                                      NULL,
+                                      OBJECT_PATH,
+                                      INTERFACE_NAME,
+                                      "EventNotify",
+                                      g_variant_new("(s)", task->json),
+                                      NULL);
+        g_print("[Srv-GDBus] emit signal: %s\n", task->json);
+    }
+    if (task) {
+        g_free(task->json);
+        g_free(task);
+    }
+    return G_SOURCE_REMOVE;
+}
+
+static void _on_name_acquired(GDBusConnection *conn, const gchar *name, gpointer user_data)
+{
+    (void)conn; (void)user_data;
+    g_print("[Srv-GDBus] ===== SUCCESS: DBus name '%s' acquired on bus =====\n", name);
+    g_atomic_int_set(&g_srv_ready, 1);
+}
+
+static void _on_name_lost(GDBusConnection *conn, const gchar *name, gpointer user_data)
+{
+    (void)conn; (void)user_data;
+    if (g_atomic_int_get(&g_srv_ready)) {
+        g_printerr("[Srv-GDBus] WARNING: DBus name '%s' LOST (was acquired before)\n", name);
+    } else {
+        g_printerr("[Srv-GDBus] ===== ERROR: FAILED to acquire DBus name '%s' on SYSTEM bus =====\n", name);
+        g_printerr("[Srv-GDBus] 常见原因 (按优先级):\n");
+        g_printerr("[Srv-GDBus]   1) 缺少权限配置: /etc/dbus-1/system.d/com.yn.ui.conf 不存在或内容错误\n");
+        g_printerr("[Srv-GDBus]   2) dbus-daemon未启动: ls /var/run/dbus/system_bus_socket 看文件是否存在\n");
+        g_printerr("[Srv-GDBus]   3) 名字已被其他进程占用: 用 lsof / fuser 或 dbus-send 检查\n");
+        g_printerr("[Srv-GDBus]   4) 当前进程用户非root且policy中未授权own该名字\n");
+    }
+    g_atomic_int_set(&g_srv_ready, 0);
+    g_atomic_int_set(&g_srv_name_fail, 1);
+    if (g_srv_loop && g_main_loop_is_running(g_srv_loop))
+        g_main_loop_quit(g_srv_loop);
+}
+
+static void *_ui_srv_thread(void *arg)
+{
+    (void)arg;
+    GError *err = NULL;
+    g_atomic_int_set(&g_srv_ready, 0);
+    g_atomic_int_set(&g_srv_name_fail, 0);
+
+    g_srv_ctx  = g_main_context_new();
+    g_main_context_push_thread_default(g_srv_ctx);
+    g_srv_loop = g_main_loop_new(g_srv_ctx, FALSE);
+
+    if (g_introspect_info == NULL) {
+        g_introspect_info = g_dbus_node_info_new_for_xml(introspect_xml, &err);
+        if (err) {
+            g_printerr("[Srv-GDBus] parse xml fail: %s\n", err->message);
+            g_error_free(err);
+            goto fail;
+        }
+    }
+
+    g_print("[Srv-GDBus] connecting to SYSTEM bus (/var/run/dbus/system_bus_socket)\n");
+
+    g_srv_conn = g_bus_get_sync(G_BUS_TYPE_SYSTEM, NULL, &err);
+    if (err) {
+        g_printerr("[Srv-GDBus] connect SYSTEM bus fail: %s\n", err->message);
+        g_printerr("[Srv-GDBus]   检查: systemctl status dbus  或  ls /var/run/dbus/system_bus_socket\n");
+        g_printerr("[Srv-GDBus]   检查: /etc/dbus-1/system.d/com.yn.ui.conf 权限配置是否存在\n");
+        g_error_free(err);
+        goto fail;
+    }
+
+    gchar *guid = g_dbus_connection_get_guid(g_srv_conn);
+    gchar *peer_name = g_dbus_connection_get_unique_name(g_srv_conn);
+    g_print("[Srv-GDBus] connected, unique_name=%s, guid=%s\n",
+            peer_name ? peer_name : "(null)", guid ? guid : "(null)");
+    g_free(guid); g_free(peer_name);
+
+    g_srv_obj_id = g_dbus_connection_register_object(g_srv_conn,
+        OBJECT_PATH,
+        g_introspect_info->interfaces[0],
+        &(GDBusInterfaceVTable){.method_call = handle_method_call},
+        NULL, NULL, &err);
+    if (err) {
+        g_printerr("[Srv-GDBus] register object fail: %s\n", err->message);
+        g_error_free(err);
+        goto fail;
+    }
+    g_print("[Srv-GDBus] object registered at %s\n", OBJECT_PATH);
+
+    g_atomic_int_set(&g_srv_name_fail, 0);
+    g_print("[Srv-GDBus] requesting name '%s' on bus (up to 3s)...\n", SERVICE_NAME);
+    g_srv_name_id = g_bus_own_name_on_connection(g_srv_conn,
+        SERVICE_NAME,
+        G_BUS_NAME_OWNER_FLAGS_NONE,
+        _on_name_acquired,
+        _on_name_lost,
+        NULL, NULL);
+
+    /* wait for async name acquire result before entering loop */
+    int i;
+    for (i = 0; i < 300; ++i) {
+        if (g_atomic_int_get(&g_srv_ready))     break;  /* 成功拿到名字 */
+        if (g_atomic_int_get(&g_srv_name_fail)) break;  /* 明确失败回调触发 */
+        /* 同时派发言线程私有context和全局default context
+         * g_bus_get_sync返回的如果是已缓存的connection,其回调可能绑定在default context上 */
+        while (g_main_context_iteration(g_srv_ctx, FALSE)) {}
+        while (g_main_context_iteration(NULL, FALSE)) {}
+        usleep(10000);
+    }
+
+    if (!g_atomic_int_get(&g_srv_ready)) {
+        if (g_atomic_int_get(&g_srv_name_fail)) {
+            g_printerr("[Srv-GDBus] name acquire FAILED (see error lines above), aborting\n");
+        } else {
+            g_printerr("[Srv-GDBus] name acquire TIMEOUT (waited %dms, no callback fired), aborting\n", i * 10);
+        }
+        goto fail;
+    }
+
+    g_print("[Srv-GDBus] service ready, thread enter main loop\n");
+
+    g_main_loop_run(g_srv_loop);
+
+    g_bus_unown_name(g_srv_name_id);
+    g_srv_name_id = 0;
+    if (g_srv_obj_id) {
+        g_dbus_connection_unregister_object(g_srv_conn, g_srv_obj_id);
+        g_srv_obj_id = 0;
+    }
+    if (g_srv_conn) {
+        g_object_unref(g_srv_conn);
+        g_srv_conn = NULL;
+    }
+    if (g_introspect_info) {
+        g_dbus_node_info_unref(g_introspect_info);
+        g_introspect_info = NULL;
+    }
+    if (g_srv_loop) {
+        g_main_loop_unref(g_srv_loop);
+        g_srv_loop = NULL;
+    }
+    if (g_srv_ctx) {
+        g_main_context_pop_thread_default(g_srv_ctx);
+        g_main_context_unref(g_srv_ctx);
+        g_srv_ctx = NULL;
+    }
+    g_atomic_int_set(&g_srv_ready, 0);
+    g_print("[Srv-GDBus] service thread exit cleanly\n");
+    return NULL;
+
+fail:
+    if (g_srv_loop) { g_main_loop_unref(g_srv_loop); g_srv_loop = NULL; }
+    if (g_srv_ctx)  {
+        g_main_context_pop_thread_default(g_srv_ctx);
+        g_main_context_unref(g_srv_ctx);
+        g_srv_ctx = NULL;
+    }
+    g_atomic_int_set(&g_srv_ready, 0);
+    return NULL;
+}
+
+int ui_srv_start(void)
+{
+    if (g_atomic_int_get(&g_srv_ready) || g_srv_tid != 0) {
+        g_print("[Srv-GDBus] service already running\n");
+        return 0;
+    }
+    int rc = pthread_create(&g_srv_tid, NULL, _ui_srv_thread, NULL);
+    if (rc != 0) {
+        g_printerr("[Srv-GDBus] pthread_create fail: %d\n", rc);
+        g_srv_tid = 0;
+        return -1;
+    }
+    for (int i = 0; i < 200; ++i) {
+        if (g_atomic_int_get(&g_srv_ready)) break;
+        usleep(10000);
+    }
+    if (!g_atomic_int_get(&g_srv_ready)) {
+        g_printerr("[Srv-GDBus] wait service ready timeout\n");
+        return -1;
+    }
+    return 0;
+}
+
+int ui_srv_stop(void)
+{
+    if (g_srv_loop && g_main_loop_is_running(g_srv_loop)) {
+        g_main_loop_quit(g_srv_loop);
+    }
+    if (g_srv_tid != 0) {
+        pthread_join(g_srv_tid, NULL);
+        g_srv_tid = 0;
+    }
+    return 0;
+}
+
+int ui_srv_send_event(const gchar *json_payload)
+{
+    if (!g_atomic_int_get(&g_srv_ready) || !g_srv_ctx || !g_srv_conn) {
+        g_printerr("[Srv-GDBus] service not ready, skip send\n");
+        return -1;
+    }
+    if (json_payload == NULL) return -1;
+
+    emit_task_t *task = g_new0(emit_task_t, 1);
+    task->json = g_strdup(json_payload);
+
+    GSource *src = g_idle_source_new();
+    g_source_set_callback(src, _emit_signal_idle, task, NULL);
+    g_source_attach(src, g_srv_ctx);
+    g_source_unref(src);
+
+    return 0;
+}
\ No newline at end of file
diff --git a/fs_overlay/app/agridetect_ui b/fs_overlay/app/agridetect_ui
new file mode 100755 (executable)
index 0000000..c818bc6
Binary files /dev/null and b/fs_overlay/app/agridetect_ui differ