diff --git a/.gitignore b/.gitignore
index fb83704..17de692 100644
--- a/.gitignore
+++ b/.gitignore
@@ -21,9 +21,14 @@ obj/
*.workspace
# -----------------------------------------------------------------------------
-# 链接 / 编译中间产物(cpu/br28/tools 下生成)
-# 注意:不要用 cpu/*/tools/*.bin —— 根目录 aac.bin/ota.bin 等是 SDK 要入库的
+# 链接 / 编译中间产物(每次 make / CodeBlocks 编译都会再生成)
+# 注意:不要用 cpu/*/tools/*.bin —— ota.bin、eq_cfg_hw_less.bin 等是 SDK 要入库的
# -----------------------------------------------------------------------------
+cpu/*/sdk.ld
+cpu/*/sdk_used_list.used
+cpu/*/tools/download.bat
+cpu/*/tools/download.sh
+cpu/*/tools/isd_config.ini
cpu/*/tools/sdk.elf
cpu/*/tools/sdk.elf.*
cpu/*/tools/sdk.map
@@ -32,6 +37,10 @@ cpu/*/tools/app.bin
cpu/*/tools/data_code.bin
cpu/*/tools/p11_code.bin
cpu/*/tools/*.bc
+cpu/*/tools/aac.bin
+cpu/*/tools/aec.bin
+cpu/*/tools/aptx.bin
+cpu/*/tools/eq_cfg_hw.bin
# 打包下载目录:每次烧录会拷贝固件、改写 .bat(可能注入 -key),不要入库
cpu/*/tools/download/**/*.bin
diff --git a/AC701N.cbp b/AC701N.cbp
index f2b466b..f570e7a 100644
--- a/AC701N.cbp
+++ b/AC701N.cbp
@@ -258,7 +258,6 @@
-
@@ -790,6 +789,24 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/JBao_JL7016_SOC_SDK_README.md b/JBao_JL7016_SOC_SDK_README.md
index f7d5594..de49de3 100644
--- a/JBao_JL7016_SOC_SDK_README.md
+++ b/JBao_JL7016_SOC_SDK_README.md
@@ -16,7 +16,7 @@ JBao_JL7016_SOC_SDK_V1.0.1/
│ ├── earphone/ # 耳机应用
│ ├── usr_jb_proto/ # 应用协议层
│ ├── usr_periph/ # 板级外设(RTC 等,源码开放)
-│ └── usr_le_code/ # BLE 协议库(库文件 + 公开头文件)
+│ └── usr_le_code/ # BLE 协议层(源码直编:协议编解码 + 广播/收发 + mjson)
├── cpu/ # 芯片相关代码与工具
├── include_lib/ # SDK 头文件
├── tools/ # 工程工具
@@ -29,7 +29,10 @@ JBao_JL7016_SOC_SDK_V1.0.1/
**apps/usr_le_code**
-- 静态库:`apps/usr_le_code/lib/`
+- 源码直编(已弃用预编译静态库 `libusr_le_code.a`),源文件随主工程一起编译:
+ - `apps/usr_le_code/ble_proto.c` / `bleproto.c` / `bleproto_packer.c`
+ - `apps/usr_le_code/usr_le_adv.c` / `usr_le_recieve.c`
+ - `apps/usr_le_code/thirdpart/mjson/mjson.c`
- 公开头文件:
- `apps/usr_le_code/usr_le_api.h`
- `apps/usr_le_code/usr_le_product.h`
diff --git a/Makefile b/Makefile
index c4761fe..f1fecac 100644
--- a/Makefile
+++ b/Makefile
@@ -621,10 +621,12 @@ c_SRC_FILES := \
apps/usr_jb_proto/Utils/jb_ringbuffer.c \
apps/usr_jb_proto/usr_jb_main.c \
apps/usr_periph/usr_rtc.c \
-
-
-# usr_le_code 预编译静态库(Release 不附带协议源码,禁止本地重建)
-USR_LE_LIB := apps/usr_le_code/lib/libusr_le_code.a
+ apps/usr_le_code/ble_proto.c \
+ apps/usr_le_code/bleproto.c \
+ apps/usr_le_code/bleproto_packer.c \
+ apps/usr_le_code/thirdpart/mjson/mjson.c \
+ apps/usr_le_code/usr_le_adv.c \
+ apps/usr_le_code/usr_le_recieve.c \
@@ -729,7 +731,6 @@ LFLAGS := \
cpu/br28/liba/libllns.a \
cpu/br28/liba/libkwscommon.a \
apps/common/third_party_profile/tuya_protocol/sdk/lib/libtuya_lib.a \
- apps/usr_le_code/lib/libusr_le_code.a \
cpu/br28/liba/lib_icsd_adt.a \
cpu/br28/liba/lib_diafx.a \
cpu/br28/liba/libFFT_pi32v2_OnChip.a \
@@ -794,7 +795,7 @@ LINK_AT ?= 1
# see: https://www.gnu.org/software/make/manual/html_node/Suffix-Rules.html
.SUFFIXES:
-all: pre_build $(USR_LE_LIB) $(OUT_ELF)
+all: pre_build $(OUT_ELF)
$(info +POST-BUILD)
$(QUITE) $(RUN_POST_SCRIPT) sdk
@@ -814,13 +815,13 @@ clean:
ifeq ($(LINK_AT), 1)
-$(OUT_ELF): $(OBJS) $(USR_LE_LIB)
+$(OUT_ELF): $(OBJS)
$(info +LINK $@)
$(shell $(MKDIR) $(@D))
$(file >$(OBJ_FILE), $(OBJS))
$(QUITE) $(LD) -o $(OUT_ELF) @$(OBJ_FILE) $(LFLAGS) $(LIBPATHS) $(LIBS)
else
-$(OUT_ELF): $(OBJS) $(USR_LE_LIB)
+$(OUT_ELF): $(OBJS)
$(info +LINK $@)
$(shell $(MKDIR) $(@D))
$(QUITE) $(LD) -o $(OUT_ELF) $(OBJS) $(LFLAGS) $(LIBPATHS) $(LIBS)
diff --git a/apps/usr_le_code/ble_proto.c b/apps/usr_le_code/ble_proto.c
new file mode 100644
index 0000000..e5b71cd
--- /dev/null
+++ b/apps/usr_le_code/ble_proto.c
@@ -0,0 +1,245 @@
+/**
+ * @file ble_proto.c
+ * @brief BLE-网关通信协议 V1.3 序列化 / 反序列化实现
+ *
+ * 结构:
+ * [Cmd:2][Reserved:4][gateway_int_cnt:1][gateway_int32[]:4*N]
+ * [device_int_len:2][device_str_len:2][device_bytes_len:2]
+ * [Payload][CRC16:2]
+ *
+ * CRC 计算范围:Cmd ~ Payload 末尾(整个包除 CRC 字段)
+ */
+
+#include "ble_proto.h"
+#include
+
+/* -----------------------------------------------------------------------
+ * 内部辅助:Big Endian 读写
+ * --------------------------------------------------------------------- */
+
+/** 写入 uint16_t(Big Endian) */
+static inline void put_be16(uint8_t *p, uint16_t v)
+{
+ p[0] = (uint8_t)(v >> 8);
+ p[1] = (uint8_t)(v & 0xFFu);
+}
+
+/** 写入 uint32_t(Big Endian) */
+static inline void put_be32(uint8_t *p, uint32_t v)
+{
+ p[0] = (uint8_t)(v >> 24);
+ p[1] = (uint8_t)((v >> 16) & 0xFFu);
+ p[2] = (uint8_t)((v >> 8) & 0xFFu);
+ p[3] = (uint8_t)( v & 0xFFu);
+}
+
+/** 读取 uint16_t(Big Endian) */
+static inline uint16_t get_be16(const uint8_t *p)
+{
+ return (uint16_t)(((uint16_t)p[0] << 8) | p[1]);
+}
+
+/** 读取 uint32_t(Big Endian) */
+static inline uint32_t get_be32(const uint8_t *p)
+{
+ return ((uint32_t)p[0] << 24)
+ | ((uint32_t)p[1] << 16)
+ | ((uint32_t)p[2] << 8)
+ | (uint32_t)p[3];
+}
+
+/* -----------------------------------------------------------------------
+ * CRC16(多项式 0x8005,初值 0xFFFF —— MODBUS 变体)
+ * --------------------------------------------------------------------- */
+uint16_t ble_proto_crc16(const uint8_t *data, size_t len)
+{
+ uint16_t crc = 0xFFFFu;
+ for (size_t i = 0; i < len; i++) {
+ crc ^= (uint16_t)data[i];
+ for (int bit = 0; bit < 8; bit++) {
+ if (crc & 0x0001u) {
+ crc = (crc >> 1) ^ 0xA001u;
+ } else {
+ crc >>= 1;
+ }
+ }
+ }
+ return crc;
+}
+
+/* -----------------------------------------------------------------------
+ * 序列化(pack)
+ * --------------------------------------------------------------------- */
+int ble_proto_pack(const ble_proto_packet_t *pkt, uint8_t *buf, size_t buf_size)
+{
+ if (!pkt || !buf) return BLE_PROTO_ERR_NULL;
+
+ /* ----- 参数合法性检查 ----- */
+ if (pkt->gateway_int_cnt > BLE_PROTO_GW_INT_MAX) return BLE_PROTO_ERR_GW_CNT;
+ if (pkt->device_int_len % 4 != 0) return BLE_PROTO_ERR_INT_ALIGN;
+
+ /* ----- 计算所需总长度 ----- */
+ size_t payload_len = (size_t)pkt->device_int_len
+ + (size_t)pkt->device_str_len
+ + (size_t)pkt->device_bytes_len;
+
+ size_t total = BLE_PROTO_HEADER_LEN /* Cmd(2) + Reserved(4) */
+ + BLE_PROTO_GW_CNT_LEN /* gateway_int_cnt (1) */
+ + (size_t)pkt->gateway_int_cnt * 4u /* gateway_int[] */
+ + BLE_PROTO_DEV_PARAM_LEN /* 3 x device_*_len */
+ + payload_len /* Payload */
+ + BLE_PROTO_CRC_LEN; /* CRC16 */
+
+ if (buf_size < total) return BLE_PROTO_ERR_BUF_SMALL;
+
+ uint8_t *p = buf;
+
+ /* ----- Protocol Header ----- */
+ put_be16(p, pkt->cmd); p += 2;
+ put_be32(p, 0); p += 4; /* Reserved 固定填 0 */
+
+ /* ----- Gateway Parameter ----- */
+ *p++ = pkt->gateway_int_cnt; /* uint8 */
+ for (uint8_t i = 0; i < pkt->gateway_int_cnt; i++) {
+ put_be32(p, (uint32_t)pkt->gateway_int[i]);
+ p += 4;
+ }
+
+ /* ----- Device Parameter ----- */
+ put_be16(p, pkt->device_int_len); p += 2;
+ put_be16(p, pkt->device_str_len); p += 2;
+ put_be16(p, pkt->device_bytes_len); p += 2;
+
+ /* ----- Payload ----- */
+ if (pkt->device_int_len > 0 && pkt->int_data) {
+ for (uint16_t i = 0; i < pkt->device_int_len / 4u; i++) {
+ put_be32(p, (uint32_t)pkt->int_data[i]);
+ p += 4;
+ }
+ }
+ if (pkt->device_str_len > 0 && pkt->str_data) {
+ memcpy(p, pkt->str_data, pkt->device_str_len);
+ p += pkt->device_str_len;
+ }
+ if (pkt->device_bytes_len > 0 && pkt->bytes_data) {
+ memcpy(p, pkt->bytes_data, pkt->device_bytes_len);
+ p += pkt->device_bytes_len;
+ }
+
+ /* ----- CRC16(从 buf[0] 开始,到 Payload 末尾) ----- */
+ uint16_t crc = ble_proto_crc16(buf, (size_t)(p - buf));
+ put_be16(p, crc);
+ p += 2;
+
+
+ return (int)(p - buf);
+}
+
+/* -----------------------------------------------------------------------
+ * 反序列化(unpack)
+ * --------------------------------------------------------------------- */
+int ble_proto_unpack(const uint8_t *buf, size_t len, ble_proto_packet_t *pkt)
+{
+ if (!buf || !pkt) return BLE_PROTO_ERR_NULL;
+
+ /* 最小包长:Header(6) + gw_cnt(1) + dev_param(6) + CRC(2) = 15 */
+ const size_t min_len = BLE_PROTO_HEADER_LEN
+ + BLE_PROTO_GW_CNT_LEN
+ + BLE_PROTO_DEV_PARAM_LEN
+ + BLE_PROTO_CRC_LEN;
+ if (len < min_len) return BLE_PROTO_ERR_LEN;
+
+ const uint8_t *p = buf;
+
+ /* ----- Protocol Header ----- */
+ pkt->cmd = get_be16(p); p += 2;
+ pkt->reserved = get_be32(p); p += 4;
+
+ /* ----- Gateway Parameter ----- */
+ pkt->gateway_int_cnt = *p++;
+ if (pkt->gateway_int_cnt > BLE_PROTO_GW_INT_MAX) return BLE_PROTO_ERR_GW_CNT;
+
+ /* 检查剩余字节是否足够容纳 gateway_int[] + dev_param + CRC */
+ size_t consumed = (size_t)(p - buf)
+ + (size_t)pkt->gateway_int_cnt * 4u
+ + BLE_PROTO_DEV_PARAM_LEN
+ + BLE_PROTO_CRC_LEN;
+ if (len < consumed) return BLE_PROTO_ERR_LEN;
+
+ for (uint8_t i = 0; i < pkt->gateway_int_cnt; i++) {
+ pkt->gateway_int[i] = (int32_t)get_be32(p);
+ p += 4;
+ }
+
+ /* ----- Device Parameter ----- */
+ pkt->device_int_len = get_be16(p); p += 2;
+ pkt->device_str_len = get_be16(p); p += 2;
+ pkt->device_bytes_len = get_be16(p); p += 2;
+
+ if (pkt->device_int_len % 4 != 0) return BLE_PROTO_ERR_INT_ALIGN;
+
+ size_t payload_len = (size_t)pkt->device_int_len
+ + (size_t)pkt->device_str_len
+ + (size_t)pkt->device_bytes_len;
+
+ /* 验证总长度(含 CRC) */
+ if ((size_t)(p - buf) + payload_len + BLE_PROTO_CRC_LEN != len) {
+ return BLE_PROTO_ERR_LEN;
+ }
+
+ /* ----- CRC16 校验(从 buf[0] 到 CRC 前一字节) ----- */
+ uint16_t crc_calc = ble_proto_crc16(buf, len - BLE_PROTO_CRC_LEN);
+ uint16_t crc_recv = get_be16(buf + len - BLE_PROTO_CRC_LEN);
+ if (crc_calc != crc_recv) return BLE_PROTO_ERR_CRC;
+
+ /* ----- Payload(零拷贝,直接指向 buf 内部) ----- */
+ if (pkt->device_int_len > 0) {
+ pkt->int_data = (const int32_t *)p;
+ } else {
+ pkt->int_data = NULL;
+ }
+ p += pkt->device_int_len;
+
+ pkt->str_data = (pkt->device_str_len > 0) ? (const char *)p : NULL;
+ p += pkt->device_str_len;
+
+ pkt->bytes_data = (pkt->device_bytes_len > 0) ? p : NULL;
+
+ // printf("cmd = %d", pkt->cmd);
+ // printf("reserved = %d", pkt->reserved);
+ // printf("gateway_int_cnt = %d", pkt->gateway_int_cnt);
+ // printf("device_int_len = %d", pkt->device_int_len);
+ // printf("device_str_len = %d", pkt->device_str_len);
+ // printf("device_bytes_len = %d", pkt->device_bytes_len);
+
+ // /* int_data 指向 buf 内部,地址未必 4 字节对齐,
+ // * 不能直接解引用 int32_t*(对齐访问会触发硬件异常);
+ // * 必须按字节读取,用 get_be32 还原数值 */
+ // if (pkt->int_data && pkt->device_int_len >= 4) {
+ // const uint8_t *ip = (const uint8_t *)pkt->int_data;
+ // printf("int_data = ");
+ // for (uint16_t i = 0; i < pkt->device_int_len / 4u; i++) {
+ // printf("%08X ", (unsigned int)get_be32(ip + (uint32_t)i * 4u));
+ // }
+ // printf("\n");
+ // }
+ // /* str_data / bytes_data 不保证有 '\0',用 printf_buf 打印 hex */
+ // if (pkt->str_data && pkt->device_str_len > 0) {
+ // printf("str_data = ");
+ // for (size_t i = 0; i < pkt->device_str_len; i++) {
+ // printf("%02X ", *(pkt->str_data + i));
+ // }
+ // printf("\n");
+ // }
+ // if (pkt->bytes_data && pkt->device_bytes_len > 0) {
+ // printf("bytes_data = ");
+ // for (size_t i = 0; i < pkt->device_bytes_len; i++) {
+ // printf("%02X ", *(pkt->bytes_data + i));
+ // }
+ // printf("\n");
+ // }
+ // printf("crc = %04X", crc_recv);
+ // printf("\n");
+
+ return BLE_PROTO_OK;
+}
diff --git a/apps/usr_le_code/ble_proto.h b/apps/usr_le_code/ble_proto.h
new file mode 100644
index 0000000..7ac15d7
--- /dev/null
+++ b/apps/usr_le_code/ble_proto.h
@@ -0,0 +1,133 @@
+/**
+ * @file ble_proto.h
+ * @brief BLE-网关通信协议 V1.3 序列化 / 反序列化接口
+ *
+ * 数据包结构(Big Endian):
+ * [Cmd:2][Reserved:4]
+ * [gateway_int_cnt:1][gateway_int32[]:4*N]
+ * [device_int_len:2][device_str_len:2][device_bytes_len:2]
+ * [Payload: int_data | str_data | bytes_data]
+ * [CRC16:2]
+ *
+ * 当前协议头(固定 6 字节):[Cmd:2][Reserved:4]
+ * (说明:本文件早期 V1.2 草案曾在 Cmd 后加入 8 字节时间戳 t,
+ * 现设备侧不再使用,已从线格式中彻底移除。)
+ *
+ * V1.1 变更(相对 V1.0):
+ * - 删除 Magic、Version、Seq 字段
+ * - 新增 Reserved(uint32,固定填 0)
+ * - Cmd 移至偏移 0
+ * - gateway_int_cnt 由 uint16 调整为 uint8
+ * - CRC 计算范围:Cmd ~ Payload 末尾(整个包除 CRC 字段本身)
+ */
+
+#ifndef BLE_PROTO_H
+#define BLE_PROTO_H
+
+#include
+#include
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/* -----------------------------------------------------------------------
+ * 协议常量
+ * --------------------------------------------------------------------- */
+
+/** Header 固定长度:Cmd(2) + Reserved(4) = 6 Bytes */
+#define BLE_PROTO_HEADER_LEN 6u
+
+/** gateway_int_cnt 字段长度(uint8) */
+#define BLE_PROTO_GW_CNT_LEN 1u
+
+/** Device Parameter 固定长度:3 x uint16 = 6 Bytes */
+#define BLE_PROTO_DEV_PARAM_LEN 6u
+
+/** CRC16 字段长度 */
+#define BLE_PROTO_CRC_LEN 2u
+
+/** 最大 Gateway int32 参数个数(防御性上限,可按需修改) */
+#define BLE_PROTO_GW_INT_MAX 16u
+
+/** 最大 Payload 总长度(按实际业务调整) */
+#define BLE_PROTO_PAYLOAD_MAX 2048u
+
+/* -----------------------------------------------------------------------
+ * 报文数据包(解包后的逻辑结构)
+ * --------------------------------------------------------------------- */
+typedef struct {
+ /* ----- Protocol Header ----- */
+ uint16_t cmd; /**< 协议命令(上报、控制、应答、OTA等) */
+ uint32_t reserved; /**< 保留字段,发送端固定填 0 */
+
+ /* ----- Gateway Parameter ----- */
+ uint8_t gateway_int_cnt; /**< Gateway int32 参数个数 */
+ int32_t gateway_int[BLE_PROTO_GW_INT_MAX]; /**< Gateway int32 参数列表 */
+
+ /* ----- Device Parameter ----- */
+ uint16_t device_int_len; /**< Payload 中 int 数据字节数(必须是 4 的整数倍) */
+ uint16_t device_str_len; /**< Payload 中 string 数据字节数(不含 '\0') */
+ uint16_t device_bytes_len; /**< Payload 中 bytes 数据字节数 */
+
+ /* ----- Payload 数据指针(指向外部 buffer,不拥有所有权) ----- */
+ const int32_t *int_data; /**< Device Int 数据(pack 输入为主机序 int32 数组,ble_proto_pack 内部逐元素 put_be32 转 BE;unpack 输出为 buf 内原始 BE 字节,调用方须用 get_be32 读取,不可直接解引用) */
+ const char *str_data; /**< Device String 数据(不含 '\0') */
+ const uint8_t *bytes_data; /**< Device Bytes 数据 */
+} ble_proto_packet_t;
+
+/* -----------------------------------------------------------------------
+ * 错误码
+ * --------------------------------------------------------------------- */
+typedef enum {
+ BLE_PROTO_OK = 0,
+ BLE_PROTO_ERR_NULL = -1, /**< 空指针 */
+ BLE_PROTO_ERR_BUF_SMALL = -2, /**< 输出缓冲区不足 */
+ BLE_PROTO_ERR_CRC = -3, /**< CRC16 校验失败 */
+ BLE_PROTO_ERR_LEN = -4, /**< 长度字段非法 / 包长不足 */
+ BLE_PROTO_ERR_GW_CNT = -5, /**< gateway_int_cnt 超出上限 */
+ BLE_PROTO_ERR_INT_ALIGN = -6, /**< device_int_len 非 4 倍数 */
+} ble_proto_err_t;
+
+/* -----------------------------------------------------------------------
+ * 接口
+ * --------------------------------------------------------------------- */
+
+/**
+ * @brief 序列化:将逻辑数据包打包成字节流
+ *
+ * @param[in] pkt 逻辑数据包(reserved 字段被忽略,固定填 0)
+ * @param[out] buf 输出缓冲区
+ * @param[in] buf_size 缓冲区大小(字节)
+ * @return 打包后实际字节数(>0),或 ble_proto_err_t 负值
+ */
+int ble_proto_pack(const ble_proto_packet_t *pkt, uint8_t *buf, size_t buf_size);
+
+/**
+ * @brief 反序列化:将字节流解析为逻辑数据包
+ *
+ * @note pkt->int_data / str_data / bytes_data 指向 buf 内部,不复制数据。
+ * buf 的生命周期必须长于 pkt 的使用期。
+ * @note pkt->reserved 的值被读出但不做校验,接收端可直接忽略。
+ *
+ * @param[in] buf 输入字节流
+ * @param[in] len 字节流长度
+ * @param[out] pkt 解析结果
+ * @return BLE_PROTO_OK,或 ble_proto_err_t 负值
+ */
+int ble_proto_unpack(const uint8_t *buf, size_t len, ble_proto_packet_t *pkt);
+
+/**
+ * @brief 计算 CRC16(MODBUS 变体,多项式 0x8005,初值 0xFFFF)
+ *
+ * @param[in] data 数据起始地址
+ * @param[in] len 数据字节数
+ * @return CRC16 值
+ */
+uint16_t ble_proto_crc16(const uint8_t *data, size_t len);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* BLE_PROTO_H */
diff --git a/apps/usr_le_code/bleproto.c b/apps/usr_le_code/bleproto.c
new file mode 100644
index 0000000..89992ad
--- /dev/null
+++ b/apps/usr_le_code/bleproto.c
@@ -0,0 +1,529 @@
+/****************************************************************************/
+/* bleproto.c
+ *
+ * Copyright (C) 2024 四川迈科创智科技有限公司
+ *
+ ****************************************************************************/
+
+/****************************************************************************/
+/* Included Files */
+/****************************************************************************/
+
+#include "bleproto.h"
+
+/****************************************************************************/
+/* Trace Definitions */
+/****************************************************************************/
+
+/****************************************************************************/
+/* Pre-processor Definitions */
+/****************************************************************************/
+
+/****************************************************************************/
+/* Private Types */
+/****************************************************************************/
+
+/****************************************************************************/
+/* Private Function Prototypes */
+/****************************************************************************/
+
+/****************************************************************************/
+/* Private Data */
+/****************************************************************************/
+
+/****************************************************************************/
+/* Public Data */
+/****************************************************************************/
+
+/****************************************************************************/
+/* Private Functions */
+/****************************************************************************/
+
+/****************************************************************************/
+/* Public Functions */
+/****************************************************************************/
+
+const char *libbleproto_version(void)
+{
+ return BLEPROTO_API_VERSION;
+}
+
+uint8_t bleproto_advdata_encode4bind(
+ uint8_t data[31],
+ int8_t txpower,
+ uint8_t manucode[BLEPROTO_ADV_TLV_LENGTH_MANUCODE],
+ uint8_t pcode[BLE_PROTO_ADV_LENGTH_PCODE],
+ uint8_t prodcode[BLEPROTO_ADV_TLV_LENGTH_PRODCODE])
+{
+ bleproto_adv_t adv = {0};
+ /* adv1 */
+ {
+ adv.adv1.length = 0x02;
+ adv.adv1.ad_type = BLEPROTO_ADV_TYPE_FLAGS;
+ adv.adv1.ad_data = 0x06;
+ }
+ /* adv2 */
+ // clang-format off
+ {
+ adv.adv2.length = 0x1B;
+ adv.adv2.ad_type = BLEPROTO_ADV_TYPE_SVC_DATA_UUID16;
+
+
+ adv.adv2.ad_data.service_data.uuid = BLEPROTO_ADV_SERVICE_UUID_TOBIND;
+ /* spec_data */
+ bleproto_adv_specdata_t *spec_data =
+ &adv.adv2.ad_data.service_data.spec_data;
+
+ spec_data->version = BLEPORTO_ADV_SERVICE_SPEC_DATA_VER;
+ spec_data->business = BELPROTO_ADV_SERVICE_SPEC_DATA_BUSINESS_NEARFIND;
+ spec_data->rfu[0] = 0;
+ spec_data->rfu[1] = 0;
+ spec_data->txpower = txpower;
+
+ spec_data->manucode.type = BLEPROTO_ADV_TLV_TYPE_MANUCODE;
+ spec_data->manucode.length = BLEPROTO_ADV_TLV_LENGTH_MANUCODE;
+ memcpy(spec_data->manucode.value, manucode, BLEPROTO_ADV_TLV_LENGTH_MANUCODE);
+
+ spec_data->prodcode.type = BLEPROTO_ADV_TLV_TYPE_PRODCODE;
+ spec_data->prodcode.length = BLEPROTO_ADV_TLV_LENGTH_PRODCODE;
+ memcpy(spec_data->prodcode.value, prodcode, BLEPROTO_ADV_TLV_LENGTH_PRODCODE);
+
+ spec_data->separator = 0xFF;
+
+ memcpy(spec_data->selfdata, pcode, BLE_PROTO_ADV_LENGTH_PCODE);
+ // spec_data->selfdata[0] = 0X30;
+ // spec_data->selfdata[1] = 0X30;
+ // spec_data->selfdata[2] = 0X30;
+ // spec_data->selfdata[3] = 0X30;
+ // spec_data->selfdata[4] = 0X30;
+ // spec_data->selfdata[5] = 0X30;
+ }
+ // clang-format on
+
+ return bleproto_advdata_serialize(&adv, data, 31);
+}
+
+void bleproto_advdata_encode4heartbeat(
+ uint8_t data[31],
+ int8_t txpower,
+ uint8_t gwmac[6],
+ uint8_t manucode[BLEPROTO_ADV_TLV_LENGTH_MANUCODE],
+ uint8_t pcode[BLE_PROTO_ADV_LENGTH_PCODE],
+ uint8_t prodcode[BLEPROTO_ADV_TLV_LENGTH_PRODCODE])
+{
+ bleproto_adv_t adv = {0};
+ /* adv1 */
+ {
+ adv.adv1.length = 0x02;
+ adv.adv1.ad_type = BLEPROTO_ADV_TYPE_FLAGS;
+ adv.adv1.ad_data = 0x06;
+ }
+ /* adv2 */
+ // clang-format off
+ {
+ adv.adv2.length = 0x1B;
+ adv.adv2.ad_type = BLEPROTO_ADV_TYPE_MFG_DATA;
+ /* mfg_data */
+ bleproto_advdata_mfg_t *mfg_data = &adv.adv2.ad_data.mfg_data;
+
+ memcpy(mfg_data->siot, pcode, BLE_PROTO_ADV_LENGTH_PCODE);
+ #if 0
+ mfg_data->siot[0] = 'S';
+ mfg_data->siot[1] = 'I';
+ mfg_data->siot[2] = 'O';
+ mfg_data->siot[3] = 'T';
+ mfg_data->siot[4] = '-';
+ mfg_data->siot[5] = '1';
+ #endif
+
+ /* HEARTBEAT */
+ mfg_data->flag = BLEPROTO_ADV_FLAG_HEARTBEAT;
+
+ mfg_data->txpower = txpower;
+ memcpy(mfg_data->gwmac, gwmac, 6);
+
+ mfg_data->manucode.type = BLEPROTO_ADV_TLV_TYPE_MANUCODE;
+ mfg_data->manucode.length = BLEPROTO_ADV_TLV_LENGTH_MANUCODE;
+ memcpy(mfg_data->manucode.value, manucode, BLEPROTO_ADV_TLV_LENGTH_MANUCODE);
+
+ mfg_data->prodcode.type = BLEPROTO_ADV_TLV_TYPE_PRODCODE;
+ mfg_data->prodcode.length = BLEPROTO_ADV_TLV_LENGTH_PRODCODE;
+ memcpy(mfg_data->prodcode.value, prodcode, BLEPROTO_ADV_TLV_LENGTH_PRODCODE);
+ }
+ // clang-format on
+
+ (void)bleproto_advdata_serialize(&adv, data, 31);
+}
+
+uint8_t bleproto_advdata_encode4reconn(
+ uint8_t data[31],
+ int8_t txpower,
+ uint8_t gwmac[6],
+ uint8_t manucode[BLEPROTO_ADV_TLV_LENGTH_MANUCODE],
+ uint8_t pcode[BLE_PROTO_ADV_LENGTH_PCODE],
+ uint8_t prodcode[BLEPROTO_ADV_TLV_LENGTH_PRODCODE])
+{
+ bleproto_adv_t adv = {0};
+ /* adv1 */
+ {
+ adv.adv1.length = 0x02;
+ adv.adv1.ad_type = BLEPROTO_ADV_TYPE_FLAGS;
+ adv.adv1.ad_data = 0x06;
+ }
+ /* adv2 */
+ // clang-format off
+ {
+ adv.adv2.length = 0x1B;
+ adv.adv2.ad_type = BLEPROTO_ADV_TYPE_MFG_DATA;
+ /* mfg_data */
+ bleproto_advdata_mfg_t *mfg_data = &adv.adv2.ad_data.mfg_data;
+
+ memcpy(mfg_data->siot, pcode, BLE_PROTO_ADV_LENGTH_PCODE);
+ #if 0
+ mfg_data->siot[0] = 'S';
+ mfg_data->siot[1] = 'I';
+ mfg_data->siot[2] = 'O';
+ mfg_data->siot[3] = 'T';
+ mfg_data->siot[4] = '-';
+ mfg_data->siot[5] = '1';
+ #endif
+
+ /* RECONNECT */
+ mfg_data->flag = BLEPROTO_ADV_FLAG_RECONNECT;
+
+ mfg_data->txpower = txpower;
+ memcpy(mfg_data->gwmac, gwmac, 6);
+
+ mfg_data->manucode.type = BLEPROTO_ADV_TLV_TYPE_MANUCODE;
+ mfg_data->manucode.length = BLEPROTO_ADV_TLV_LENGTH_MANUCODE;
+ memcpy(mfg_data->manucode.value, manucode, BLEPROTO_ADV_TLV_LENGTH_MANUCODE);
+
+ mfg_data->prodcode.type = BLEPROTO_ADV_TLV_TYPE_PRODCODE;
+ mfg_data->prodcode.length = BLEPROTO_ADV_TLV_LENGTH_PRODCODE;
+ memcpy(mfg_data->prodcode.value, prodcode, BLEPROTO_ADV_TLV_LENGTH_PRODCODE);
+ }
+ // clang-format on
+
+ return bleproto_advdata_serialize(&adv, data, 31);
+}
+
+int bleproto_advdata_decode(const uint8_t *data,
+ uint8_t len,
+ bleproto_adv_t *adv)
+{
+ return bleproto_advdata_deserialize(data, len, adv);
+}
+
+int bleproto_appdata_encode(uint8_t *txbuf,
+ uint16_t size,
+ uint8_t packetlen,
+ bleproto_appdata_desc_t *desc)
+{
+ int rc;
+ uint16_t txbuf_size = size;
+
+ /*
+ * appdata.data[] 在 SMALL 模式下约 2.3KB,供 JSON/OTA 编码中间缓冲。
+ * JB 55AA 透传可走 bleproto_appdata_wrap_raw,不必经本函数。
+ * 此处用 static,避免在调用方任务栈上临时分配。
+ */
+ static bleproto_appdata_t s_enc_appdata;
+ bleproto_appdata_t *appdata = &s_enc_appdata;
+
+ /* header */
+ {
+ appdata->header = desc->header;
+ }
+ /* data */
+ if (appdata->header.msgtype == BLEPROTO_APPDATA_MSGTYPE_REQ)
+ {
+ switch (appdata->header.serviceid)
+ {
+ case E_BLEPROTO_SERVICE_ID_DEVICEINFO:
+ rc = bleproto_encjson_deviceinfo_req(&desc->datast.deviceinfo_req,
+ appdata->data);
+ break;
+ case E_BLEPROTO_SERVICE_ID_AUTHSETUP:
+ rc = bleproto_encjson_authsetup_req(&desc->datast.authsetup_req,
+ appdata->data);
+ break;
+ case E_BLEPROTO_SERVICE_ID_AUTHDELETE:
+ rc = bleproto_encjson_authdelete_req(&desc->datast.authdelete_req,
+ appdata->data);
+ break;
+ case E_BLEPROTO_SERVICE_ID_RUNCMD:
+ rc = bleproto_encjson_runcmd_req(&desc->datast.runcmd_req,
+ appdata->data);
+ break;
+ case E_BLEPROTO_SERVICE_ID_REPORTCMD:
+ rc = bleproto_encjson_reportcmd_req(&desc->datast.reportcmd_req,
+ appdata->data);
+ break;
+ case E_BLEPROTO_SERVICE_ID_DOACTION:
+ rc = bleproto_encjson_doaction_req(&desc->datast.doaction_req,
+ appdata->data);
+ break;
+ case E_BLEPROTO_SERVICE_ID_OTANOTIFY:
+ rc = bleproto_encjson_otanotify_req(&desc->datast.otanotify_req,
+ appdata->data);
+ break;
+ case E_BLEPROTO_SERVICE_ID_OTADATA:
+ rc = bleproto_encjson_otadata_req(&desc->datast.otadata_req,
+ appdata->data);
+ break;
+ case E_BLEPROTO_SERVICE_ID_RUNCMD_V2:
+ rc = ble_proto_pack(&desc->datast.runcmd_v2_req, appdata->data, sizeof(appdata->data));
+ break;
+ case E_BLEPROTO_SERVICE_ID_REPORTCMD_V2:
+ rc = ble_proto_pack(&desc->datast.reportcmd_v2_req, appdata->data, sizeof(appdata->data));
+ break;
+ case E_BLEPROTO_SERVICE_ID_OTADATA_V2:
+ rc = ble_proto_pack(&desc->datast.otadata_v2_req, appdata->data, sizeof(appdata->data));
+ break;
+ default:
+ /* unkown serviceid */
+ return (-1);
+ }
+ }
+ else if (appdata->header.msgtype == BLEPROTO_APPDATA_MSGTYPE_RSP)
+ {
+ switch (appdata->header.serviceid)
+ {
+ case E_BLEPROTO_SERVICE_ID_DEVICEINFO:
+ rc = bleproto_encjson_deviceinfo_rsp(&desc->datast.deviceinfo_rsp,
+ appdata->data);
+ break;
+ case E_BLEPROTO_SERVICE_ID_AUTHSETUP:
+ rc = bleproto_encjson_authsetup_rsp(&desc->datast.authsetup_rsp,
+ appdata->data);
+ break;
+ case E_BLEPROTO_SERVICE_ID_AUTHDELETE:
+ rc = bleproto_encjson_authdelete_rsp(&desc->datast.authdelete_rsp,
+ appdata->data);
+ break;
+ case E_BLEPROTO_SERVICE_ID_RUNCMD:
+ rc = bleproto_encjson_runcmd_rsp(&desc->datast.runcmd_rsp,
+ appdata->data);
+ break;
+ case E_BLEPROTO_SERVICE_ID_REPORTCMD:
+ rc = bleproto_encjson_reportcmd_rsp(&desc->datast.reportcmd_rsp,
+ appdata->data);
+ break;
+ case E_BLEPROTO_SERVICE_ID_DOACTION:
+ rc = bleproto_encjson_doaction_rsp(&desc->datast.doaction_rsp,
+ appdata->data);
+ break;
+ case E_BLEPROTO_SERVICE_ID_OTANOTIFY:
+ rc = bleproto_encjson_otanotify_rsp(&desc->datast.otanotify_rsp,
+ appdata->data);
+ break;
+ case E_BLEPROTO_SERVICE_ID_OTADATA:
+ rc = bleproto_encbin_otadata_rsp(&desc->datast.otadata_rsp,
+ appdata->data);
+ break;
+ case E_BLEPROTO_SERVICE_ID_RUNCMD_V2:
+ rc = ble_proto_pack(&desc->datast.runcmd_v2_rsp, appdata->data, sizeof(appdata->data));
+ break;
+ case E_BLEPROTO_SERVICE_ID_REPORTCMD_V2:
+ rc = ble_proto_pack(&desc->datast.reportcmd_v2_rsp, appdata->data, sizeof(appdata->data));
+ break;
+ case E_BLEPROTO_SERVICE_ID_OTADATA_V2:
+ rc = ble_proto_pack(&desc->datast.otadata_v2_rsp, appdata->data, sizeof(appdata->data));
+ break;
+ default:
+ /* unkown serviceid */
+ return (-1);
+ }
+ }
+ else
+ {
+ /* unkown msgtype */
+ return (-1);
+ }
+ /* failed to encjson struct */
+ if (rc <= 0)
+ {
+ return (-1);
+ }
+
+ /* datalen */
+ appdata->header.datalen = (uint16_t)rc;
+
+ /* appdata_serialize */
+ return bleproto_appdata_serialize(appdata, packetlen, txbuf, txbuf_size);
+}
+
+int bleproto_appdata_decode(uint8_t *rxbuf,
+ uint16_t len,
+ bleproto_appdata_desc_t *desc)
+{
+ int rc, rlen;
+
+ /*
+ * V2(ble_proto_unpack) 零拷贝:bytes_data 等指向 appdata.data。
+ * 若用栈局部变量,函数返回后指针悬空,usr_run_cmd_code_v2 会踩坏数据。
+ * 使用 static,保证 desc 内指针在下次 decode 前有效。
+ */
+ static bleproto_appdata_t s_appdata;
+ bleproto_appdata_t *appdata = &s_appdata;
+
+ /* appdata_deserialize */
+ rlen = bleproto_appdata_deserialize(rxbuf, len, appdata);
+ if (rlen <= 0)
+ {
+ return (rlen);
+ }
+
+ /* header */
+ {
+ desc->header = appdata->header;
+ }
+ /* data */
+ if (appdata->header.msgtype == BLEPROTO_APPDATA_MSGTYPE_REQ)
+ {
+ switch (appdata->header.serviceid)
+ {
+ case E_BLEPROTO_SERVICE_ID_DEVICEINFO:
+ rc = bleproto_decjson_deviceinfo_req(appdata->data,
+ appdata->header.datalen,
+ &desc->datast.deviceinfo_req);
+ break;
+ case E_BLEPROTO_SERVICE_ID_AUTHSETUP:
+ rc = bleproto_decjson_authsetup_req(appdata->data,
+ appdata->header.datalen,
+ &desc->datast.authsetup_req);
+ break;
+ case E_BLEPROTO_SERVICE_ID_AUTHDELETE:
+ rc = bleproto_decjson_authdelete_req(appdata->data,
+ appdata->header.datalen,
+ &desc->datast.authdelete_req);
+ break;
+ case E_BLEPROTO_SERVICE_ID_RUNCMD:
+ rc = bleproto_decjson_runcmd_req(appdata->data,
+ appdata->header.datalen,
+ &desc->datast.runcmd_req);
+ break;
+ case E_BLEPROTO_SERVICE_ID_REPORTCMD:
+ rc = bleproto_decjson_reportcmd_req(appdata->data,
+ appdata->header.datalen,
+ &desc->datast.reportcmd_req);
+ break;
+ case E_BLEPROTO_SERVICE_ID_DOACTION:
+ rc = bleproto_decjson_doaction_req(appdata->data,
+ appdata->header.datalen,
+ &desc->datast.doaction_req);
+ break;
+ case E_BLEPROTO_SERVICE_ID_OTANOTIFY:
+ rc = bleproto_decjson_otanotify_req(appdata->data,
+ appdata->header.datalen,
+ &desc->datast.otanotify_req);
+ break;
+ case E_BLEPROTO_SERVICE_ID_OTADATA:
+ rc = bleproto_decjson_otadata_req(appdata->data,
+ appdata->header.datalen,
+ &desc->datast.otadata_req);
+ break;
+ case E_BLEPROTO_SERVICE_ID_RUNCMD_V2:
+ printf("runcmd_v2_req \n");
+ rc = ble_proto_unpack(appdata->data, appdata->header.datalen, &desc->datast.runcmd_v2_req);
+ printf("runcmd_v2_req rc = %d \n", rc);
+ break;
+ case E_BLEPROTO_SERVICE_ID_REPORTCMD_V2:
+ printf("reportcmd_v2_req \n");
+ rc = ble_proto_unpack(appdata->data, appdata->header.datalen, &desc->datast.reportcmd_v2_req);
+ printf("reportcmd_v2_req rc = %d \n", rc);
+ break;
+ case E_BLEPROTO_SERVICE_ID_OTADATA_V2:
+ printf("otadata_v2_req \n");
+ rc = ble_proto_unpack(appdata->data, appdata->header.datalen, &desc->datast.otadata_v2_req);
+ printf("otadata_v2_req rc = %d \n", rc);
+ break;
+ default:
+ /* unkown serviceid */
+ return (-1);
+ }
+ }
+ else if (appdata->header.msgtype == BLEPROTO_APPDATA_MSGTYPE_RSP)
+ {
+ switch (appdata->header.serviceid)
+ {
+ case E_BLEPROTO_SERVICE_ID_DEVICEINFO:
+ rc =
+ bleproto_decjson_deviceinfo_rsp(appdata->data,
+ appdata->header.datalen,
+ &desc->datast.deviceinfo_rsp);
+ break;
+ case E_BLEPROTO_SERVICE_ID_AUTHSETUP:
+ rc = bleproto_decjson_authsetup_rsp(appdata->data,
+ appdata->header.datalen,
+ &desc->datast.authsetup_rsp);
+ break;
+ case E_BLEPROTO_SERVICE_ID_AUTHDELETE:
+ rc =
+ bleproto_decjson_authdelete_rsp(appdata->data,
+ appdata->header.datalen,
+ &desc->datast.authdelete_rsp);
+ break;
+ case E_BLEPROTO_SERVICE_ID_RUNCMD:
+ rc = bleproto_decjson_runcmd_rsp(appdata->data,
+ appdata->header.datalen,
+ &desc->datast.runcmd_rsp);
+ break;
+ case E_BLEPROTO_SERVICE_ID_REPORTCMD:
+ rc = bleproto_decjson_reportcmd_rsp(appdata->data,
+ appdata->header.datalen,
+ &desc->datast.reportcmd_rsp);
+ break;
+ case E_BLEPROTO_SERVICE_ID_DOACTION:
+ rc = bleproto_decjson_doaction_rsp(appdata->data,
+ appdata->header.datalen,
+ &desc->datast.doaction_rsp);
+ break;
+ case E_BLEPROTO_SERVICE_ID_OTANOTIFY:
+ rc = bleproto_decjson_otanotify_rsp(appdata->data,
+ appdata->header.datalen,
+ &desc->datast.otanotify_rsp);
+ break;
+ case E_BLEPROTO_SERVICE_ID_OTADATA:
+ rc = bleproto_debin_otadata_rsp(appdata->data,
+ appdata->header.datalen,
+ &desc->datast.otadata_rsp);
+ break;
+ case E_BLEPROTO_SERVICE_ID_RUNCMD_V2:
+ printf("runcmd_v2_rsp \n");
+ rc = ble_proto_unpack(appdata->data, appdata->header.datalen, &desc->datast.runcmd_v2_rsp);
+ printf("runcmd_v2_rsp rc = %d \n", rc);
+ break;
+ case E_BLEPROTO_SERVICE_ID_REPORTCMD_V2:
+ printf("reportcmd_v2_rsp \n");
+ rc = ble_proto_unpack(appdata->data, appdata->header.datalen, &desc->datast.reportcmd_v2_rsp);
+ printf("reportcmd_v2_rsp rc = %d \n", rc);
+ break;
+ case E_BLEPROTO_SERVICE_ID_OTADATA_V2:
+ printf("otadata_v2_rsp \n");
+ rc = ble_proto_unpack(appdata->data, appdata->header.datalen, &desc->datast.otadata_v2_rsp);
+ printf("otadata_v2_rsp rc = %d \n", rc);
+ break;
+ default:
+ /* unkown serviceid */
+ return (-1);
+ }
+ }
+ else
+ {
+ /* unkown msgtype */
+ return (-1);
+ }
+ /* failed to decjson struct */
+ if (rc < 0)
+ {
+ return (-1);
+ }
+
+ return (rlen);
+}
+/****************************************************************************/
+/* */
+/* End of file. */
+/* */
+/****************************************************************************/
diff --git a/apps/usr_le_code/bleproto.h b/apps/usr_le_code/bleproto.h
new file mode 100644
index 0000000..b917a12
--- /dev/null
+++ b/apps/usr_le_code/bleproto.h
@@ -0,0 +1,53 @@
+/****************************************************************************/
+/* bleproto.h
+ *
+ * Copyright (C) 2021 四川迈科创智科技有限公司
+ *
+ ****************************************************************************/
+#ifndef BLEPROTO_H_INCLUDE
+#define BLEPROTO_H_INCLUDE
+/****************************************************************************/
+/* Included Files */
+/****************************************************************************/
+
+/* api */
+#include "bleproto_api.h"
+
+/* thirdpart api */
+#include "mjson.h"
+
+/****************************************************************************/
+/* Configure Definitions */
+/****************************************************************************/
+
+/****************************************************************************/
+/* Pre-processor Definitions */
+/****************************************************************************/
+
+/****************************************************************************/
+/* Public Types */
+/****************************************************************************/
+
+/****************************************************************************/
+/* Public Data */
+/****************************************************************************/
+
+/****************************************************************************/
+#ifdef __cplusplus
+extern "C" {
+#endif
+/****************************************************************************/
+/* Public Function Prototypes */
+/****************************************************************************/
+
+/****************************************************************************/
+#ifdef __cplusplus
+}
+#endif
+/****************************************************************************/
+#endif /* BLEPROTO_H_INCLUDE */
+/****************************************************************************/
+/* */
+/* End of file. */
+/* */
+/****************************************************************************/
diff --git a/apps/usr_le_code/bleproto_api.h b/apps/usr_le_code/bleproto_api.h
new file mode 100644
index 0000000..f36f92d
--- /dev/null
+++ b/apps/usr_le_code/bleproto_api.h
@@ -0,0 +1,303 @@
+/****************************************************************************/
+/* bleproto_api.h
+ *
+ * Copyright (C) 2021 四川迈科创智科技有限公司
+ *
+ ****************************************************************************/
+/**
+ * @page bleproto_api_guides API Guides
+ *
+ * @ingroup bleproto_api_guides
+ * @addtogroup bleproto_api bleproto
+ *
+ * wiki
+ * ====
+ * - https://gogos.mkcziot.com:13000/iot-device/cziot-sdk/src/master/doc/wiki/ble/mk蓝牙设备开发指南.md
+ *
+ * @{
+ */
+
+#ifndef BLEPROTO_API_H_INCLUDE
+#define BLEPROTO_API_H_INCLUDE
+/****************************************************************************/
+/* Included Files */
+/****************************************************************************/
+
+/* system */
+//#include
+/*#include
+#include
+#include
+#include */
+
+/* group */
+#include "bleproto_packer.h"
+#include "ble_proto.h"
+/****************************************************************************/
+/* Configure Definitions */
+/****************************************************************************/
+
+/****************************************************************************/
+/* Pre-processor Definitions */
+/****************************************************************************/
+
+/* api version */
+#define BLEPROTO_API_VERSION "1.1.4"
+
+/****************************************************************************/
+/* Public Types */
+/****************************************************************************/
+
+/**
+ * @brief 应用数据描述
+ */
+typedef struct bleproto_appdata_desc {
+ /** 包头 */
+ bleproto_appdata_header_t header;
+ /**
+ * 根据
+ * - header.msgtype:请求(0=req)、响应(1=rsp)
+ * - header.serviceid @ref bleproto_service_id_e
+ * datast取对应的member
+ *
+ * 比如 header.msgtype = 0(请求req), header.serviceid = E_BLEPROTO_SERVICE_ID_DEVICEINFO
+ * datast 对应 deviceinfo_req
+ */
+ union {
+ bleproto_deviceinfo_req_t deviceinfo_req;
+ bleproto_deviceinfo_rsp_t deviceinfo_rsp;
+ bleproto_authsetup_req_t authsetup_req;
+ bleproto_authsetup_rsp_t authsetup_rsp;
+ bleproto_authdelete_req_t authdelete_req;
+ bleproto_authdelete_rsp_t authdelete_rsp;
+ bleproto_runcmd_req_t runcmd_req;
+ bleproto_runcmd_rsp_t runcmd_rsp;
+ bleproto_reportcmd_req_t reportcmd_req;
+ bleproto_reportcmd_rsp_t reportcmd_rsp;
+ bleproto_doaction_req_t doaction_req;
+ bleproto_doaction_rsp_t doaction_rsp;
+ bleproto_otanotify_req_t otanotify_req;
+ bleproto_otanotify_rsp_t otanotify_rsp;
+ bleproto_otadata_req_t otadata_req;
+ bleproto_otadata_rsp_t otadata_rsp;
+
+ ble_proto_packet_t runcmd_v2_req;
+ ble_proto_packet_t runcmd_v2_rsp;
+ ble_proto_packet_t reportcmd_v2_req;
+ ble_proto_packet_t reportcmd_v2_rsp;
+ ble_proto_packet_t otadata_v2_req;
+ ble_proto_packet_t otadata_v2_rsp;
+
+ } datast;
+} bleproto_appdata_desc_t;
+
+/****************************************************************************/
+/* Public Data */
+/****************************************************************************/
+
+/****************************************************************************/
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/****************************************************************************/
+/* Public Function Prototypes */
+/****************************************************************************/
+
+/**
+ * @brief Get library version
+ *
+ * @return The string of library version
+ */
+const char *libbleproto_version(void);
+
+/**
+ * @brief 序列化请求注册绑定广播数据(广播数据长度为31)
+ *
+ * @param[out] data - 序列化数据缓冲区, 固定为31个字节.
+ * @param[in] txpower - 蓝牙发射功率[-127,128]dBm
+ * @param[in] manucode - 厂商编码, 现在固定填0
+ * @param[in] pcode - 平台pcode, 比如pcode为AAABBB
+ * pcode[0] = 'A' = 0x41
+ * pcode[1] = 'A' = 0x41
+ * pcode[2] = 'A' = 0x41
+ * pcode[3] = 'B' = 0x42
+ * pcode[4] = 'B' = 0x42
+ * pcode[5] = 'B' = 0x42
+ * @param[in] prodcode - 产品型号, 比如 宠物喂食器 CBFD,
+ * prodcode[0] = 'C' = 0x43
+ * prodcode[1] = 'B' = 0x42
+ * prodcode[2] = 'F' = 0x46
+ * prodcode[3] = 'D' = 0x44
+ */
+uint8_t bleproto_advdata_encode4bind(
+ uint8_t data[31],
+ int8_t txpower,
+ uint8_t manucode[BLEPROTO_ADV_TLV_LENGTH_MANUCODE],
+ uint8_t pcode[BLE_PROTO_ADV_LENGTH_PCODE],
+ uint8_t prodcode[BLEPROTO_ADV_TLV_LENGTH_PRODCODE]);
+
+/**
+ * @brief 序列化心跳广播数据(广播数据长度为31)
+ *
+ * @param[out] data - 序列化数据缓冲区, 固定为31个字节.
+ * @param[in] txpower - 蓝牙发射功率[-127,128]dBm
+ * @param[in] gwmac - 主控设备mac地址(子设备绑定到主控设备,authStep会下发主控设备的mac地址),
+ * 例如mac地址 "11:22:33:44:55:66"
+ * gwmac[0] = 0x11
+ * gwmac[1] = 0x22
+ * gwmac[2] = 0x33
+ * gwmac[3] = 0x44
+ * gwmac[4] = 0x55
+ * gwmac[5] = 0x66
+ * @param[in] manucode - 厂商编码, 现在固定填0
+ * @param[in] pcode - 平台pcode, 比如pcode为AAABBB
+ * pcode[0] = 'A' = 0x41
+ * pcode[1] = 'A' = 0x41
+ * pcode[2] = 'A' = 0x41
+ * pcode[3] = 'B' = 0x42
+ * pcode[4] = 'B' = 0x42
+ * pcode[5] = 'B' = 0x42
+ * @param[in] prodcode - 产品型号, 比如 宠物喂食器 CBFD,
+ * prodcode[0] = 'C' = 0x43
+ * prodcode[1] = 'B' = 0x42
+ * prodcode[2] = 'F' = 0x46
+ * prodcode[3] = 'D' = 0x44
+ */
+void bleproto_advdata_encode4heartbeat(
+ uint8_t data[31],
+ int8_t txpower,
+ uint8_t gwmac[6],
+ uint8_t manucode[BLEPROTO_ADV_TLV_LENGTH_MANUCODE],
+ uint8_t pcode[BLE_PROTO_ADV_LENGTH_PCODE],
+ uint8_t prodcode[BLEPROTO_ADV_TLV_LENGTH_PRODCODE]);
+
+/**
+ * @brief 序列化回连广播数据(广播数据长度为31)
+ *
+ * @param[out] data - 序列化数据缓冲区, 固定为31个字节.
+ * @param[in] txpower - 蓝牙发射功率[-127,128]dBm
+ * @param[in] gwmac - 主控设备mac地址(子设备绑定到主控设备,authStep会下发主控设备的mac地址),
+ * 例如mac地址 "11:22:33:44:55:66"
+ * gwmac[0] = 0x11
+ * gwmac[1] = 0x22
+ * gwmac[2] = 0x33
+ * gwmac[3] = 0x44
+ * gwmac[4] = 0x55
+ * gwmac[5] = 0x66
+ * @param[in] manucode - 厂商编码, 现在固定填0
+ * @param[in] pcode - 平台pcode, 比如pcode为AAABBB
+ * pcode[0] = 'A' = 0x41
+ * pcode[1] = 'A' = 0x41
+ * pcode[2] = 'A' = 0x41
+ * pcode[3] = 'B' = 0x42
+ * pcode[4] = 'B' = 0x42
+ * pcode[5] = 'B' = 0x42
+ * @param[in] prodcode - 产品型号, 比如 宠物喂食器 CBFD,
+ * prodcode[0] = 'C' = 0x43
+ * prodcode[1] = 'B' = 0x42
+ * prodcode[2] = 'F' = 0x46
+ * prodcode[3] = 'D' = 0x44
+ *
+ * @return 小于0表示失败,大于0表示序列化后的长度(31)
+ */
+uint8_t bleproto_advdata_encode4reconn(
+ uint8_t data[31],
+ int8_t txpower,
+ uint8_t gwmac[6],
+ uint8_t manucode[BLEPROTO_ADV_TLV_LENGTH_MANUCODE],
+ uint8_t pcode[BLE_PROTO_ADV_LENGTH_PCODE],
+ uint8_t prodcode[BLEPROTO_ADV_TLV_LENGTH_PRODCODE]);
+
+/**
+ * @brief 反序列化广播数据(广播数据长度为31)
+ *
+ * @param[in] data - 反序列化数据指针
+ * @param[in] len - 反序列化数据长度
+ * @param[out] adv - 广播数据结构体
+ *
+ * @return 小于0表示失败,大于0表示反序列化使用data的长度.
+ */
+int bleproto_advdata_decode(const uint8_t * data,
+ uint8_t len,
+ bleproto_adv_t *adv);
+
+/**
+ * @brief 序列化应用数据结构体到txbuf
+ *
+ * @note packetlen说明
+ *
+ * ```c
+ * ble4.0 通常协商的mtu=27, packetlen = 27 - 4 - 3 = 20
+ * ble4.2 通常协商的mtu=251, packelen = 251 - 4 - 3 = 244
+ * ble5.0 通常协商的mtu=251, packelen = 251 - 4 - 3 = 244
+ * ```
+ *
+ * 如果报文数据长度超过 BLE GATT单包传输有效长度,需要按照文档方式分包,
+ * +----------------+
+ * | 1 | 第一包按照packetlen填满
+ * +----------------+
+ * | |
+ * | ... | 中间包按照packetlen填满
+ * | |
+ * +----------------+
+ * | N | 最后一包长度 = totallen - (packetlen * (N -1))
+ * +----------------+
+ *
+ * 需要按照每包的顺序发给对端
+ *
+ * @param[out] txbuf - 发送数据缓冲区指针
+ * @param[in] size - 发送数据缓冲器长度
+ * @param[in] packetlen - BLE GATT单包传输有效长度, 查看上面说明
+ * @param[in] desc - 应用数据结构体描述
+ *
+ * @return 小于0表示失败,大于0表示序列化后的长度
+ */
+int bleproto_appdata_encode(uint8_t * txbuf,
+ uint16_t size,
+ uint8_t packetlen,
+ bleproto_appdata_desc_t *desc);
+
+/**
+ * @brief 反序列化rxbuf到应用数据结构体
+ *
+ *
+ * 如果报文数据长度超过 BLE GATT单包传输有效长度,需要按照文档方式分包,
+ * +----------------+
+ * | 1 | 第一包按照packetlen填满
+ * +----------------+
+ * | |
+ * | ... | 中间包按照packetlen填满
+ * | |
+ * +----------------+
+ * | N | 最后一包长度 = totallen - (packetlen * (N -1))
+ * +----------------+
+ *
+ * 因此接收到数据
+ * 1. 函数返回等于0,以为还有分包数据还没有接收完成,
+ * 接收到下包数据 append 在buf尾部,再调用函数的解析数据包
+ * 2. 函数返回大于0,表示收到数据解析了多少字节,需要将头上对应长度数据移除掉
+ * 3. 函数返回小于0,表示收到非法的数据包,无法解析
+ *
+ * @param[in] rxbuf - 接收缓冲区指针
+ * @param[in] len - 接收缓冲区数据长度.
+ * @param[out] desc - 应用数据结构体.
+ *
+ * @return 大于0表示解析成功, 返回当前解析了多少个字节,
+ * 等于0表示解析未完成, 只接受到分包的部分数据, 需要继续接收数据
+ * 小于0表示解析失败
+ */
+int bleproto_appdata_decode(uint8_t* rxbuf,
+ uint16_t len,
+ bleproto_appdata_desc_t *desc);
+/****************************************************************************/
+#ifdef __cplusplus
+}
+#endif
+/****************************************************************************/
+#endif /* BLEPROTO_API_H_INCLUDE */
+/****************************************************************************/
+/* */
+/* End of file. */
+/* */
+/****************************************************************************/
diff --git a/apps/usr_le_code/bleproto_packer.c b/apps/usr_le_code/bleproto_packer.c
new file mode 100644
index 0000000..b1c6159
--- /dev/null
+++ b/apps/usr_le_code/bleproto_packer.c
@@ -0,0 +1,3054 @@
+/****************************************************************************/
+/* bleproto_packer.c
+ *
+ * Copyright (C) 2024 四川迈科创智科技有限公司
+ *
+ ****************************************************************************/
+
+/****************************************************************************/
+/* Included Files */
+/****************************************************************************/
+
+#include "bleproto.h"
+#include "system/includes.h"
+#include "inttypes.h"
+/****************************************************************************/
+/* Trace Definitions */
+/****************************************************************************/
+
+/****************************************************************************/
+/* Pre-processor Definitions */
+/****************************************************************************/
+/**
+ * @def UTILS_BITFIELD_GET
+ * @brief get bitfield value.
+ *
+ * @note MUSTBE `s`<=`e`.
+ *
+ * @param[in] v - The value to get.
+ * @param[in] e - The end-bit number.
+ * @param[in] s - The start-bit number.
+ *
+ * @code
+ * uint8_t ctrl;
+ * - bit7-2: type
+ * - bit1-0: id
+ * type = UTILS_BITFIELD_GET(ctrl, 7, 2);
+ * id = UTILS_BITFIELD_GET(ctrl, 1, 0);
+ * @endcode
+ */
+/**
+ * @def UTILS_BITFIELD_SET
+ * @brief set bitfield value.
+ *
+ * @note MUSTBE `s`<=`e`.
+ *
+ * @param[in] v - The value to set.
+ * @param[in] e - The end-bit number.
+ * @param[in] s - The start-bit number.
+ *
+ * @code
+ * uint8_t ctrl;
+ * - bit7-2: type
+ * - bit1-0: id
+ * ctrl = UTILS_BITFIELD_SET(type, 7, 2) | UTILS_BITFIELD_SET(id, 1, 0);
+ * @endcode
+ */
+/* Helper bitfield encode/decode macros */
+#define UTILS_STATIC_ASSERT_OR_ZERO(cond) (sizeof(char[1 - 2 * !(cond)]) - 1)
+#define UTILS_BITFILED_CHECK(e, s) UTILS_STATIC_ASSERT_OR_ZERO((e) >= (s))
+#define UTILS_BITFIELD_MASK(e, s) \
+ (UTILS_BITFILED_CHECK(e, s) + (((1UL << ((e) - (s) + 1)) - 1UL) << (s)))
+#define UTILS_BITFIELD_GET(v, e, s) \
+ (UTILS_BITFILED_CHECK(e, s) + \
+ (((v) >> (s)) & UTILS_BITFIELD_MASK(((e) - (s)), 0)))
+#define UTILS_BITFIELD_SET(v, e, s) \
+ (UTILS_BITFILED_CHECK(e, s) + \
+ (((v)&UTILS_BITFIELD_MASK(((e) - (s)), 0)) << (s)))
+#define UTILS_BITFIELD_CLR(v, e, s) \
+ (UTILS_BITFILED_CHECK(e, s) + ((v) & (~(UTILS_BITFIELD_MASK(e, s)))))
+#define UTILS_BITFIELD_UPD(oldv, e, s, newv) \
+ (UTILS_BITFILED_CHECK(e, s) + \
+ (UTILS_BITFIELD_CLR(oldv, e, s) | UTILS_BITFIELD_SET(newv, e, s)))
+
+/**
+ * @def UTILS_MIN
+ * @brief Calculates the minimum of x and y.
+ */
+#define UTILS_MIN(x, y) ((x) < (y) ? (x) : (y))
+
+/****************************************************************************/
+/* Private Types */
+/****************************************************************************/
+
+/****************************************************************************/
+/* Private Function Prototypes */
+/****************************************************************************/
+
+/****************************************************************************/
+/* Private Data */
+/****************************************************************************/
+
+/****************************************************************************/
+/* Public Data */
+/****************************************************************************/
+
+/****************************************************************************/
+/* Private Functions */
+/****************************************************************************/
+
+static uint8_t hex_char_to_int(char c)
+{
+ // 将十六进制字符转换为对应的数值
+ if (c >= '0' && c <= '9') {
+ return c - '0';
+ } else if (c >= 'A' && c <= 'F') {
+ return c - 'A' + 10;
+ } else if (c >= 'a' && c <= 'f') {
+ return c - 'a' + 10;
+ }
+ // 非十六进制字符,返回无效值
+ return 0xFF;
+}
+
+/* utils */
+static void proto_bytes_put_le16(uint8_t dst[2], uint16_t val)
+{
+ dst[0] = val;
+ dst[1] = val >> 8;
+}
+
+static uint16_t proto_bytes_get_le16(const uint8_t src[2])
+{
+ return ((uint16_t)src[1] << 8) | src[0];
+}
+
+static int proto_strhex_to_byte(const char *str, uint8_t *bytes, size_t size)
+{
+ // string转bytes
+ if (str == NULL || bytes == NULL) {
+ BLEPROTO_T_E("Invalid parameters");
+ return -1;
+ }
+
+ size_t str_len = strlen(str);
+ if (str_len % 2 != 0 || str_len / 2 > size) {
+ BLEPROTO_T_E("Invalid string length or buffer size");
+ return -1;
+ }
+
+ for (size_t i = 0; i < str_len; i += 2) {
+ uint8_t high = hex_char_to_int(str[i]);
+ uint8_t low = hex_char_to_int(str[i + 1]);
+ if (high == 0xFF || low == 0xFF) {
+ BLEPROTO_T_E("Invalid hex character");
+ return -1;
+ }
+ bytes[i / 2] = (high << 4) | low;
+ }
+
+ return (int)(str_len / 2);
+}
+
+/****************************************************************************/
+/* Public Functions */
+/****************************************************************************/
+
+int bleproto_advdata_serialize(bleproto_adv_t *adv,
+ uint8_t * data,
+ uint8_t size)
+{
+ uint8_t offset = 0;
+
+ /* check params */
+ if (!adv || !data || size < BLEPROTO_ADV_MAX_SZ) {
+ BLEPROTO_T_E("Invalid parameters");
+ return (-1);
+ }
+
+ /* check adv2 type */
+ if (adv->adv2.ad_type != BLEPROTO_ADV_TYPE_SVC_DATA_UUID16 &&
+ adv->adv2.ad_type != BLEPROTO_ADV_TYPE_MFG_DATA) {
+ BLEPROTO_T_E("Invalid adv2.adv_type");
+ return (-1);
+ }
+
+ /* clear */
+ memset(data, 0, size);
+
+ /* adv1 */
+ {
+ /* rewrite member */
+ adv->adv1.length = 0x02;
+ adv->adv1.ad_type = BLEPROTO_ADV_TYPE_FLAGS;
+ adv->adv1.ad_data = 0x06;
+
+ data[offset++] = adv->adv1.length;
+ data[offset++] = adv->adv1.ad_type;
+ data[offset++] = adv->adv1.ad_data;
+ }
+
+ /* adv2 */
+ adv->adv2.length = BLEPROTO_ADV_MAX_SZ - 3 - 1;
+ {
+ /* adv2 length */
+ data[offset++] = adv->adv2.length;
+ /* adv2 type */
+ data[offset++] = adv->adv2.ad_type;
+ }
+ if (adv->adv2.ad_type == BLEPROTO_ADV_TYPE_SVC_DATA_UUID16) {
+ /* uuid, little endian */
+ proto_bytes_put_le16(&data[offset],
+ adv->adv2.ad_data.service_data.uuid);
+ offset += 2;
+ /////////////////////////////////////////
+ // spec_data
+ /////////////////////////////////////////
+ bleproto_adv_specdata_t *spec_data =
+ &adv->adv2.ad_data.service_data.spec_data;
+ /* version */
+ data[offset++] = spec_data->version;
+ /* business */
+ data[offset++] = spec_data->business;
+ /* rfu */
+ data[offset++] = 0;
+ data[offset++] = 0;
+ /* txpower */
+ data[offset++] = (uint8_t)spec_data->txpower;
+ /* manucode */
+ {
+ spec_data->manucode.type = BLEPROTO_ADV_TLV_TYPE_MANUCODE;
+ spec_data->manucode.length = BLEPROTO_ADV_TLV_LENGTH_MANUCODE;
+
+ data[offset++] = spec_data->manucode.type;
+ data[offset++] = spec_data->manucode.length;
+ memcpy(&data[offset],
+ spec_data->manucode.value,
+ BLEPROTO_ADV_TLV_LENGTH_MANUCODE);
+ offset += BLEPROTO_ADV_TLV_LENGTH_MANUCODE;
+ }
+ /* prodcode */
+ {
+ spec_data->prodcode.type = BLEPROTO_ADV_TLV_TYPE_PRODCODE;
+ spec_data->prodcode.length = BLEPROTO_ADV_TLV_LENGTH_PRODCODE;
+
+ data[offset++] = spec_data->prodcode.type;
+ data[offset++] = spec_data->prodcode.length;
+ memcpy(&data[offset],
+ spec_data->prodcode.value,
+ BLEPROTO_ADV_TLV_LENGTH_PRODCODE);
+ offset += BLEPROTO_ADV_TLV_LENGTH_PRODCODE;
+ }
+ /* separator */
+ {
+ spec_data->separator = 0xFF;
+
+ data[offset++] = spec_data->separator;
+ }
+ /* selfdata */
+ {
+ memcpy(&data[offset],
+ spec_data->selfdata,
+ sizeof(spec_data->selfdata));
+ offset += (uint8_t)sizeof(spec_data->selfdata);
+ }
+ } else if (adv->adv2.ad_type == BLEPROTO_ADV_TYPE_MFG_DATA) {
+ bleproto_advdata_mfg_t *mfg_data = &adv->adv2.ad_data.mfg_data;
+ /* siot */
+ data[offset++] = mfg_data->siot[0];
+ data[offset++] = mfg_data->siot[1];
+ data[offset++] = mfg_data->siot[2];
+ data[offset++] = mfg_data->siot[3];
+ data[offset++] = mfg_data->siot[4];
+ data[offset++] = mfg_data->siot[5];
+ /* flag */
+ data[offset++] = mfg_data->flag;
+ /* txpower */
+ data[offset++] = (uint8_t)mfg_data->txpower;
+ /* gwmac */
+ data[offset++] = mfg_data->gwmac[0];
+ data[offset++] = mfg_data->gwmac[1];
+ data[offset++] = mfg_data->gwmac[2];
+ data[offset++] = mfg_data->gwmac[3];
+ data[offset++] = mfg_data->gwmac[4];
+ data[offset++] = mfg_data->gwmac[5];
+ /* manucode */
+ {
+ mfg_data->manucode.type = BLEPROTO_ADV_TLV_TYPE_MANUCODE;
+ mfg_data->manucode.length = BLEPROTO_ADV_TLV_LENGTH_MANUCODE;
+
+ data[offset++] = mfg_data->manucode.type;
+ data[offset++] = mfg_data->manucode.length;
+ memcpy(&data[offset],
+ mfg_data->manucode.value,
+ BLEPROTO_ADV_TLV_LENGTH_MANUCODE);
+ offset += BLEPROTO_ADV_TLV_LENGTH_MANUCODE;
+ }
+ /* prodcode */
+ {
+ mfg_data->prodcode.type = BLEPROTO_ADV_TLV_TYPE_PRODCODE;
+ mfg_data->prodcode.length = BLEPROTO_ADV_TLV_LENGTH_PRODCODE;
+
+ data[offset++] = mfg_data->prodcode.type;
+ data[offset++] = mfg_data->prodcode.length;
+ memcpy(&data[offset],
+ mfg_data->prodcode.value,
+ BLEPROTO_ADV_TLV_LENGTH_PRODCODE);
+ offset += BLEPROTO_ADV_TLV_LENGTH_PRODCODE;
+ }
+ }
+
+ return (offset);
+}
+
+int bleproto_advdata_deserialize(const uint8_t * data,
+ uint8_t len,
+ bleproto_adv_t *adv)
+{
+ int rc;
+ uint8_t offset = 0;
+
+ /* check parameters */
+ if (!data || !adv) {
+ BLEPROTO_T_E("Invalid parameters");
+ return (-1);
+ }
+
+ /* check len */
+ if (len != BLEPROTO_ADV_MAX_SZ) {
+ BLEPROTO_T_E("Invalid len");
+ return (-1);
+ }
+
+ do {
+ /* clear */
+ memset(adv, 0, sizeof(*adv));
+
+ /* adv1 */
+ adv->adv1.length = data[offset++];
+ adv->adv1.ad_type = data[offset++];
+ adv->adv1.ad_data = data[offset++];
+ if (adv->adv1.length != 0x02 ||
+ adv->adv1.ad_type != BLEPROTO_ADV_TYPE_FLAGS ||
+ adv->adv1.ad_data != 0x06) {
+ BLEPROTO_T_E("Invalid adv1 data");
+ rc = -1;
+ break;
+ }
+
+ adv->adv2.length = data[offset++];
+ adv->adv2.ad_type = data[offset++];
+ if (adv->adv2.length != BLEPROTO_ADV_MAX_SZ - 3 - 1) {
+ BLEPROTO_T_E("Invalid adv2 len");
+ rc = -1;
+ break;
+ }
+
+ /* adv2 */
+ if (adv->adv2.ad_type == BLEPROTO_ADV_TYPE_SVC_DATA_UUID16) {
+ /* uuid, little endian */
+ adv->adv2.ad_data.service_data.uuid =
+ proto_bytes_get_le16(&data[offset]);
+ offset += 2;
+ /////////////////////////////////////////
+ // spec_data
+ /////////////////////////////////////////
+ bleproto_adv_specdata_t *spec_data =
+ &adv->adv2.ad_data.service_data.spec_data;
+ /* version */
+ spec_data->version = data[offset++];
+ /* business */
+ spec_data->business = data[offset++];
+ /* rfu */
+ spec_data->rfu[0] = data[offset++];
+ spec_data->rfu[1] = data[offset++];
+ /* txpower */
+ spec_data->txpower = (int8_t)data[offset++];
+ /* manucode */
+ {
+ spec_data->manucode.type = data[offset++];
+ if (spec_data->manucode.type !=
+ BLEPROTO_ADV_TLV_TYPE_MANUCODE) {
+ BLEPROTO_T_E("Invalid adv2 service_data.manucode.type");
+ rc = -1;
+ break;
+ }
+ spec_data->manucode.length = data[offset++];
+ if (spec_data->manucode.length !=
+ BLEPROTO_ADV_TLV_LENGTH_MANUCODE) {
+ BLEPROTO_T_E("Invalid adv2 service_data.manucode.length");
+ rc = -1;
+ break;
+ }
+ memcpy(spec_data->manucode.value,
+ &data[offset],
+ spec_data->manucode.length);
+ offset += spec_data->manucode.length;
+ }
+ /* prodcode */
+ {
+ spec_data->prodcode.type = data[offset++];
+ if (spec_data->prodcode.type !=
+ BLEPROTO_ADV_TLV_TYPE_PRODCODE) {
+ BLEPROTO_T_E("Invalid adv2 service_data.prodcode.type");
+ rc = -1;
+ break;
+ }
+ spec_data->prodcode.length = data[offset++];
+ if (spec_data->prodcode.length !=
+ BLEPROTO_ADV_TLV_LENGTH_PRODCODE) {
+ BLEPROTO_T_E("Invalid adv2 service_data.prodcode.length");
+ rc = -1;
+ break;
+ }
+ memcpy(spec_data->prodcode.value,
+ &data[offset],
+ spec_data->prodcode.length);
+ offset += spec_data->prodcode.length;
+ }
+ /* separator */
+ {
+ spec_data->separator = data[offset++];
+ if (spec_data->separator != 0xff) {
+ BLEPROTO_T_E("Invalid adv2 service_data.separator");
+ rc = -1;
+ break;
+ }
+ }
+ /* selfdata */
+ {
+ memcpy(spec_data->selfdata,
+ &data[offset],
+ sizeof(spec_data->selfdata));
+ offset += (uint8_t)sizeof(spec_data->selfdata);
+ }
+ } else if (adv->adv2.ad_type == BLEPROTO_ADV_TYPE_MFG_DATA) {
+ bleproto_advdata_mfg_t *mfg_data = &adv->adv2.ad_data.mfg_data;
+ /* fix "SIOT-1" */
+ memcpy(mfg_data->siot, &data[offset], 6);
+ // if (mfg_data->siot[0] != 'S' || mfg_data->siot[1] != 'I' ||
+ // mfg_data->siot[2] != 'O' || mfg_data->siot[3] != 'T' ||
+ // mfg_data->siot[4] != '-') {
+ // BLEPROTO_T_E("Invalid adv2 mfg_data.siot");
+ // rc = -1;
+ // break;
+ // }
+ offset += 6;
+
+ /* flag */
+ mfg_data->flag = data[offset++];
+ /* txpower */
+ mfg_data->txpower = (int8_t)data[offset++];
+ /* gwmac */
+ memcpy(mfg_data->gwmac, &data[offset], 6);
+ offset += 6;
+ /* manucode */
+ {
+ mfg_data->manucode.type = data[offset++];
+ if (mfg_data->manucode.type !=
+ BLEPROTO_ADV_TLV_TYPE_MANUCODE) {
+ BLEPROTO_T_E("Invalid adv2 mfg_data.manucode.type");
+ rc = -1;
+ break;
+ }
+ mfg_data->manucode.length = data[offset++];
+ if (mfg_data->manucode.length !=
+ BLEPROTO_ADV_TLV_LENGTH_MANUCODE) {
+ BLEPROTO_T_E("Invalid adv2 mfg_data.manucode.length");
+ rc = -1;
+ break;
+ }
+ memcpy(mfg_data->manucode.value,
+ &data[offset],
+ mfg_data->manucode.length);
+ offset += mfg_data->manucode.length;
+ }
+ /* prodcode */
+ {
+ mfg_data->prodcode.type = data[offset++];
+ if (mfg_data->prodcode.type !=
+ BLEPROTO_ADV_TLV_TYPE_PRODCODE) {
+ BLEPROTO_T_E("Invalid adv2 mfg_data.prodcode.type");
+ rc = -1;
+ break;
+ }
+ mfg_data->prodcode.length = data[offset++];
+ if (mfg_data->prodcode.length !=
+ BLEPROTO_ADV_TLV_LENGTH_PRODCODE) {
+ BLEPROTO_T_E("Invalid adv2 mfg_data.prodcode.length");
+ rc = -1;
+ break;
+ }
+ memcpy(mfg_data->prodcode.value,
+ &data[offset],
+ mfg_data->prodcode.length);
+ offset += mfg_data->prodcode.length;
+ }
+ } else {
+ BLEPROTO_T_E("Invalid adv2 adv_type");
+ rc = -1;
+ break;
+ }
+
+ /* check offset */
+ if (offset != 31) {
+ BLEPROTO_T_E("Invalid offset");
+ rc = -1;
+ break;
+ }
+ rc = offset;
+ } while (0);
+
+ return (rc);
+}
+
+int bleproto_appdata_serialize_len(bleproto_appdata_t *appdata,
+ uint8_t packetlen,
+ uint16_t * outlen)
+{
+ /* check param */
+ if (!appdata || packetlen <= BLEPROTO_APPDATA_HEADR_LEN) {
+ BLEPROTO_T_E("Invalid parameters");
+ return -1;
+ }
+
+ /* data total len */
+ uint16_t datalen = appdata->header.datalen;
+
+ /* each frame max payload length */
+ uint8_t frame_max_payload = packetlen - BLEPROTO_APPDATA_HEADR_LEN;
+
+ /* calculate total frames needed */
+ uint16_t totalframe;
+ if (datalen == 0) {
+ /* even with no data, we need at least one frame for the header */
+ totalframe = 1;
+ } else {
+ /* calculate frames needed for the data */
+ totalframe = (datalen + frame_max_payload - 1) / frame_max_payload;
+ }
+ if (totalframe > 255) {
+ BLEPROTO_T_E("Invalid appdata.datalen too long >(%u)",
+ (uint16_t)frame_max_payload * 255);
+ return -1;
+ }
+
+ /* calculate total buffer size needed */
+ if (totalframe <= 1) {
+ /* at least one frame is needed */
+ if (outlen) {
+ *outlen = datalen + BLEPROTO_APPDATA_HEADR_LEN;
+ }
+ } else {
+ /* calculate size of full frames */
+ uint16_t full_frames_size = (uint16_t)(totalframe - 1) * packetlen;
+
+ // clang-format off
+ /* calculate size of last frame */
+ uint16_t last_frame_size =
+ /* header */ BLEPROTO_APPDATA_HEADR_LEN +
+ /* payload */ datalen - (uint16_t)((totalframe - 1) * frame_max_payload);
+ // clang-format on
+
+ /* total size is sum of full frames and last frame */
+ if (outlen) {
+ *outlen = full_frames_size + last_frame_size;
+ }
+ }
+
+ return 0;
+}
+
+int bleproto_appdata_serialize(bleproto_appdata_t *appdata,
+ uint8_t packetlen,
+ uint8_t * buf,
+ uint16_t size)
+
+{
+ int rc, offset = 0;
+ uint16_t data_offset = 0;
+
+ /* check param */
+ if (!appdata || packetlen <= BLEPROTO_APPDATA_HEADR_LEN) {
+ BLEPROTO_T_E("Invalid parameters");
+ return -1;
+ }
+
+ /* totoal len */
+ uint16_t total_len;
+ rc = bleproto_appdata_serialize_len(appdata, packetlen, &total_len);
+ if (rc < 0) {
+ return -1;
+ }
+ if (size < total_len) {
+ BLEPROTO_T_E("Invalid datalen:%u, buf too short(%u<%u)",
+ appdata->header.datalen,
+ size,
+ total_len);
+ return -1;
+ }
+
+ /* data total len */
+ uint16_t datalen = appdata->header.datalen;
+
+ /* each frame max payload length */
+ uint8_t frame_max_payload = packetlen - BLEPROTO_APPDATA_HEADR_LEN;
+
+ /* calculate total frames needed */
+ uint16_t totalframe;
+ if (datalen == 0) {
+ /* even with no data, we need at least one frame for the header */
+ totalframe = 1;
+ } else {
+ /* calculate frames needed for the data */
+ totalframe = (datalen + frame_max_payload - 1) / frame_max_payload;
+ }
+ if (totalframe > 255) {
+ BLEPROTO_T_E("Invalid appdata.datalen too long");
+ return -1;
+ }
+
+ for (uint8_t i = 0; i < (uint8_t)totalframe; i++) {
+ /* pthis_frame_len */
+ uint8_t pthis_frame_len = 0;
+ if (totalframe == 1) {
+ /* only one frame */
+ pthis_frame_len = (uint8_t)datalen;
+ } else if (i + 1 < totalframe) {
+ /* full size frames */
+ pthis_frame_len = frame_max_payload;
+ } else {
+ /* last frame */
+ pthis_frame_len = (uint8_t)(datalen - data_offset);
+ }
+
+ /* header */
+ bleproto_appdata_header_t hdr = appdata->header;
+ {
+ hdr.totalframe = totalframe;
+ if (totalframe == 1) {
+ hdr.frameseq = 0;
+ } else {
+ hdr.frameseq = i + 1;
+ }
+ }
+ /* serialize_header */
+ {
+ /* buf[0]: version[2:0] | datafmt[3:3] | msgtype[7:4] */
+ buf[offset + 0] = UTILS_BITFIELD_SET(hdr.version, 2, 0) |
+ UTILS_BITFIELD_SET(hdr.datafmt, 3, 3) |
+ UTILS_BITFIELD_SET(hdr.msgtype, 7, 4);
+ /* buf[1]: msgid[3:0] | encrypt[4:4] | reserve[7:5] */
+ buf[offset + 1] = UTILS_BITFIELD_SET(hdr.msgid, 3, 0) |
+ UTILS_BITFIELD_SET(hdr.encrypt, 4, 4) |
+ UTILS_BITFIELD_SET(hdr.reserve, 7, 5);
+
+ buf[offset + 2] = hdr.totalframe;
+ buf[offset + 3] = hdr.frameseq;
+ buf[offset + 4] = pthis_frame_len;
+ buf[offset + 5] = hdr.serviceid;
+
+ /* datalen in little endian */
+ proto_bytes_put_le16(&buf[offset + 6], hdr.datalen);
+ }
+ offset += BLEPROTO_APPDATA_HEADR_LEN;
+
+ /* payload */
+ if (pthis_frame_len != 0) {
+ memcpy(
+ &buf[offset], &appdata->data[data_offset], pthis_frame_len);
+ /* offset */
+ offset += pthis_frame_len;
+ /* data_offset */
+ data_offset += pthis_frame_len;
+ }
+ }
+ if (offset != total_len) {
+ BLEPROTO_T_E("Error calc appdata total_len");
+ return -1;
+ }
+
+ return (offset);
+}
+
+int bleproto_appdata_wrap_raw(uint8_t *txbuf,
+ uint16_t txbuf_size,
+ const bleproto_appdata_header_t *header,
+ const uint8_t *payload,
+ uint16_t payload_len)
+{
+ uint16_t total;
+
+ if (!txbuf || !header) {
+ BLEPROTO_T_E("Invalid parameters");
+ return -1;
+ }
+ if (payload_len > 0 && !payload) {
+ BLEPROTO_T_E("Invalid payload");
+ return -1;
+ }
+ /* 单帧 this_frame_len 为 uint8,超过 255 需走分包 serialize */
+ if (payload_len > 255u) {
+ BLEPROTO_T_E("payload too long for single frame");
+ return -1;
+ }
+
+ total = (uint16_t)(BLEPROTO_APPDATA_HEADR_LEN + payload_len);
+ if (txbuf_size < total) {
+ BLEPROTO_T_E("txbuf too short");
+ return -1;
+ }
+
+ /* buf[0]: version[2:0] | datafmt[3:3] | msgtype[7:4] */
+ txbuf[0] = UTILS_BITFIELD_SET(header->version, 2, 0) |
+ UTILS_BITFIELD_SET(header->datafmt, 3, 3) |
+ UTILS_BITFIELD_SET(header->msgtype, 7, 4);
+ /* buf[1]: msgid[3:0] | encrypt[4:4] | reserve[7:5] */
+ txbuf[1] = UTILS_BITFIELD_SET(header->msgid, 3, 0) |
+ UTILS_BITFIELD_SET(header->encrypt, 4, 4) |
+ UTILS_BITFIELD_SET(header->reserve, 7, 5);
+ txbuf[2] = 1; /* totalframe */
+ txbuf[3] = 0; /* frameseq:单帧为 0 */
+ txbuf[4] = (uint8_t)payload_len; /* this frame payload len */
+ txbuf[5] = header->serviceid;
+ proto_bytes_put_le16(&txbuf[6], payload_len);
+
+ if (payload_len > 0) {
+ memcpy(&txbuf[BLEPROTO_APPDATA_HEADR_LEN], payload, payload_len);
+ }
+
+ return (int)total;
+}
+
+int bleproto_appdata_deserialize(uint8_t * buf,
+ uint16_t len,
+ bleproto_appdata_t *appdata)
+{
+ /* check parameters */
+ if (!buf || !appdata) {
+ BLEPROTO_T_E("Invalid parameters");
+ return -1;
+ }
+
+ /* 检查是否至少有一个完整的包头 */
+ if (len < BLEPROTO_APPDATA_HEADR_LEN) {
+ // 数据不够,需要更多数据
+ return 0;
+ }
+
+ int offset = 0;
+ uint8_t msgid;
+ uint8_t totalframe;
+ uint8_t frameseq;
+ uint16_t datalen;
+ uint8_t frame_payload_len;
+ uint8_t max_payload = 0;
+ uint8_t recv_frames = 0;
+
+ /* 第一轮: 扫描所有数据,验证分包的完整性和一致性 */
+ {
+ int scan_offset = 0;
+ bool first_frame = true;
+
+ while (scan_offset < len) {
+ /* 解析header中的关键字段 */
+ msgid = UTILS_BITFIELD_GET(buf[scan_offset + 1], 3, 0);
+ totalframe = buf[scan_offset + 2];
+ frameseq = buf[scan_offset + 3];
+ frame_payload_len = buf[scan_offset + 4];
+ datalen = proto_bytes_get_le16(&buf[scan_offset + 6]);
+ BLEPROTO_T_S("[%u/%u]=0x%02X(%u),msgid:%u,datalen:0x%02X(%u)",
+ frameseq,
+ totalframe,
+ frame_payload_len,
+ frame_payload_len,
+ msgid,
+ datalen,
+ datalen);
+
+ /* 基本参数检查 */
+ if (totalframe == 0) {
+ BLEPROTO_T_E("Invalid totalframe");
+ return -1;
+ }
+ if (frameseq > totalframe) {
+ BLEPROTO_T_E("Invalid frameseq");
+ return -1;
+ }
+ if (datalen > BLEPROTO_APPDATA_DATA_MAX_SZ) {
+ BLEPROTO_T_E("Invalid datalen");
+ return -1;
+ }
+
+ /* 分包一致性检查 */
+ if (first_frame) {
+ first_frame = false;
+ // 使用第一帧的payload长度作为最大payload
+ max_payload = frame_payload_len;
+ } else {
+ /* 检查msgid一致性 */
+ if (msgid != UTILS_BITFIELD_GET(buf[1], 3, 0)) {
+ BLEPROTO_T_E("Inconsistent msgid");
+ return -1;
+ }
+ /* 检查totalframe一致性 */
+ if (totalframe != buf[2]) {
+ BLEPROTO_T_E("Inconsistent totalframe");
+ return -1;
+ }
+ /* 检查frameseq连续性 */
+ uint8_t last_frameseq =
+ buf[scan_offset -
+ (BLEPROTO_APPDATA_HEADR_LEN + max_payload) + 3];
+ if (frameseq != (last_frameseq + 1)) {
+ BLEPROTO_T_E("Non-sequential frameseq:%u!=%u",
+ frameseq,
+ (last_frameseq + 1));
+ return -1;
+ }
+ /* 检查非最后一帧的payload长度是否与第一帧相同 */
+ if (frameseq < (totalframe - 1) &&
+ frame_payload_len != max_payload) {
+ BLEPROTO_T_E("Inconsistent frame payload length");
+ return -1;
+ }
+ }
+
+ /* 检查payload长度 */
+ if ((len - scan_offset) <
+ (BLEPROTO_APPDATA_HEADR_LEN + frame_payload_len)) {
+ return 0; // 需要更多数据
+ }
+
+ /* 验证frame_payload_len */
+ if (totalframe == 1) {
+ if (frame_payload_len != datalen) {
+ BLEPROTO_T_E(
+ "Invalid frame_payload_len for single frame");
+ return -1;
+ }
+ } else {
+ if (frameseq < totalframe) {
+ /* 非最后一帧必须是满包 */
+ if (frame_payload_len != max_payload) {
+ BLEPROTO_T_E(
+ "Invalid frame_payload_len for non-last frame");
+ return -1;
+ }
+ } else {
+ /* 最后一帧的长度计算 */
+ uint16_t last_frame_payload = datalen % max_payload;
+ if (last_frame_payload == 0) {
+ last_frame_payload = max_payload;
+ }
+ if (frame_payload_len != last_frame_payload) {
+ BLEPROTO_T_E(
+ "Invalid frame_payload_len for last frame(%u!=%u)",
+ frame_payload_len,
+ last_frame_payload);
+ return -1;
+ }
+ }
+ }
+
+ /* recv_frames */
+ recv_frames++;
+
+ scan_offset += BLEPROTO_APPDATA_HEADR_LEN + frame_payload_len;
+ }
+
+ /* 检查是否收到了完整的包 */
+ if (recv_frames != totalframe) {
+ // 还没收到所有分包
+ return 0;
+ }
+ }
+
+ /* 第二轮: 解析数据并填充到appdata结构中 */
+ {
+ /* 解析第一帧header */
+ bleproto_appdata_header_t *hdr = &appdata->header;
+
+ /* buf[0]: version[2:0] | datafmt[3:3] | msgtype[7:4] */
+ hdr->version = UTILS_BITFIELD_GET(buf[0], 2, 0);
+ hdr->datafmt = UTILS_BITFIELD_GET(buf[0], 3, 3);
+ hdr->msgtype = UTILS_BITFIELD_GET(buf[0], 7, 4);
+
+ /* buf[1]: msgid[3:0] | encrypt[4:4] | reserve[7:5] */
+ hdr->msgid = UTILS_BITFIELD_GET(buf[1], 3, 0);
+ hdr->encrypt = UTILS_BITFIELD_GET(buf[1], 4, 4);
+ hdr->reserve = UTILS_BITFIELD_GET(buf[1], 7, 5);
+
+ hdr->totalframe = buf[2];
+ hdr->frameseq = buf[3];
+ hdr->framelen = buf[4];
+ hdr->serviceid = buf[5];
+ hdr->datalen = proto_bytes_get_le16(&buf[6]);
+
+ /* 复制所有payload数据 */
+ uint16_t data_offset = 0;
+ uint8_t frames_processed = 0;
+
+ /* clear offset */
+ offset = 0;
+ while (frames_processed < hdr->totalframe) {
+ /* this frame payload length */
+ frame_payload_len = buf[offset + 4];
+
+ if (frame_payload_len > 0) {
+ uint8_t curr_frameseq = buf[offset + 3];
+ if (curr_frameseq == 0) {
+ data_offset = 0;
+ } else {
+ data_offset = (curr_frameseq - 1) * max_payload;
+ }
+
+ /* copy payload data */
+ memcpy(&appdata->data[data_offset],
+ &buf[offset + BLEPROTO_APPDATA_HEADR_LEN],
+ frame_payload_len);
+ }
+
+ offset += BLEPROTO_APPDATA_HEADR_LEN + frame_payload_len;
+ frames_processed++;
+ }
+ }
+
+ /* 返回处理的字节数 */
+ return offset;
+}
+
+int bleproto_encjson_ycmd(const bleproto_ycmd_t *ycmd,
+ uint8_t data[BLEPROTO_APPDATA_DATA_MAX_SZ])
+{
+ int offset, size = BLEPROTO_APPDATA_DATA_MAX_SZ;
+ uint16_t i;
+
+ /* check param */
+ if (!ycmd || !data) {
+ BLEPROTO_T_E("Invalid parameters");
+ return -1;
+ }
+ if (ycmd->arg_int32_count > YCMD_INT32_MAX_COUNT) {
+ BLEPROTO_T_E("Invalid ycmd.arg_int32_count");
+ return -1;
+ }
+ if (ycmd->arg_string_count > YCMD_STRING_MAX_COUNT) {
+ BLEPROTO_T_E("Invalid ycmd.arg_string_count");
+ return -1;
+ }
+ for (i = 0; i < ycmd->arg_string_count; i++) {
+ if (strlen(ycmd->arg_string[i]) == 0) {
+ BLEPROTO_T_E("Invalid ycmd.arg_string[%u]", i);
+ return -1;
+ }
+ }
+
+ if (ycmd->arg_bytes_count > YCMD_BYTES_MAX_COUNT) {
+ BLEPROTO_T_E("Invalid ycmd.arg_bytes_count");
+ return -1;
+ }
+
+ char *str = (char *)data;
+ // {"cmd_id":xxxx,"arg_int32":[],"arg_string":[],"arg_bytes":"xxxx","t":"xxxxxxxx" }
+
+ // {
+ offset = snprintf(str, size, "%s", "{");
+
+ // cmd_id
+ {
+ offset += snprintf(&str[offset],
+ size - offset,
+ "\"%s\":%" PRId32 ",",
+ "cmd_id",
+ (int)ycmd->cmd_id);
+ }
+
+ // arg_int32
+ if (ycmd->arg_int32_count > 0) {
+ offset +=
+ snprintf(&str[offset], size - offset, "\"%s\":[", "arg_int32");
+ for (i = 0; i < ycmd->arg_int32_count; i++) {
+ offset += snprintf(&str[offset],
+ size - offset,
+ "%" PRId32 "",
+ ycmd->arg_int32[i]);
+ if (i != ycmd->arg_int32_count - 1) {
+ offset += snprintf(&str[offset], size - offset, "%s", ",");
+ }
+ }
+ offset += snprintf(&str[offset], size - offset, "%s", "],");
+ }
+
+ // arg_string
+ if (ycmd->arg_string_count > 0) {
+ offset +=
+ snprintf(&str[offset], size - offset, "\"%s\":[", "arg_string");
+ for (i = 0; i < ycmd->arg_string_count; i++) {
+ offset += snprintf(
+ &str[offset], size - offset, "\"%s\"", ycmd->arg_string[i]);
+ if (i != ycmd->arg_string_count - 1) {
+ offset += snprintf(&str[offset], size - offset, "%s", ",");
+ }
+ }
+ offset += snprintf(&str[offset], size - offset, "%s", "],");
+ }
+
+ // arg_bytes
+ if (ycmd->arg_bytes_count > 0) {
+ offset +=
+ snprintf(&str[offset], size - offset, "\"%s\":\"", "arg_bytes");
+ for (i = 0; i < ycmd->arg_bytes_count; i++) {
+ offset += snprintf(
+ &str[offset], size - offset, "%02X", ycmd->arg_bytes[i]);
+ }
+ offset += snprintf(&str[offset], size - offset, "%s", "\",");
+ }
+
+ // t
+ {
+ offset += snprintf(&str[offset],
+ size - offset,
+ "\"%s\":\"%" PRIu64 "\"",
+ "t",
+ ycmd->t);
+ }
+
+ // }
+ offset += snprintf((&str[offset]), size - offset, "%s", "}");
+
+ /* dump output data */
+ BLEPROTO_T_D("ycmd:%.*s", (int)offset, str);
+
+ return (offset);
+}
+
+int bleproto_decjson_ycmd(const uint8_t * data,
+ uint16_t len,
+ bleproto_ycmd_t *ycmd)
+{
+ int rc, i;
+
+ /* check param */
+ if (!data || len == 0 || !ycmd) {
+ BLEPROTO_T_E("Invalid parameters");
+ return -1;
+ }
+
+ const char *str = (const char *)data;
+ /* dump input data */
+ BLEPROTO_T_D("ycmd:%.*s", (int)len, str);
+
+ /* clear */
+ memset(ycmd, 0, sizeof(*ycmd));
+
+ // {"cmd_id":xxxx,"arg_int32":[],"arg_string":[],"arg_bytes":"xxxx","t":"xxxxxxxx" }
+ char value_str[BLEPROTO_APPDATA_DATA_MAX_SZ] = { 0 };
+ double v;
+
+ // cmd_id
+ rc = mjson_get_number(
+ /* s */ str,
+ /* len */ (int)len,
+ /* path */ "$.cmd_id",
+ /* v */ &v);
+ if (rc > 0) {
+ ycmd->cmd_id = (int)v;
+ } else {
+ BLEPROTO_T_E("Error parse cmd_id");
+ return -1;
+ }
+
+ // arg_int32
+ for (i = 0; i < YCMD_INT32_MAX_COUNT; i++) {
+ const char *ptr = NULL;
+ int n;
+ char key[sizeof("$.arg_int32[65535]") + 1] = { 0 };
+ snprintf(key, sizeof(key), "$.arg_int32[%d]", i);
+ if (mjson_find(str, (int)len, key, &ptr, &n) == MJSON_TOK_NUMBER) {
+ char vstr[32] = { 0 };
+ memcpy(vstr, ptr, UTILS_MIN(n, 31));
+ ycmd->arg_int32[ycmd->arg_int32_count] =
+ (int32_t)strtol(vstr, NULL, 10);
+ ycmd->arg_int32_count++;
+ }
+ }
+
+ // arg_string
+ for (i = 0; i < YCMD_STRING_MAX_COUNT; i++) {
+ const char *ptr = NULL;
+ int n;
+ char key[sizeof("$.arg_string[65535]") + 1] = { 0 };
+ snprintf(key, sizeof(key), "$.arg_string[%d]", i);
+ if (mjson_find(str, (int)len, key, &ptr, &n) == MJSON_TOK_STRING) {
+ if (n >= 2 && ptr[0] == '"' && ptr[n - 1] == '"') {
+ ptr++; // 跳过首引号
+ n -= 2; // 去掉首尾引号的长度
+ } else {
+ BLEPROTO_T_E("Error parse arg_string");
+ return -1;
+ }
+ memcpy(ycmd->arg_string[ycmd->arg_string_count],
+ ptr,
+ UTILS_MIN(n, YCMD_STRING_MAX_SIZE));
+ ycmd->arg_string_count++;
+ }
+ }
+
+ // arg_bytes
+ rc = mjson_get_string(
+ /* s */ str,
+ /* len */ (int)len,
+ /* path */ "$.arg_bytes",
+ /* to */ value_str,
+ /* n */ (int)sizeof(value_str));
+ if (rc > 0) {
+ // strhex to byte
+ rc = proto_strhex_to_byte(
+ value_str, ycmd->arg_bytes, sizeof(ycmd->arg_bytes));
+ if (rc >= 0) {
+ ycmd->arg_bytes_count = (uint16_t)rc;
+ }
+ }
+
+ // t
+ rc = mjson_get_string(
+ /* s */ str,
+ /* len */ (int)len,
+ /* path */ "$.t",
+ /* to */ value_str,
+ /* n */ (int)sizeof(value_str));
+ if (rc > 0) {
+ ycmd->t = (uint64_t)strtoull(value_str, NULL, 10);
+ } else {
+ BLEPROTO_T_E("Error parse t");
+ return -1;
+ }
+
+ return (0);
+}
+
+int bleproto_encjson_deviceinfo_req(const bleproto_deviceinfo_req_t *p,
+ uint8_t data[BLEPROTO_APPDATA_DATA_MAX_SZ])
+{
+ int offset, size = BLEPROTO_APPDATA_DATA_MAX_SZ;
+
+ /* check param */
+ if (!p || !data) {
+ BLEPROTO_T_E("Invalid parameters");
+ return -1;
+ }
+
+ char *str = (char *)data;
+ //{"t":"xxxxxxxx",gmtoff:%d}
+
+ // {
+ offset = snprintf(str, size, "%s", "{");
+
+ // t
+ {
+ offset += snprintf(
+ &str[offset], size - offset, "\"t\":\"%" PRIu64 "\",", p->t);
+ }
+
+ // gmtoff
+ {
+ offset +=
+ snprintf(&str[offset], size - offset, "\"gmtoff\":%d", p->gmtoff);
+ }
+
+ // }
+ offset += snprintf((&str[offset]), size - offset, "%s", "}");
+
+ /* dump output data */
+ BLEPROTO_T_D("data:%.*s", (int)offset, str);
+
+ return (offset);
+}
+
+int bleproto_encjson_deviceinfo_rsp(const bleproto_deviceinfo_rsp_t *p,
+ uint8_t data[BLEPROTO_APPDATA_DATA_MAX_SZ])
+{
+ int offset, size = BLEPROTO_APPDATA_DATA_MAX_SZ;
+
+ /* check param */
+ if (!p || !data) {
+ BLEPROTO_T_E("Invalid parameters");
+ return -1;
+ }
+
+ /* check params */
+ if (strlen(p->hwv) == 0) {
+ BLEPROTO_T_E("Invalid deviceinfo.rsp.hwv");
+ return -1;
+ }
+ if (strlen(p->swv) == 0) {
+ BLEPROTO_T_E("Invalid deviceinfo.rsp.swv");
+ return -1;
+ }
+
+ char *str = (char *)data;
+ // {"hwv":"%s","swv":"%s","prototype":%u,"hbcycle":%u,"longcon":%u}
+
+ // {
+ offset = snprintf(str, size, "%s", "{");
+
+ // hwv
+ {
+ offset += snprintf(
+ &str[offset], size - offset, "\"%s\":\"%s\",", "hwv", p->hwv);
+ }
+ // swv
+ {
+ offset += snprintf(
+ &str[offset], size - offset, "\"%s\":\"%s\",", "swv", p->swv);
+ }
+ // prototype
+ {
+ offset += snprintf(&str[offset],
+ size - offset,
+ "\"%s\":%u,",
+ "prototype",
+ p->prototype);
+ }
+ // hbcycle
+ {
+ offset += snprintf(
+ &str[offset], size - offset, "\"%s\":%u,", "hbcycle", p->hbcycle);
+ }
+ // longcon
+ {
+ offset += snprintf(
+ &str[offset], size - offset, "\"%s\":%u", "longcon", p->longcon);
+ }
+ // }
+ offset += snprintf((&str[offset]), size - offset, "%s", "}");
+
+ /* dump output data */
+ BLEPROTO_T_D("data:%.*s", (int)offset, str);
+
+ return (offset);
+}
+
+int bleproto_encjson_authsetup_req(const bleproto_authsetup_req_t *p,
+ uint8_t data[BLEPROTO_APPDATA_DATA_MAX_SZ])
+{
+ int offset, size = BLEPROTO_APPDATA_DATA_MAX_SZ;
+
+ /* check param */
+ if (!p || !data) {
+ BLEPROTO_T_E("Invalid parameters");
+ return -1;
+ }
+
+ /* check params */
+ if (strlen(p->devid) == 0) {
+ BLEPROTO_T_E("Invalid authsetup.req.devid");
+ return -1;
+ }
+ if (strlen(p->authcode) == 0) {
+ BLEPROTO_T_E("Invalid authsetup.req.authcode");
+ return -1;
+ }
+
+ char *str = (char *)data;
+ // {"gwmac":"xxxx","devid":"xxxx","authcode":"xxxx"}
+
+ // {
+ offset = snprintf(str, size, "%s", "{");
+
+ // gwmac
+ {
+ offset += snprintf(&str[offset],
+ size - offset,
+ "\"%s\":\"%02X%02X%02X%02X%02X%02X\",",
+ "gwmac",
+ p->gwmac[0],
+ p->gwmac[1],
+ p->gwmac[2],
+ p->gwmac[3],
+ p->gwmac[4],
+ p->gwmac[5]);
+ }
+
+ // devid
+ {
+ offset += snprintf(
+ &str[offset], size - offset, "\"%s\":\"%s\",", "devid", p->devid);
+ }
+
+ // authcode
+ {
+ offset += snprintf(&str[offset],
+ size - offset,
+ "\"%s\":\"%s\"",
+ "authcode",
+ p->authcode);
+ }
+
+ // }
+ offset += snprintf((&str[offset]), size - offset, "%s", "}");
+
+ /* dump output data */
+ BLEPROTO_T_D("data:%.*s", (int)offset, str);
+
+ return (offset);
+}
+
+int bleproto_encjson_authsetup_rsp(const bleproto_authsetup_rsp_t *p,
+ uint8_t data[BLEPROTO_APPDATA_DATA_MAX_SZ])
+{
+ int offset, size = BLEPROTO_APPDATA_DATA_MAX_SZ;
+
+ /* check param */
+ if (!p || !data) {
+ BLEPROTO_T_E("Invalid parameters");
+ return -1;
+ }
+
+ char *str = (char *)data;
+ // {"errcode":xxx}
+
+ // {
+ offset = snprintf(str, size, "%s", "{");
+
+ // errcode
+ {
+ offset += snprintf(&str[offset],
+ size - offset,
+ "\"%s\":%d",
+ "errcode",
+ (int)p->errcode);
+ }
+
+ // }
+ offset += snprintf((&str[offset]), size - offset, "%s", "}");
+
+ /* dump output data */
+ BLEPROTO_T_D("data:%.*s", (int)offset, str);
+
+ return (offset);
+}
+
+int bleproto_encjson_authdelete_req(const bleproto_authdelete_req_t *p,
+ uint8_t data[BLEPROTO_APPDATA_DATA_MAX_SZ])
+{
+ int offset, size = BLEPROTO_APPDATA_DATA_MAX_SZ;
+
+ /* check param */
+ if (!p || !data) {
+ BLEPROTO_T_E("Invalid parameters");
+ return -1;
+ }
+
+ /* check params */
+ if (strlen(p->authcode) == 0) {
+ BLEPROTO_T_E("Invalid authdelete.req.authcode");
+ return -1;
+ }
+
+ char *str = (char *)data;
+ // { "authcode": "xxxx"}
+
+ // {
+ offset = snprintf(str, size, "%s", "{");
+
+ // authcode
+ {
+ offset += snprintf(&str[offset],
+ size - offset,
+ "\"%s\":\"%s\"",
+ "authcode",
+ p->authcode);
+ }
+
+ // }
+ offset += snprintf((&str[offset]), size - offset, "%s", "}");
+
+ /* dump output data */
+ BLEPROTO_T_D("data:%.*s", (int)offset, str);
+
+ return (offset);
+}
+
+int bleproto_encjson_authdelete_rsp(const bleproto_authdelete_rsp_t *p,
+ uint8_t data[BLEPROTO_APPDATA_DATA_MAX_SZ])
+{
+ int offset, size = BLEPROTO_APPDATA_DATA_MAX_SZ;
+
+ /* check param */
+ if (!p || !data) {
+ BLEPROTO_T_E("Invalid parameters");
+ return -1;
+ }
+
+ char *str = (char *)data;
+ // {"gwmac": "xxxx","errcode":xxx}
+
+ // {
+ offset = snprintf(str, size, "%s", "{");
+
+ // gwmac
+ {
+ offset += snprintf(&str[offset],
+ size - offset,
+ "\"%s\":\"%02X%02X%02X%02X%02X%02X\",",
+ "gwmac",
+ p->gwmac[0],
+ p->gwmac[1],
+ p->gwmac[2],
+ p->gwmac[3],
+ p->gwmac[4],
+ p->gwmac[5]);
+ }
+
+ // errcode
+ {
+ offset += snprintf(&str[offset],
+ size - offset,
+ "\"%s\":%d",
+ "errcode",
+ (int)p->errcode);
+ }
+
+ // }
+ offset += snprintf((&str[offset]), size - offset, "%s", "}");
+
+ /* dump output data */
+ BLEPROTO_T_D("data:%.*s", (int)offset, str);
+
+ return (offset);
+}
+
+int bleproto_encjson_runcmd_req(const bleproto_runcmd_req_t *p,
+ uint8_t data[BLEPROTO_APPDATA_DATA_MAX_SZ])
+{
+ int offset, size = BLEPROTO_APPDATA_DATA_MAX_SZ;
+ uint16_t i;
+
+ /* check param */
+ if (!p || !data) {
+ BLEPROTO_T_E("Invalid parameters");
+ return -1;
+ }
+ if (p->ycmd.arg_int32_count > YCMD_INT32_MAX_COUNT) {
+ BLEPROTO_T_E("Invalid ycmd.arg_int32_count");
+ return -1;
+ }
+ if (p->ycmd.arg_string_count > YCMD_STRING_MAX_COUNT) {
+ BLEPROTO_T_E("Invalid ycmd.arg_string_count");
+ return -1;
+ }
+ for (i = 0; i < p->ycmd.arg_string_count; i++) {
+ if (strlen(p->ycmd.arg_string[i]) == 0) {
+ BLEPROTO_T_E("Invalid runcmd.req.arg_string[%u]", i);
+ return -1;
+ }
+ }
+
+ if (p->ycmd.arg_bytes_count > YCMD_BYTES_MAX_COUNT) {
+ BLEPROTO_T_E("Invalid ycmd.arg_bytes_count");
+ return -1;
+ }
+
+ char *str = (char *)data;
+ // {"cmd_id":xxxx,"arg_int32":[],"arg_string":[],"arg_bytes":"xxxx","t":"xxxxxxxx" }
+
+ // {
+ offset = snprintf(str, size, "%s", "{");
+
+ // cmd_id
+ {
+ offset += snprintf(&str[offset],
+ size - offset,
+ "\"%s\":%" PRId32 ",",
+ "cmd_id",
+ (int)p->ycmd.cmd_id);
+ }
+
+ // arg_int32
+ if (p->ycmd.arg_int32_count > 0) {
+ offset +=
+ snprintf(&str[offset], size - offset, "\"%s\":[", "arg_int32");
+ for (i = 0; i < p->ycmd.arg_int32_count; i++) {
+ offset += snprintf(&str[offset],
+ size - offset,
+ "%" PRId32 "",
+ p->ycmd.arg_int32[i]);
+ if (i != p->ycmd.arg_int32_count - 1) {
+ offset += snprintf(&str[offset], size - offset, "%s", ",");
+ }
+ }
+ offset += snprintf(&str[offset], size - offset, "%s", "],");
+ }
+
+ // arg_string
+ if (p->ycmd.arg_string_count > 0) {
+ offset +=
+ snprintf(&str[offset], size - offset, "\"%s\":[", "arg_string");
+ for (i = 0; i < p->ycmd.arg_string_count; i++) {
+ offset += snprintf(
+ &str[offset], size - offset, "\"%s\"", p->ycmd.arg_string[i]);
+ if (i != p->ycmd.arg_string_count - 1) {
+ offset += snprintf(&str[offset], size - offset, "%s", ",");
+ }
+ }
+ offset += snprintf(&str[offset], size - offset, "%s", "],");
+ }
+
+ // arg_bytes
+ if (p->ycmd.arg_bytes_count > 0) {
+ offset +=
+ snprintf(&str[offset], size - offset, "\"%s\":\"", "arg_bytes");
+ for (i = 0; i < p->ycmd.arg_bytes_count; i++) {
+ offset += snprintf(
+ &str[offset], size - offset, "%02X", p->ycmd.arg_bytes[i]);
+ }
+ offset += snprintf(&str[offset], size - offset, "%s", "\",");
+ }
+
+ // t
+ {
+ offset += snprintf(&str[offset],
+ size - offset,
+ "\"%s\":\"%" PRIu64 "\"",
+ "t",
+ p->ycmd.t);
+ }
+
+ // }
+ offset += snprintf((&str[offset]), size - offset, "%s", "}");
+
+ /* dump output data */
+ BLEPROTO_T_D("data:%.*s", (int)offset, str);
+
+ return (offset);
+}
+
+int bleproto_encjson_runcmd_rsp(const bleproto_runcmd_rsp_t *p,
+ uint8_t data[BLEPROTO_APPDATA_DATA_MAX_SZ])
+{
+ int offset, size = BLEPROTO_APPDATA_DATA_MAX_SZ;
+ uint16_t i;
+
+ /* check param */
+ if (!p || !data) {
+ BLEPROTO_T_E("Invalid parameters");
+ return -1;
+ }
+ if (p->ycmd.arg_int32_count > YCMD_INT32_MAX_COUNT) {
+ BLEPROTO_T_E("Invalid ycmd.arg_int32_count");
+ return -1;
+ }
+ if (p->ycmd.arg_string_count > YCMD_STRING_MAX_COUNT) {
+ BLEPROTO_T_E("Invalid ycmd.arg_string_count");
+ return -1;
+ }
+ for (i = 0; i < p->ycmd.arg_string_count; i++) {
+ if (strlen(p->ycmd.arg_string[i]) == 0) {
+ BLEPROTO_T_E("Invalid runcmd.rsp.arg_string[%u]", i);
+ return -1;
+ }
+ }
+ if (p->ycmd.arg_bytes_count > YCMD_BYTES_MAX_COUNT) {
+ BLEPROTO_T_E("Invalid ycmd.arg_bytes_count");
+ return -1;
+ }
+
+ char *str = (char *)data;
+ // {"cmd_id":xxxx,"arg_int32":[],"arg_string":[],"arg_bytes":"xxxx","t":"xxxxxxxx" }
+
+ // {
+ offset = snprintf(str, size, "%s", "{");
+
+ // cmd_id
+ {
+ offset += snprintf(&str[offset],
+ size - offset,
+ "\"%s\":%" PRId32 ",",
+ "cmd_id",
+ (int)p->ycmd.cmd_id);
+ }
+
+ // arg_int32
+ if (p->ycmd.arg_int32_count > 0) {
+ offset +=
+ snprintf(&str[offset], size - offset, "\"%s\":[", "arg_int32");
+ for (i = 0; i < p->ycmd.arg_int32_count; i++) {
+ offset += snprintf(&str[offset],
+ size - offset,
+ "%" PRId32 "",
+ p->ycmd.arg_int32[i]);
+ if (i != p->ycmd.arg_int32_count - 1) {
+ offset += snprintf(&str[offset], size - offset, "%s", ",");
+ }
+ }
+ offset += snprintf(&str[offset], size - offset, "%s", "],");
+ }
+
+ // arg_string
+ if (p->ycmd.arg_string_count > 0) {
+ offset +=
+ snprintf(&str[offset], size - offset, "\"%s\":[", "arg_string");
+ for (i = 0; i < p->ycmd.arg_string_count; i++) {
+ offset += snprintf(
+ &str[offset], size - offset, "\"%s\"", p->ycmd.arg_string[i]);
+ if (i != p->ycmd.arg_string_count - 1) {
+ offset += snprintf(&str[offset], size - offset, "%s", ",");
+ }
+ }
+ offset += snprintf(&str[offset], size - offset, "%s", "],");
+ }
+
+ // arg_bytes
+ if (p->ycmd.arg_bytes_count > 0) {
+ offset +=
+ snprintf(&str[offset], size - offset, "\"%s\":\"", "arg_bytes");
+ for (i = 0; i < p->ycmd.arg_bytes_count; i++) {
+ offset += snprintf(
+ &str[offset], size - offset, "%02X", p->ycmd.arg_bytes[i]);
+ }
+ offset += snprintf(&str[offset], size - offset, "%s", "\",");
+ }
+
+ // t
+ {
+ offset += snprintf(&str[offset],
+ size - offset,
+ "\"%s\":\"%" PRIu64 "\"",
+ "t",
+ p->ycmd.t);
+ }
+
+ // }
+ offset += snprintf((&str[offset]), size - offset, "%s", "}");
+
+ /* dump output data */
+ BLEPROTO_T_D("data:%.*s", (int)offset, str);
+
+ return (offset);
+}
+
+int bleproto_encjson_reportcmd_req(const bleproto_reportcmd_req_t *p,
+ uint8_t data[BLEPROTO_APPDATA_DATA_MAX_SZ])
+{
+ int offset, size = BLEPROTO_APPDATA_DATA_MAX_SZ;
+ uint16_t i;
+
+ /* check param */
+ if (!p || !data) {
+ BLEPROTO_T_E("Invalid parameters");
+ return -1;
+ }
+ if (p->ycmd.arg_int32_count > YCMD_INT32_MAX_COUNT) {
+ BLEPROTO_T_E("Invalid ycmd.arg_int32_count");
+ return -1;
+ }
+ if (p->ycmd.arg_string_count > YCMD_STRING_MAX_COUNT) {
+ BLEPROTO_T_E("Invalid ycmd.arg_string_count");
+ return -1;
+ }
+ for (i = 0; i < p->ycmd.arg_string_count; i++) {
+ if (strlen(p->ycmd.arg_string[i]) == 0) {
+ BLEPROTO_T_E("Invalid reportcmd.req.arg_string[%u]", i);
+ return -1;
+ }
+ }
+ if (p->ycmd.arg_bytes_count > YCMD_BYTES_MAX_COUNT) {
+ BLEPROTO_T_E("Invalid ycmd.arg_bytes_count");
+ return -1;
+ }
+
+ char *str = (char *)data;
+ // {"cmd_id":xxxx,"arg_int32":[],"arg_string":[],"arg_bytes":"xxxx","t":"xxxxxxxx"}
+
+ // {
+ offset = snprintf(str, size, "%s", "{");
+
+ // cmd_id
+ {
+ offset += snprintf(&str[offset],
+ size - offset,
+ "\"%s\":%" PRId32 ",",
+ "cmd_id",
+ (int)p->ycmd.cmd_id);
+ }
+
+ // arg_int32
+ if (p->ycmd.arg_int32_count > 0) {
+ offset +=
+ snprintf(&str[offset], size - offset, "\"%s\":[", "arg_int32");
+ for (i = 0; i < p->ycmd.arg_int32_count; i++) {
+ offset += snprintf(&str[offset],
+ size - offset,
+ "%" PRId32 "",
+ p->ycmd.arg_int32[i]);
+ if (i != p->ycmd.arg_int32_count - 1) {
+ offset += snprintf(&str[offset], size - offset, "%s", ",");
+ }
+ }
+ offset += snprintf(&str[offset], size - offset, "%s", "],");
+ }
+
+ // arg_string
+ if (p->ycmd.arg_string_count > 0) {
+ offset +=
+ snprintf(&str[offset], size - offset, "\"%s\":[", "arg_string");
+ for (i = 0; i < p->ycmd.arg_string_count; i++) {
+ offset += snprintf(
+ &str[offset], size - offset, "\"%s\"", p->ycmd.arg_string[i]);
+ if (i != p->ycmd.arg_string_count - 1) {
+ offset += snprintf(&str[offset], size - offset, "%s", ",");
+ }
+ }
+ offset += snprintf(&str[offset], size - offset, "%s", "],");
+ }
+
+ // arg_bytes
+ if (p->ycmd.arg_bytes_count > 0) {
+ offset +=
+ snprintf(&str[offset], size - offset, "\"%s\":\"", "arg_bytes");
+ for (i = 0; i < p->ycmd.arg_bytes_count; i++) {
+ offset += snprintf(
+ &str[offset], size - offset, "%02X", p->ycmd.arg_bytes[i]);
+ }
+ offset += snprintf(&str[offset], size - offset, "%s", "\",");
+ }
+
+ // t
+ {
+ offset += snprintf(&str[offset],
+ size - offset,
+ "\"%s\":\"%" PRIu64 "\"",
+ "t",
+ p->ycmd.t);
+ }
+
+ // }
+ offset += snprintf((&str[offset]), size - offset, "%s", "}");
+
+ /* dump output data */
+ BLEPROTO_T_D("data:%.*s", (int)offset, str);
+
+ return (offset);
+}
+
+int bleproto_encjson_reportcmd_rsp(const bleproto_reportcmd_rsp_t *p,
+ uint8_t data[BLEPROTO_APPDATA_DATA_MAX_SZ])
+{
+ int offset, size = BLEPROTO_APPDATA_DATA_MAX_SZ;
+
+ /* check param */
+ if (!p || !data) {
+ BLEPROTO_T_E("Invalid parameters");
+ return -1;
+ }
+
+ char *str = (char *)data;
+ // {"errcode":xxx}
+
+ // {
+ offset = snprintf(str, size, "%s", "{");
+
+ // errcode
+ {
+ offset += snprintf(&str[offset],
+ size - offset,
+ "\"%s\":%d",
+ "errcode",
+ (int)p->errcode);
+ }
+
+ // }
+ offset += snprintf((&str[offset]), size - offset, "%s", "}");
+
+ /* dump output data */
+ BLEPROTO_T_D("data:%.*s", (int)offset, str);
+
+ return (offset);
+}
+
+int bleproto_encjson_doaction_req(const bleproto_doaction_req_t *p,
+ uint8_t data[BLEPROTO_APPDATA_DATA_MAX_SZ])
+{
+ int offset, size = BLEPROTO_APPDATA_DATA_MAX_SZ;
+
+ /* check param */
+ if (!p || !data) {
+ BLEPROTO_T_E("Invalid parameters");
+ return -1;
+ }
+
+ char *str = (char *)data;
+ // {"action":%d}
+
+ // {
+ offset = snprintf(str, size, "%s", "{");
+
+ // action
+ {
+ offset += snprintf(
+ &str[offset], size - offset, "\"%s\":%d", "action", p->action);
+ }
+
+ // }
+ offset += snprintf((&str[offset]), size - offset, "%s", "}");
+
+ /* dump output data */
+ BLEPROTO_T_D("data:%.*s", (int)offset, str);
+
+ return (offset);
+}
+
+int bleproto_encjson_doaction_rsp(const bleproto_doaction_rsp_t *p,
+ uint8_t data[BLEPROTO_APPDATA_DATA_MAX_SZ])
+{
+ int offset, size = BLEPROTO_APPDATA_DATA_MAX_SZ;
+
+ /* check param */
+ if (!p || !data) {
+ BLEPROTO_T_E("Invalid parameters");
+ return -1;
+ }
+
+ char *str = (char *)data;
+ // {"errcode":xxx}
+
+ // {
+ offset = snprintf(str, size, "%s", "{");
+
+ // errcode
+ {
+ offset += snprintf(&str[offset],
+ size - offset,
+ "\"%s\":%d",
+ "errcode",
+ (int)p->errcode);
+ }
+
+ // }
+ offset += snprintf((&str[offset]), size - offset, "%s", "}");
+
+ /* dump output data */
+ BLEPROTO_T_D("data:%.*s", (int)offset, str);
+
+ return (offset);
+}
+
+int bleproto_encjson_otanotify_req(const bleproto_otanotify_req_t *p,
+ uint8_t data[BLEPROTO_APPDATA_DATA_MAX_SZ])
+{
+ int offset, size = BLEPROTO_APPDATA_DATA_MAX_SZ;
+
+ /* check param */
+ if (!p || !data) {
+ BLEPROTO_T_E("Invalid parameters");
+ return -1;
+ }
+
+ char *str = (char *)data;
+ // {"id": %d, "ver":"xxxx", "size":%d, "md5":"xxxxxxx"}
+
+ // {
+ offset = snprintf(str, size, "%s", "{");
+
+ // id
+ {
+ offset +=
+ snprintf(&str[offset], size - offset, "\"%s\":%d,", "id", p->id);
+ }
+ // ver
+ {
+ offset += snprintf(
+ &str[offset], size - offset, "\"%s\":\"%s\",", "ver", p->version);
+ }
+ // size
+ {
+ offset += snprintf(
+ &str[offset], size - offset, "\"%s\":%u,", "size", p->size);
+ }
+ // md5
+ {
+ offset += snprintf(
+ &str[offset], size - offset, "\"%s\":\"%s\",", "md5", p->md5);
+ }
+
+ // }
+ offset += snprintf((&str[offset]), size - offset, "%s", "}");
+
+ /* dump output data */
+ BLEPROTO_T_D("data:%.*s", (int)offset, str);
+
+ return (offset);
+}
+
+int bleproto_encjson_otanotify_rsp(const bleproto_otanotify_rsp_t *p,
+ uint8_t data[BLEPROTO_APPDATA_DATA_MAX_SZ])
+{
+ int offset, size = BLEPROTO_APPDATA_DATA_MAX_SZ;
+
+ /* check param */
+ if (!p || !data) {
+ BLEPROTO_T_E("Invalid parameters");
+ return -1;
+ }
+
+ char *str = (char *)data;
+ // {"errcode":xxx}
+
+ // {
+ offset = snprintf(str, size, "%s", "{");
+
+ // errcode
+ {
+ offset += snprintf(&str[offset],
+ size - offset,
+ "\"%s\":%d",
+ "errcode",
+ (int)p->errcode);
+ }
+
+ // }
+ offset += snprintf((&str[offset]), size - offset, "%s", "}");
+
+ /* dump output data */
+ BLEPROTO_T_D("data:%.*s", (int)offset, str);
+
+ return (offset);
+}
+
+int bleproto_encjson_otadata_req(const bleproto_otadata_req_t *p,
+ uint8_t data[BLEPROTO_APPDATA_DATA_MAX_SZ])
+{
+ int offset, size = BLEPROTO_APPDATA_DATA_MAX_SZ;
+
+ /* check param */
+ if (!p || !data) {
+ BLEPROTO_T_E("Invalid parameters");
+ return -1;
+ }
+
+ char *str = (char *)data;
+ // {"id": %d, "offset":%d, "maxsize":%d}
+
+ // {
+ offset = snprintf(str, size, "%s", "{");
+
+ // id
+ {
+ offset += snprintf(
+ &str[offset], size - offset, "\"%s\":%d, ", "id", (int)p->id);
+ }
+ // offset
+ {
+ offset += snprintf(&str[offset],
+ size - offset,
+ "\"%s\":%d, ",
+ "offset",
+ (int)p->offset);
+ }
+ // maxsize
+ {
+ offset += snprintf(&str[offset],
+ size - offset,
+ "\"%s\":%d",
+ "maxsize",
+ (int)p->maxsize);
+ }
+
+ // }
+ offset += snprintf((&str[offset]), size - offset, "%s", "}");
+
+ /* dump output data */
+ BLEPROTO_T_D("data:%.*s", (int)offset, str);
+
+ return (offset);
+}
+
+int bleproto_encbin_otadata_rsp(const bleproto_otadata_rsp_t *p,
+ uint8_t data[BLEPROTO_APPDATA_DATA_MAX_SZ])
+{
+ int offset = 0, size = BLEPROTO_APPDATA_DATA_MAX_SZ;
+
+ /* check param */
+ if (!p || !data) {
+ BLEPROTO_T_E("Invalid parameters");
+ return -1;
+ }
+
+ /* check buffer size */
+ if ((size_t)size < (sizeof(p->errcode) + sizeof(p->id) +
+ sizeof(p->offset) + sizeof(p->len) + p->len)) {
+ BLEPROTO_T_E("Buffer too small");
+ return -1;
+ }
+
+ /* serialize errcode (little-endian) */
+ data[offset++] = (uint8_t)(p->errcode & 0xFF);
+ data[offset++] = (uint8_t)((p->errcode >> 8) & 0xFF);
+ data[offset++] = (uint8_t)((p->errcode >> 16) & 0xFF);
+ data[offset++] = (uint8_t)((p->errcode >> 24) & 0xFF);
+
+ /* serialize id (little-endian) */
+ data[offset++] = (uint8_t)(p->id & 0xFF);
+ data[offset++] = (uint8_t)((p->id >> 8) & 0xFF);
+ data[offset++] = (uint8_t)((p->id >> 16) & 0xFF);
+ data[offset++] = (uint8_t)((p->id >> 24) & 0xFF);
+
+ /* serialize offset (little-endian) */
+ data[offset++] = (uint8_t)(p->offset & 0xFF);
+ data[offset++] = (uint8_t)((p->offset >> 8) & 0xFF);
+ data[offset++] = (uint8_t)((p->offset >> 16) & 0xFF);
+ data[offset++] = (uint8_t)((p->offset >> 24) & 0xFF);
+
+ /* serialize len (little-endian) */
+ data[offset++] = (uint8_t)(p->len & 0xFF);
+ data[offset++] = (uint8_t)((p->len >> 8) & 0xFF);
+ data[offset++] = (uint8_t)((p->len >> 16) & 0xFF);
+ data[offset++] = (uint8_t)((p->len >> 24) & 0xFF);
+
+ /* serialize data(data 为外部指针,不再内嵌数组) */
+ if (p->len > 0 && p->len <= BLEPROTO_APPDATA_OTADATA_SZ) {
+ if (!p->data) {
+ BLEPROTO_T_E("otadata_rsp.data is NULL");
+ return -1;
+ }
+ memcpy(&data[offset], p->data, p->len);
+ offset += p->len;
+ }
+
+ return offset;
+}
+
+int bleproto_decjson_deviceinfo_req(const uint8_t * data,
+ uint16_t len,
+ bleproto_deviceinfo_req_t *p)
+{
+ int rc;
+
+ /* check param */
+ if (!data || len == 0 || !p) {
+ BLEPROTO_T_E("Invalid parameters");
+ return -1;
+ }
+
+ const char *str = (const char *)data;
+ /* dump input data */
+ BLEPROTO_T_D("data:%.*s", (int)len, str);
+
+ /* clear */
+ memset(p, 0, sizeof(*p));
+
+ //{"t":"xxxxxxxx",gmtoff:%d}
+ char value_str[BLEPROTO_APPDATA_DATA_MAX_SZ] = { 0 };
+ double v;
+
+ // t
+ rc = mjson_get_string(
+ /* s */ str,
+ /* len */ (int)len,
+ /* path */ "$.t",
+ /* to */ value_str,
+ /* n */ (int)sizeof(value_str));
+ if (rc > 0) {
+ p->t = (uint64_t)strtoull(value_str, NULL, 10);
+ } else {
+ BLEPROTO_T_E("Error parse t");
+ return -1;
+ }
+
+ // gmtoff
+ rc = mjson_get_number(
+ /* s */ str,
+ /* len */ (int)len,
+ /* path */ "$.gmtoff",
+ /* result */ &v);
+ if (rc > 0) {
+ p->gmtoff = (int)v;
+ } else {
+ BLEPROTO_T_E("Error parse gmtoff");
+ return -1;
+ }
+
+ return (0);
+}
+
+int bleproto_decjson_deviceinfo_rsp(const uint8_t * data,
+ uint16_t len,
+ bleproto_deviceinfo_rsp_t *p)
+{
+ int rc;
+
+ /* check param */
+ if (!data || len == 0 || !p) {
+ BLEPROTO_T_E("Invalid parameters");
+ return -1;
+ }
+
+ const char *str = (const char *)data;
+ /* dump input data */
+ BLEPROTO_T_D("data:%.*s", (int)len, str);
+
+ /* clear */
+ memset(p, 0, sizeof(*p));
+
+ // {"hwv":"%s","swv":"%s","prototype":%u, "hbcycle":%u,"longcon":%u}
+ char value_str[BLEPROTO_APPDATA_DATA_MAX_SZ] = { 0 };
+ double v;
+
+ // hwv
+ rc = mjson_get_string(
+ /* s */ str,
+ /* len */ (int)len,
+ /* path */ "$.hwv",
+ /* to */ value_str,
+ /* n */ (int)sizeof(value_str));
+ if (rc > 0) {
+ snprintf(p->hwv, sizeof(p->hwv), "%s", value_str);
+ } else {
+ BLEPROTO_T_E("Error parse hwv");
+ return -1;
+ }
+
+ // swv
+ rc = mjson_get_string(
+ /* s */ str,
+ /* len */ (int)len,
+ /* path */ "$.swv",
+ /* to */ value_str,
+ /* n */ (int)sizeof(value_str));
+ if (rc > 0) {
+ snprintf(p->swv, sizeof(p->swv), "%s", value_str);
+ } else {
+ BLEPROTO_T_E("Error parse swv");
+ return -1;
+ }
+
+ // prototype
+ rc = mjson_get_number(
+ /* s */ str,
+ /* len */ (int)len,
+ /* path */ "$.prototype",
+ /* result */ &v);
+ if (rc > 0) {
+ p->prototype = (uint8_t)v;
+ } else {
+ BLEPROTO_T_E("Error parse prototype");
+ return -1;
+ }
+
+ // hbcycle
+ rc = mjson_get_number(
+ /* s */ str,
+ /* len */ (int)len,
+ /* path */ "$.hbcycle",
+ /* result */ &v);
+ if (rc > 0) {
+ p->hbcycle = (uint32_t)v;
+ } else {
+ BLEPROTO_T_E("Error parse hbcycle");
+ return -1;
+ }
+
+ // longcon
+ rc = mjson_get_number(
+ /* s */ str,
+ /* len */ (int)len,
+ /* path */ "$.longcon",
+ /* result */ &v);
+ if (rc > 0) {
+ p->longcon = (uint8_t)v;
+ } else {
+ BLEPROTO_T_E("Error parse longcon");
+ return -1;
+ }
+
+ return (0);
+}
+
+int bleproto_decjson_authsetup_req(const uint8_t * data,
+ uint16_t len,
+ bleproto_authsetup_req_t *p)
+{
+ int rc;
+
+ /* check param */
+ if (!data || len == 0 || !p) {
+ BLEPROTO_T_E("Invalid parameters");
+ return -1;
+ }
+
+ const char *str = (const char *)data;
+ /* dump input data */
+ BLEPROTO_T_D("data:%.*s", (int)len, str);
+
+ /* clear */
+ memset(p, 0, sizeof(*p));
+
+ // {"gwmac":"xxxx","devid":"xxxx","authcode":"xxxx"}
+ char value_str[BLEPROTO_APPDATA_DATA_MAX_SZ] = { 0 };
+
+ // gwmac
+ rc = mjson_get_string(
+ /* s */ str,
+ /* len */ (int)len,
+ /* path */ "$.gwmac",
+ /* to */ value_str,
+ /* n */ (int)sizeof(value_str));
+ if (rc > 0) {
+ int nr = proto_strhex_to_byte(value_str, p->gwmac, sizeof(p->gwmac));
+ if (nr != (int)sizeof(p->gwmac)) {
+ BLEPROTO_T_E("Error parse gwmac");
+ return -1;
+ }
+ } else {
+ BLEPROTO_T_E("Error parse gwmac");
+ return -1;
+ }
+
+ // devid
+ rc = mjson_get_string(
+ /* s */ str,
+ /* len */ (int)len,
+ /* path */ "$.devid",
+ /* to */ value_str,
+ /* n */ (int)sizeof(value_str));
+ if (rc > 0) {
+ snprintf(p->devid, sizeof(p->devid), "%s", value_str);
+ } else {
+ BLEPROTO_T_E("Error parse devid");
+ return -1;
+ }
+
+ // authcode
+ rc = mjson_get_string(
+ /* s */ str,
+ /* len */ (int)len,
+ /* path */ "$.authcode",
+ /* to */ value_str,
+ /* n */ (int)sizeof(value_str));
+ if (rc > 0) {
+ snprintf(p->authcode, sizeof(p->authcode), "%s", value_str);
+ } else {
+ BLEPROTO_T_E("Error parse authcode");
+ return -1;
+ }
+
+ return (0);
+}
+
+int bleproto_decjson_authsetup_rsp(const uint8_t * data,
+ uint16_t len,
+ bleproto_authsetup_rsp_t *p)
+{
+ int rc;
+
+ /* check param */
+ if (!data || len == 0 || !p) {
+ BLEPROTO_T_E("Invalid parameters");
+ return -1;
+ }
+
+ const char *str = (const char *)data;
+ /* dump input data */
+ BLEPROTO_T_D("data:%.*s", (int)len, str);
+
+ /* clear */
+ memset(p, 0, sizeof(*p));
+
+ // {"errcode":xxx}
+ double v;
+
+ // errcode
+ rc = mjson_get_number(
+ /* s */ str,
+ /* len */ (int)len,
+ /* path */ "$.errcode",
+ /* result */ &v);
+ if (rc > 0) {
+ p->errcode = (int32_t)v;
+ } else {
+ BLEPROTO_T_E("Error parse errcode");
+ return -1;
+ }
+
+ return (0);
+}
+
+int bleproto_decjson_authdelete_req(const uint8_t * data,
+ uint16_t len,
+ bleproto_authdelete_req_t *p)
+{
+ int rc;
+
+ /* check param */
+ if (!data || len == 0 || !p) {
+ BLEPROTO_T_E("Invalid parameters");
+ return -1;
+ }
+
+ const char *str = (const char *)data;
+ /* dump input data */
+ BLEPROTO_T_D("data:%.*s", (int)len, str);
+
+ /* clear */
+ memset(p, 0, sizeof(*p));
+
+ // {"authcode": "xxxx"}
+ char value_str[BLEPROTO_APPDATA_DATA_MAX_SZ] = { 0 };
+
+ // authcode
+ rc = mjson_get_string(
+ /* s */ str,
+ /* len */ (int)len,
+ /* path */ "$.authcode",
+ /* to */ value_str,
+ /* n */ (int)sizeof(value_str));
+ if (rc > 0) {
+ snprintf(p->authcode, sizeof(p->authcode), "%s", value_str);
+ } else {
+ BLEPROTO_T_E("Error parse authcode");
+ return -1;
+ }
+
+ return (0);
+}
+
+int bleproto_decjson_authdelete_rsp(const uint8_t * data,
+ uint16_t len,
+ bleproto_authdelete_rsp_t *p)
+{
+ int rc;
+
+ /* check param */
+ if (!data || len == 0 || !p) {
+ BLEPROTO_T_E("Invalid parameters");
+ return -1;
+ }
+
+ const char *str = (const char *)data;
+ /* dump input data */
+ BLEPROTO_T_D("data:%.*s", (int)len, str);
+
+ /* clear */
+ memset(p, 0, sizeof(*p));
+
+ // {"gwmac":"xxxx","errcode":xxx}
+ char value_str[BLEPROTO_APPDATA_DATA_MAX_SZ] = { 0 };
+ double v;
+
+ // gwmac
+ rc = mjson_get_string(
+ /* s */ str,
+ /* len */ (int)len,
+ /* path */ "$.gwmac",
+ /* to */ value_str,
+ /* n */ (int)sizeof(value_str));
+ if (rc > 0) {
+ int nr = proto_strhex_to_byte(value_str, p->gwmac, sizeof(p->gwmac));
+ if (nr != (int)sizeof(p->gwmac)) {
+ BLEPROTO_T_E("Error parse gwmac");
+ return -1;
+ }
+ } else {
+ BLEPROTO_T_E("Error parse gwmac");
+ return -1;
+ }
+
+ // errcode
+ rc = mjson_get_number(
+ /* s */ str,
+ /* len */ (int)len,
+ /* path */ "$.errcode",
+ /* result */ &v);
+ if (rc > 0) {
+ p->errcode = (int32_t)v;
+ } else {
+ BLEPROTO_T_E("Error parse errcode");
+ return -1;
+ }
+
+ return (0);
+}
+
+int bleproto_decjson_runcmd_req(const uint8_t * data,
+ uint16_t len,
+ bleproto_runcmd_req_t *p)
+{
+ int rc, i;
+
+ /* check param */
+ if (!data || len == 0 || !p) {
+ BLEPROTO_T_E("Invalid parameters");
+ return -1;
+ }
+
+ const char *str = (const char *)data;
+ /* dump input data */
+ BLEPROTO_T_D("data:%.*s", (int)len, str);
+
+ /* clear */
+ memset(p, 0, sizeof(*p));
+
+ // {"cmd_id":xxxx,"arg_int32":[],"arg_string":[],"arg_bytes":"xxxx","t":"xxxxxxxx" }
+ char value_str[BLEPROTO_APPDATA_DATA_MAX_SZ] = { 0 };
+ double v;
+
+ // cmd_id
+ rc = mjson_get_number(
+ /* s */ str,
+ /* len */ (int)len,
+ /* path */ "$.cmd_id",
+ /* v */ &v);
+ if (rc > 0) {
+ p->ycmd.cmd_id = (int)v;
+ } else {
+ BLEPROTO_T_E("Error parse cmd_id");
+ return -1;
+ }
+
+ // arg_int32
+ for (i = 0; i < YCMD_INT32_MAX_COUNT; i++) {
+ const char *ptr = NULL;
+ int n;
+ char key[sizeof("$.arg_int32[65535]") + 1] = { 0 };
+ snprintf(key, sizeof(key), "$.arg_int32[%d]", i);
+ if (mjson_find(str, (int)len, key, &ptr, &n) == MJSON_TOK_NUMBER) {
+ char vstr[32] = { 0 };
+ memcpy(vstr, ptr, UTILS_MIN(n, 31));
+ p->ycmd.arg_int32[p->ycmd.arg_int32_count] =
+ (int32_t)strtol(vstr, NULL, 10);
+ p->ycmd.arg_int32_count++;
+ }
+ }
+
+ // arg_string
+ for (i = 0; i < YCMD_STRING_MAX_COUNT; i++) {
+ const char *ptr = NULL;
+ int n;
+ char key[sizeof("$.arg_string[65535]") + 1] = { 0 };
+ snprintf(key, sizeof(key), "$.arg_string[%d]", i);
+ if (mjson_find(str, (int)len, key, &ptr, &n) == MJSON_TOK_STRING) {
+ if (n >= 2 && ptr[0] == '"' && ptr[n - 1] == '"') {
+ ptr++; // 跳过首引号
+ n -= 2; // 去掉首尾引号的长度
+ } else {
+ BLEPROTO_T_E("Error parse arg_string");
+ return -1;
+ }
+ memcpy(p->ycmd.arg_string[p->ycmd.arg_string_count],
+ ptr,
+ UTILS_MIN(n, YCMD_STRING_MAX_SIZE));
+ p->ycmd.arg_string_count++;
+ }
+ }
+
+ // arg_bytes
+ rc = mjson_get_string(
+ /* s */ str,
+ /* len */ (int)len,
+ /* path */ "$.arg_bytes",
+ /* to */ value_str,
+ /* n */ (int)sizeof(value_str));
+ if (rc > 0) {
+ // strhex to byte
+ rc = proto_strhex_to_byte(
+ value_str, p->ycmd.arg_bytes, sizeof(p->ycmd.arg_bytes));
+ if (rc >= 0) {
+ p->ycmd.arg_bytes_count = (uint16_t)rc;
+ }
+ }
+
+ // t
+ rc = mjson_get_string(
+ /* s */ str,
+ /* len */ (int)len,
+ /* path */ "$.t",
+ /* to */ value_str,
+ /* n */ (int)sizeof(value_str));
+ if (rc > 0) {
+ p->ycmd.t = (uint64_t)strtoull(value_str, NULL, 10);
+ } else {
+ BLEPROTO_T_E("Error parse t");
+ return -1;
+ }
+
+ return (0);
+}
+
+int bleproto_decjson_runcmd_rsp(const uint8_t * data,
+ uint16_t len,
+ bleproto_runcmd_rsp_t *p)
+{
+ int rc, i;
+
+ /* check param */
+ if (!data || len == 0 || !p) {
+ BLEPROTO_T_E("Invalid parameters");
+ return -1;
+ }
+
+ const char *str = (const char *)data;
+ /* dump input data */
+ BLEPROTO_T_D("data:%.*s", (int)len, str);
+
+ /* clear */
+ memset(p, 0, sizeof(*p));
+
+ // {"cmd_id":xxxx,"arg_int32":[],"arg_string":[],"arg_bytes":"xxxx","t":"xxxxxxxx" }
+ char value_str[BLEPROTO_APPDATA_DATA_MAX_SZ] = { 0 };
+ double v;
+
+ // cmd_id
+ rc = mjson_get_number(
+ /* s */ str,
+ /* len */ (int)len,
+ /* path */ "$.cmd_id",
+ /* v */ &v);
+ if (rc > 0) {
+ p->ycmd.cmd_id = (int)v;
+ } else {
+ BLEPROTO_T_E("Error parse cmd_id");
+ return -1;
+ }
+
+ // arg_int32
+ for (i = 0; i < YCMD_INT32_MAX_COUNT; i++) {
+ const char *ptr = NULL;
+ int n;
+ char key[sizeof("$.arg_int32[65535]") + 1] = { 0 };
+ snprintf(key, sizeof(key), "$.arg_int32[%d]", i);
+ if (mjson_find(str, (int)len, key, &ptr, &n) == MJSON_TOK_NUMBER) {
+ char vstr[32] = { 0 };
+ memcpy(vstr, ptr, UTILS_MIN(n, 31));
+ p->ycmd.arg_int32[p->ycmd.arg_int32_count] =
+ (int32_t)strtol(vstr, NULL, 10);
+ p->ycmd.arg_int32_count++;
+ }
+ }
+
+ // arg_string
+ for (i = 0; i < YCMD_STRING_MAX_COUNT; i++) {
+ const char *ptr = NULL;
+ int n;
+ char key[sizeof("$.arg_string[65535]") + 1] = { 0 };
+ snprintf(key, sizeof(key), "$.arg_string[%d]", i);
+ if (mjson_find(str, (int)len, key, &ptr, &n) == MJSON_TOK_STRING) {
+ if (n >= 2 && ptr[0] == '"' && ptr[n - 1] == '"') {
+ ptr++; // 跳过首引号
+ n -= 2; // 去掉首尾引号的长度
+ } else {
+ BLEPROTO_T_E("Error parse arg_string");
+ return -1;
+ }
+ memcpy(p->ycmd.arg_string[p->ycmd.arg_string_count],
+ ptr,
+ UTILS_MIN(n, YCMD_STRING_MAX_SIZE));
+ p->ycmd.arg_string_count++;
+ }
+ }
+
+ // arg_bytes
+ rc = mjson_get_string(
+ /* s */ str,
+ /* len */ (int)len,
+ /* path */ "$.arg_bytes",
+ /* to */ value_str,
+ /* n */ (int)sizeof(value_str));
+ if (rc > 0) {
+ // strhex to byte
+ rc = proto_strhex_to_byte(
+ value_str, p->ycmd.arg_bytes, sizeof(p->ycmd.arg_bytes));
+ if (rc >= 0) {
+ p->ycmd.arg_bytes_count = (uint16_t)rc;
+ }
+ }
+
+ // t
+ rc = mjson_get_string(
+ /* s */ str,
+ /* len */ (int)len,
+ /* path */ "$.t",
+ /* to */ value_str,
+ /* n */ (int)sizeof(value_str));
+ if (rc > 0) {
+ p->ycmd.t = (uint64_t)strtoull(value_str, NULL, 10);
+ } else {
+ BLEPROTO_T_E("Error parse t");
+ return -1;
+ }
+
+ return (0);
+}
+
+int bleproto_decjson_reportcmd_req(const uint8_t * data,
+ uint16_t len,
+ bleproto_reportcmd_req_t *p)
+{
+ int rc, i;
+
+ /* check param */
+ if (!data || len == 0 || !p) {
+ BLEPROTO_T_E("Invalid parameters");
+ return -1;
+ }
+
+ const char *str = (const char *)data;
+ /* dump input data */
+ BLEPROTO_T_D("data:%.*s", (int)len, str);
+
+ /* clear */
+ memset(p, 0, sizeof(*p));
+
+ // {"cmd_id":xxxx,"arg_int32":[],"arg_string":[],"arg_bytes":"xxxx","t":"xxxxxxxx" }
+ char value_str[BLEPROTO_APPDATA_DATA_MAX_SZ] = { 0 };
+ double v;
+
+ // cmd_id
+ rc = mjson_get_number(
+ /* s */ str,
+ /* len */ (int)len,
+ /* path */ "$.cmd_id",
+ /* v */ &v);
+ if (rc > 0) {
+ p->ycmd.cmd_id = (int)v;
+ } else {
+ BLEPROTO_T_E("Error parse cmd_id");
+ return -1;
+ }
+
+ // arg_int32
+ for (i = 0; i < YCMD_INT32_MAX_COUNT; i++) {
+ const char *ptr = NULL;
+ int n;
+ char key[sizeof("$.arg_int32[65535]") + 1] = { 0 };
+ snprintf(key, sizeof(key), "$.arg_int32[%d]", i);
+ if (mjson_find(str, (int)len, key, &ptr, &n) == MJSON_TOK_NUMBER) {
+ char vstr[32] = { 0 };
+ memcpy(vstr, ptr, UTILS_MIN(n, 31));
+ p->ycmd.arg_int32[p->ycmd.arg_int32_count] =
+ (int32_t)strtol(vstr, NULL, 10);
+ p->ycmd.arg_int32_count++;
+ }
+ }
+
+ // arg_string
+ for (i = 0; i < YCMD_STRING_MAX_COUNT; i++) {
+ const char *ptr = NULL;
+ int n;
+ char key[sizeof("$.arg_string[65535]") + 1] = { 0 };
+ snprintf(key, sizeof(key), "$.arg_string[%d]", i);
+ if (mjson_find(str, (int)len, key, &ptr, &n) == MJSON_TOK_STRING) {
+ if (n >= 2 && ptr[0] == '"' && ptr[n - 1] == '"') {
+ ptr++; // 跳过首引号
+ n -= 2; // 去掉首尾引号的长度
+ } else {
+ BLEPROTO_T_E("Error parse arg_string");
+ return -1;
+ }
+ memcpy(p->ycmd.arg_string[p->ycmd.arg_string_count],
+ ptr,
+ UTILS_MIN(n, YCMD_STRING_MAX_SIZE));
+ p->ycmd.arg_string_count++;
+ }
+ }
+
+ // arg_bytes
+ rc = mjson_get_string(
+ /* s */ str,
+ /* len */ (int)len,
+ /* path */ "$.arg_bytes",
+ /* to */ value_str,
+ /* n */ (int)sizeof(value_str));
+ if (rc > 0) {
+ // strhex to byte
+ rc = proto_strhex_to_byte(
+ value_str, p->ycmd.arg_bytes, sizeof(p->ycmd.arg_bytes));
+ if (rc >= 0) {
+ p->ycmd.arg_bytes_count = (uint16_t)rc;
+ }
+ }
+
+ // t
+ rc = mjson_get_string(
+ /* s */ str,
+ /* len */ (int)len,
+ /* path */ "$.t",
+ /* to */ value_str,
+ /* n */ (int)sizeof(value_str));
+ if (rc > 0) {
+ p->ycmd.t = (uint64_t)strtoull(value_str, NULL, 10);
+ } else {
+ BLEPROTO_T_E("Error parse t");
+ return -1;
+ }
+
+ return (0);
+}
+
+int bleproto_decjson_reportcmd_rsp(const uint8_t * data,
+ uint16_t len,
+ bleproto_reportcmd_rsp_t *p)
+{
+ int rc;
+
+ /* check param */
+ if (!data || len == 0 || !p) {
+ BLEPROTO_T_E("Invalid parameters");
+ return -1;
+ }
+
+ const char *str = (const char *)data;
+ /* dump input data */
+ BLEPROTO_T_D("data:%.*s", (int)len, str);
+
+ /* clear */
+ memset(p, 0, sizeof(*p));
+
+ // {"errcode":xxx}
+ double v;
+
+ // errcode
+ rc = mjson_get_number(
+ /* s */ str,
+ /* len */ (int)len,
+ /* path */ "$.errcode",
+ /* result */ &v);
+ if (rc > 0) {
+ p->errcode = (int32_t)v;
+ } else {
+ BLEPROTO_T_E("Error parse errcode");
+ return -1;
+ }
+
+ return (0);
+}
+
+int bleproto_decjson_doaction_req(const uint8_t * data,
+ uint16_t len,
+ bleproto_doaction_req_t *p)
+{
+ int rc;
+
+ /* check param */
+ if (!data || len == 0 || !p) {
+ BLEPROTO_T_E("Invalid parameters");
+ return -1;
+ }
+
+ const char *str = (const char *)data;
+ /* dump input data */
+ BLEPROTO_T_D("data:%.*s", (int)len, str);
+
+ /* clear */
+ memset(p, 0, sizeof(*p));
+
+ // {"action":%d}
+ double v;
+
+ // action
+ rc = mjson_get_number(
+ /* s */ str,
+ /* len */ (int)len,
+ /* path */ "$.action",
+ /* v */ &v);
+ if (rc > 0) {
+ p->action = (int)v;
+ } else {
+ BLEPROTO_T_E("Error parse action");
+ return -1;
+ }
+
+ return (0);
+}
+
+int bleproto_decjson_doaction_rsp(const uint8_t * data,
+ uint16_t len,
+ bleproto_doaction_rsp_t *p)
+{
+ int rc;
+
+ /* check param */
+ if (!data || len == 0 || !p) {
+ BLEPROTO_T_E("Invalid parameters");
+ return -1;
+ }
+
+ const char *str = (const char *)data;
+ /* dump input data */
+ BLEPROTO_T_D("data:%.*s", (int)len, str);
+
+ /* clear */
+ memset(p, 0, sizeof(*p));
+
+ // {"errcode":xxx}
+ double v;
+
+ // errcode
+ rc = mjson_get_number(
+ /* s */ str,
+ /* len */ (int)len,
+ /* path */ "$.errcode",
+ /* result */ &v);
+ if (rc > 0) {
+ p->errcode = (int32_t)v;
+ } else {
+ BLEPROTO_T_E("Error parse errcode");
+ return -1;
+ }
+
+ return (0);
+}
+
+int bleproto_decjson_otanotify_req(const uint8_t * data,
+ uint16_t len,
+ bleproto_otanotify_req_t *p)
+{
+ int rc;
+
+ /* check param */
+ if (!data || len == 0 || !p) {
+ BLEPROTO_T_E("Invalid parameters");
+ return -1;
+ }
+
+ const char *str = (const char *)data;
+ /* dump input data */
+ BLEPROTO_T_D("data:%.*s", (int)len, str);
+
+ /* clear */
+ memset(p, 0, sizeof(*p));
+
+ // {"id": %d, "ver":"xxxx", "size":%d, "md5":"xxxxxxx"}
+ char value_str[BLEPROTO_APPDATA_DATA_MAX_SZ] = { 0 };
+ double v;
+
+ // id
+ rc = mjson_get_number(
+ /* s */ str,
+ /* len */ (int)len,
+ /* path */ "$.id",
+ /* result */ &v);
+ if (rc > 0) {
+ p->id = (int)v;
+ } else {
+ BLEPROTO_T_E("Error parse errcode");
+ return -1;
+ }
+
+ // ver
+ rc = mjson_get_string(
+ /* s */ str,
+ /* len */ (int)len,
+ /* path */ "$.ver",
+ /* to */ value_str,
+ /* n */ (int)sizeof(value_str));
+ if (rc > 0) {
+ snprintf(p->version, sizeof(p->version), "%s", value_str);
+ } else {
+ BLEPROTO_T_E("Error parse version");
+ return -1;
+ }
+
+ // size
+ rc = mjson_get_number(
+ /* s */ str,
+ /* len */ (int)len,
+ /* path */ "$.size",
+ /* result */ &v);
+ if (rc > 0) {
+ p->size = (uint32_t)v;
+ } else {
+ BLEPROTO_T_E("Error parse errcode");
+ return -1;
+ }
+
+ // md5
+ rc = mjson_get_string(
+ /* s */ str,
+ /* len */ (int)len,
+ /* path */ "$.md5",
+ /* to */ value_str,
+ /* n */ (int)sizeof(value_str));
+ if (rc > 0) {
+ snprintf(p->md5, sizeof(p->md5), "%s", value_str);
+ } else {
+ BLEPROTO_T_E("Error parse md5");
+ return -1;
+ }
+
+ return (0);
+}
+
+int bleproto_decjson_otanotify_rsp(const uint8_t * data,
+ uint16_t len,
+ bleproto_otanotify_rsp_t *p)
+{
+ int rc;
+
+ /* check param */
+ if (!data || len == 0 || !p) {
+ BLEPROTO_T_E("Invalid parameters");
+ return -1;
+ }
+
+ const char *str = (const char *)data;
+ /* dump input data */
+ BLEPROTO_T_D("data:%.*s", (int)len, str);
+
+ /* clear */
+ memset(p, 0, sizeof(*p));
+
+ // {"errcode":xxx}
+ double v;
+
+ // errcode
+ rc = mjson_get_number(
+ /* s */ str,
+ /* len */ (int)len,
+ /* path */ "$.errcode",
+ /* result */ &v);
+ if (rc > 0) {
+ p->errcode = (int32_t)v;
+ } else {
+ BLEPROTO_T_E("Error parse errcode");
+ return -1;
+ }
+
+ return (0);
+}
+
+int bleproto_decjson_otadata_req(const uint8_t * data,
+ uint16_t len,
+ bleproto_otadata_req_t *p)
+{
+ int rc;
+
+ /* check param */
+ if (!data || len == 0 || !p) {
+ BLEPROTO_T_E("Invalid parameters");
+ return -1;
+ }
+
+ const char *str = (const char *)data;
+ /* dump input data */
+ BLEPROTO_T_D("data:%.*s", (int)len, str);
+
+ /* clear */
+ memset(p, 0, sizeof(*p));
+
+ // {"id": %d, "offset":%d, "maxsize":%d}
+ double v;
+
+ // id
+ rc = mjson_get_number(
+ /* s */ str,
+ /* len */ (int)len,
+ /* path */ "$.id",
+ /* result */ &v);
+ if (rc > 0) {
+ p->id = (int)v;
+ } else {
+ BLEPROTO_T_E("Error parse errcode");
+ return -1;
+ }
+
+ // offset
+ rc = mjson_get_number(
+ /* s */ str,
+ /* len */ (int)len,
+ /* path */ "$.offset",
+ /* result */ &v);
+ if (rc > 0) {
+ p->offset = (int32_t)v;
+ } else {
+ BLEPROTO_T_E("Error parse offset");
+ return -1;
+ }
+
+ // maxsize
+ rc = mjson_get_number(
+ /* s */ str,
+ /* len */ (int)len,
+ /* path */ "$.maxsize",
+ /* result */ &v);
+ if (rc > 0) {
+ p->maxsize = (uint32_t)v;
+ } else {
+ BLEPROTO_T_E("Error parse maxsize");
+ return -1;
+ }
+
+ return (0);
+}
+
+int bleproto_debin_otadata_rsp(const uint8_t * data,
+ uint16_t len,
+ bleproto_otadata_rsp_t *rsp)
+{
+ int offset = 0;
+
+ /* check param */
+ if (!data || len == 0 || !rsp) {
+ BLEPROTO_T_E("Invalid parameters");
+ return -1;
+ }
+
+ /* check minimum buffer size (errcode + id + offset + len = 16 bytes) */
+ if (len < 16) {
+ BLEPROTO_T_E("Buffer too small");
+ return -1;
+ }
+
+ /* deserialize errcode (little-endian) */
+ rsp->errcode =
+ ((int32_t)data[offset]) | ((int32_t)data[offset + 1] << 8) |
+ ((int32_t)data[offset + 2] << 16) | ((int32_t)data[offset + 3] << 24);
+ offset += 4;
+
+ /* deserialize id (little-endian) */
+ rsp->id = ((uint32_t)data[offset]) | ((uint32_t)data[offset + 1] << 8) |
+ ((uint32_t)data[offset + 2] << 16) |
+ ((uint32_t)data[offset + 3] << 24);
+ offset += 4;
+
+ /* deserialize offset (little-endian) */
+ rsp->offset = ((uint32_t)data[offset]) |
+ ((uint32_t)data[offset + 1] << 8) |
+ ((uint32_t)data[offset + 2] << 16) |
+ ((uint32_t)data[offset + 3] << 24);
+ offset += 4;
+
+ /* deserialize len (little-endian) */
+ rsp->len = ((uint32_t)data[offset]) | ((uint32_t)data[offset + 1] << 8) |
+ ((uint32_t)data[offset + 2] << 16) |
+ ((uint32_t)data[offset + 3] << 24);
+ offset += 4;
+
+ /* check data length validity */
+ if (rsp->len > BLEPROTO_APPDATA_OTADATA_SZ) {
+ BLEPROTO_T_E("Data length too large: %u", rsp->len);
+ return -1;
+ }
+
+ /* check remaining buffer size */
+ if (len < (offset + rsp->len)) {
+ BLEPROTO_T_E("Insufficient data for payload");
+ return -1;
+ }
+
+ /* 零拷贝:指向输入缓冲,调用方须在下次 decode 前用完 */
+ if (rsp->len > 0) {
+ rsp->data = &data[offset];
+ offset += rsp->len;
+ } else {
+ rsp->data = NULL;
+ }
+
+ return offset;
+}
+/****************************************************************************/
+/* */
+/* End of file. */
+/* */
+/****************************************************************************/
diff --git a/apps/usr_le_code/bleproto_packer.h b/apps/usr_le_code/bleproto_packer.h
new file mode 100644
index 0000000..8ec82c1
--- /dev/null
+++ b/apps/usr_le_code/bleproto_packer.h
@@ -0,0 +1,702 @@
+/****************************************************************************/
+/* bleproto_packer.h
+ *
+ * Copyright (C) 2020 wanshijie wanshijie@126.com
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 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 General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ *
+ ****************************************************************************/
+/**
+ * @addtogroup bleproto_packer packer
+ * @ingroup bleproto_api
+ * @brief ble proto packer
+ *
+ * @{
+ */
+#ifndef BLEPROTO_PACKER_H_INCLUDE
+#define BLEPROTO_PACKER_H_INCLUDE
+/****************************************************************************/
+/* Included Files */
+/****************************************************************************/
+
+#include "system/includes.h"
+
+
+#if !defined(BLEPROTO_API_H_INCLUDE)
+#error "Only 'bleproto/bleproto_api.h' can be included directly."
+#endif /* BLEPROTO_API_H_INCLUDE */
+
+/****************************************************************************/
+/* Configure Definitions */
+/****************************************************************************/
+
+#define BLEPOROTO_RAM_LARGE 0 ///< 大內存模式
+#define BLEPOROTO_RAM_MID 1 ///< 中等內存模式
+#define BLEPOROTO_RAM_SMALL 2 ///< 小內存模式
+
+/* default 內存模式 */
+#ifndef BLEPOROTO_RAM_MODE
+//#define BLEPOROTO_RAM_MODE BLEPOROTO_RAM_LARGE
+//#define BLEPOROTO_RAM_MODE BLEPOROTO_RAM_MID
+#define BLEPOROTO_RAM_MODE BLEPOROTO_RAM_SMALL
+#endif /* BLEPOROTO_RAM_MODE */
+
+/****************************************************************************/
+/* Pre-processor Definitions */
+/****************************************************************************/
+
+///////////////////////////////////////////////////////////
+// trace log define
+///////////////////////////////////////////////////////////
+#ifndef BLEPROTO_TRACE_ENABLE
+#define BLEPROTO_TRACE_ENABLE 0//Jim
+#endif /* BLEPROTO_TRACE_ENABLE */
+
+/* trace default printf */
+#ifndef BLEPROTO_TRACE_PRINTF
+#define BLEPROTO_TRACE_PRINTF printf
+#endif /* BLEPROTO_TRACE_PRINTF */
+
+/* trace strfunc */
+#if defined(__STDC_VERSION__) && __STDC_VERSION__ >= 19901L
+#define BLEPROTO_TRACE_STRFUNC ((const char *)(__func__))
+#else
+#define BLEPROTO_TRACE_STRFUNC ((const char *)(__FUNCTION__))
+#endif /* __STDC_VERSION__ */
+/* trace file line */
+#define BLEPROTO_TRACE_INTLINE ((int)(__LINE__))
+
+#if BLEPROTO_TRACE_ENABLE
+#define BLEPROTO_TRACE(lvl, ...) \
+ do { \
+ BLEPROTO_TRACE_PRINTF("[%s][%s:%d]", \
+ lvl, \
+ BLEPROTO_TRACE_STRFUNC, \
+ BLEPROTO_TRACE_INTLINE); \
+ BLEPROTO_TRACE_PRINTF(__VA_ARGS__); \
+ BLEPROTO_TRACE_PRINTF("\r\n"); \
+ } while (0)
+#else
+#define BLEPROTO_TRACE(lvl, ...) \
+ do { \
+ } while (0)
+#endif /* FLOG_TRACE_ENABLE */
+
+/* trace log error */
+#ifndef BLEPROTO_T_E
+#define BLEPROTO_T_E(...) BLEPROTO_TRACE("E", __VA_ARGS__)
+#endif /* BLEPROTO_T_E */
+
+/* trace log debug */
+#ifndef BLEPROTO_T_D
+#define BLEPROTO_T_D(...) BLEPROTO_TRACE("D", __VA_ARGS__)
+#endif /* BLEPROTO_T_D */
+
+/* printf log slient */
+#ifndef BLEPROTO_T_S
+#define BLEPROTO_T_S(...)
+#endif /* BLEPROTO_T_S */
+
+// clang-format off
+///////////////////////////////////////////////////////////
+// ADV
+///////////////////////////////////////////////////////////
+/** ADV Data Max Size. */
+#define BLEPROTO_ADV_MAX_SZ 31
+
+/** ADV Type: Flags. */
+#define BLEPROTO_ADV_TYPE_FLAGS 0x01
+/** ADV Type: Service Data - 16-bit UUID. */
+#define BLEPROTO_ADV_TYPE_SVC_DATA_UUID16 0x16
+/** ADV Type: Manufacturer Specific Data. */
+#define BLEPROTO_ADV_TYPE_MFG_DATA 0xff
+
+/** ADV service uuid */
+#define BLEPROTO_ADV_SERVICE_UUID_TOBIND 0xFDEE
+/** ADV service spec data version */
+#define BLEPORTO_ADV_SERVICE_SPEC_DATA_VER 0x01
+/** ADV service spec data business */
+#define BELPROTO_ADV_SERVICE_SPEC_DATA_BUSINESS_NEARFIND 0x01
+
+/* ADV TLV Type */
+#define BLEPROTO_ADV_TLV_TYPE_MANUCODE 0x10
+#define BLEPROTO_ADV_TLV_TYPE_PRODCODE 0x11
+/* ADV TLV Len */
+#define BLEPROTO_ADV_TLV_LENGTH_MANUCODE 4
+#define BLEPROTO_ADV_TLV_LENGTH_PRODCODE 4
+
+/* ADV PCDE */
+#define BLE_PROTO_ADV_LENGTH_PCODE 6
+
+/** ADV flag value */
+#define BLEPROTO_ADV_FLAG_HEARTBEAT 0x00
+#define BLEPROTO_ADV_FLAG_RECONNECT 0x01
+
+///////////////////////////////////////////////////////////
+// APPDATA
+///////////////////////////////////////////////////////////
+/** APPDATA header len 8bytes */
+#define BLEPROTO_APPDATA_HEADR_LEN 8
+/** APPDATA version */
+#define BLEPROTO_APPDATA_VERSION 0
+/** APPDATA data fmt */
+#define BLEPROTO_APPDATA_DATAFMT_JSON 0
+#define BLEPROTO_APPDATA_DATAFMT_RAW 1
+/** APPDATA msg type */
+#define BLEPROTO_APPDATA_MSGTYPE_REQ 0
+#define BLEPROTO_APPDATA_MSGTYPE_RSP 1
+
+#if (BLEPOROTO_RAM_MODE == BLEPOROTO_RAM_LARGE)
+/** APPDATA OTA data max size */
+#define BLEPROTO_APPDATA_OTADATA_SZ (1024*16)
+/** APPDATA data max size */
+#define BLEPROTO_APPDATA_DATA_MAX_SZ (BLEPROTO_APPDATA_OTADATA_SZ + 16 + 16)
+/** APP tx buf max size */
+#define BLEPROTO_TXRXBUF_MAX_SZ (BLEPROTO_APPDATA_DATA_MAX_SZ + 1024 * 2)
+#elif (BLEPOROTO_RAM_MODE == BLEPOROTO_RAM_MID)
+/** APPDATA OTA data max size */
+#define BLEPROTO_APPDATA_OTADATA_SZ (1024*4)
+/** APPDATA data max size */
+#define BLEPROTO_APPDATA_DATA_MAX_SZ (BLEPROTO_APPDATA_OTADATA_SZ + 16 + 16)
+/** APP tx buf max size */
+#define BLEPROTO_TXRXBUF_MAX_SZ (BLEPROTO_APPDATA_DATA_MAX_SZ + 1024 * 2)
+#else
+/** APPDATA OTA data max size */
+#define BLEPROTO_APPDATA_OTADATA_SZ (1024+1024+256)
+/** APPDATA data max size */
+#define BLEPROTO_APPDATA_DATA_MAX_SZ (BLEPROTO_APPDATA_OTADATA_SZ + 16 + 16)
+/** APP tx buf max size */
+//#define BLEPROTO_TXRXBUF_MAX_SZ (BLEPROTO_APPDATA_DATA_MAX_SZ + 1024 * 2)
+#endif /* BLEPOROTO_RAM_MODE */
+
+// clang-format on
+
+/****************************************************************************/
+/* Public Types */
+/****************************************************************************/
+
+/**
+ * @brief 厂商编码-manucode(manufacturer code) TLV desc.
+ */
+typedef struct bleproto_adv_manucode {
+ // clang-format off
+ uint8_t type; ///< 厂商编码T, @ref BLEPROTO_ADV_TLV_TYPE_MANUCODE
+ uint8_t length; ///< 厂商编码L, @ref BLEPROTO_ADV_TLV_LEN_MANUCODE
+ uint8_t value[BLEPROTO_ADV_TLV_LENGTH_MANUCODE]; ///< 厂商信息V, 现在固定填写0x00000000
+ // clang-format off
+} bleproto_adv_manucode_t;
+
+/**
+ * @brief 产品型号-prodcode(product code) TLV desc.
+ */
+typedef struct bleproto_adv_prodcode {
+ // clang-format off
+ uint8_t type; ///< 产品型号T, @ref BLEPROTO_ADV_TLV_TYPE_PRODCODE
+ uint8_t length; ///< 产品型号L, @ref BLEPROTO_ADV_TLV_LENGTH_PRODCODE
+ uint8_t value[BLEPROTO_ADV_TLV_LENGTH_PRODCODE]; ///< 产品型号V, 平台定义,需要转换成ASCII码值
+ // clang-format on
+} bleproto_adv_prodcode_t;
+
+/**
+ * @brief 请求配对广播的Spec Data结构.
+ */
+typedef struct bleproto_adv_specdata {
+ // clang-format off
+ uint8_t version; ///< 蓝牙广播协议版本, 当前1 @ref BLEPORTO_ADV_SERVICE_SPEC_DATA_VER
+ uint8_t business; ///< 设备发现模式, 固定填写0x01,表示靠近发现 @ref BELPROTO_ADV_SERVICE_SPEC_DATA_BUSINESS_NEARFIND
+ uint8_t rfu[2]; ///< 保留
+ int8_t txpower; ///< 蓝牙发射功率[-127,128]dBm
+ bleproto_adv_manucode_t manucode; ///< 厂商编码
+ bleproto_adv_prodcode_t prodcode; ///< 产品型号
+ uint8_t separator; ///< 分隔符, 固定填写0xFF
+ uint8_t selfdata[6]; ///< 自定义数据
+ // clang-format on
+} bleproto_adv_specdata_t;
+
+/**
+ * @brief 请求注册广播数据.
+ */
+typedef struct bleproto_advdata_service {
+ // clang-format off
+ uint16_t uuid; ///< 服务uuid16 @ref BLEPROTO_ADV_SERVICE_UUID_TOBIND
+ bleproto_adv_specdata_t spec_data;///< 协议数据(24bytes)
+ // clang-format on
+} bleproto_advdata_service_t;
+
+/**
+ * @brief 心跳广播, 回连广播数据.
+ */
+typedef struct bleproto_advdata_mfg {
+ // clang-format off
+ uint8_t siot[6]; ///< 固定填写SIOT-1
+ uint8_t flag; ///< 0表示心跳,1表示请求回连 @ref BLEPROTO_ADV_FLAG_HEARTBEAT or @ref BLEPROTO_ADV_FLAG_RECONNECT
+ int8_t txpower; ///< 蓝牙发射功率[-127,128]dBm
+ uint8_t gwmac[6]; ///< gwmac "11:22:33:44:55:66", gwmac[6] = {0x11, 0x22, 0x33, 0x44, 0x55, 0x66 }
+ bleproto_adv_manucode_t manucode; ///< 厂商编码
+ bleproto_adv_prodcode_t prodcode; ///< 产品型号
+ // clang-format on
+} bleproto_advdata_mfg_t;
+
+/**
+ * @brief AD Structure1结构.
+ */
+typedef struct bleproto_adv1 {
+ // clang-format off
+ /**
+ * 表示AD Type与AD Data的总长度,
+ * 此处取值固定为0x02
+ */
+ uint8_t length;
+
+ /**
+ * 表示该广播数据代表的含义
+ * 此处取值固定为0x01 @ref BLEPROTO_ADV_TYPE_FLAGS
+ */
+ uint8_t ad_type;
+
+ /**
+ * 固定为0x06,表示LE通用可发现模式,且不支持BR/EDR
+ * 表示蓝牙设备的物理连接能力,
+ * bit0:LE受限可发现模式。
+ * bit1:LE通用可发现模式。
+ * bit2:不支持BR/EDR。
+ * bit3:对Same Device Capable(控制器)同时支持BLE和BR/EDR。
+ * bit4:对Same Device Capable(主机)同时支持BLE和BR/EDR。
+ * bit5~7:预留
+ */
+ uint8_t ad_data;
+ // clang-format on
+} bleproto_adv1_t;
+
+/**
+ * @brief AD Structure2结构.
+ */
+typedef struct bleproto_adv2 {
+ // clang-format off
+ /**
+ * 表示AD Type与AD Data的总长度,
+ * 此处取值固定为0x1B = 27
+ */
+ uint8_t length;
+
+ /** 广播数据代表的含义
+ * BLEPROTO_ADV_TYPE_SVC_DATA_UUID16 - 0x16表示蓝牙服务数据(bleproto_advdata_service_t),
+ * BLEPROTO_ADV_TYPE_MFG_DATA - 0xFF表示厂商数据(bleproto_advdata_mfg_t)
+ */
+ uint8_t ad_type;
+
+ /** adv data */
+ union {
+ bleproto_advdata_service_t service_data; ///< 蓝牙服务数据(请求注册广播时携带)
+ bleproto_advdata_mfg_t mfg_data; ///< 厂商数据(心跳广播,回连广播时携带)
+ } ad_data;
+ // clang-format on
+} bleproto_adv2_t;
+
+/**
+ * @brief 广播数据总结构
+ */
+typedef struct bleproto_adv {
+ bleproto_adv1_t adv1; ///< ADV Structure1
+ bleproto_adv2_t adv2; ///< ADV Structure2
+} bleproto_adv_t;
+
+/**
+ * @brief 应用协议报文头(8字节)
+ */
+typedef struct bleproto_appdata_header {
+ // clang-format off
+ uint8_t version : 3; ///< byte0[2:0]:蓝牙BLE应用层协议的版本号,当前为0,根据业务演进递增 @ref BLEPROTO_APPDATA_VERSION
+ uint8_t datafmt : 1; ///< byte0[3:3]:数据格式, 当前只支持JSON字符串格式,取值固定为0, @ref BLEPROTO_APPDATA_DATAFMT_JSON
+ uint8_t msgtype : 4; ///< byte0[7:4]:消息类型, 包括:请求(0=req)、响应(1=rsp), @ref BLEPROTO_APPDATA_MSGTYPE_REQ
+ uint8_t msgid : 4; ///< byte1[3:0]:消息序号, 单调递增
+ uint8_t encrypt : 1; ///< byte1[4:4]:数据加密方式, 当前固定填写0,表示不加密
+ uint8_t reserve : 3; ///< byte1[7:5]:保留
+ uint8_t totalframe; ///< byte2 :总包数, 范围 1~255, 0x01:不分包时,取值为1, 0x02~0xFF:分包时,取值为≥2
+ uint8_t frameseq; ///< byte3 :分包包序号, 0x00:不分包时取值为0, 0x01~0xFF: 分包时, 取值为从1开始依次递增
+ uint8_t framelen; ///< byte4 :该包数据长度
+ uint8_t serviceid; ///< byte5 :应用数据服务id @ref bleproto_service_id_e
+ uint16_t datalen; ///< byte6-7 :应用数据总长度
+ // clang-format on
+} bleproto_appdata_header_t;
+
+/**
+ * @brief 应用数据
+ */
+typedef struct bleproto_appdata {
+ bleproto_appdata_header_t header;
+ uint8_t data[BLEPROTO_APPDATA_DATA_MAX_SZ];
+} bleproto_appdata_t;
+
+/**
+ * @brief service id定义
+ */
+typedef uint8_t bleproto_service_id_e;
+enum {
+ E_BLEPROTO_SERVICE_ID_UNSPECIFIED = 0, ///< 保留
+ E_BLEPROTO_SERVICE_ID_DEVICEINFO = 1, ///< deviceInfo
+ E_BLEPROTO_SERVICE_ID_AUTHSETUP = 2, ///< authSetup
+ E_BLEPROTO_SERVICE_ID_AUTHDELETE = 3, ///< authDelete
+ E_BLEPROTO_SERVICE_ID_RUNCMD = 4, ///< runCmd
+ E_BLEPROTO_SERVICE_ID_REPORTCMD = 5, ///< reportCmd
+ E_BLEPROTO_SERVICE_ID_DOACTION = 6, ///< doAction
+ E_BLEPROTO_SERVICE_ID_OTANOTIFY = 7, ///< otaNotify
+ E_BLEPROTO_SERVICE_ID_OTADATA = 8, ///< otaData
+ E_BLEPROTO_SERVICE_ID_RUNCMD_V2 = 20, ///< runCmdV2
+ E_BLEPROTO_SERVICE_ID_REPORTCMD_V2 = 21, ///< reportCmdV2
+ E_BLEPROTO_SERVICE_ID_OTADATA_V2 = 22, ///< otaDataV2
+};
+
+/**
+ * @brief ycmd 定义
+ */
+#define YCMD_INT32_MAX_COUNT 32
+#define YCMD_STRING_MAX_COUNT 16
+#define YCMD_STRING_MAX_SIZE 32
+#define YCMD_BYTES_MAX_COUNT 8
+typedef struct bleproto_ycmd {
+ int32_t cmd_id;
+ uint16_t arg_int32_count;
+ int32_t arg_int32[YCMD_INT32_MAX_COUNT];
+ uint16_t arg_string_count;
+ char arg_string[YCMD_STRING_MAX_COUNT][YCMD_STRING_MAX_SIZE];
+ uint16_t arg_bytes_count;
+ uint8_t arg_bytes[YCMD_BYTES_MAX_COUNT];
+ uint64_t t;
+} bleproto_ycmd_t;
+
+//////////////////////////////////////////////////////////////////////
+// E_BLEPROTO_SERVICE_ID_DEVICEINFO
+//////////////////////////////////////////////////////////////////////
+typedef struct bleproto_deviceinfo_req {
+ uint64_t t; ///< utcms时间戳
+ int gmtoff; ///< 时区偏移,单位秒,例如东八区(8x60x60=28800秒)
+} bleproto_deviceinfo_req_t;
+
+typedef struct bleproto_deviceinfo_rsp {
+ // clang-format off
+ char hwv[16]; ///< 硬件版本号
+ char swv[16]; ///< 软件版本号
+ uint8_t prototype; ///< 协议类型,固定填写为4,表示Ble设备
+ uint32_t hbcycle; ///< 设备心跳广播心跳周期,ms
+ uint8_t longcon; ///< 是否长链接, 1=长链接,0=短链接
+ // clang-format on
+} bleproto_deviceinfo_rsp_t;
+
+//////////////////////////////////////////////////////////////////////
+// E_BLEPROTO_SERVICE_ID_AUTHSETUP
+//////////////////////////////////////////////////////////////////////
+typedef struct bleproto_authsetup_req {
+ // clang-format off
+ uint8_t gwmac[6]; ///< 主控mac地址, 设备需要保存
+ char devid[36 + 1]; ///< 主控分配的子设备id, 设备需要保存
+ char authcode[32 + 1]; ///< 主控分配的子设备认证码, 设备需要保存
+ uint8_t paired_flag;
+ // clang-format on
+} bleproto_authsetup_req_t;
+
+typedef struct bleproto_authsetup_rsp {
+ int32_t errcode; ///< 返回码,0表示成功, 其他表示失败
+} bleproto_authsetup_rsp_t;
+
+//////////////////////////////////////////////////////////////////////
+// E_BLEPROTO_SERVICE_ID_AUTHDELETE
+//////////////////////////////////////////////////////////////////////
+typedef struct bleproto_authdelete_req {
+ char authcode[32 + 1]; ///< 子设备认证码
+} bleproto_authdelete_req_t;
+
+typedef struct bleproto_authdelete_rsp {
+ uint8_t gwmac[6]; ///< 绑定主控设备的mac地址
+ int32_t errcode; ///< 返回码,0表示成功, 其他表示失败
+} bleproto_authdelete_rsp_t;
+
+//////////////////////////////////////////////////////////////////////
+// E_BLEPROTO_SERVICE_ID_RUNCMD
+//////////////////////////////////////////////////////////////////////
+typedef struct bleproto_runcmd_req {
+ bleproto_ycmd_t ycmd; ///< Request Ycmd
+} bleproto_runcmd_req_t;
+
+typedef struct bleproto_runcmd_rsp {
+ bleproto_ycmd_t ycmd; ///< Response Ycmd
+} bleproto_runcmd_rsp_t;
+
+//////////////////////////////////////////////////////////////////////
+// E_BLEPROTO_SERVICE_ID_REPORTCMD
+//////////////////////////////////////////////////////////////////////
+typedef struct bleproto_reportcmd_req {
+ bleproto_ycmd_t ycmd; ///< Ycmd
+} bleproto_reportcmd_req_t;
+
+typedef struct bleproto_reportcmd_rsp {
+ int32_t errcode; ///< 返回码,0表示成功, 其他表示失败
+} bleproto_reportcmd_rsp_t;
+
+//////////////////////////////////////////////////////////////////////
+// E_BLEPROTO_SERVICE_ID_DOACTION
+//////////////////////////////////////////////////////////////////////
+typedef struct bleproto_doaction_req {
+ int action; ///< 0:重启, 1:指示,收到命令设备指示灯闪烁或者音频发音
+} bleproto_doaction_req_t;
+
+typedef struct bleproto_doaction_rsp {
+ int32_t errcode; ///< 返回码,0表示成功, 其他表示失败
+} bleproto_doaction_rsp_t;
+
+//////////////////////////////////////////////////////////////////////
+// E_BLEPROTO_SERVICE_ID_OTANOTIFY
+//////////////////////////////////////////////////////////////////////
+typedef struct bleproto_otanotify_req {
+ int id; ///< file_id
+ char version[16]; ///< 版本号
+ uint32_t size; ///< 固件大小
+ char md5[32 + 1]; ///< 固件的md5值
+} bleproto_otanotify_req_t;
+
+typedef struct bleproto_otanotify_rsp {
+ int32_t errcode; ///< 返回码,0表示成功, 其他表示失败
+} bleproto_otanotify_rsp_t;
+//////////////////////////////////////////////////////////////////////
+// E_BLEPROTO_SERVICE_ID_OTADATA
+//////////////////////////////////////////////////////////////////////
+typedef struct bleproto_otadata_req {
+ int id; ///< file_id
+ int32_t offset; ///< 要读取数据的偏移
+ uint32_t maxsize; ///< 每次最大读取的大小
+} bleproto_otadata_req_t;
+
+typedef struct bleproto_otadata_rsp {
+ int32_t errcode; ///< 返回码,0表示成功, 其他表示失败
+ int id; ///< file_id
+ int32_t offset; ///< 当前读取到的数据偏移
+ uint32_t len; ///< 当次读取数据的大小
+ /**
+ * 固件数据指针(不内嵌大数组,避免 bleproto_appdata_desc_t 膨胀到 2KB+)
+ * - decode:指向 appdata 内部缓冲(零拷贝),下次 decode 前有效
+ * - encode:由调用方提供可读缓冲
+ */
+ const uint8_t *data;
+} bleproto_otadata_rsp_t;
+/****************************************************************************/
+/* Public Data */
+/****************************************************************************/
+
+/****************************************************************************/
+#ifdef __cplusplus
+extern "C" {
+#endif
+/****************************************************************************/
+/* Public Function Prototypes */
+/****************************************************************************/
+
+/**
+ * @brief 序列化广播数据(广播数据长度为31)
+ *
+ * @param[in] adv - 广播数据结构体.
+ * @param[out] data - 序列化数据缓冲区, 固定为31个字节.
+ * @param[in] size - 序列化数据缓冲区长度
+ *
+ * @return 小于0表示失败,大于0表示序列化后的长度(31)
+ */
+int bleproto_advdata_serialize(bleproto_adv_t *adv,
+ uint8_t * data,
+ uint8_t size);
+
+/**
+ * @brief 反序列化广播数据(广播数据长度为31)
+ *
+ * @param[in] data - 反序列化数据指针
+ * @param[in] len - 反序列化数据长度
+ * @param[out] adv - 广播数据结构体
+ *
+ * @return 小于0表示失败,大于0表示反序列化使用data的长度(31)
+ */
+int bleproto_advdata_deserialize(const uint8_t * data,
+ uint8_t len,
+ bleproto_adv_t *adv);
+
+/**
+ * @brief 计算序列化应用数据长度
+ *
+ * @note packetlen说明
+ *
+ * ```c
+ * ble4.0 通常协商的mtu=27, packetlen = 27 - 4 - 3 = 20
+ * ble4.2 通常协商的mtu=251, packelen = 251 - 4 - 3 = 244
+ * ble5.0 通常协商的mtu=251, packelen = 251 - 4 - 3 = 244
+ * ```
+ *
+ * @param[in] appdata - 应用数据结构体
+ * @param[in] packetlen - BLE GATT单包传输有效长度, 查看上面说明
+ * @param[out] outlen - 计算返回总长度,每个包都含有包头
+ *
+ * @return 成功返回0,其他值表示失败
+ */
+int bleproto_appdata_serialize_len(bleproto_appdata_t *appdata,
+ uint8_t packetlen,
+ uint16_t * outlen);
+
+/**
+ * @brief 序列化应用数据
+ *
+ * @note packetlen说明
+ *
+ * ```c
+ * ble4.0 通常协商的mtu=27, packetlen = 27 - 4 - 3 = 20
+ * ble4.2 通常协商的mtu=251, packelen = 251 - 4 - 3 = 244
+ * ble5.0 通常协商的mtu=251, packelen = 251 - 4 - 3 = 244
+ * ```
+ *
+ * 如果报文数据长度超过 BLE GATT单包传输有效长度,需要按照文档方式分包,
+ * +----------------+
+ * | 1 | 第一包按照packetlen填满
+ * +----------------+
+ * | |
+ * | ... | 中间包按照packetlen填满
+ * | |
+ * +----------------+
+ * | N | 最后一包长度 = totallen - (packetlen * (N -1))
+ * +----------------+
+ *
+ * 需要按照每包的顺序发给对端
+ *
+ * @param[in] appdata - 应用数据结构体
+ * @param[in] packetlen - BLE GATT单包传输有效长度, 查看上面说明
+ * @param[out] buf - 数据缓冲区指针
+ * @param[in] size - 数据缓冲区大小
+ *
+ * @return 小于0表示失败,大于0表示序列化后的长度
+ */
+int bleproto_appdata_serialize(bleproto_appdata_t *appdata,
+ uint8_t packetlen,
+ uint8_t * buf,
+ uint16_t size);
+
+/**
+ * @brief 将已打包好的 payload 包装成单帧 appdata(不分包)
+ * @param txbuf 输出缓冲
+ * @param txbuf_size 输出缓冲大小
+ * @param header 应用层头(datalen/totalframe/frameseq 由本函数填写)
+ * @param payload 已序列化的 service 数据;可为 NULL(payload_len==0)
+ * @param payload_len payload 长度,须 <=255(单帧 pthis_frame_len 为 u8)
+ * @return >0 总字节数;<0 失败
+ * @note 小包场景(JB 55AA 透传等)用此接口,避免 bleproto_appdata_t 大缓冲
+ */
+int bleproto_appdata_wrap_raw(uint8_t *txbuf,
+ uint16_t txbuf_size,
+ const bleproto_appdata_header_t *header,
+ const uint8_t *payload,
+ uint16_t payload_len);
+
+/**
+ * @brief 反序列化应用数据
+ *
+ *
+ * 如果报文数据长度超过 BLE GATT单包传输有效长度,需要按照文档方式分包,
+ * +----------------+
+ * | 1 | 第一包按照packetlen填满
+ * +----------------+
+ * | |
+ * | ... | 中间包按照packetlen填满
+ * | |
+ * +----------------+
+ * | N | 最后一包长度 = totallen - (packetlen * (N -1))
+ * +----------------+
+ *
+ * 因此接收到数据
+ * 1. 函数返回等于0,以为还有分包数据还没有接收完成,
+ * 接收到下包数据 append 在buf尾部,再调用函数的解析数据包
+ * 2. 函数返回大于0,表示收到数据解析了多少字节,需要将头上对应长度数据移除掉
+ * 3. 函数返回小于0,表示收到非法的数据包,无法解析
+ *
+ * @param[in] buf - 数据缓冲区指针.
+ * @param[in] len - 数据缓冲区长度.
+ * @param[out] app_data - 应用数据结构体.
+ *
+ * @return 大于0表示解析成功, 返回当前解析了多少个字节,
+ * 等于0表示解析未完成, 只接受到分包的部分数据, 需要继续接收数据
+ * 小于0表示解析失败
+ */
+int bleproto_appdata_deserialize(uint8_t * buf,
+ uint16_t len,
+ bleproto_appdata_t *appdata);
+
+////////////////////////////////////////////////////////////////////////
+// encjson 序列化, 成功返回json序列化的长度,失败返回小于0
+// decjson 反序列化, 成功返回0, 其他值表示失败
+////////////////////////////////////////////////////////////////////////
+// clang-format off
+int bleproto_encjson_ycmd(const bleproto_ycmd_t *ycmd, uint8_t data[BLEPROTO_APPDATA_DATA_MAX_SZ]);
+int bleproto_decjson_ycmd(const uint8_t *data, uint16_t len, bleproto_ycmd_t *ycmd);
+// clang-format on
+
+////////////////////////////////////////////////////////////////////////
+// encjson 序列化, 成功返回json序列化的长度,失败返回小于0
+// decjson 反序列化, 成功返回0, 其他值表示失败
+////////////////////////////////////////////////////////////////////////
+// clang-format off
+int bleproto_encjson_deviceinfo_req(const bleproto_deviceinfo_req_t *req, uint8_t data[BLEPROTO_APPDATA_DATA_MAX_SZ]);
+int bleproto_encjson_deviceinfo_rsp(const bleproto_deviceinfo_rsp_t *rsp, uint8_t data[BLEPROTO_APPDATA_DATA_MAX_SZ]);
+int bleproto_encjson_authsetup_req(const bleproto_authsetup_req_t *req, uint8_t data[BLEPROTO_APPDATA_DATA_MAX_SZ]);
+int bleproto_encjson_authsetup_rsp(const bleproto_authsetup_rsp_t *rsp, uint8_t data[BLEPROTO_APPDATA_DATA_MAX_SZ]);
+int bleproto_encjson_authdelete_req(const bleproto_authdelete_req_t *req, uint8_t data[BLEPROTO_APPDATA_DATA_MAX_SZ]);
+int bleproto_encjson_authdelete_rsp(const bleproto_authdelete_rsp_t *rsp, uint8_t data[BLEPROTO_APPDATA_DATA_MAX_SZ]);
+int bleproto_encjson_runcmd_req(const bleproto_runcmd_req_t *req, uint8_t data[BLEPROTO_APPDATA_DATA_MAX_SZ]);
+int bleproto_encjson_runcmd_rsp(const bleproto_runcmd_rsp_t *rsp, uint8_t data[BLEPROTO_APPDATA_DATA_MAX_SZ]);
+int bleproto_encjson_reportcmd_req(const bleproto_reportcmd_req_t *req, uint8_t data[BLEPROTO_APPDATA_DATA_MAX_SZ]);
+int bleproto_encjson_reportcmd_rsp(const bleproto_reportcmd_rsp_t *rsp, uint8_t data[BLEPROTO_APPDATA_DATA_MAX_SZ]);
+int bleproto_encjson_doaction_req(const bleproto_doaction_req_t *req, uint8_t data[BLEPROTO_APPDATA_DATA_MAX_SZ]);
+int bleproto_encjson_doaction_rsp(const bleproto_doaction_rsp_t *rsp, uint8_t data[BLEPROTO_APPDATA_DATA_MAX_SZ]);
+int bleproto_encjson_otanotify_req(const bleproto_otanotify_req_t *req, uint8_t data[BLEPROTO_APPDATA_DATA_MAX_SZ]);
+int bleproto_encjson_otanotify_rsp(const bleproto_otanotify_rsp_t *rsp, uint8_t data[BLEPROTO_APPDATA_DATA_MAX_SZ]);
+// otadata 序列化请求走json,回复走二进制
+int bleproto_encjson_otadata_req(const bleproto_otadata_req_t *req, uint8_t data[BLEPROTO_APPDATA_DATA_MAX_SZ]);
+int bleproto_encbin_otadata_rsp(const bleproto_otadata_rsp_t *rsp, uint8_t data[BLEPROTO_APPDATA_DATA_MAX_SZ]);
+
+int bleproto_decjson_deviceinfo_req(const uint8_t *data, uint16_t len, bleproto_deviceinfo_req_t *req);
+int bleproto_decjson_deviceinfo_rsp(const uint8_t *data, uint16_t len, bleproto_deviceinfo_rsp_t *rsp);
+int bleproto_decjson_authsetup_req(const uint8_t *data, uint16_t len, bleproto_authsetup_req_t *req);
+int bleproto_decjson_authsetup_rsp(const uint8_t *data, uint16_t len, bleproto_authsetup_rsp_t *rsp);
+int bleproto_decjson_authdelete_req(const uint8_t *data, uint16_t len, bleproto_authdelete_req_t *req);
+int bleproto_decjson_authdelete_rsp(const uint8_t *data, uint16_t len, bleproto_authdelete_rsp_t *rsp);
+int bleproto_decjson_runcmd_req(const uint8_t *data, uint16_t len, bleproto_runcmd_req_t *req);
+int bleproto_decjson_runcmd_rsp(const uint8_t *data, uint16_t len, bleproto_runcmd_rsp_t *rsp);
+int bleproto_decjson_reportcmd_req(const uint8_t *data, uint16_t len, bleproto_reportcmd_req_t *req);
+int bleproto_decjson_reportcmd_rsp(const uint8_t *data, uint16_t len, bleproto_reportcmd_rsp_t *rsp);
+int bleproto_decjson_doaction_req(const uint8_t *data, uint16_t len, bleproto_doaction_req_t *req);
+int bleproto_decjson_doaction_rsp(const uint8_t *data, uint16_t len, bleproto_doaction_rsp_t *rsp);
+int bleproto_decjson_otanotify_req(const uint8_t *data, uint16_t len, bleproto_otanotify_req_t *req);
+int bleproto_decjson_otanotify_rsp(const uint8_t *data, uint16_t len, bleproto_otanotify_rsp_t *rsp);
+//otadata 反序列化请求走json,回复走二进制
+int bleproto_decjson_otadata_req(const uint8_t *data, uint16_t len, bleproto_otadata_req_t *req);
+int bleproto_debin_otadata_rsp(const uint8_t *data, uint16_t len, bleproto_otadata_rsp_t *rsp);
+// clang-format on
+
+/****************************************************************************/
+#ifdef __cplusplus
+}
+#endif
+/****************************************************************************/
+#endif /* BLEPROTO_PACKER_H_INCLUDE */
+/****************************************************************************/
+/**
+ * @} (end addtogroup bleproto_packer)
+ */
+/****************************************************************************/
+/* */
+/* End of file. */
+/* */
+/****************************************************************************/
diff --git a/apps/usr_le_code/lib/libusr_le_code.a b/apps/usr_le_code/lib/libusr_le_code.a
deleted file mode 100644
index f337979..0000000
Binary files a/apps/usr_le_code/lib/libusr_le_code.a and /dev/null differ
diff --git a/apps/usr_le_code/thirdpart/mjson/mjson.c b/apps/usr_le_code/thirdpart/mjson/mjson.c
new file mode 100644
index 0000000..75548d4
--- /dev/null
+++ b/apps/usr_le_code/thirdpart/mjson/mjson.c
@@ -0,0 +1,1066 @@
+// Copyright (c) 2018-2020 Cesanta Software Limited
+// All rights reserved
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+// SOFTWARE.
+
+#include
+#include
+
+#include "mjson.h"
+
+#if defined(_MSC_VER)
+#define alloca(x) _alloca(x)
+#endif
+
+#if defined(_MSC_VER) && _MSC_VER < 1700
+#define va_copy(x, y) (x) = (y)
+#define isinf(x) !_finite(x)
+#define isnan(x) _isnan(x)
+#endif
+
+static double mystrtod(const char *str, const char **end);
+
+static int mjson_esc(int c, int esc) {
+ const char *p, *esc1 = "\b\f\n\r\t\\\"", *esc2 = "bfnrt\\\"";
+ for (p = esc ? esc1 : esc2; *p != '\0'; p++) {
+ if (*p == c) return esc ? esc2[p - esc1] : esc1[p - esc2];
+ }
+ return 0;
+}
+
+static int mjson_escape(int c) {
+ return mjson_esc(c, 1);
+}
+
+static int mjson_pass_string(const char *s, int len) {
+ int i;
+ for (i = 0; i < len; i++) {
+ if (s[i] == '\\' && i + 1 < len && mjson_escape(s[i + 1])) {
+ i++;
+ } else if (s[i] == '\0') {
+ return MJSON_ERROR_INVALID_INPUT;
+ } else if (s[i] == '"') {
+ return i;
+ }
+ }
+ return MJSON_ERROR_INVALID_INPUT;
+}
+
+int mjson(const char *s, int len, mjson_cb_t cb, void *ud) {
+ enum { S_VALUE, S_KEY, S_COLON, S_COMMA_OR_EOO } expecting = S_VALUE;
+ unsigned char nesting[MJSON_MAX_DEPTH];
+ int i, depth = 0;
+#define MJSONCALL(ev) \
+ if (cb != NULL && cb(ev, s, start, i - start + 1, ud)) return i + 1;
+
+// In the ascii table, the distance between `[` and `]` is 2.
+// Ditto for `{` and `}`. Hence +2 in the code below.
+#define MJSONEOO() \
+ do { \
+ if (c != nesting[depth - 1] + 2) return MJSON_ERROR_INVALID_INPUT; \
+ depth--; \
+ if (depth == 0) { \
+ MJSONCALL(tok); \
+ return i + 1; \
+ } \
+ } while (0)
+
+ for (i = 0; i < len; i++) {
+ int start = i;
+ unsigned char c = ((const unsigned char *) s)[i];
+ int tok = c;
+ if (c == ' ' || c == '\t' || c == '\n' || c == '\r') continue;
+ // printf("- %c [%.*s] %d %d\n", c, i, s, depth, expecting);
+ switch (expecting) {
+ case S_VALUE:
+ if (c == '{') {
+ if (depth >= (int) sizeof(nesting)) return MJSON_ERROR_TOO_DEEP;
+ nesting[depth++] = c;
+ expecting = S_KEY;
+ break;
+ } else if (c == '[') {
+ if (depth >= (int) sizeof(nesting)) return MJSON_ERROR_TOO_DEEP;
+ nesting[depth++] = c;
+ break;
+ } else if (c == ']' && depth > 0) { // Empty array
+ MJSONEOO();
+ } else if (c == 't' && i + 3 < len && memcmp(&s[i], "true", 4) == 0) {
+ i += 3;
+ tok = MJSON_TOK_TRUE;
+ } else if (c == 'n' && i + 3 < len && memcmp(&s[i], "null", 4) == 0) {
+ i += 3;
+ tok = MJSON_TOK_NULL;
+ } else if (c == 'f' && i + 4 < len && memcmp(&s[i], "false", 5) == 0) {
+ i += 4;
+ tok = MJSON_TOK_FALSE;
+ } else if (c == '-' || ((c >= '0' && c <= '9'))) {
+ const char *end = NULL;
+ mystrtod(&s[i], &end);
+ if (end != NULL) i += (int) (end - &s[i] - 1);
+ tok = MJSON_TOK_NUMBER;
+ } else if (c == '"') {
+ int n = mjson_pass_string(&s[i + 1], len - i - 1);
+ if (n < 0) return n;
+ i += n + 1;
+ tok = MJSON_TOK_STRING;
+ } else {
+ return MJSON_ERROR_INVALID_INPUT;
+ }
+ if (depth == 0) {
+ MJSONCALL(tok);
+ return i + 1;
+ }
+ expecting = S_COMMA_OR_EOO;
+ break;
+
+ case S_KEY:
+ if (c == '"') {
+ int n = mjson_pass_string(&s[i + 1], len - i - 1);
+ if (n < 0) return n;
+ i += n + 1;
+ tok = MJSON_TOK_KEY;
+ expecting = S_COLON;
+ } else if (c == '}') { // Empty object
+ MJSONEOO();
+ expecting = S_COMMA_OR_EOO;
+ } else {
+ return MJSON_ERROR_INVALID_INPUT;
+ }
+ break;
+
+ case S_COLON:
+ if (c == ':') {
+ expecting = S_VALUE;
+ } else {
+ return MJSON_ERROR_INVALID_INPUT;
+ }
+ break;
+
+ case S_COMMA_OR_EOO:
+ if (depth <= 0) return MJSON_ERROR_INVALID_INPUT;
+ if (c == ',') {
+ expecting = (nesting[depth - 1] == '{') ? S_KEY : S_VALUE;
+ } else if (c == ']' || c == '}') {
+ MJSONEOO();
+ } else {
+ return MJSON_ERROR_INVALID_INPUT;
+ }
+ break;
+ }
+ MJSONCALL(tok);
+ }
+ return MJSON_ERROR_INVALID_INPUT;
+}
+
+struct msjon_get_data {
+ const char *path; // Lookup json path
+ int pos; // Current path position
+ int d1; // Current depth of traversal
+ int d2; // Expected depth of traversal
+ int i1; // Index in an array
+ int i2; // Expected index in an array
+ int obj; // If the value is array/object, offset where it starts
+ const char **tokptr; // Destination
+ int *toklen; // Destination length
+ int tok; // Returned token
+};
+
+//#include
+
+static int plen1(const char *s) {
+ int i = 0, n = 0;
+ while (s[i] != '\0' && s[i] != '.' && s[i] != '[')
+ n++, i += s[i] == '\\' ? 2 : 1;
+ // printf("PLEN: s: [%s], [%.*s] => %d\n", s, i, s, n);
+ return n;
+}
+
+static int plen2(const char *s) {
+ int i = 0, n = 0;
+ while (s[i] != '\0' && s[i] != '.' && s[i] != '[')
+ n++, i += s[i] == '\\' ? 2 : 1;
+ // printf("PLEN: s: [%s], [%.*s] => %d\n", s, i, s, n);
+ return i;
+}
+
+static int kcmp(const char *a, const char *b, int n) {
+ int i = 0, j = 0, r = 0;
+ for (i = 0, j = 0; j < n; i++, j++) {
+ if (b[i] == '\\') i++;
+ if ((r = a[j] - b[i]) != 0) return r;
+ }
+ // printf("KCMP: a: [%.*s], b:[%.*s] ==> %d\n", n, a, i, b, r);
+ return r;
+}
+
+static int mjson_get_cb(int tok, const char *s, int off, int len, void *ud) {
+ struct msjon_get_data *d = (struct msjon_get_data *) ud;
+#if 0
+ printf("--> %2x %2d %2d %2d %2d\t %2d %2d\t'%s' '%s' '%s' '%s'\n", tok, d->d1,
+ d->d2, d->i1, d->i2, (int) off, (int) d->pos, s, d->path, s + off,
+ d->path + d->pos);
+#endif
+ if (d->tok != MJSON_TOK_INVALID) return 1; // Found
+ if (tok == '{' || tok == '[') {
+ if (d->d1 < d->d2) d->obj = -1;
+ if (d->d1 == d->d2) d->obj = off;
+ if (d->d1 == d->d2 && tok == '[' && d->path[d->pos] == '[') {
+ d->i1 = 0;
+ d->i2 = (int) mystrtod(&d->path[d->pos + 1], NULL);
+ if (d->i1 == d->i2) {
+ while (d->path[d->pos] && d->path[d->pos] != ']') d->pos++;
+ if (d->path[d->pos] == ']') d->pos++;
+ d->d2++;
+ }
+ }
+ d->d1++;
+ } else if (tok == '}' || tok == ']') {
+ if (tok == ']' && d->d1 == d->d2) d->i1 = 0;
+ d->d1--;
+ // printf("X %s %d %d %d %d %d\n", d->path + d->pos, d->d1, d->d2, d->i1,
+ // d->i2, d->obj);
+ if (!d->path[d->pos] && d->d1 == d->d2 && d->obj != -1) {
+ d->tok = tok - 2;
+ if (d->tokptr) *d->tokptr = s + d->obj;
+ if (d->toklen) *d->toklen = off - d->obj + 1;
+ return 1;
+ }
+ } else if (tok == ',' && d->d1 == d->d2 && d->pos &&
+ d->path[d->pos - 1] == ']') {
+ return 1; // Not found in the current elem array
+ } else if (tok == ',' && d->d1 == d->d2 + 1 && d->path[d->pos] == '[') {
+ // printf("GG '%s' '%s'\n", d->path, &d->path[d->pos]);
+ d->i1++;
+ if (d->i1 == d->i2) {
+ while (d->path[d->pos] && d->path[d->pos] != ']') d->pos++;
+ if (d->path[d->pos] == ']') d->pos++;
+ d->d2++;
+ }
+ } else if (tok == MJSON_TOK_KEY && d->d1 == d->d2 + 1 &&
+ d->path[d->pos] == '.' && s[off] == '"' &&
+ s[off + len - 1] == '"' &&
+ plen1(&d->path[d->pos + 1]) == len - 2 &&
+ kcmp(s + off + 1, &d->path[d->pos + 1], len - 2) == 0) {
+ d->d2++;
+ d->pos += plen2(&d->path[d->pos + 1]) + 1;
+ } else if (tok == MJSON_TOK_KEY && d->d1 == d->d2) {
+ return 1; // Exhausted path, not found
+ } else if (MJSON_TOK_IS_VALUE(tok)) {
+ // printf("T %d %d %d %d %d\n", tok, d->d1, d->d2, d->i1, d->i2);
+ if (d->d1 == d->d2 && d->i1 == d->i2 && !d->path[d->pos]) {
+ d->tok = tok;
+ if (d->tokptr) *d->tokptr = s + off;
+ if (d->toklen) *d->toklen = len;
+ return 1;
+ }
+ }
+ return 0;
+}
+
+int mjson_find(const char *s, int n, const char *jp, const char **tp, int *tl) {
+ struct msjon_get_data data = {jp, 1, 0, 0, 0,
+ 0, -1, tp, tl, MJSON_TOK_INVALID};
+ if (jp[0] != '$') return MJSON_TOK_INVALID;
+ if (mjson(s, n, mjson_get_cb, &data) < 0) return MJSON_TOK_INVALID;
+ return data.tok;
+}
+
+int mjson_get_number(const char *s, int len, const char *path, double *v) {
+ const char *p;
+ int tok, n;
+ if ((tok = mjson_find(s, len, path, &p, &n)) == MJSON_TOK_NUMBER) {
+ if (v != NULL) *v = mystrtod(p, NULL);
+ }
+ return tok == MJSON_TOK_NUMBER ? 1 : 0;
+}
+
+int mjson_get_bool(const char *s, int len, const char *path, int *v) {
+ int tok = mjson_find(s, len, path, NULL, NULL);
+ if (tok == MJSON_TOK_TRUE && v != NULL) *v = 1;
+ if (tok == MJSON_TOK_FALSE && v != NULL) *v = 0;
+ return tok == MJSON_TOK_TRUE || tok == MJSON_TOK_FALSE ? 1 : 0;
+}
+
+static unsigned char unhex(unsigned char c) {
+ return (c >= '0' && c <= '9') ? (unsigned char) (c - '0')
+ : (c >= 'A' && c <= 'F') ? (unsigned char) (c - '7')
+ : (unsigned char) (c - 'W');
+}
+
+static unsigned char mjson_unhex_nimble(const char *s) {
+ const unsigned char *u = (const unsigned char *) s;
+ return (unsigned char) (((unsigned char) (unhex(u[0]) << 4)) | unhex(u[1]));
+}
+
+static int mjson_unescape(const char *s, int len, char *to, int n) {
+ int i, j;
+ for (i = 0, j = 0; i < len && j < n; i++, j++) {
+ if (s[i] == '\\' && i + 5 < len && s[i + 1] == 'u') {
+ // \uXXXX escape. We could process a simple one-byte chars
+ // \u00xx from the ASCII range. More complex chars would require
+ // dragging in a UTF8 library, which is too much for us
+ if (s[i + 2] != '0' || s[i + 3] != '0') return -1; // Too much, give up
+ ((unsigned char *) to)[j] = mjson_unhex_nimble(s + i + 4);
+ i += 5;
+ } else if (s[i] == '\\' && i + 1 < len) {
+ int c = mjson_esc(s[i + 1], 0);
+ if (c == 0) return -1;
+ to[j] = (char) (unsigned char) c;
+ i++;
+ } else {
+ to[j] = s[i];
+ }
+ }
+ if (j >= n) return -1;
+ if (n > 0) to[j] = '\0';
+ return j;
+}
+
+int mjson_get_string(const char *s, int len, const char *path, char *to,
+ int n) {
+ const char *p;
+ int sz;
+ if (mjson_find(s, len, path, &p, &sz) != MJSON_TOK_STRING) return -1;
+ return mjson_unescape(p + 1, sz - 2, to, n);
+}
+
+int mjson_get_hex(const char *s, int len, const char *x, char *to, int n) {
+ const char *p;
+ int i, j, sz;
+ if (mjson_find(s, len, x, &p, &sz) != MJSON_TOK_STRING) return -1;
+ for (i = j = 0; i < sz - 3 && j < n; i += 2, j++) {
+ ((unsigned char *) to)[j] = mjson_unhex_nimble(p + i + 1);
+ }
+ if (j < n) to[j] = '\0';
+ return j;
+}
+
+#if MJSON_ENABLE_BASE64
+static unsigned char mjson_base64rev(int c) {
+ if (c >= 'A' && c <= 'Z') {
+ return (unsigned char) (c - 'A');
+ } else if (c >= 'a' && c <= 'z') {
+ return (unsigned char) (c + 26 - 'a');
+ } else if (c >= '0' && c <= '9') {
+ return (unsigned char) (c + 52 - '0');
+ } else if (c == '+') {
+ return 62;
+ } else if (c == '/') {
+ return 63;
+ } else {
+ return 64;
+ }
+}
+
+int mjson_base64_dec(const char *src, int n, char *dst, int dlen) {
+ const char *end = src + n;
+ int len = 0;
+ while (src + 3 < end && len < dlen) {
+ unsigned char a = mjson_base64rev(src[0]), b = mjson_base64rev(src[1]),
+ c = mjson_base64rev(src[2]), d = mjson_base64rev(src[3]);
+ dst[len++] = (char) (unsigned char) ((a << 2) | (b >> 4));
+ if (src[2] != '=' && len < dlen) {
+ dst[len++] = (char) (unsigned char) ((b << 4) | (c >> 2));
+ if (src[3] != '=' && len < dlen) {
+ dst[len++] = (char) (unsigned char) ((c << 6) | d);
+ }
+ }
+ src += 4;
+ }
+ if (len < dlen) dst[len] = '\0';
+ return len;
+}
+
+int mjson_get_base64(const char *s, int len, const char *path, char *to,
+ int n) {
+ const char *p;
+ int sz;
+ if (mjson_find(s, len, path, &p, &sz) != MJSON_TOK_STRING) return 0;
+ return mjson_base64_dec(p + 1, sz - 2, to, n);
+}
+#endif // MJSON_ENABLE_BASE64
+
+#if MJSON_ENABLE_NEXT
+struct nextdata {
+ int off, len, depth, t, vo, arrayindex;
+ int *koff, *klen, *voff, *vlen, *vtype;
+};
+
+static int next_cb(int tok, const char *s, int off, int len, void *ud) {
+ struct nextdata *d = (struct nextdata *) ud;
+ // int i;
+ switch (tok) {
+ case '{':
+ case '[':
+ if (d->depth == 0 && tok == '[') d->arrayindex = 0;
+ if (d->depth == 1 && off > d->off) {
+ d->vo = off;
+ d->t = tok == '{' ? MJSON_TOK_OBJECT : MJSON_TOK_ARRAY;
+ if (d->voff) *d->voff = off;
+ if (d->vtype) *d->vtype = d->t;
+ }
+ d->depth++;
+ break;
+ case '}':
+ case ']':
+ d->depth--;
+ if (d->depth == 1 && d->vo) {
+ d->len = off + len;
+ if (d->vlen) *d->vlen = d->len - d->vo;
+ if (d->arrayindex >= 0) {
+ if (d->koff) *d->koff = d->arrayindex; // koff holds array index
+ if (d->klen) *d->klen = 0; // klen holds 0
+ }
+ return 1;
+ }
+ if (d->depth == 1 && d->arrayindex >= 0) d->arrayindex++;
+ break;
+ case ',':
+ case ':':
+ break;
+ case MJSON_TOK_KEY:
+ if (d->depth == 1 && d->off < off) {
+ if (d->koff) *d->koff = off; // And report back to the user
+ if (d->klen) *d->klen = len; // If we have to
+ }
+ break;
+ default:
+ if (d->depth != 1) break;
+ // If we're iterating over the array
+ if (off > d->off) {
+ d->len = off + len;
+ if (d->vlen) *d->vlen = len; // value length
+ if (d->voff) *d->voff = off; // value offset
+ if (d->vtype) *d->vtype = tok; // value type
+ if (d->arrayindex >= 0) {
+ if (d->koff) *d->koff = d->arrayindex; // koff holds array index
+ if (d->klen) *d->klen = 0; // klen holds 0
+ }
+ return 1;
+ }
+ if (d->arrayindex >= 0) d->arrayindex++;
+ break;
+ }
+ (void) s;
+ return 0;
+}
+
+int mjson_next(const char *s, int n, int off, int *koff, int *klen, int *voff,
+ int *vlen, int *vtype) {
+ struct nextdata d = {off, 0, 0, 0, 0, -1, koff, klen, voff, vlen, vtype};
+ mjson(s, n, next_cb, &d);
+ return d.len;
+}
+#endif
+
+#if MJSON_ENABLE_PRINT
+int mjson_print_fixed_buf(const char *ptr, int len, void *fn_data) {
+ struct mjson_fixedbuf *fb = (struct mjson_fixedbuf *) fn_data;
+ int i, left = fb->size - 1 - fb->len;
+ if (left < len) len = left;
+ for (i = 0; i < len; i++) fb->ptr[fb->len + i] = ptr[i];
+ fb->len += len;
+ fb->ptr[fb->len] = '\0';
+ return len;
+}
+
+// This function allocates memory in chunks of size MJSON_DYNBUF_CHUNK
+// to decrease memory fragmentation, when many calls are executed to
+// print e.g. a base64 string or a hex string.
+int mjson_print_dynamic_buf(const char *ptr, int len, void *fn_data) {
+ char *s, *buf = *(char **) fn_data;
+ size_t curlen = buf == NULL ? 0 : strlen(buf);
+ size_t new_size = curlen + (size_t) len + 1 + MJSON_DYNBUF_CHUNK;
+ new_size -= new_size % MJSON_DYNBUF_CHUNK;
+
+ if ((s = (char *) MJSON_REALLOC(buf, new_size)) == NULL) {
+ return 0;
+ } else {
+ memcpy(s + curlen, ptr, (size_t) len);
+ s[curlen + (size_t) len] = '\0';
+ *(char **) fn_data = s;
+ return len;
+ }
+}
+
+int mjson_snprintf(char *buf, size_t len, const char *fmt, ...) {
+ va_list ap;
+ struct mjson_fixedbuf fb = {buf, (int) len, 0};
+ va_start(ap, fmt);
+ mjson_vprintf(mjson_print_fixed_buf, &fb, fmt, &ap);
+ va_end(ap);
+ return fb.len;
+}
+
+char *mjson_aprintf(const char *fmt, ...) {
+ va_list ap;
+ char *result = NULL;
+ va_start(ap, fmt);
+ mjson_vprintf(mjson_print_dynamic_buf, &result, fmt, &ap);
+ va_end(ap);
+ return result;
+}
+
+int mjson_print_null(const char *ptr, int len, void *userdata) {
+ (void) ptr;
+ (void) userdata;
+ return len;
+}
+
+int mjson_print_buf(mjson_print_fn_t fn, void *fnd, const char *buf, int len) {
+ return fn(buf, len, fnd);
+}
+
+int mjson_print_long(mjson_print_fn_t fn, void *fnd, long val, int is_signed) {
+ unsigned long v = (unsigned long) val, s = 0, n, i;
+ char buf[20], t;
+ if (is_signed && val < 0) buf[s++] = '-', v = (unsigned long) (-val);
+ // This loop prints a number in reverse order. I guess this is because we
+ // write numbers from right to left: least significant digit comes last.
+ // Maybe because we use Arabic numbers, and Arabs write RTL?
+ for (n = 0; v > 0; v /= 10) buf[s + n++] = "0123456789"[v % 10];
+ // Reverse a string
+ for (i = 0; i < n / 2; i++)
+ t = buf[s + i], buf[s + i] = buf[s + n - i - 1], buf[s + n - i - 1] = t;
+ if (val == 0) buf[n++] = '0'; // Handle special case
+ return fn(buf, (int) (s + n), fnd);
+}
+
+int mjson_print_int(mjson_print_fn_t fn, void *fnd, int v, int s) {
+ return mjson_print_long(fn, fnd, s ? (long) v : (long) (unsigned) v, s);
+}
+
+static int addexp(char *buf, int e, int sign) {
+ int n = 0;
+ buf[n++] = 'e';
+ buf[n++] = (char) sign;
+ if (e > 400) return 0;
+ if (e < 10) buf[n++] = '0';
+ if (e >= 100) buf[n++] = (char) (e / 100 + '0'), e -= 100 * (e / 100);
+ if (e >= 10) buf[n++] = (char) (e / 10 + '0'), e -= 10 * (e / 10);
+ buf[n++] = (char) (e + '0');
+ return n;
+}
+
+int mjson_print_dbl(mjson_print_fn_t fn, void *fnd, double d, int width) {
+ char buf[40];
+ int i, s = 0, n = 0, e = 0;
+ double t, mul, saved;
+ if (d == 0.0) return fn("0", 1, fnd);
+ if (isinf(d)) return fn(d > 0 ? "inf" : "-inf", d > 0 ? 3 : 4, fnd);
+ if (isnan(d)) return fn("nan", 3, fnd);
+ if (d < 0.0) d = -d, buf[s++] = '-';
+
+ // Round
+ saved = d;
+ mul = 1.0;
+ while (d >= 10.0 && d / mul >= 10.0) mul *= 10.0;
+ while (d <= 1.0 && d / mul <= 1.0) mul /= 10.0;
+ for (i = 0, t = mul * 5; i < width; i++) t /= 10.0;
+ d += t;
+ // Calculate exponent, and 'mul' for scientific representation
+ mul = 1.0;
+ while (d >= 10.0 && d / mul >= 10.0) mul *= 10.0, e++;
+ while (d < 1.0 && d / mul < 1.0) mul /= 10.0, e--;
+ // printf(" --> %g %d %g %g\n", saved, e, t, mul);
+
+ if (e >= width) {
+ struct mjson_fixedbuf fb = {buf + s, (int) sizeof(buf) - s, 0};
+ n = mjson_print_dbl(mjson_print_fixed_buf, &fb, saved / mul, width);
+ // printf(" --> %.*g %d [%.*s]\n", 10, d / t, e, fb.len, fb.ptr);
+ n += addexp(buf + s + n, e, '+');
+ return fn(buf, s + n, fnd);
+ } else if (e <= -width) {
+ struct mjson_fixedbuf fb = {buf + s, (int) sizeof(buf) - s, 0};
+ n = mjson_print_dbl(mjson_print_fixed_buf, &fb, saved / mul, width);
+ // printf(" --> %.*g %d [%.*s]\n", 10, d / mul, e, fb.len, fb.ptr);
+ n += addexp(buf + s + n, -e, '-');
+ return fn(buf, s + n, fnd);
+ } else {
+ for (i = 0, t = mul; t >= 1.0 && s + n < (int) sizeof(buf); i++) {
+ int ch = (int) (d / t);
+ if (n > 0 || ch > 0) buf[s + n++] = (char) (ch + '0');
+ d -= ch * t;
+ t /= 10.0;
+ }
+ // printf(" --> [%g] -> %g %g (%d) [%.*s]\n", saved, d, t, n, s + n, buf);
+ if (n == 0) buf[s++] = '0';
+ while (t >= 1.0 && n + s < (int) sizeof(buf)) buf[n++] = '0', t /= 10.0;
+ if (s + n < (int) sizeof(buf)) buf[n + s++] = '.';
+ // printf(" 1--> [%g] -> [%.*s]\n", saved, s + n, buf);
+ for (i = 0, t = 0.1; s + n < (int) sizeof(buf) && n < width; i++) {
+ int ch = (int) (d / t);
+ buf[s + n++] = (char) (ch + '0');
+ d -= ch * t;
+ t /= 10.0;
+ }
+ }
+ while (n > 0 && buf[s + n - 1] == '0') n--; // Trim trailing zeros
+ if (n > 0 && buf[s + n - 1] == '.') n--; // Trim trailing dot
+ buf[s + n] = '\0';
+ return fn(buf, s + n, fnd);
+}
+
+int mjson_print_str(mjson_print_fn_t fn, void *fnd, const char *s, int len) {
+ int i, n = fn("\"", 1, fnd);
+ for (i = 0; i < len; i++) {
+ char c = (char) (unsigned char) mjson_escape(s[i]);
+ if (c) {
+ n += fn("\\", 1, fnd);
+ n += fn(&c, 1, fnd);
+ } else {
+ n += fn(&s[i], 1, fnd);
+ }
+ }
+ return n + fn("\"", 1, fnd);
+}
+
+#if MJSON_ENABLE_BASE64
+int mjson_print_b64(mjson_print_fn_t fn, void *fnd, const unsigned char *s,
+ int n) {
+ const char *t =
+ "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
+ int i, len = fn("\"", 1, fnd);
+ for (i = 0; i < n; i += 3) {
+ int a = s[i], b = i + 1 < n ? s[i + 1] : 0, c = i + 2 < n ? s[i + 2] : 0;
+ char buf[4] = {t[a >> 2], t[(a & 3) << 4 | (b >> 4)], '=', '='};
+ if (i + 1 < n) buf[2] = t[(b & 15) << 2 | (c >> 6)];
+ if (i + 2 < n) buf[3] = t[c & 63];
+ len += fn(buf, sizeof(buf), fnd);
+ }
+ return len + fn("\"", 1, fnd);
+}
+#endif /* MJSON_ENABLE_BASE64 */
+
+int mjson_vprintf(mjson_print_fn_t fn, void *fnd, const char *fmt,
+ va_list *ap) {
+ int i = 0, n = 0;
+ while (fmt[i] != '\0') {
+ if (fmt[i] == '%') {
+ char fc = fmt[++i];
+ int is_long = 0;
+ if (fc == 'l') {
+ is_long = 1;
+ fc = fmt[i + 1];
+ }
+ if (fc == 'Q') {
+ char *buf = va_arg(*ap, char *);
+ n += mjson_print_str(fn, fnd, buf ? buf : "",
+ buf ? (int) strlen(buf) : 0);
+ } else if (strncmp(&fmt[i], ".*Q", 3) == 0) {
+ int len = va_arg(*ap, int);
+ char *buf = va_arg(*ap, char *);
+ n += mjson_print_str(fn, fnd, buf, len);
+ i += 2;
+ } else if (fc == 'd' || fc == 'u') {
+ int is_signed = (fc == 'd');
+ if (is_long) {
+ long val = va_arg(*ap, long);
+ n += mjson_print_long(fn, fnd, val, is_signed);
+ i++;
+ } else {
+ int val = va_arg(*ap, int);
+ n += mjson_print_int(fn, fnd, val, is_signed);
+ }
+ } else if (fc == 'B') {
+ const char *s = va_arg(*ap, int) ? "true" : "false";
+ n += mjson_print_buf(fn, fnd, s, (int) strlen(s));
+ } else if (fc == 's') {
+ char *buf = va_arg(*ap, char *);
+ n += mjson_print_buf(fn, fnd, buf, (int) strlen(buf));
+ } else if (strncmp(&fmt[i], ".*s", 3) == 0) {
+ int len = va_arg(*ap, int);
+ char *buf = va_arg(*ap, char *);
+ n += mjson_print_buf(fn, fnd, buf, len);
+ i += 2;
+ } else if (fc == 'g') {
+ n += mjson_print_dbl(fn, fnd, va_arg(*ap, double), 6);
+ } else if (strncmp(&fmt[i], ".*g", 3) == 0) {
+ int width = va_arg(*ap, int);
+ n += mjson_print_dbl(fn, fnd, va_arg(*ap, double), width);
+ i += 2;
+#if MJSON_ENABLE_BASE64
+ } else if (fc == 'V') {
+ int len = va_arg(*ap, int);
+ const char *buf = va_arg(*ap, const char *);
+ n += mjson_print_b64(fn, fnd, (const unsigned char *) buf, len);
+#endif
+ } else if (fc == 'H') {
+ const char *hex = "0123456789abcdef";
+ int j, len = va_arg(*ap, int);
+ const unsigned char *p = va_arg(*ap, const unsigned char *);
+ n += fn("\"", 1, fnd);
+ for (j = 0; j < len; j++) {
+ n += fn(&hex[(p[j] >> 4) & 15], 1, fnd);
+ n += fn(&hex[p[j] & 15], 1, fnd);
+ }
+ n += fn("\"", 1, fnd);
+ } else if (fc == 'M') {
+ mjson_vprint_fn_t vfn = va_arg(*ap, mjson_vprint_fn_t);
+ n += vfn(fn, fnd, ap);
+ }
+ i++;
+ } else {
+ n += mjson_print_buf(fn, fnd, &fmt[i++], 1);
+ }
+ }
+ return n;
+}
+
+int mjson_printf(mjson_print_fn_t fn, void *fnd, const char *fmt, ...) {
+ va_list ap;
+ int len;
+ va_start(ap, fmt);
+ len = mjson_vprintf(fn, fnd, fmt, &ap);
+ va_end(ap);
+ return len;
+}
+#endif /* MJSON_ENABLE_PRINT */
+
+static int is_digit(int c) {
+ return c >= '0' && c <= '9';
+}
+
+/* NOTE: strtod() implementation by Yasuhiro Matsumoto. */
+static double mystrtod(const char *str, const char **end) {
+ double d = 0.0;
+ int sign = 1, n = 0;
+ const char *p = str, *a = str;
+
+ /* decimal part */
+ if (*p == '-') {
+ sign = -1;
+ ++p;
+ } else if (*p == '+') {
+ ++p;
+ }
+ if (is_digit(*p)) {
+ d = (double) (*p++ - '0');
+ while (*p && is_digit(*p)) {
+ d = d * 10.0 + (double) (*p - '0');
+ ++p;
+ ++n;
+ }
+ a = p;
+ } else if (*p != '.') {
+ goto done;
+ }
+ d *= sign;
+
+ /* fraction part */
+ if (*p == '.') {
+ double f = 0.0;
+ double base = 0.1;
+ ++p;
+
+ if (is_digit(*p)) {
+ while (*p && is_digit(*p)) {
+ f += base * (*p - '0');
+ base /= 10.0;
+ ++p;
+ ++n;
+ }
+ }
+ d += f * sign;
+ a = p;
+ }
+
+ /* exponential part */
+ if ((*p == 'E') || (*p == 'e')) {
+ int i, e = 0, neg = 0;
+ p++;
+ if (*p == '-') p++, neg++;
+ if (*p == '+') p++;
+ while (is_digit(*p)) e = e * 10 + *p++ - '0';
+ if (neg) e = -e;
+#if 0
+ if (d == 2.2250738585072011 && e == -308) {
+ d = 0.0;
+ a = p;
+ goto done;
+ }
+ if (d == 2.2250738585072012 && e <= -308) {
+ d *= 1.0e-308;
+ a = p;
+ goto done;
+ }
+#endif
+ for (i = 0; i < e; i++) d *= 10;
+ for (i = 0; i < -e; i++) d /= 10;
+ a = p;
+ } else if (p > str && !is_digit(*(p - 1))) {
+ a = str;
+ goto done;
+ }
+
+done:
+ if (end) *end = a;
+ return d;
+}
+
+#if MJSON_ENABLE_MERGE
+int mjson_merge(const char *s, int n, const char *s2, int n2,
+ mjson_print_fn_t fn, void *userdata) {
+ int koff, klen, voff, vlen, t, t2, k, off = 0, len = 0, comma = 0;
+ if (n < 2) return len;
+ len += fn("{", 1, userdata);
+ while ((off = mjson_next(s, n, off, &koff, &klen, &voff, &vlen, &t)) != 0) {
+ char *path = (char *) alloca((size_t) klen + 1);
+ const char *val;
+ memcpy(path, "$.", 2);
+ memcpy(path + 2, s + koff + 1, (size_t) (klen - 2));
+ path[klen] = '\0';
+ if ((t2 = mjson_find(s2, n2, path, &val, &k)) != MJSON_TOK_INVALID) {
+ if (t2 == MJSON_TOK_NULL) continue; // null deletes the key
+ } else {
+ val = s + voff; // Key is not found in the update. Copy the old value.
+ }
+ if (comma) len += fn(",", 1, userdata);
+ len += fn(s + koff, klen, userdata);
+ len += fn(":", 1, userdata);
+ if (t == MJSON_TOK_OBJECT && t2 == MJSON_TOK_OBJECT) {
+ len += mjson_merge(s + voff, vlen, val, k, fn, userdata);
+ } else {
+ if (t2 != MJSON_TOK_INVALID) vlen = k;
+ len += fn(val, vlen, userdata);
+ }
+ comma = 1;
+ }
+ // Add missing keys
+ off = 0;
+ while ((off = mjson_next(s2, n2, off, &koff, &klen, &voff, &vlen, &t)) != 0) {
+ char *path = (char *) alloca((size_t) klen + 1);
+ const char *val;
+ if (t == MJSON_TOK_NULL) continue;
+ memcpy(path, "$.", 2);
+ memcpy(path + 2, s2 + koff + 1, (size_t) (klen - 2));
+ path[klen] = '\0';
+ if (mjson_find(s, n, path, &val, &vlen) != MJSON_TOK_INVALID) continue;
+ if (comma) len += fn(",", 1, userdata);
+ len += fn(s2 + koff, klen, userdata);
+ len += fn(":", 1, userdata);
+ len += fn(s2 + voff, vlen, userdata);
+ comma = 1;
+ }
+ len += fn("}", 1, userdata);
+ return len;
+}
+#endif // MJSON_ENABLE_MERGE
+
+#if MJSON_ENABLE_PRETTY
+struct prettydata {
+ int level;
+ int len;
+ int prev;
+ const char *pad;
+ int padlen;
+ mjson_print_fn_t fn;
+ void *userdata;
+};
+
+static int pretty_cb(int ev, const char *s, int off, int len, void *ud) {
+ struct prettydata *d = (struct prettydata *) ud;
+ int i;
+ switch (ev) {
+ case '{':
+ case '[':
+ d->level++;
+ d->len += d->fn(s + off, len, d->userdata);
+ break;
+ case '}':
+ case ']':
+ d->level--;
+ if (d->prev != '[' && d->prev != '{' && d->padlen > 0) {
+ d->len += d->fn("\n", 1, d->userdata);
+ for (i = 0; i < d->level; i++)
+ d->len += d->fn(d->pad, d->padlen, d->userdata);
+ }
+ d->len += d->fn(s + off, len, d->userdata);
+ break;
+ case ',':
+ d->len += d->fn(s + off, len, d->userdata);
+ if (d->padlen > 0) {
+ d->len += d->fn("\n", 1, d->userdata);
+ for (i = 0; i < d->level; i++)
+ d->len += d->fn(d->pad, d->padlen, d->userdata);
+ }
+ break;
+ case ':':
+ d->len += d->fn(s + off, len, d->userdata);
+ if (d->padlen > 0) d->len += d->fn(" ", 1, d->userdata);
+ break;
+ case MJSON_TOK_KEY:
+ if (d->prev == '{' && d->padlen > 0) {
+ d->len += d->fn("\n", 1, d->userdata);
+ for (i = 0; i < d->level; i++)
+ d->len += d->fn(d->pad, d->padlen, d->userdata);
+ }
+ d->len += d->fn(s + off, len, d->userdata);
+ break;
+ default:
+ if (d->prev == '[' && d->padlen > 0) {
+ d->len += d->fn("\n", 1, d->userdata);
+ for (i = 0; i < d->level; i++)
+ d->len += d->fn(d->pad, d->padlen, d->userdata);
+ }
+ d->len += d->fn(s + off, len, d->userdata);
+ break;
+ }
+ d->prev = ev;
+ return 0;
+}
+
+int mjson_pretty(const char *s, int n, const char *pad, mjson_print_fn_t fn,
+ void *userdata) {
+ struct prettydata d = {0, 0, 0, pad, (int) strlen(pad), fn, userdata};
+ if (mjson(s, n, pretty_cb, &d) < 0) return -1;
+ return d.len;
+}
+#endif // MJSON_ENABLE_PRETTY
+
+#if MJSON_ENABLE_RPC
+struct jsonrpc_ctx jsonrpc_default_context;
+
+int mjson_globmatch(const char *s1, int n1, const char *s2, int n2) {
+ int i = 0, j = 0, ni = 0, nj = 0;
+ while (i < n1 || j < n2) {
+ if (i < n1 && j < n2 && (s1[i] == '?' || s2[j] == s1[i])) {
+ i++, j++;
+ } else if (i < n1 && (s1[i] == '*' || s1[i] == '#')) {
+ ni = i, nj = j + 1, i++;
+ } else if (nj > 0 && nj <= n2 && (s1[i - 1] == '#' || s2[j] != '/')) {
+ i = ni, j = nj;
+ } else {
+ return 0;
+ }
+ }
+ return 1;
+}
+
+void jsonrpc_return_errorv(struct jsonrpc_request *r, int code,
+ const char *message, const char *data_fmt,
+ va_list *ap) {
+ if (r->id_len == 0) return;
+ mjson_printf(r->fn, r->fn_data,
+ "{\"id\":%.*s,\"error\":{\"code\":%d,\"message\":%Q", r->id_len,
+ r->id, code, message == NULL ? "" : message);
+ if (data_fmt != NULL) {
+ mjson_printf(r->fn, r->fn_data, ",\"data\":");
+ mjson_vprintf(r->fn, r->fn_data, data_fmt, ap);
+ }
+ mjson_printf(r->fn, r->fn_data, "}}\n");
+}
+
+void jsonrpc_return_error(struct jsonrpc_request *r, int code,
+ const char *message, const char *data_fmt, ...) {
+ va_list ap;
+ va_start(ap, data_fmt);
+ jsonrpc_return_errorv(r, code, message, data_fmt, &ap);
+ va_end(ap);
+}
+
+void jsonrpc_return_successv(struct jsonrpc_request *r, const char *result_fmt,
+ va_list *ap) {
+ if (r->id_len == 0) return;
+ mjson_printf(r->fn, r->fn_data, "{\"id\":%.*s,\"result\":", r->id_len, r->id);
+ if (result_fmt != NULL) {
+ mjson_vprintf(r->fn, r->fn_data, result_fmt, ap);
+ } else {
+ mjson_printf(r->fn, r->fn_data, "%s", "null");
+ }
+ mjson_printf(r->fn, r->fn_data, "}\n");
+}
+
+void jsonrpc_return_success(struct jsonrpc_request *r, const char *result_fmt,
+ ...) {
+ va_list ap;
+ va_start(ap, result_fmt);
+ jsonrpc_return_successv(r, result_fmt, &ap);
+ va_end(ap);
+}
+
+void jsonrpc_ctx_process(struct jsonrpc_ctx *ctx, const char *buf, int len,
+ mjson_print_fn_t fn, void *fn_data, void *ud) {
+ const char *result = NULL, *error = NULL;
+ int result_sz = 0, error_sz = 0;
+ struct jsonrpc_method *m = NULL;
+ struct jsonrpc_request r = {ctx, buf, len, 0, 0, 0, 0, 0, 0, fn, fn_data, ud};
+
+ // Is is a response frame?
+ mjson_find(buf, len, "$.result", &result, &result_sz);
+ if (result == NULL) mjson_find(buf, len, "$.error", &error, &error_sz);
+ if (result_sz > 0 || error_sz > 0) {
+ if (ctx->response_cb) ctx->response_cb(buf, len, ctx->response_cb_data);
+ return;
+ }
+
+ // Method must exist and must be a string
+ if (mjson_find(buf, len, "$.method", &r.method, &r.method_len) !=
+ MJSON_TOK_STRING) {
+ mjson_printf(fn, fn_data,
+ "{\"error\":{\"code\":-32700,\"message\":%.*Q}}\n", len, buf);
+ return;
+ }
+
+ // id and params are optional
+ mjson_find(buf, len, "$.id", &r.id, &r.id_len);
+ mjson_find(buf, len, "$.params", &r.params, &r.params_len);
+
+ for (m = ctx->methods; m != NULL; m = m->next) {
+ if (mjson_globmatch(m->method, m->method_sz, r.method + 1,
+ r.method_len - 2) > 0) {
+ if (r.params == NULL) r.params = "";
+ m->cb(&r);
+ break;
+ }
+ }
+ if (m == NULL) {
+ jsonrpc_return_error(&r, JSONRPC_ERROR_NOT_FOUND, "method not found", NULL);
+ }
+}
+
+static int jsonrpc_print_methods(mjson_print_fn_t fn, void *fn_data,
+ va_list *ap) {
+ struct jsonrpc_ctx *ctx = va_arg(*ap, struct jsonrpc_ctx *);
+ struct jsonrpc_method *m;
+ int len = 0;
+ for (m = ctx->methods; m != NULL; m = m->next) {
+ if (m != ctx->methods) len += mjson_print_buf(fn, fn_data, ",", 1);
+ len += mjson_print_str(fn, fn_data, m->method, (int) strlen(m->method));
+ }
+ return len;
+}
+
+void jsonrpc_list(struct jsonrpc_request *r) {
+ jsonrpc_return_success(r, "[%M]", jsonrpc_print_methods, r->ctx);
+}
+
+void jsonrpc_ctx_init(struct jsonrpc_ctx *ctx, mjson_print_fn_t response_cb,
+ void *response_cb_data) {
+ ctx->methods = NULL;
+ ctx->response_cb = response_cb;
+ ctx->response_cb_data = response_cb_data;
+}
+
+void jsonrpc_init(mjson_print_fn_t response_cb, void *userdata) {
+ struct jsonrpc_ctx *ctx = &jsonrpc_default_context;
+ jsonrpc_ctx_init(ctx, response_cb, userdata);
+ jsonrpc_ctx_export(ctx, MJSON_RPC_LIST_NAME, jsonrpc_list);
+}
+#endif // MJSON_ENABLE_RPC
diff --git a/apps/usr_le_code/thirdpart/mjson/mjson.h b/apps/usr_le_code/thirdpart/mjson/mjson.h
new file mode 100644
index 0000000..d8156e0
--- /dev/null
+++ b/apps/usr_le_code/thirdpart/mjson/mjson.h
@@ -0,0 +1,220 @@
+// Copyright (c) 2018-2020 Cesanta Software Limited
+// All rights reserved
+//
+// 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 MJSON_H
+#define MJSON_H
+
+#include
+#include
+#include
+
+#ifndef MJSON_ENABLE_PRINT
+#define MJSON_ENABLE_PRINT 1
+#endif
+
+#ifndef MJSON_ENABLE_RPC
+#define MJSON_ENABLE_RPC 1
+#endif
+
+#ifndef MJSON_ENABLE_BASE64
+#define MJSON_ENABLE_BASE64 1
+#endif
+
+#ifndef MJSON_ENABLE_MERGE
+#define MJSON_ENABLE_MERGE 1
+#endif
+
+#ifndef MJSON_ENABLE_PRETTY
+#define MJSON_ENABLE_PRETTY 1
+#endif
+
+#ifndef MJSON_ENABLE_NEXT
+#define MJSON_ENABLE_NEXT 1
+#endif
+
+#ifndef MJSON_RPC_LIST_NAME
+#define MJSON_RPC_LIST_NAME "rpc.list"
+#endif
+
+#ifndef MJSON_DYNBUF_CHUNK
+#define MJSON_DYNBUF_CHUNK 256 // Allocation granularity for print_dynamic_buf
+#endif
+
+#ifndef MJSON_REALLOC
+#define MJSON_REALLOC realloc
+#endif
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#define MJSON_ERROR_INVALID_INPUT (-1)
+#define MJSON_ERROR_TOO_DEEP (-2)
+#define MJSON_TOK_INVALID 0
+#define MJSON_TOK_KEY 1
+#define MJSON_TOK_STRING 11
+#define MJSON_TOK_NUMBER 12
+#define MJSON_TOK_TRUE 13
+#define MJSON_TOK_FALSE 14
+#define MJSON_TOK_NULL 15
+#define MJSON_TOK_ARRAY 91
+#define MJSON_TOK_OBJECT 123
+#define MJSON_TOK_IS_VALUE(t) ((t) > 10 && (t) < 20)
+
+typedef int (*mjson_cb_t)(int event, const char *buf, int offset, int len,
+ void *fn_data);
+
+#ifndef MJSON_MAX_DEPTH
+#define MJSON_MAX_DEPTH 20
+#endif
+
+int mjson(const char *buf, int len, mjson_cb_t cb, void *ud);
+int mjson_find(const char *buf, int len, const char *jp, const char **tp,
+ int *tl);
+int mjson_get_number(const char *buf, int len, const char *path, double *v);
+int mjson_get_bool(const char *buf, int len, const char *path, int *v);
+int mjson_get_string(const char *buf, int len, const char *path, char *to,
+ int n);
+int mjson_get_hex(const char *buf, int len, const char *path, char *to, int n);
+
+#if MJSON_ENABLE_NEXT
+int mjson_next(const char *buf, int len, int offset, int *key_offset,
+ int *key_len, int *val_offset, int *val_len, int *vale_type);
+#endif
+
+#if MJSON_ENABLE_BASE64
+int mjson_get_base64(const char *buf, int len, const char *path, char *dst,
+ int dst_len);
+int mjson_base64_dec(const char *src, int src_len, char *dst, int dst_len);
+#endif
+
+#if MJSON_ENABLE_PRINT
+typedef int (*mjson_print_fn_t)(const char *buf, int len, void *fn_data);
+typedef int (*mjson_vprint_fn_t)(mjson_print_fn_t fn, void *, va_list *);
+
+struct mjson_fixedbuf {
+ char *ptr;
+ int size, len;
+};
+
+int mjson_printf(mjson_print_fn_t fn, void *fn_data, const char *fmt, ...);
+int mjson_vprintf(mjson_print_fn_t fn, void *fn_data, const char *fmt,
+ va_list *ap);
+int mjson_print_str(mjson_print_fn_t fn, void *fn_data, const char *buf,
+ int len);
+int mjson_print_int(mjson_print_fn_t fn, void *fn_data, int value,
+ int is_signed);
+int mjson_print_long(mjson_print_fn_t fn, void *fn_data, long value,
+ int is_signed);
+int mjson_print_buf(mjson_print_fn_t fn, void *fn_data, const char *buf,
+ int len);
+int mjson_print_dbl(mjson_print_fn_t fn, void *fn_data, double d, int width);
+
+int mjson_print_null(const char *ptr, int len, void *fn_data);
+int mjson_print_fixed_buf(const char *ptr, int len, void *fn_data);
+int mjson_print_dynamic_buf(const char *ptr, int len, void *fn_data);
+
+int mjson_snprintf(char *buf, size_t len, const char *fmt, ...);
+char *mjson_aprintf(const char *fmt, ...);
+
+#if MJSON_ENABLE_PRETTY
+int mjson_pretty(const char *s, int n, const char *pad, mjson_print_fn_t fn,
+ void *fn_data);
+#endif
+
+#if MJSON_ENABLE_MERGE
+int mjson_merge(const char *s, int n, const char *s2, int n2,
+ mjson_print_fn_t fn, void *fn_data);
+#endif
+
+#endif // MJSON_ENABLE_PRINT
+
+#if MJSON_ENABLE_RPC
+
+void jsonrpc_init(mjson_print_fn_t response_cb, void *fn_data);
+int mjson_globmatch(const char *s1, int n1, const char *s2, int n2);
+
+struct jsonrpc_request {
+ struct jsonrpc_ctx *ctx;
+ const char *frame; // Points to the whole frame
+ int frame_len; // Frame length
+ const char *params; // Points to the "params" in the request frame
+ int params_len; // Length of the "params"
+ const char *id; // Points to the "id" in the request frame
+ int id_len; // Length of the "id"
+ const char *method; // Points to the "method" in the request frame
+ int method_len; // Length of the "method"
+ mjson_print_fn_t fn; // Printer function
+ void *fn_data; // Printer function data
+ void *userdata; // Callback's user data as specified at export time
+};
+
+struct jsonrpc_method {
+ const char *method;
+ int method_sz;
+ void (*cb)(struct jsonrpc_request *);
+ struct jsonrpc_method *next;
+};
+
+// Main RPC context, stores current request information and a list of
+// exported RPC methods.
+struct jsonrpc_ctx {
+ struct jsonrpc_method *methods;
+ mjson_print_fn_t response_cb;
+ void *response_cb_data;
+};
+
+// Registers function fn under the given name within the given RPC context
+#define jsonrpc_ctx_export(ctx, name, fn) \
+ do { \
+ static struct jsonrpc_method m = {(name), sizeof(name) - 1, (fn), 0}; \
+ m.next = (ctx)->methods; \
+ (ctx)->methods = &m; \
+ } while (0)
+
+void jsonrpc_ctx_init(struct jsonrpc_ctx *ctx, mjson_print_fn_t response_cb,
+ void *response_cb_data);
+void jsonrpc_return_error(struct jsonrpc_request *r, int code,
+ const char *message, const char *data_fmt, ...);
+void jsonrpc_return_success(struct jsonrpc_request *r, const char *result_fmt,
+ ...);
+void jsonrpc_ctx_process(struct jsonrpc_ctx *ctx, const char *req, int req_sz,
+ mjson_print_fn_t fn, void *fn_data, void *userdata);
+
+extern struct jsonrpc_ctx jsonrpc_default_context;
+extern void jsonrpc_list(struct jsonrpc_request *r);
+
+#define jsonrpc_export(name, fn) \
+ jsonrpc_ctx_export(&jsonrpc_default_context, (name), (fn))
+
+#define jsonrpc_process(buf, len, fn, fnd, ud) \
+ jsonrpc_ctx_process(&jsonrpc_default_context, (buf), (len), (fn), (fnd), (ud))
+
+#define JSONRPC_ERROR_INVALID -32700 /* Invalid JSON was received */
+#define JSONRPC_ERROR_NOT_FOUND -32601 /* The method does not exist */
+#define JSONRPC_ERROR_BAD_PARAMS -32602 /* Invalid params passed */
+#define JSONRPC_ERROR_INTERNAL -32603 /* Internal JSON-RPC error */
+
+#endif // MJSON_ENABLE_RPC
+#ifdef __cplusplus
+}
+#endif
+#endif // MJSON_H
diff --git a/apps/usr_le_code/usr_le_adv.c b/apps/usr_le_code/usr_le_adv.c
new file mode 100644
index 0000000..9faa88c
--- /dev/null
+++ b/apps/usr_le_code/usr_le_adv.c
@@ -0,0 +1,340 @@
+/******************************************************************************
+ * @file usr_le_adv.c
+ * @brief BLE 广播 / 配对 / OTA 广播切换
+ * @author cyWu <1917507415@qq.com>
+ * @date 2026.08.19
+ * @version V1.1.0
+ * @history
+ * - V1.0.0, 2026.08.03, cyWu, 首次发布
+ * - V1.1.0, 2026.08.19, cyWu, 对齐模组注释与助手;保留 SOC 上电绑广播策略
+ ******************************************************************************/
+
+#include "system/includes.h"
+#include "app_config.h"
+#include "app_main.h"
+#include "vm.h"
+#include "bleproto.h"
+#include "bleproto_api.h"
+#include "usr_le_product.h"
+
+#define LOG_TAG_CONST APP
+#define LOG_TAG "[LE_ADV]"
+#define LOG_ERROR_ENABLE
+#define LOG_DEBUG_ENABLE
+#define LOG_INFO_ENABLE
+#include "debug.h"
+
+/******************************************************************************
+ * 广播相关三个标志(务必区分):
+ *
+ * 1) usr_auth_data.paired_flag —— 配网结果(存 VM,掉电保持)
+ * - 0:未配网
+ * - 1:已配网(三元组已保存)
+ *
+ * 2) usr_var.usr_goto_pair —— 是否主动进入配网流程(RAM,掉电丢失)
+ * - 0:非配网流程
+ * - 1:app_main 上电 / usr_goto_pair_mode() 触发,发【绑定广播】
+ *
+ * 3) usr_var.usr_adv_flag —— 广播内容是否需要刷新到协议栈(一次性)
+ * - 1:usr_ble_adv_updata() 会重新 set adv data 并 enable
+ * - 0:本周期不刷新
+ *
+ * SOC 决策表(与模组不同:未配网也发绑定广播,便于上电配网):
+ * usr_goto_pair==1 → 绑定广播
+ * paired_flag==0 → 绑定广播
+ * paired_flag==1 → 回连广播
+ ******************************************************************************/
+
+extern u8 muti_adv_data[31];
+extern u8 muti_adv_data_len;
+
+/* 定义在 usr_le_recieve.c,库内共用,不对外导出 */
+extern bleproto_authsetup_req_t usr_auth_data;
+
+extern u16 usr_get_conn_service(void);
+extern int muti_make_set_adv_data(u8 *data, u8 data_len);
+extern int muti_make_set_adv_data_updata(void);
+extern void usr_set_adv_interval(u16 val);
+extern u16 usr_get_adv_interval(void);
+extern void ble_multi_trans_disconnect(void);
+extern void ble_trans_module_enable(u8 flag);
+extern void usr_timer_loop(void);
+extern u8 usr_get_ota_status(void);
+extern void usr_ota_exit(void);
+
+void usr_ble_adv_init(void);
+void usr_ble_adv_updata(void);
+
+static int le_timer_handle = 0;
+
+/**
+ * @brief BLE 是否已连接
+ * @return 1=已连接,0=未连接
+ */
+uint8_t usr_ble_is_connected(void)
+{
+ return (usr_get_conn_service() != 0) ? 1u : 0u;
+}
+
+/**
+ * @brief 从 VM 读取配对信息到 usr_auth_data
+ * @note 失败则清零,并将 paired_flag 置 0 写回
+ */
+void usr_get_pair_info(void)
+{
+ int ret;
+
+ ret = syscfg_read(CFG_USER_PAIR_INFO, (u8 *)&usr_auth_data, sizeof(usr_auth_data));
+ if (ret <= 0)
+ {
+ memset(&usr_auth_data, 0x00, sizeof(usr_auth_data));
+ usr_auth_data.paired_flag = 0;
+ syscfg_write(CFG_USER_PAIR_INFO, (u8 *)&usr_auth_data, sizeof(usr_auth_data));
+ }
+}
+
+/**
+ * @brief 标记已配网并保存三元组到 VM
+ * @note AUTHSETUP 成功后调用,paired_flag = 1
+ */
+void usr_write_pair_info(void)
+{
+ usr_auth_data.paired_flag = 1;
+ syscfg_write(CFG_USER_PAIR_INFO, (u8 *)&usr_auth_data, sizeof(usr_auth_data));
+}
+
+/**
+ * @brief 清除配对信息并延时复位
+ */
+void usr_clear_pair_info(void)
+{
+ printf("usr_clear_pair_info_reset\n");
+ memset(&usr_auth_data, 0x00, sizeof(usr_auth_data));
+ usr_auth_data.paired_flag = 0;
+ syscfg_write(CFG_USER_PAIR_INFO, (u8 *)&usr_auth_data, sizeof(usr_auth_data));
+ sys_timeout_add(NULL, cpu_reset, 600);
+}
+
+/**
+ * @brief 清除配对信息但不复位(用于重新配网)
+ */
+void usr_clear_pair_info_noreset(void)
+{
+ printf("usr_clear_pair_info_noreset\n");
+ memset(&usr_auth_data, 0x00, sizeof(usr_auth_data));
+ usr_auth_data.paired_flag = 0;
+ syscfg_write(CFG_USER_PAIR_INFO, (u8 *)&usr_auth_data, sizeof(usr_auth_data));
+}
+
+/**
+ * @brief 进入配网模式:清配对 + 置 usr_goto_pair + 发绑定广播
+ */
+void usr_goto_pair_mode(void)
+{
+ ble_multi_trans_disconnect();
+ usr_clear_pair_info_noreset();
+ usr_var.usr_goto_pair = 1;
+ os_time_dly(5);
+ usr_ble_adv_init();
+}
+
+/**
+ * @brief 断开 BLE 并停止广播(复位/重启前)
+ */
+void usr_ble_disconnect_and_stop_adv(void)
+{
+ printf("usr_ble_disconnect_and_stop_adv\n");
+ ble_multi_trans_disconnect();
+ usr_var.usr_goto_pair = 0;
+ usr_var.usr_adv_flag = 0;
+ ble_trans_module_enable(0);
+}
+
+/**
+ * @brief 按当前标志刷新广播策略并启动周期更新
+ * @note 见文件头「三个标志」;SOC 未配网也发绑定广播
+ */
+void usr_ble_adv_init(void)
+{
+ int8_t txpower = 0;
+ uint8_t manucode[BLEPROTO_ADV_TLV_LENGTH_MANUCODE] = {0};
+ uint8_t prodcode[BLEPROTO_ADV_TLV_LENGTH_PRODCODE];
+ uint8_t gmac[6] = {0};
+ uint8_t pcode[BLE_PROTO_ADV_LENGTH_PCODE];
+
+ /* 产品身份由应用层 g_usr_le_* 提供(见 usr_jb_main.c) */
+ memcpy(prodcode, g_usr_le_prodcode, BLEPROTO_ADV_TLV_LENGTH_PRODCODE);
+ memcpy(pcode, g_usr_le_pcode, BLE_PROTO_ADV_LENGTH_PCODE);
+
+ usr_set_adv_interval(80);
+ if (usr_var.usr_ota_succ_flag)
+ {
+ return;
+ }
+
+ if (usr_var.usr_goto_pair)
+ {
+ /* app_main 上电已置 usr_goto_pair=1 并清配对信息,此处发绑定广播供网关配网 */
+ usr_clear_pair_info_noreset();
+ printf("goto pair bind adv, paired_flag=%d\n", usr_auth_data.paired_flag);
+ muti_adv_data_len = bleproto_advdata_encode4bind(muti_adv_data, txpower,
+ manucode, pcode, prodcode);
+ usr_var.usr_adv_flag = 1;
+ }
+ else
+ {
+ usr_get_pair_info();
+ if (usr_auth_data.paired_flag == 0)
+ {
+ /* SOC:未配网也发绑定广播(模组此处为不广播) */
+ muti_adv_data_len = bleproto_advdata_encode4bind(muti_adv_data, txpower,
+ manucode, pcode, prodcode);
+ usr_var.usr_adv_flag = 0;
+ }
+ else
+ {
+ memcpy(gmac, usr_auth_data.gwmac, 6);
+ muti_adv_data_len = bleproto_advdata_encode4reconn(muti_adv_data, txpower, gmac,
+ manucode, pcode, prodcode);
+ usr_var.usr_adv_flag = 1;
+ }
+ }
+
+ usr_ble_adv_updata();
+ if (le_timer_handle == 0)
+ {
+ le_timer_handle = sys_timer_add(NULL, usr_ble_adv_updata, 500);
+ }
+}
+
+/**
+ * @brief 获取是否已配网
+ * @return 1=已配网,0=未配网
+ */
+u8 usr_get_pair_flag(void)
+{
+ return usr_auth_data.paired_flag;
+}
+
+/**
+ * @brief 周期处理广播刷新(由 500ms 定时器调用)
+ * @note 仅当 usr_adv_flag==1 时:停广播 → 写入 muti_adv_data → 再开广播
+ */
+void usr_ble_adv_updata(void)
+{
+ static u16 usr_goto_slow_adv = 0;
+
+ if (usr_var.usr_adv_flag)
+ {
+ ble_trans_module_enable(0);
+ usr_var.usr_adv_flag = 0;
+ muti_make_set_adv_data(muti_adv_data, muti_adv_data_len);
+ printf("###muti_adv_data = ");
+ printf_buf(muti_adv_data, muti_adv_data_len);
+ ble_trans_module_enable(1);
+ }
+
+ if (!usr_ble_is_connected())
+ {
+ /* 未连接:回连快广播(80)持续约 60s(500ms×120)后切慢广播 */
+ if (usr_get_adv_interval() == 80)
+ {
+ if ((usr_var.usr_goto_pair == 0) && usr_auth_data.paired_flag)
+ {
+ if (usr_var.usr_ota_succ_flag == 0)
+ {
+ usr_goto_slow_adv++;
+ printf("usr_goto_slow_adv = %d\n", usr_goto_slow_adv);
+ }
+ if (usr_goto_slow_adv >= 120)
+ {
+ usr_goto_slow_adv = 0;
+ usr_set_adv_interval(80 * 10);
+ usr_var.usr_adv_flag = 1;
+ }
+ }
+ }
+ else
+ {
+ usr_goto_slow_adv = 0;
+ }
+ }
+ else
+ {
+ usr_goto_slow_adv = 0;
+ }
+
+ if (usr_get_ota_status() == 0)
+ {
+ if (!usr_ble_is_connected())
+ {
+ if (usr_var.usr_ota_succ_flag == 0)
+ {
+ usr_ota_exit();
+ }
+ }
+ }
+
+ /* 协议层周期处理(上报/应答) */
+ usr_timer_loop();
+}
+
+void usr_soft_off(void)
+{
+ sys_enter_soft_poweroff(NULL);
+}
+
+void usr_ble_adv_updata_OTA(void)
+{
+ ble_trans_module_enable(0);
+ usr_var.usr_adv_flag = 0;
+
+ extern u8 usr_mac_addr[6];
+ extern int le_controller_set_mac(void *addr);
+ usr_mac_addr[0] = usr_mac_addr[0] + 1;
+ le_controller_set_mac(usr_mac_addr);
+ muti_make_set_adv_data_updata();
+ printf("###muti_adv_data = ");
+ printf_buf(muti_adv_data, muti_adv_data_len);
+ ble_trans_module_enable(1);
+}
+
+void usr_ota_process(void)
+{
+ static u8 cnt = 0;
+
+ if (cnt == 0)
+ {
+ ble_multi_trans_disconnect();
+ }
+
+ if (!usr_ble_is_connected())
+ {
+ cnt++;
+ if (cnt == 2)
+ {
+ usr_ble_adv_updata_OTA();
+ }
+ if (cnt >= 60)
+ {
+ cnt = 0;
+ cpu_reset();
+ }
+ }
+ else
+ {
+ cnt = 1;
+ }
+}
+
+/**
+ * @brief 旧版 RCSP/JSON OTA 入口;产品 JB 0x30/0x32 路径不要调用
+ */
+void usr_app_ota_init(void)
+{
+ usr_var.usr_goto_updata = 1;
+ if (usr_var.ota_timer == 0)
+ {
+ usr_var.ota_timer = sys_timer_add(NULL, usr_ota_process, 1000);
+ }
+}
diff --git a/apps/usr_le_code/usr_le_recieve.c b/apps/usr_le_code/usr_le_recieve.c
new file mode 100644
index 0000000..4e0ddfe
--- /dev/null
+++ b/apps/usr_le_code/usr_le_recieve.c
@@ -0,0 +1,377 @@
+/******************************************************************************
+ * @file usr_le_recieve.c
+ * @brief BLE 收包入口:bleproto 解析后分发配网 / 对时 / JB 协议 / 组应答
+ * @author cyWu <1917507415@qq.com>
+ * @date 2026.08.19
+ * @version V1.1.0
+ * @history
+ * - V1.0.0, 2026.08.03, cyWu, 首次发布
+ * - V1.1.0, 2026.08.19, cyWu, 对齐模组结构;废弃 JSON OTA;修 AUTHDELETE serviceid
+ ******************************************************************************/
+
+#include "system/includes.h"
+#include "app_config.h"
+#include "app_main.h"
+#include "vm.h"
+#include "bleproto.h"
+#include "bleproto_api.h"
+#include "ble_proto.h"
+#include "usr_rtc.h"
+#include "usr_le_api.h"
+#include "jb_protocol.h"
+
+#define LOG_TAG_CONST APP
+#define LOG_TAG "[USR_LE]"
+#define LOG_ERROR_ENABLE
+#define LOG_DEBUG_ENABLE
+#define LOG_INFO_ENABLE
+#include "debug.h"
+
+/* 拼 GATT 分包:业务包 ≈ bleproto头 + V2 开销 + JB 帧(<=128),1024 足够 */
+#define USR_LE_RX_BUF_LEN 1024
+#define USR_LE_V2_WRAP_OVERHEAD 32u /* V2 头开销,JB 帧最大 128 → 约 160 */
+#define USR_LE_V2_CMD_REPORT 100u /* REPORTCMD_V2 内层 cmd */
+#define USR_LE_V2_CMD_RUN 110u /* RUNCMD_V2 内层 cmd */
+#define USR_LE_JB_CMD_OFF 4u /* 55 AA | LEN_H LEN_L | CMD */
+
+static int encode_len = 0;
+static u8 txbuf[384] = {0};
+static u8 rxbuf[USR_LE_RX_BUF_LEN] = {0};
+static u8 s_last_runcmd_msgid = 0; /* RUNCMD_V2 应答须回填最近 msgid */
+
+bleproto_authsetup_req_t usr_auth_data;
+
+extern void usr_ble_send_data(u8 *data, u16 len);
+extern u8 usr_ble_is_notify_ready(void);
+extern void usr_write_pair_info(void);
+extern void usr_clear_pair_info(void);
+extern void usr_jb_le_recieve_data(u8 *data, u16 len);
+extern int8_t jbReportAckCheck(u16 cmd, u8 gateway_int_cnt, int32_t gateway_int0);
+
+static void usr_data_ana(bleproto_appdata_desc_t *desc);
+static void usr_run_cmd_code_v2(ble_proto_packet_t *runcmd_par, u8 usr_msg_id);
+
+/**
+ * @brief 填 bleproto 应答头
+ * @param out 输出 desc
+ * @param in 请求 desc(取 msgid)
+ * @param serviceid 服务号
+ */
+static void usr_le_fill_rsp_header(bleproto_appdata_desc_t *out,
+ const bleproto_appdata_desc_t *in,
+ uint8_t serviceid)
+{
+ out->header.version = 0;
+ out->header.datafmt = BLEPROTO_APPDATA_DATAFMT_JSON;
+ out->header.msgtype = BLEPROTO_APPDATA_MSGTYPE_RSP;
+ out->header.msgid = in->header.msgid;
+ out->header.encrypt = 0;
+ out->header.serviceid = serviceid;
+}
+
+/**
+ * @brief 编码并经 BLE 发出
+ * @param desc 已填好的应答
+ */
+static void usr_le_encode_and_send(bleproto_appdata_desc_t *desc)
+{
+ encode_len = bleproto_appdata_encode(txbuf, sizeof(txbuf), sizeof(txbuf), desc);
+ if (encode_len > 0)
+ {
+ printf("encode_len = %d\n", encode_len);
+ usr_ble_send_data(txbuf, encode_len);
+ }
+ else
+ {
+ printf("encode_len fail %d\n", encode_len);
+ }
+}
+
+/**
+ * @brief 是否走网关主动上报(REPORTCMD_V2)
+ * @param jb_cmd 55AA 命令字
+ * @return 1=主动上报,0=RUNCMD 应答
+ */
+static uint8_t usr_le_is_gateway_report_cmd(uint8_t jb_cmd)
+{
+ return (jb_cmd == CMD_REPORT ||
+ jb_cmd == CMD_OTA_COMPLETE ||
+ jb_cmd == CMD_OTA_STOP_MCU)
+ ? 1u
+ : 0u;
+}
+
+/**
+ * @brief BLE 收包入口
+ * @param data 收包数据
+ * @param len 数据长度
+ */
+void usr_le_data_recieve(u8 *data, u16 len)
+{
+ static u16 usr_len = 0;
+ /* desc 含 ycmd 等 union,放 static,避免每次收包在栈上开大块 */
+ static bleproto_appdata_desc_t s_rx_desc;
+ int rc_result = 0;
+
+ if (!data || len == 0)
+ {
+ return;
+ }
+ if ((u32)usr_len + len > sizeof(rxbuf))
+ {
+ printf("### rxbuf overflow, usr_len=%u len=%u, reset\n", usr_len, len);
+ usr_len = 0;
+ return;
+ }
+
+ memcpy(&rxbuf[usr_len], data, len);
+ usr_len += len;
+ rc_result = bleproto_appdata_decode(rxbuf, usr_len, &s_rx_desc);
+ if (rc_result < 0)
+ {
+ printf("### invild pack\n");
+ usr_len = 0;
+ }
+ else if (rc_result == 0)
+ {
+ printf("### keep recieving\n");
+ }
+ else
+ {
+ printf("### pack recieved ok\n");
+ usr_len = 0;
+ usr_data_ana(&s_rx_desc);
+ }
+}
+
+/**
+ * @brief 解析 bleproto 服务并分发
+ * @param desc 已 decode 的包
+ */
+static void usr_data_ana(bleproto_appdata_desc_t *desc)
+{
+ static bleproto_appdata_desc_t s_encode_desc;
+
+ memset(&s_encode_desc, 0, sizeof(s_encode_desc));
+ printf("desc serviceid=%d msgtype=%d\n",
+ desc->header.serviceid, desc->header.msgtype);
+
+ if (desc->header.msgtype == BLEPROTO_APPDATA_MSGTYPE_REQ)
+ {
+ switch (desc->header.serviceid)
+ {
+ case E_BLEPROTO_SERVICE_ID_DEVICEINFO: {
+ bleproto_deviceinfo_req_t *req = &desc->datast.deviceinfo_req;
+ bleproto_deviceinfo_rsp_t *rsp = &s_encode_desc.datast.deviceinfo_rsp;
+
+ /* 网关从子设备连上开始计时,每 12 小时经 DEVICEINFO 同步一次 */
+ usr_rtc_set_from_unix(req->t, (int32_t)req->gmtoff);
+
+ usr_le_fill_rsp_header(&s_encode_desc, desc, E_BLEPROTO_SERVICE_ID_DEVICEINFO);
+ rsp->hbcycle = 1000;
+ strcpy(rsp->swv, "V1.0.0.00");
+ strcpy(rsp->hwv, "V1.0.0.00");
+ rsp->longcon = 1;
+ rsp->prototype = 4;
+ usr_le_encode_and_send(&s_encode_desc);
+ break;
+ }
+ case E_BLEPROTO_SERVICE_ID_AUTHSETUP: {
+ bleproto_authsetup_rsp_t *au_rsp = &s_encode_desc.datast.authsetup_rsp;
+
+ printf("E_BLEPROTO_SERVICE_ID_AUTHSETUP\n");
+ usr_le_fill_rsp_header(&s_encode_desc, desc, E_BLEPROTO_SERVICE_ID_AUTHSETUP);
+ au_rsp->errcode = 0;
+ memcpy(&usr_auth_data, &desc->datast.authsetup_req, sizeof(usr_auth_data));
+ if (usr_auth_data.paired_flag == 0)
+ {
+ usr_write_pair_info();
+ usr_var.usr_goto_pair = 0; // 新增:退出强制配网
+ printf("usr_auth_data %s %s ", usr_auth_data.authcode, usr_auth_data.devid);
+ printf_buf(usr_auth_data.gwmac, 6);
+ }
+ usr_le_encode_and_send(&s_encode_desc);
+ break;
+ }
+ case E_BLEPROTO_SERVICE_ID_AUTHDELETE: {
+ bleproto_authdelete_rsp_t *aude_rsp = &s_encode_desc.datast.authdelete_rsp;
+
+ printf("E_BLEPROTO_SERVICE_ID_AUTHDELETE\n");
+ usr_le_fill_rsp_header(&s_encode_desc, desc, E_BLEPROTO_SERVICE_ID_AUTHDELETE);
+ memcpy(aude_rsp->gwmac, usr_auth_data.gwmac, 6);
+ if (!memcmp(usr_auth_data.authcode, desc->datast.authdelete_req.authcode, 32))
+ {
+ aude_rsp->errcode = 0;
+ usr_clear_pair_info();
+ }
+ else
+ {
+ aude_rsp->errcode = 501;
+ }
+ usr_le_encode_and_send(&s_encode_desc);
+ break;
+ }
+ case E_BLEPROTO_SERVICE_ID_RUNCMD:
+ printf("E_BLEPROTO_SERVICE_ID_RUNCMD\n");
+ break;
+ case E_BLEPROTO_SERVICE_ID_RUNCMD_V2:
+ printf("E_BLEPROTO_SERVICE_ID_RUNCMD_V2\n");
+ usr_run_cmd_code_v2(&desc->datast.runcmd_v2_req, desc->header.msgid);
+ break;
+ case E_BLEPROTO_SERVICE_ID_OTANOTIFY:
+ case E_BLEPROTO_SERVICE_ID_OTADATA:
+ case E_BLEPROTO_SERVICE_ID_OTADATA_V2:
+ /* JSON OTA 已废弃,SOC 走 JB 0x30/0x32 */
+ printf("JSON OTA deprecated, use JB 0x30/0x32\n");
+ break;
+ default:
+ printf("err !!! default event desc->header.serviceid =%d\n",
+ desc->header.serviceid);
+ break;
+ }
+ return;
+ }
+
+ if (desc->header.msgtype == BLEPROTO_APPDATA_MSGTYPE_RSP)
+ {
+ switch (desc->header.serviceid)
+ {
+ case E_BLEPROTO_SERVICE_ID_REPORTCMD:
+ printf("E_BLEPROTO_SERVICE_ID_REPORTCMD errcode=%d\n",
+ desc->datast.reportcmd_rsp.errcode);
+ break;
+ case E_BLEPROTO_SERVICE_ID_REPORTCMD_V2: {
+ ble_proto_packet_t *rpt_ack = &desc->datast.reportcmd_v2_rsp;
+
+ printf("REPORTCMD_V2 cmd=%u cnt=%u int0=%ld\n",
+ (unsigned)rpt_ack->cmd,
+ (unsigned)rpt_ack->gateway_int_cnt,
+ (long)((rpt_ack->gateway_int_cnt > 0) ? rpt_ack->gateway_int[0] : 0));
+ jbReportAckCheck(rpt_ack->cmd,
+ rpt_ack->gateway_int_cnt,
+ (rpt_ack->gateway_int_cnt > 0) ? rpt_ack->gateway_int[0] : -1);
+ break;
+ }
+ case E_BLEPROTO_SERVICE_ID_OTADATA:
+ printf("JSON OTA deprecated, use JB 0x32\n");
+ break;
+ default:
+ printf("unhandled RSP serviceid=%d\n", desc->header.serviceid);
+ break;
+ }
+ }
+}
+
+/**
+ * @brief APP RUNCMD_V2:55AA 字节流转交 JB 协议层
+ * @param runcmd_par 内层包
+ * @param usr_msg_id bleproto msgid
+ */
+static void usr_run_cmd_code_v2(ble_proto_packet_t *runcmd_par, u8 usr_msg_id)
+{
+ u8 jb_frame[MAX_PACKAGE_LEN];
+ u16 copy_len;
+
+ if (!runcmd_par || !runcmd_par->bytes_data || runcmd_par->device_bytes_len == 0)
+ {
+ printf("usr_run_cmd_code_v2 invalid bytes, len=%u\n",
+ runcmd_par ? runcmd_par->device_bytes_len : 0);
+ return;
+ }
+
+ printf("runcmd_par id = %d, bytes_len = %u\n",
+ runcmd_par->cmd, runcmd_par->device_bytes_len);
+
+ copy_len = runcmd_par->device_bytes_len;
+ if (copy_len > sizeof(jb_frame))
+ {
+ printf("usr_run_cmd_code_v2 bytes too long %u\n", copy_len);
+ return;
+ }
+ memcpy(jb_frame, runcmd_par->bytes_data, copy_len);
+
+ s_last_runcmd_msgid = usr_msg_id;
+ usr_jb_le_recieve_data(jb_frame, copy_len);
+}
+
+/**
+ * @brief 将 JB 协议帧封装为 bleproto V2 后通过 BLE 发送
+ * @param data JB 协议原始帧(55 AA | LEN | CMD | ...)
+ * @param len 帧长度
+ * @note 主动上报(0x07/0x34/0x38) → REPORTCMD_V2;其余 → RUNCMD_V2 应答
+ * 对外符号名保持 ble_send_data,供 jb_protocol 调用
+ */
+void ble_send_data(u8 *data, u16 len)
+{
+ ble_proto_packet_t pkt;
+ bleproto_appdata_header_t hdr;
+ u8 v2_buf[MAX_PACKAGE_LEN + USR_LE_V2_WRAP_OVERHEAD];
+ u8 jb_cmd;
+ u8 is_active_send;
+ int plen;
+ int elen;
+
+ if (!data || len < 5)
+ {
+ printf("ble_send_data invalid param, len=%d\n", len);
+ return;
+ }
+ // if (len > MAX_PACKAGE_LEN)
+ // {
+ // printf("ble_send_data frame too long %u\n", len);
+ // return;
+ // }
+ if (!usr_ble_is_notify_ready())
+ {
+ printf("ble_send_data wait CCC cmd=0x%02X\n", data[USR_LE_JB_CMD_OFF]);
+ return;
+ }
+
+ jb_cmd = data[USR_LE_JB_CMD_OFF];
+ is_active_send = usr_le_is_gateway_report_cmd(jb_cmd);
+
+ memset(&pkt, 0, sizeof(pkt));
+ memset(&hdr, 0, sizeof(hdr));
+ hdr.version = 0;
+ hdr.datafmt = BLEPROTO_APPDATA_DATAFMT_JSON;
+ hdr.encrypt = 0;
+
+ if (is_active_send)
+ {
+ hdr.msgtype = BLEPROTO_APPDATA_MSGTYPE_REQ;
+ hdr.msgid = 0;
+ hdr.serviceid = E_BLEPROTO_SERVICE_ID_REPORTCMD_V2;
+ pkt.cmd = USR_LE_V2_CMD_REPORT;
+ pkt.gateway_int_cnt = 0;
+ }
+ else
+ {
+ hdr.msgtype = BLEPROTO_APPDATA_MSGTYPE_RSP;
+ hdr.msgid = s_last_runcmd_msgid;
+ hdr.serviceid = E_BLEPROTO_SERVICE_ID_RUNCMD_V2;
+ pkt.cmd = USR_LE_V2_CMD_RUN;
+ pkt.gateway_int_cnt = 2;
+ pkt.gateway_int[0] = 0;
+ pkt.gateway_int[1] = 0;
+ }
+
+ pkt.device_bytes_len = len;
+ pkt.bytes_data = data;
+
+ plen = ble_proto_pack(&pkt, v2_buf, sizeof(v2_buf));
+ if (plen <= 0)
+ {
+ printf("ble_send_data pack fail %d\n", plen);
+ return;
+ }
+
+ elen = bleproto_appdata_wrap_raw(txbuf, sizeof(txbuf), &hdr, v2_buf, (uint16_t)plen);
+ printf("ble_send_data jb_cmd=0x%02X active=%d encode_len=%d msgid=%d\n",
+ jb_cmd, is_active_send, elen, hdr.msgid);
+ if (elen <= 0)
+ {
+ return;
+ }
+ usr_ble_send_data(txbuf, elen);
+ printf_buf(txbuf, elen);
+}