+++ /dev/null
-[submodule "tuya-iot-core-sdk"]
- path = tuya-iot-core-sdk
- url = https://github.com/tuya/tuya-iot-core-sdk.git
cmake_minimum_required(VERSION 3.8)
-project(mg_app)
+project(rfjb_app)
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -pie -fPIE -g2 -O2")
add_subdirectory( ${CMAKE_CURRENT_LIST_DIR}/button )
add_subdirectory( ${CMAKE_CURRENT_LIST_DIR}/led )
add_subdirectory( ${CMAKE_CURRENT_LIST_DIR}/log )
-add_subdirectory( ${CMAKE_CURRENT_LIST_DIR}/buzzer )
-add_subdirectory( ${CMAKE_CURRENT_LIST_DIR}/eia485 )
-add_subdirectory( ${CMAKE_CURRENT_LIST_DIR}/udp )
+++ /dev/null
-\r
-# TW8013中间件接口定义\r
----\r
-1. 按键\r
-2. LED包括 按键背光 装饰灯带 红外补光 灯圈\r
-3. 人感TOF\r
-4. 环境光\r
-5. EIA485\r
-6. 蜂鸣器\r
----\r
-## 1.按键管理\r
-### 1.1 数据类型定义\r
-#### 键值定义\r
- 支持8个按键,BUTTON_1 到BUTTON_8\r
- typedef enum{\r
- BUTTON_1 = (1<<0),\r
- BUTTON_2 = (1<<1),\r
- BUTTON_3 = (1<<2),\r
- BUTTON_4 = (1<<3),\r
- BUTTON_5 = (1<<4),\r
- BUTTON_6 = (1<<5),\r
- BUTTON_7 = (1<<6),\r
- BUTTON_8 = (1<<7),\r
- BUTTON_ALL = 0xff,\r
- }button_code_t;\r
-#### 事件类型定义:\r
- 普通按键事件:单击、双击、长按、长按释放\r
- 组合按键事件:组合键按下\r
- typedef enum{\r
- EVENT_SINGLE_CLICK = (1<<0),\r
- EVENT_DOUBLE_CLICK = (1<<1),\r
- EVENT_LONG_PRESS = (1<<2),\r
- EVENT_LONG_PRESS_2S = (1<<3),\r
- EVENT_LONG_PRESS_5S = (1<<4),\r
- EVENT_LONG_PRESS_UP = (1<<5),\r
- EVENT_COMB_PRESS = (1<<6),\r
- EVENT_COMB_PRESS_2S = (1<<7),\r
- EVENT_COMB_PRESS_5S = (1<<8),\r
- }button_event_t;\r
-#### 按键控制描述符\r
- typedef void* btn_ctrl_t;\r
-#### 回调函数\r
- typedef void ( * button_event_cb_t )( button_code_t code, button_event_t evt, void * value );\r
- 参数定义:\r
- code:键值,对于组合键可以是多个键值组合值\r
- evt: 按键类型 ,单击 双击 组合键长按等事件\r
- value: 预留参数\r
- 返回值: 无\r
-### 1.2 控制接口\r
-#### 获取按键控制器\r
- 默认按键设备:\r
- #define BUTTON_DEVICE_PATH "/dev/input/event2" \r
- \r
- btn_ctrl_t mg_button_open( char * button_device_path );\r
- 参数定义:\r
- button_device_path:键盘设备文件, 如/dev/input/event1\r
- 如果是NULL,则使用默认设备\r
- 返回值: \r
- 打开失败,返回 NULL, 成功,返回按键控制器描述符。\r
-#### 关闭按键控制器\r
- void mg_button_close( btn_ctrl_t btn_ctrl );\r
- 参数定义:\r
- btn_ctrl: 按键控制器描述符\r
- 返回值: 无\r
-#### 注册普通按键事件\r
- int32_t mg_button_event_register( btn_ctrl_t btn_ctrl, button_code_t code, button_event_t event, button_event_cb_t cb );\r
- 参数定义:\r
- btn_ctrl: 按键控制器描述符\r
- code: 键值,可以是包含多个按键值\r
- event: 按键事件类型,可以包含多个事件类型\r
- cb: 按键触发时的回调函数\r
- 返回值:\r
- 0: 成功\r
- -1:失败\r
-#### 注册组合按键事件\r
- int32_t mg_button_event_combonation_register( btn_ctrl_t *btn_ctrl, button_code_t code, button_event_t event, uint32_t time_ms, button_event_cb_t cb );\r
- 参数定义:\r
- btn_ctrl: 按键控制器描述符\r
- code: 键值,包含多个按键值\r
- event: 按键事件类型\r
- time: 组合键按下时间,单位毫秒\r
- cb: 事件触发的回调函数\r
- 返回值:\r
- 0: 成功\r
- -1:失败\r
-#### 读取按键状态\r
- uint32_t mg_button_pressed_code( btn_ctrl_t btn_ctrl ); //读取button按下状态,\r
- 参数定义:\r
- btn_ctrl: 按键控制器描述符\r
- 返回值:\r
- 返回值bit0到bit7,其每个bit为1对应一个按键按下,例如\r
- 0x00: 当前8个键全部释放\r
- 0xff: 当前8个键全部按下\r
----\r
-## 2 LED显示管理\r
-### 2.1 数据类型定义\r
-#### LED ID定义\r
-8个按键灯\r
-\r
- #define LED_ID_KEY_1 (1<<0)\r
- #define LED_ID_KEY_2 (1<<1)\r
- #define LED_ID_KEY_3 (1<<2)\r
- #define LED_ID_KEY_4 (1<<3)\r
- #define LED_ID_KEY_5 (1<<4)\r
- #define LED_ID_KEY_6 (1<<5)\r
- #define LED_ID_KEY_7 (1<<6)\r
- #define LED_ID_KEY_8 (1<<7)\r
- #define LED_ID_KEY_ALL (0xff)\r
-5个装饰灯\r
-\r
- #define LED_ID_ATMOS_1 (1<<0)\r
- #define LED_ID_ATMOS_2 (1<<1)\r
- #define LED_ID_ATMOS_3 (1<<2)\r
- #define LED_ID_ATMOS_4 (1<<3)\r
- #define LED_ID_ATMOS_5 (1<<4)\r
- #define LED_ID_ATMOS_ALL ( 0x1f )\r
-##### LED状态\r
- typedef struct{\r
- uint32_t on; //0:常灭, 1:常亮, 2:闪烁, 3:呼吸\r
- uint32_t period; //闪烁或呼吸的周期 单位毫秒\r
- uint32_t br_max; //亮度\r
- } light_st_t;\r
-#### LED控制描述符\r
- typedef void* light_ctrl_t;\r
-### 2.2控制接口\r
-#### 获取LED控制器\r
- light_ctrl_t mg_led_open( void );\r
- 参数定义:\r
- 无\r
- 返回值: \r
- 打开失败,返回 NULL;\r
- 成功,返回LED控制器描述符。\r
-#### 关闭控制器\r
- void mg_led_close( light_ctrl_t ctrl );\r
- 参数定义:\r
- light_ctrl: LED控制器描述符\r
- 返回值: 无\r
-#### 亮度设置\r
- void mg_led_br_set( light_ctrl_t ctrl, uint8_t brightness[101] );\r
- 参数定义:\r
- ctrl: LED控制器描述符\r
- brightness: 写入0到100各级亮度值, 取值:0-关闭,255-最大亮度\r
- 返回值: 无\r
-#### 亮度读取\r
- void mg_led_br_get( light_ctrl_t ctrl, uint8_t brightness[101] );\r
- 参数定义:\r
- ctrl: LED控制器描述符\r
- brightness: 读取0到100各级亮度值, 取值:0-关闭,255-最大亮度\r
- 返回值: 无\r
-#### 按键背光灯控制接口\r
-##### 渐变到常亮\r
- int32_t key_led_on( light_ctrl_t ctrl, uint32_t led_id, uint32_t br_from, uint32_t br_to, uint32_t transition_time );\r
- 参数定义:\r
- ctrl: LED控制器描述符\r
- led_id:LED ID,可以是多个LED\r
- br_from: 渐变的起始亮度\r
- br_to: 渐变的目标亮度\r
- transition_time: 从0到100亮度渐变时间,单位毫秒\r
- 返回值:\r
- 0: 成功\r
- -1:失败\r
-##### 渐变到常灭\r
- int32_t key_led_off( light_ctrl_t ctrl, uint32_t led_id, uint32_t br_from, uint32_t br_to, uint32_t transition_time );\r
- 参数定义:\r
- ctrl: LED控制器描述符\r
- led_id:LED ID,可以是多个LED\r
- br_from: 渐变的起始亮度\r
- br_to: 渐变的目标亮度\r
- transition_time: 从0到100亮度渐变时间,单位毫秒\r
- 返回值:\r
- 0: 成功\r
- -1:失败\r
-##### 闪烁\r
- int32_t key_led_flash( light_ctrl_t ctrl, uint32_t led_id, uint32_t period_ms, uint32_t duration_ms );\r
- 参数定义:\r
- ctrl: LED控制器描述符\r
- led_id:LED ID,可以是多个LED\r
- period_ms: 闪烁周期,单位毫秒\r
- duration_ms:持续时间,单位毫秒, 为0则一直保持闪烁不退出。\r
- 返回值:\r
- 0: 成功\r
- -1:失败\r
-##### 亮度修改\r
- int32_t key_led_br_update( light_ctrl_t ctrl, uint32_t led_id, uint32_t br );\r
- 参数定义:\r
- ctrl: LED控制器描述符\r
- led_id:LED ID,可以是多个LED\r
- br: 亮度\r
- 返回值:\r
- 0: 成功\r
- -1:失败\r
-##### 读取状态\r
- int32_t key_led_st( light_ctrl_t ctrl, uint32_t led_id, light_st_t *st );\r
- 参数定义:\r
- ctrl: LED控制器描述符\r
- led_id:LED ID\r
- st: 状态返回值\r
- 返回值:\r
- 0: 成功\r
- -1:失败\r
-#### 氛围灯控制接口\r
-##### 渐变到常亮\r
- int32_t atmos_led_on( light_ctrl_t ctrl, uint32_t led_id, uint32_t br_from, uint32_t br_to, uint32_t transition_time );\r
- 参数定义:\r
- ctrl: LED控制器描述符\r
- led_id:LED ID,可以是多个LED\r
- br_from: 渐变的起始亮度\r
- br_to: 渐变的目标亮度\r
- transition_time: 从0到100亮度渐变时间,单位毫秒\r
- 返回值:\r
- 0: 成功\r
- -1:失败\r
-##### 渐变到常灭\r
- int32_t atmos_led_off( light_ctrl_t ctrl, uint32_t led_id, uint32_t br_from, uint32_t br_to, uint32_t transition_time );\r
- 参数定义:\r
- ctrl: LED控制器描述符\r
- led_id:LED ID,可以是多个LED\r
- br_from: 渐变的起始亮度\r
- br_to: 渐变的目标亮度\r
- transition_time: 从0到100亮度渐变时间,单位毫秒\r
- 返回值:\r
- 0: 成功\r
- -1:失败\r
-##### 闪烁\r
- int32_t atmos_led_flash( light_ctrl_t ctrl, uint32_t led_id, uint32_t period_ms, uint32_t duration_ms );\r
- 参数定义:\r
- ctrl: LED控制器描述符\r
- led_id:LED ID,可以是多个LED\r
- period_ms: 闪烁周期,单位毫秒\r
- duration_ms:持续时间,单位毫秒, 为0则一直保持闪烁不退出。\r
- 返回值:\r
- 0: 成功\r
- -1:失败\r
-##### 亮度修改\r
- int32_t atmos_led_br_update( light_ctrl_t ctrl, uint32_t led_id, uint32_t br );\r
- 参数定义:\r
- ctrl: LED控制器描述符\r
- led_id:LED ID,可以是多个LED\r
- br: 亮度\r
- 返回值:\r
- 0: 成功\r
- -1:失败\r
-##### 读取状态\r
- int32_t atmos_led_st( light_ctrl_t ctrl, uint32_t led_id, light_st_t *st );\r
- 参数定义:\r
- ctrl: LED控制器描述符\r
- led_id:LED ID\r
- st: 状态返回值\r
- 返回值:\r
- 0: 成功\r
- -1:失败\r
-#### 灯圈控制接口\r
-##### 渐变到常亮\r
- int32_t ring_led_on( light_ctrl_t ctrl,uint32_t br_from, uint32_t br_to, uint32_t transition_time );\r
- 参数定义:\r
- ctrl: LED控制器描述符\r
- br_from: 渐变的起始亮度\r
- br_to: 渐变的目标亮度\r
- transition_time: 从0到100亮度渐变时间,单位毫秒\r
- 返回值:\r
- 0: 成功\r
- -1:失败\r
-##### 渐变到常灭\r
- int32_t ring_led_off( light_ctrl_t ctrl, uint32_t br_from, uint32_t br_to, uint32_t transition_time );\r
- 参数定义:\r
- ctrl: LED控制器描述符\r
- br_from: 渐变的起始亮度\r
- br_to: 渐变的目标亮度\r
- transition_time: 从0到100亮度渐变时间,单位毫秒\r
- 返回值:\r
- 0: 成功\r
- -1:失败\r
-##### 呼吸\r
- int32_t ring_led_breath( light_ctrl_t ctrl, uint32_t increase_ms, uint32_t decrease_ms, uint32_t apnea_ms, uint32_t duration_ms );\r
- 参数定义:\r
- ctrl: LED控制器描述符\r
- increase_ms: 呼吸灯渐亮时间,单位毫秒\r
- increase_ms: 呼吸灯渐暗时间,单位毫秒\r
- apnea_ms: 呼吸灯关闭时间,单位毫秒\r
- duration_ms:持续时间,单位毫秒, 为0则一直保持呼吸不退出。\r
- 返回值:\r
- 0: 成功\r
- -1:失败\r
-##### 亮度修改\r
- int32_t ring_led_br_update( light_ctrl_t ctrl, uint32_t br );\r
- 参数定义:\r
- ctrl: LED控制器描述符\r
- br: 亮度\r
- 返回值:\r
- 0: 成功\r
- -1:失败\r
-##### 读取状态\r
- int32_t ring_led_st( light_ctrl_t ctrl, light_st_t *st );\r
- 参数定义:\r
- ctrl: LED控制器描述符\r
- st: 状态返回值\r
- 返回值:\r
- 0: 成功\r
- -1:失败\r
-#### 红外补光灯制接口\r
-##### 打开\r
- int32_t ir_led_on( light_ctrl_t ctrl, uint32_t br );\r
- 参数定义:\r
- ctrl: LED控制器描述符\r
- br: 亮度\r
- 返回值:\r
- 0: 成功\r
- -1:失败\r
-##### 关闭\r
- int32_t ir_led_off( light_ctrl_t ctrl );\r
- 参数定义:\r
- ctrl: LED控制器描述符\r
- 返回值:\r
- 0: 成功\r
- -1:失败\r
-##### 亮度修改\r
- int32_t ring_led_br_update( light_ctrl_t ctrl, uint32_t br );\r
- 参数定义:\r
- ctrl: LED控制器描述符\r
- br: 亮度\r
- 返回值:\r
- 0: 成功\r
- -1:失败\r
-##### 读取状态\r
- int32_t ring_led_st( light_ctrl_t ctrl, light_st_t *st );\r
- 参数定义:\r
- ctrl: LED控制器描述符\r
- st: 状态返回值\r
- 返回值:\r
- 0: 成功\r
- -1:失败\r
-\r
----\r
-## 3 人感TOF\r
-### 3.1 数据类型定义\r
-#### 传感器侦测到状态\r
- typedef enum {\r
- TOF_NOBODY = 0, //无人\r
- TOF_FIXED_BARRIER, //固定障碍物\r
- TOF_ANYBODY, //有人\r
- }tof_st_t;\r
-\r
-#### 传感器完整状态信息\r
- typedef struct{\r
- uint32_t enable; //启停状态\r
- tof_st_t status; //有人、无人、障碍物\r
- uint32_t distance; //有人或障碍物距离,单位mm\r
- }tof_info_t;\r
-\r
-#### TOF控制描述符\r
- struct mg_tof;\r
- typedef struct mg_tof mg_tof_t;\r
-\r
-#### 人感事件回调函数\r
- typedef void ( * tof_event_cb_t )( tof_info_t *info, void * value );\r
- 参数定义:\r
- info:传感器状态\r
- value: 预留参数\r
- 返回值: 无\r
-\r
-### 3.2控制接口\r
-\r
-#### 获取TOF控制器\r
- mg_tof_t * mg_tof_open(uint32_t distance);\r
- 参数定义:\r
- 监测距离\r
- 返回值: \r
- 打开失败,返回 NULL;\r
- 成功,返回TOF控制器指针。\r
-\r
-#### 关闭控制器\r
- void mg_tof_close( mg_tof_t * tof_ctrl );\r
- 参数定义:\r
- tof_ctrl: tof控制器\r
- 返回值: 无\r
-\r
-#### TOF 启用\r
- int32_t mg_tof_enable( mg_tof_t *tof_ctrl );\r
- 参数定义:\r
- tof_ctrl: TOF控制器\r
- 返回值:\r
- 0: 成功\r
- -1:失败\r
-\r
-#### TOF 停用\r
- int32_t mg_tof_disable( mg_tof_t *tof_ctrl );\r
- 参数定义:\r
- tof_ctrl: TOF控制器\r
- 返回值:\r
- 0: 成功\r
- -1:失败\r
-\r
-#### TOF状态查询\r
- int32_t mg_tof_read( mg_tof_t *tof_ctrl, tof_info_t *info );\r
- 参数定义:\r
- tof_ctrl: TOF控制器\r
- info: TOF状态,启用/停用,有人/无人, 距离 信息\r
- 返回值:\r
- 0: 成功\r
- -1:失败\r
-\r
-#### TOF 动态修改监测距离\r
-\r
- int32_t Distance_parameter_correction(mg_tof_t *tof_ctrl,uint32_t distance);\r
- 参数定义:\r
- btn_ctrl: 按键控制器\r
- distance 监测距离\r
- 返回值:\r
- 0: 成功\r
- -1:失败\r
-\r
-#### TOF 事件注册\r
-\r
- int32_t mg_tof_event_register(mg_tof_t *tof_ctrl,tof_event_cb_t cb);\r
- 参数定义:\r
- btn_ctrl: 按键控制器\r
- cb: 事件回调函数\r
- 返回值:\r
- 0: 成功\r
- -1:失败\r
----\r
-\r
-## 4 环境光\r
-### 4.1 数据类型定义\r
-#### 传感器侦测到状态\r
- typedef enum {\r
- BRIGHT = 1, //亮\r
- DARK = 0, //暗\r
- }als_st_t;\r
-\r
-#### 传感器完整状态信息\r
- typedef struct{\r
- als_st_t status; //传感器侦测到状态\r
- uint32_t ad_value; //AD采样值\r
- uint32_t threshold_low; //阈值1\r
- uint32_t threshold_high; //阈值2\r
- }als_info_t;\r
-\r
-#### 传感器控制描述符\r
- struct mg_als{\r
- char* dev_path; //文件路径\r
- int fd; //文件描述符\r
- als_info_t data; //传感器完整状态信息\r
- };\r
- \r
- struct mg_als;\r
- typedef struct mg_als mg_als_t;\r
-\r
-### 4.2控制接口\r
-#### 获取环境光传感控制器\r
- mg_als_t * mg_als_open( void );\r
- 参数定义:\r
- 无\r
- 返回值: \r
- 打开失败,返回 NULL;\r
- 成功,返回ALS控制器指针。\r
-\r
-#### 关闭控制器\r
- void mg_als_close( mg_als_t * als_ctrl );\r
- 参数定义:\r
- als_ctrl: 按键控制器\r
- 返回值: 无\r
-\r
-#### 读取ALS信息\r
- als_info_t * mg_als_read( mg_als_t * als_ctrl )\r
- 参数定义:\r
- als_ctrl: 按键控制器\r
- 返回值:\r
- 读取失败,返回NULL;\r
- 成功,返回传感器信息\r
-\r
-#### 设置阈值\r
- void mg_als_cfg( mg_als_t * als_ctrl, uint32_t threshold_high, uint32_t threshold_low );\r
- 参数定义:\r
- als_ctrl: 按键控制器\r
- threshold_high: 阈值1\r
- threshold_low: 阈值2\r
- 返回值: 无\r
----\r
-\r
-## 5 EIA485\r
-### 5.1 数据类型定义\r
-#### 串口参数\r
-数据位长度\r
-\r
- enum{\r
- DATA_BITS_5 = 0,\r
- DATA_BITS_6,\r
- DATA_BITS_7,\r
- DATA_BITS_8,\r
- };\r
-\r
-停止位长度\r
-\r
- enum{\r
- STOP_BITS_1 = 0,\r
- DATA_BITS_1P5,\r
- DATA_BITS_2,\r
- };\r
-\r
-校验位\r
-\r
- enum{\r
- PARITY_NONE=0,\r
- PARITY_ODD,\r
- PARITY_EVEN,\r
- };\r
-\r
-#### EIA485控制描述符\r
- struct mg_eia485;\r
- typedef struct mg_eia485 mg_eia485_t;\r
-### 6.2控制接口\r
-#### 打开EIA485控制器\r
- mg_eia485_t * mg_eia485_open( uint32_t baud, uint32_t data_bits, uint32_t stop_bits, uint32_t parity );\r
- 参数定义:\r
- baud: 波特率\r
- data_bits:数据位长度\r
- stop_bits: 停止位长度\r
- parity: 校验位\r
- 返回值: \r
- 打开失败,返回 NULL;\r
- 成功,返回TOF控制器指针。\r
-#### 关闭控制器\r
- void mg_eia485_close( mg_eia485_t * eia485_ctrl );\r
- 参数定义:\r
- eia485_ctrl: EIA485控制器\r
- 返回值: 无\r
-#### 发送数据\r
- void mg_eia485_write( mg_eia485_t * eia485_ctrl,uint8_t * tx_data, uint32_t tx_size );\r
- 参数定义:\r
- eia485_ctrl: EIA485控制器\r
- tx_data: 发送数据\r
- tx_size: 发送数据长度\r
- 返回值:\r
- 0: 成功\r
- -1:失败\r
-#### 接收数据\r
- int32_t mg_eia485_read( mg_eia485_t * eia485_ctrl,uint8_t * rx_data, uint32_t rx_size, uint32_t timeout_ms );\r
- 参数定义:\r
- eia485_ctrl: EIA485控制器\r
- tx_data: 接收buffer\r
- tx_size: 最大读取长度\r
- timeout_ms: 等待超时时间,单位毫秒,如果值是0则立即返回\r
- 返回值:\r
- 大于0:读取到的数据长度\r
- 0: 无数据 \r
- -1: 操作失败失败\r
----\r
-\r
-\r
-## 6 蜂鸣器\r
-### 6.1 数据类型定义\r
-#### 蜂鸣器的参数\r
- struct buzzer_status{\r
- float freq_hz; //频率\r
- int32_t duty_cycle; //占空比\r
- };\r
- typedef struct buzzer_status buzzer_status_t;\r
-\r
-#### 蜂鸣器控制描述符\r
- struct mg_buzzer{\r
- char* dev_path[5]; //文件路径\r
- uint32_t enable; //蜂鸣器状态\r
- uint32_t time_ms; //时间\r
- buzzer_status_t buzzer_x_t[2];\r
-};\r
- struct mg_buzzer;\r
- typedef struct mg_buzzer mg_buzzer_t;\r
-\r
-### 6.2控制接口\r
-#### 获取蜂鸣器控制器\r
- mg_buzzer_t * mg_buzzer_open(void);\r
- 参数定义:\r
- 无\r
- 返回值: \r
- 打开失败,返回 NULL;\r
- 成功,返回buzzer控制器指针。\r
-\r
-#### 关闭控制器\r
- void mg_buzzer_close(mg_buzzer_t * buzzer_ctrl);\r
- 参数定义:\r
- buzzer_ctrl: buzzer控制器\r
- 返回值: 无\r
-\r
-#### 蜂鸣器播放声音\r
- void mg_buzzer_start( mg_buzzer_t * buzzer_ctrl, float freq_hz, uint32_t duty_cycle, uint32_t time_ms );\r
- 参数定义:\r
- buzzer_ctrl: 蜂鸣器控制器\r
- freq_hz: 频率,如果值是0,则立即关闭蜂鸣器\r
- duty_cycle: 占空比\r
- time_ms: 播放时间, 单位毫秒,到达时间后自动关闭,如果值是0 则一直开启\r
- 返回值: 无\r
-\r
-#### 获取蜂鸣器的状态\r
- void mg_buzzer_get( mg_buzzer_t * buzzer_ctrl, float *freq_hz, uint32_t *duty_cycle, uint32_t *time_ms, uint32_t* enable)\r
- 参数定义:\r
- buzzer_ctrl: 蜂鸣器控制器\r
- freq_hz : 存放频率\r
- duty_cycle : 存放占空比\r
- time_ms : 存放时间\r
- enable : 存放蜂鸣器的状态\r
- 返回值: 无\r
-\r
----\r
+++ /dev/null
-#TW8013 代码说明\r
-\r
-## 1.硬件平台,介绍\r
-\r
-Rockchip RV1126,512M DDR3,512MB spinand\r
-\r
-8个按键,8个背光灯,5个装饰灯,提示灯光圈,\r
-\r
-EIA485,wifi和蓝牙模块,人感检测传感器,\r
-\r
-环境光检测传感器,红外补光灯,蜂鸣器,\r
-\r
-两个摄像头,算法加密芯片\r
-\r
-## 2.软件SDK,介绍\r
-\r
-基于RockChip默认SDK开发,各个需要修改模块路径\r
-\r
- ⚫ device/rockchip :存放每个平台的一些编译和打包固件的脚步和预备文件。\r
- ⚫ kernel :kernel 源码\r
- ⚫ u-boot :U-boot 源码目录\r
- ⚫ buildroot :SDK 包使用的文件系统为 buildroot\r
- ⚫ external : 存放相关的库,包括音频,视频等\r
- ⚫ app/mg_app : tw8013主应用程序\r
-## 3.软件各个模块说明\r
-\r
-### 3.1 bootloader\r
-\r
-使用SDK默认代码, 增加上电灯全亮250ms功能:\r
-\r
-路径为/sdk/u-boot/arch/arm/mach-rockchip/board.c\r
-\r
-```\r
-__weak int rk_board_init(void)\r
-{\r
- int i = 0;\r
- int LED_GPIO[] = {82,77,76,84,90,89,88,91,15,14,16,100,92,102};\r
- char LED_NUM[10];\r
- for(i = 0;i < sizeof(LED_GPIO)/sizeof(LED_GPIO[0]);i++)\r
- {\r
- sprintf(LED_NUM,"led%d",i);\r
-\r
- gpio_request(LED_GPIO[i], LED_NUM);\r
- gpio_direction_output( LED_GPIO[i],1);\r
- \r
- memset(LED_NUM,0,sizeof(LED_NUM));\r
- }\r
- mdelay(250);\r
- for(i = 0;i < sizeof(LED_GPIO)/sizeof(LED_GPIO[0]);i++)\r
- {\r
- gpio_direction_output(LED_GPIO[i],0);\r
- gpio_free(LED_GPIO[i]);\r
- }\r
- return 0;\r
-\r
-}\r
-```\r
-\r
-### 3.2 内核驱动\r
-\r
-#### 设备树\r
-\r
-文件 sdk/kernel/arch/arm/boot/dts/tw8013.dts\r
-\r
-#### 按键:\r
-\r
-设备树配置:\r
-\r
-sdk/kernel/arch/arm/boot/dts/rv1126-pinctrl.dtsi\r
-\r
-```\r
- keys:keys{\r
- rockchip,pins = \r
- /*key1*/\r
- <2 RK_PC0 0 &pcfg_pull_none>,\r
- /*key2*/\r
- <2 RK_PB7 0 &pcfg_pull_none>,\r
- /*key3*/\r
- <2 RK_PB6 0 &pcfg_pull_none>,\r
- /*key4*/\r
- <2 RK_PC1 0 &pcfg_pull_none>,\r
- /*key5*/\r
- <2 RK_PC3 0 &pcfg_pull_none>,\r
- /*key6*/\r
- <2 RK_PC5 0 &pcfg_pull_none>,\r
- /*key7*/\r
- <2 RK_PC7 0 &pcfg_pull_none>,\r
- /*key8*/\r
- <2 RK_PC6 0 &pcfg_pull_none>;\r
- };\r
-```\r
-\r
-sdk/kernel/arch/arm/boot/dts/tw8013.dts\r
-\r
- gpio_keys {\r
- compatible = "gpio-keys";\r
- #address-cells = <1>;\r
- #size-cells = <0>;\r
- \r
- pinctrl-names = "default";\r
- pinctrl-0 = <&keys>;\r
- autorepeat;\r
- key1: key1 {\r
- label = "GPIO Key1";\r
- gpios = <&gpio2 RK_PC0 GPIO_ACTIVE_LOW>;\r
- linux,code = <KEY_8>;\r
- linux,input-type = <1>;\r
- debounce-interval = <20>;\r
- };\r
- key2: key2 {\r
- label = "GPIO Key2";\r
- gpios = <&gpio2 RK_PB7 GPIO_ACTIVE_LOW>;\r
- linux,code = <KEY_7>;\r
- linux,input-type = <1>;\r
- debounce-interval = <20>;\r
- };\r
- key3: key3 {\r
- label = "GPIO Key3";\r
- gpios = <&gpio2 RK_PB6 GPIO_ACTIVE_LOW>;\r
- linux,code = <KEY_5>;\r
- linux,input-type = <1>;\r
- debounce-interval = <20>;\r
- };\r
- key4: key4 {\r
- label = "GPIO Key4";\r
- gpios = <&gpio2 RK_PC1 GPIO_ACTIVE_LOW>;\r
- linux,code = <KEY_6>;\r
- linux,input-type = <1>;\r
- debounce-interval = <20>;\r
- };\r
- key5: key5 {\r
- label = "GPIO Key5";\r
- gpios = <&gpio2 RK_PC3 GPIO_ACTIVE_LOW>;\r
- linux,code = <KEY_4>;\r
- linux,input-type = <1>;\r
- debounce-interval = <20>;\r
- };\r
- key6: key6 {\r
- label = "GPIO Key6";\r
- gpios = <&gpio2 RK_PC5 GPIO_ACTIVE_LOW>;\r
- linux,code = <KEY_3>;\r
- linux,input-type = <1>;\r
- debounce-interval = <20>;\r
- };\r
- key7: key7 {\r
- label = "GPIO Key7";\r
- gpios = <&gpio2 RK_PC7 GPIO_ACTIVE_LOW>;\r
- linux,code = <KEY_1>;\r
- linux,input-type = <1>;\r
- debounce-interval = <20>;\r
- };\r
- key8: key8 {\r
- label = "GPIO Key8";\r
- gpios = <&gpio2 RK_PC6 GPIO_ACTIVE_LOW>;\r
- linux,code = <KEY_2>;\r
- linux,input-type = <1>;\r
- debounce-interval = <20>;\r
- };\r
- };\r
-\r
-驱动文件目录sdk/kernel/drivers/input/keyboard/gpio_keys.c\r
-\r
-#### 按键背光灯:\r
-\r
-设备树配置:sdk/kernel/arch/arm/boot/dts/rv1126-pinctrl.dtsi\r
-\r
-将引脚复用为普通GPIO功能\r
-\r
-```\r
-key_leds:key_leds{\r
- rockchip,pins = \r
- /*LED_1*/\r
- <2 RK_PC2 0 &pcfg_pull_none>,\r
- /*LED_2*/\r
- <2 RK_PB5 0 &pcfg_pull_none>,\r
- /*LED_3*/\r
- <2 RK_PB4 0 &pcfg_pull_none>,\r
- /*LED_4*/\r
- <2 RK_PC4 0 &pcfg_pull_none>,\r
- /*LED_5*/\r
- <2 RK_PD2 0 &pcfg_pull_none>,\r
- /*LED_6*/\r
- <2 RK_PD1 0 &pcfg_pull_none>,\r
- /*LED_7*/\r
- <2 RK_PD0 0 &pcfg_pull_none>,\r
- /*LED_8*/\r
- <2 RK_PD3 0 &pcfg_pull_none>;\r
-};\r
-```\r
-\r
-设置相关配置:同目录下tw8013.dts\r
-\r
-```\r
-pwm-gpio1 {\r
- compatible = "pwm-gpio";\r
- pinctrl-names = "default";\r
- pinctrl-0 = <&key_leds>;\r
- #pwm-cells = <3>;\r
- label = "key_led8";\r
- pwm-gpio = <&gpio2 RK_PC2 GPIO_ACTIVE_HIGH>;\r
- };\r
-pwm-gpio2 {\r
- compatible = "pwm-gpio";\r
- #pwm-cells = <3>;\r
- label = "key_led7";\r
- pwm-gpio = <&gpio2 RK_PB5 GPIO_ACTIVE_HIGH>;\r
- };\r
-pwm-gpio3 {\r
- compatible = "pwm-gpio";\r
- #pwm-cells = <3>;\r
- label = "key_led5";\r
- pwm-gpio = <&gpio2 RK_PB4 GPIO_ACTIVE_HIGH>;\r
- };\r
-pwm-gpio4 {\r
- compatible = "pwm-gpio";\r
- #pwm-cells = <3>;\r
- label = "key_led6";\r
- pwm-gpio = <&gpio2 RK_PC4 GPIO_ACTIVE_HIGH>;\r
- };\r
-pwm-gpio5 {\r
- compatible = "pwm-gpio";\r
- #pwm-cells = <3>;\r
- label = "key_led4";\r
- pwm-gpio = <&gpio2 RK_PD2 GPIO_ACTIVE_HIGH>;\r
- };\r
-pwm-gpio6 {\r
- compatible = "pwm-gpio";\r
- #pwm-cells = <3>;\r
- label = "key_led3";\r
- pwm-gpio = <&gpio2 RK_PD1 GPIO_ACTIVE_HIGH>;\r
- };\r
-pwm-gpio7 {\r
- compatible = "pwm-gpio";\r
- #pwm-cells = <3>;\r
- label = "key_led1";\r
- pwm-gpio = <&gpio2 RK_PD0 GPIO_ACTIVE_HIGH>;\r
- };\r
-pwm-gpio8 {\r
- compatible = "pwm-gpio";\r
- #pwm-cells = <3>;\r
- label = "key_led2";\r
- pwm-gpio = <&gpio2 RK_PD3 GPIO_ACTIVE_HIGH>;\r
- };\r
-```\r
-\r
-使用内核高精度定时器实现软件pwm驱动:\r
-\r
-sdk/kernel/drivers/pwm/pwm-gpio.c\r
-\r
-```\r
-static int gpio_pwm_probe(struct platform_device *pdev)\r
-{\r
- int ret;\r
- struct gpio_pwm_chip *pc;\r
-\r
- pc = devm_kzalloc(&pdev->dev, sizeof(*pc), GFP_KERNEL);\r
- if (!pc)\r
- return -ENOMEM;\r
- //将驱动注册进led子系统添加配置\r
- pc->cdev.name = of_get_property(pdev->dev.of_node, "label", NULL) ? : "soft-pwm";\r
- pc->cdev.brightness = 0;\r
- pc->cdev.max_brightness = 255;\r
- pc->cdev.flags = LED_CORE_SUSPENDRESUME;\r
- pc->cdev.brightness_set_blocking = soft_pwm_set;\r
- pc->my_period = 1000000;\r
- //为pwm设备进行配置\r
- pc->chip.dev = &pdev->dev;\r
- pc->chip.ops = &gpio_pwm_ops;\r
- pc->chip.base = -1;\r
- pc->chip.npwm = 1;\r
- pc->chip.of_xlate = of_pwm_xlate_with_flags;\r
- pc->chip.of_pwm_n_cells = 3;\r
- //pc->chip.can_sleep = true;\r
- \r
- pc->gpiod = devm_gpiod_get(&pdev->dev, "pwm", GPIOD_OUT_LOW);\r
- \r
- if (IS_ERR(pc->gpiod))\r
- return PTR_ERR(pc->gpiod);\r
- //高精度定时器初始化\r
- hrtimer_init(&pc->timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);\r
- pc->timer.function = &gpio_pwm_timer;\r
- pc->pin_on = false;\r
- \r
- if (!hrtimer_is_hres_active(&pc->timer))\r
- dev_warn(&pdev->dev, "HR timer unavailable, restricting to "\r
- "low resolution\n");\r
- //添加到pwm子系统中\r
- ret = pwmchip_add(&pc->chip);\r
- if (ret < 0) {\r
- dev_err(&pdev->dev, "failed to add PWM chip: %d\n", ret);\r
- return ret;\r
- }\r
- //添加到led子系统中\r
- platform_set_drvdata(pdev, pc);\r
- ret = led_classdev_register(&pdev->dev, &pc->cdev);\r
- return 0;\r
-\r
-}\r
-```\r
-\r
-上层使用led子系统设置占空比和频率时会调用下面的函数:\r
-\r
-```\r
-static int soft_pwm_set(struct led_classdev *led_cdev,\r
- enum led_brightness brightness)\r
-{\r
- struct gpio_pwm_chip *pc = container_of(led_cdev, struct gpio_pwm_chip, cdev);\r
- unsigned int max = pc->cdev.max_brightness;\r
-\r
- pc->br = brightness>max?255:brightness*255/max;\r
- \r
- if( pc->br == 0 || pc->br == 255 ){\r
- //关闭和最大亮度,关闭timer\r
- if( pc->br_timer_start ){\r
- //printk( "pwm set[%s] timer -> 0\n", pc->cdev.name );\r
- }\r
- pc->br_timer_start = 0;\r
- if( pc->br == 0 ){\r
- gpio_pwm_off(pc);\r
- pc->pin_on = 0;\r
- }else{\r
- gpio_pwm_on(pc);\r
- pc->pin_on = 1;\r
- }\r
- }else{\r
- if( pc->br_timer_start == 0 ){\r
- pc->br_tick= 0;\r
- //pwm亮度调节,启动timer\r
- if( !pc->br_timer_start ){\r
- //printk( "pwm set[%s] timer -> 1\n", pc->cdev.name );\r
- }\r
- pc->br_timer_start = 1;\r
- hrtimer_start(&pc->timer, ktime_set(0, 0), HRTIMER_MODE_REL);\r
- }\r
- }\r
-\r
-}\r
-```\r
-\r
-之后启动定时器会调用到函数:\r
-\r
-```\r
-static enum hrtimer_restart gpio_pwm_timer(struct hrtimer *timer)\r
-{\r
- struct gpio_pwm_chip *pc = container_of(timer,\r
- struct gpio_pwm_chip,\r
- timer);\r
- //原驱动方式,led闪烁严重,这里修改为固定间隔定时器方式\r
- //定时器 256次中断为一个led的pwm周期。\r
- //40us x 256 pwm周期是 10.24ms\r
- if( !pc->br_timer_start ){\r
- pc->br_tick = 0;\r
- //printk( "gpio-pwm[%s] timer stop\n", pc->cdev.name );\r
- return HRTIMER_NORESTART;\r
- }\r
-\r
- hrtimer_forward_now(&pc->timer, ns_to_ktime(40*1000));\r
- \r
- if( pc->br_tick <= pc->br){\r
- //计数器[0--br] 打开led\r
- if( !pc->pin_on ){\r
- gpio_pwm_on(pc);\r
- pc->pin_on = 1;\r
- }\r
- }else{\r
- //计数器[br--255] 关闭led\r
- if( pc->pin_on ){\r
- gpio_pwm_off(pc);\r
- pc->pin_on = 0;\r
- }\r
- }\r
- pc->br_tick ++; //计数值255后溢出自动归零\r
- return HRTIMER_RESTART;\r
-\r
-}\r
-```\r
-\r
-其中gpio_pwm_off和gpio_pwm_on对gpio口进行拉高拉低操作\r
-\r
-```\r
-static void gpio_pwm_off(struct gpio_pwm_chip *pc)\r
-{\r
- enum pwm_polarity polarity = pwm_get_polarity(pc->chip.pwms);\r
-\r
- gpiod_set_value(pc->gpiod, polarity ? 1 : 0);\r
-\r
-}\r
-\r
-static void gpio_pwm_on(struct gpio_pwm_chip *pc)\r
-{\r
- enum pwm_polarity polarity = pwm_get_polarity(pc->chip.pwms);\r
-\r
- gpiod_set_value(pc->gpiod, polarity ? 0 : 1);\r
-\r
-}\r
-```\r
-\r
-\r
-\r
-#### led灯:\r
-\r
-装饰灯带、红外补光灯、光圈采用的是硬件PWM控制。在本项目中硬件pwm控制的led采用了两个驱动,一个是linux系统中的pwm子系统驱动用于初始化pwm控制使其能输出pwm脉冲;第二驱动是leds子系统驱动用于设备文件提供让应用层已读写文件的方式与内核交互。\r
-\r
-pwm控制器驱动及设备树\r
-\r
-PWM设备树配置代码:sdk/kernel/arch/arm/boot/dts/tw8013.dts\r
-每个led连接着一个硬件pwm,所以首先通过设备树配置硬件pwm控制器 \r
-\r
- &pwm0{ //fun_led2\r
- status = "okay";\r
- };\r
- &pwm1{ //fun_led1\r
- status = "okay";\r
- };\r
- &pwm2{ //fun_led3\r
- status = "okay";\r
- };\r
- &pwm6{ //fun_led5\r
- status = "okay";\r
- pinctrl-names = "active";\r
- pinctrl-0 = <&pwm6m1_pins>; \r
- };\r
- &pwm8{ //fun_led4\r
- status = "okay";\r
- };\r
- &pwm3{ //ir_led\r
- status = "okay";\r
- }; \r
- &pwm10{ //ring_led\r
- status = "okay";\r
- };\r
-\r
-PWM控制器驱动代码路径:kernel/drivers/pwm/pwm-rockchip.c\r
- 这里的PWM控制器驱动使用的是内核自带的驱动程序。\r
-\r
-leds子系统设备树配置\r
-\r
-leds设备树配置代码:sdk/kernel/arch/arm/boot/dts/tw8013.dts\r
-\r
- pwm_fun_led{\r
- compatible = "pwm-leds"; //与驱动匹配的唯一条件\r
- fun_led1 {\r
- label = "fun_led1"; //标签名,生成的设备节点会采用这个名字\r
- pwms = <&pwm1 0 5000 0>; //pwm1:PWM控制器1 0:通道0 10000:PWM周期单位ns 0:表示pwm的输出极性\r
- max-brightness = <255>; //led的最大亮度\r
- };\r
- fun_led2 {\r
- label = "fun_led2";\r
- pwms = <&pwm0 0 5000 0>;\r
- max-brightness = <255>;\r
- };\r
- fun_led3 {\r
- label = "fun_led3";\r
- pwms = <&pwm2 0 5000 0>;\r
- max-brightness = <255>;\r
- };\r
- fun_led4 {\r
- label = "fun_led4";\r
- pwms = <&pwm8 0 5000 0>;\r
- max-brightness = <255>;\r
- };\r
- fun_led5 {\r
- label = "fun_led5";\r
- pwms = <&pwm6 0 5000 0>;\r
- max-brightness = <255>;\r
- };\r
- ir_led {\r
- label = "ir_led";\r
- pwms = <&pwm3 0 5000 0>;\r
- max-brightness = <255>;\r
- };\r
- ring_led {\r
- label = "ring_led";\r
- pwms = <&pwm10 0 5000 0>;\r
- max-brightness = <255>;\r
- };\r
- };\r
-\r
-leds子系统驱动代码路径:kernel/drivers/leds/leds-pwm.c\r
- 这里使用的是内核自带的驱动程序,该驱动主要是关联需要控制的pwm控制器,创建设备文件供上层调用。\r
-\r
-#### 环境光\r
-\r
-设备树配置代码:sdk/kernel/arch/arm/boot/dts/rv1126.dtsi\r
-\r
-该设备树节点对应的是saradc控制器,该控制有6各adc采集通道,将改节点的状态设置成"okay"之后就会与相应的驱动进行匹配,并且会在/sys/bus/iio/devices/iio:device0/生成设备节点,我们本次使用是通道4,只需要对in_voltage4_raw的节点进行读取就可以了。\r
-\r
- saradc: saradc@ff5e0000 {\r
- compatible = "rockchip,rk3399-saradc";\r
- reg = <0xff5e0000 0x100>;\r
- interrupts = <GIC_SPI 40 IRQ_TYPE_LEVEL_HIGH>;\r
- #io-channel-cells = <1>;\r
- clocks = <&cru CLK_SARADC>, <&cru PCLK_SARADC>;\r
- clock-names = "saradc", "apb_pclk";\r
- resets = <&cru SRST_SARADC_P>;\r
- reset-names = "saradc-apb";\r
- status = "okay";\r
- };\r
-\r
-驱动代码路径:sdk/kernel/drivers/iio/adc/rockchip_saradc.c\r
- 该驱动主要负责初始化adc控制器生成设备节点供应用层操作\r
-\r
-#### 人感\r
-\r
-i2c接口\r
-\r
-原理图中链接人感的i2c接口是i2c2,在原有的设备树中已经将GPIO口初始化完成了。需要对i2c进行配置:\r
-\r
-sdk/kernel/arch/arm/boot/dts/tw8013.dts\r
-\r
-```c\r
-&i2c2 {\r
- status = "okay";\r
- clock-frequency = <400000>;\r
- stmvl53l1: stmvl53l1@29{\r
- compatible = "st,stmvl53l1";\r
- reg = <0x29>;\r
- pinctrl-names = "default";\r
- pinctrl-0 = <&tof_pin>;\r
- xsdn-gpio = <70>;\r
- intr-gpio = <71>;\r
- };\r
-};\r
-```\r
-\r
-另外还有两个控制引脚\r
-\r
-sdk/kernel/arch/arm/boot/dts/rv1126-pinctrl.dtsi\r
-\r
-```\r
-tof_pin:tof_pin {\r
- rockchip,pins = \r
- <2 RK_PA6 0 &pcfg_pull_none>,\r
- <2 RK_PA7 0 &pcfg_pull_none>;\r
-};\r
-```\r
-\r
-驱动程序代码放置在sdk/kernel/drivers/input/misc/vl53L1/目录下,其中stmvl53l1_module-i2c.c是和设备树进行匹配的驱动文件。主要功能实现在stmvl53l1_module.c中其中stmvl53l1_ioctl函数为上层获取传感器数据提供接口:\r
-\r
-```c\r
-static long stmvl53l1_ioctl(struct file *file,\r
- unsigned int cmd, unsigned long arg)\r
-{\r
- long ret;\r
- struct stmvl53l1_data *data =\r
- container_of(file->private_data,\r
- struct stmvl53l1_data, miscdev);\r
- ret = stmvl53l1_ioctl_handler(data, cmd, arg, (void __user *)arg);\r
- return ret;\r
-}\r
-```\r
-\r
-调用了stmvl53l1_ioctl_handler函数,通上层调用ioctl接口传递下来的cmd去判断需要返回给上层什么数据。\r
-\r
-```c\r
-static int stmvl53l1_ioctl_handler(\r
- struct stmvl53l1_data *data,\r
- unsigned int cmd, unsigned long arg,\r
- void __user *p)\r
-{\r
- int rc = 0;\r
-\r
- if (!data)\r
- return -EINVAL;\r
-\r
- switch (cmd) {\r
-\r
- case VL53L1_IOCTL_START:\r
- ......\r
- case VL53L1_IOCTL_STOP:\r
- ......\r
- case VL53L1_IOCTL_GETDATAS:\r
- ......\r
- case VL53L1_IOCTL_GETDATAS_BLOCKING:\r
- ......\r
- case VL53L1_IOCTL_REGISTER:\r
- ......\r
- case VL53L1_IOCTL_PARAMETER:\r
- ......\r
- case VL53L1_IOCTL_ROI:\r
- ......\r
- case VL53L1_IOCTL_MZ_DATA:\r
- ......\r
- case VL53L1_IOCTL_MZ_DATA_BLOCKING:\r
- ......\r
- case VL53L1_IOCTL_CALIBRATION_DATA:\r
- ......\r
- case VL53L1_IOCTL_PERFORM_CALIBRATION:\r
- ......\r
- case VL53L1_IOCTL_AUTONOMOUS_CONFIG:\r
- ......\r
- case VL53L1_IOCTL_ZONE_CALIBRATION_DATA:\r
- ......\r
- case VL53L1_IOCTL_MZ_DATA_ADDITIONAL:\r
- ......\r
- case VL53L1_IOCTL_MZ_DATA_ADDITIONAL_BLOCKING:\r
- ......\r
- }\r
- return rc;\r
-}\r
-```\r
-\r
-#### 摄像头\r
-\r
-设备树相应代码:sdk/kernel/arch/arm/boot/dts/tw8013.dts\r
-\r
- 这部分代码由算法厂商提供\r
-\r
-\r
-#### 加密芯片\r
-\r
-设备树配置代码:sdk/kernel/arch/arm/boot/dts/tw8013.dts\r
-原理图中加密芯片使用的i2c接口是i2c5\r
-\r
- &i2c5{\r
- status = "okay"; //设备树的状态\r
- clock-frequency = <100000>; //i2c通讯速率单位HZ\r
- crypto@64 {\r
- compatible = "atmel,atsha204a";//与驱动匹配的名字\r
- reg = <0x64>; //i2c设备地址\r
- }; \r
- };\r
-\r
-驱动代码路径:sdk/kernel/drivers/crypto/atmel-i2c.c\r
- sdk/kernel/drivers/crypto/atmel-sha204a.c\r
-\r
-#### WIFI/BLE模块\r
-\r
-设备树配置:sdk/kernel/arch/arm/boot/dts/rv1126-pinctrl.dtsi\r
-\r
-将引脚复用为普通GPIO功能\r
-\r
-```\r
-wifi_en_pin:wifi_en_pin {\r
- rockchip,pins = \r
- <1 RK_PD0 0 &pcfg_pull_none>;\r
- };\r
-```\r
-\r
-设置相关配置:sdk/kernel/arch/arm/boot/dts/tw8013.dts\r
-\r
-```\r
-wifi_en {\r
- compatible = "wifi_en";\r
- status = "okay";\r
- pinctrl-names = "default";\r
- pinctrl-0 = <&wifi_en_pin>; \r
- gpios = <&gpio1 RK_PD0 GPIO_ACTIVE_HIGH>;\r
- };\r
-```\r
-\r
-使能引脚驱动放置在: kernel/drivers/gpio/gpio-wifi-en.c\r
-\r
-蓝牙驱动代码:\r
-\r
- kernel/drivers/bluetooth/\r
- rtk_btusb.c\r
- rtk_misc.c\r
- rtk_coex.c\r
-蓝牙固件:\r
-\r
- sdk/buildroot/board/rockchip/rv1126_rv1109/fs-overlay-tw8013/usr/lib/firmware/\r
- rtl8723du_config\r
- rtl8723du_fw\r
-### 3.3 中间件\r
-\r
-### 按键中间件\r
-\r
-路径:sdk/app/mg_app/button/\r
-\r
- src/button.c 主要按键逻辑\r
- src/button-scan.c 扫描按键状态\r
-\r
-中间件调用open接口以后,启动一个task,周期扫描按键状态,检查按键事件是否有注册,如果已经注册了事件,则调用注册的回调函数报告事件信息。\r
-按键逻辑主要在 button_task中完成,\r
-\r
-应用中访问按键的设备名\r
-\r
- ctrl = mg_button_open("/dev/input/by-path/platform-gpio_keys-event" );\r
-\r
-读取按键事件\r
-\r
- rd = read(fd, ev, sizeof(ev));\r
-\r
-记录当前按键状态\r
-\r
- 108 if( type==EV_KEY ){\r
- 109 if( value == 0 ){\r
- 110 pressed_code &= ~ 1<< (code - KEY_1 ) );\r
- 112 }else if( value == 1 ){\r
- 113 pressed_code |=( 1<< (code - KEY_1 ) );\r
- }\r
-\r
-扫描并上报按键事件:\r
-\r
- 89 btn_scan( (btn_ctrl_t)p_button, pressed_code );\r
-\r
-### LED灯中间件\r
-\r
-路径:sdk/app/mg_app/led/\r
-\r
- src/led.c \r
-\r
-管理8个按键灯,5个装饰灯,一个光圈灯,一个红外补光灯。\r
-\r
-对应LED的设备接口\r
-\r
- 415 const struct led_path led_path_info[LED_NR] = {\r
- 416 { LED_KEY_1, "KEY_LED_1", "/sys/class/leds/key_led1" },\r
- 417 { LED_KEY_2, "KEY_LED_2", "/sys/class/leds/key_led2" },\r
- 418 { LED_KEY_3, "KEY_LED_3", "/sys/class/leds/key_led3" },\r
- 419 { LED_KEY_4, "KEY_LED_4", "/sys/class/leds/key_led4" },\r
- 420 { LED_KEY_5, "KEY_LED_5", "/sys/class/leds/key_led5" },\r
- 421 { LED_KEY_6, "KEY_LED_6", "/sys/class/leds/key_led6" },\r
- 422 { LED_KEY_7, "KEY_LED_7", "/sys/class/leds/key_led7" },\r
- 423 { LED_KEY_8, "KEY_LED_8", "/sys/class/leds/key_led8" },\r
- 424 { LED_ATMOS_1, "FUN_LED_1", "/sys/class/leds/fun_led1" },\r
- 425 { LED_ATMOS_2, "FUN_LED_2", "/sys/class/leds/fun_led2" },\r
- 426 { LED_ATMOS_3, "FUN_LED_3", "/sys/class/leds/fun_led3" },\r
- 427 { LED_ATMOS_4, "FUN_LED_4", "/sys/class/leds/fun_led4" },\r
- 428 { LED_ATMOS_5, "FUN_LED_5", "/sys/class/leds/fun_led5" },\r
- 429 { LED_RING, "RING_LED", "/sys/class/leds/ring_led" },\r
- 430 { LED_IR, "IR_LED", "/sys/class/leds/ir_led" },\r
- 431 };\r
- 432\r
-\r
-中间件调用open接口以后,为每一个led控制启动一个线程task,在task中按50毫秒周期检查led的显示模式, 显示的时间,计算对应的显示亮度并更新led状态。\r
-\r
- 471 void* led_thread_fun( void *led )\r
- 472 {\r
- 478 dev = (led_dev_t *)led;\r
- 480 while(1){\r
- 481 usleep( 50*1000 );\r
- 483 now_ms = now_msec();\r
- 485 led_dev_lock( dev );\r
- 487 curr_br = dev->br_curr;\r
- 488 if( dev->duration_ms && now_ms > dev->duration_stop_ms){\r
- 489 //时间到,关闭闪烁或呼吸\r
- 490 dev->flash = 0;\r
- 491 dev->duration_ms = 0;\r
- 492 curr_br = dev->br_max;\r
- 494 }\r
- 495\r
- 496 if( dev->flash == 1 ){\r
- 497 static uint32_t flash_br = 0;\r
- 498 //flash\r
- 499 if( (now_ms % dev->period_ms) *2 > dev->period_ms )\r
- 500 curr_br = dev->br_max;\r
- 501 else\r
- 502 curr_br = 0;\r
- 503 if( curr_br != flash_br ){\r
- 504 //printf( "[%d] %s thread, flash br %d -> %d\n", now_ms, dev->name, flash_br, curr_br );\r
- 505 flash_br = curr_br;\r
- 506 }\r
- 507\r
- 508 }else if( dev->flash == 2 ){\r
- 509 //breath;\r
- 510 //呼吸周期计算\r
-\r
-### TOF中间件\r
-\r
-路径:sdk/app/mg_app/tof/\r
-\r
-```\r
-tof.c 主要控制逻辑\r
-\r
-/*开关tof函数*/\r
-int32_t mg_tof_enable(mg_tof_t *tof_ctrl);\r
-int32_t mg_tof_disable(mg_tof_t *tof_ctrl);\r
-\r
-/*打开线程函数*/\r
-mg_tof_t * mg_tof_open(uint32_t distance);\r
-\r
-/*停止线程函数*/\r
-void mg_tof_close( mg_tof_t * tof_ctrl );\r
-\r
-/*状态查询函数*/\r
-int32_t mg_tof_read( mg_tof_t *tof_ctrl, tof_info_t *info );\r
-\r
-/*事件注册函数*/\r
-int32_t mg_tof_event_register(mg_tof_t *tof_ctrl,tof_event_cb_t cb);\r
-\r
-/*动态距离修改*/\r
-int32_t Distance_parameter_correction(mg_tof_t *tof_ctrl,uint32_t distance);\r
-```\r
-\r
-中间件调用mg_tof_open函数设置初始监测距离并获取tof控制器,使用mg_tof_event_register函数注册人感事件并传入回调函数,使用mg_tof_read函数可以获取当前人感状态传入控制器结构和tof_info_t,读取到的结果会保存在传入的tof_info_t结构中。使用Distance_parameter_correction函数来实现涂鸦平台下发的监测距离的修改。mg_tof_enable和mg_tof_disable可以在需要的时候停止或者重新开启tof。\r
-\r
-```\r
-mg_tof_open函数中对tof进行相关的设置\r
-\r
-const char *buffer = "0 15 15 0";\r
-\r
-rc = mg_tof_disable_my(NULL);\r
-if(rc != 0)\r
-{\r
- goto error;\r
-}\r
-\r
-//设置为模式4,按照传感器手册来设置即为通用模式\r
-HANDLE_PARAMETER_MY_DATA(mode,"mode",4);\r
-\r
-//设置传感器在空间中的测量坐标系,根据手册设置的是最大测量坐标 const char *buffer = "0 15 15 0";\r
-rc= parse_roi_arg(buffer, dev_rois, &u32);\r
-if(rc >= 0){\r
- verbose("%d roi to set", u32);\r
- dump_roi(stdout,dev_rois, u32);\r
- rc = stmvl53l1_set_roi(dev_fd, dev_rois,u32);\r
-}\r
-else{\r
- error("set roi");\r
- goto error;\r
-}\r
-\r
-//设置每次测量的间隔时间,现在设置的是最短时间60ms\r
-HANDLE_PARAMETER_MY_DATA(timing_budget, "timing budget",60000);\r
-rc = mg_tof_enable_my(NULL);\r
-if(rc != 0)\r
-{\r
- goto error;\r
-}\r
-\r
-//检测input子系统中的节点是否生成并获取input子系统上报的信息\r
-open_input_subsystem();\r
-if (rc < 0){\r
- printf("open_input_subsystem failed!!\n");\r
- goto error;\r
-}\r
-```\r
-\r
-测量函数\r
-\r
-```\r
-int run_meas_loop(int n_loops)\r
-{\r
- int rc = 0;\r
- int i;\r
- uint32_t prev_ts = -1;\r
-\r
- //is_sysfs这个标志位在open中调用过了open_input_subsystem,所以值一直为0\r
- if (is_sysfs) {\r
- rc = open_input_subsystem();\r
- if (rc < 0)\r
- return rc;\r
- }\r
- //通过传入n_loops决定测量次数\r
- for(i=0; i< n_loops; i++) {\r
- //此函数实现见下方\r
- rc = stmvl53l1_get_data_blocking(dev_fd, &dev_1xrange_data);\r
- if (rc != 0) {\r
- break;\r
- }\r
- //最终的测量结果保存在dev_1xrange_data.TimeStamp \r
- }\r
- if (is_sysfs)\r
- close_input_subsystem();\r
-\r
- return rc;\r
-}\r
-```\r
-\r
-stmvl53l1*get*data_blocking函数实现\r
-\r
-```\r
-int stmvl53l1_get_mz_data_blocking(int fd, VL53L1_MultiRangingData_t *data)\r
-{\r
- //根据is_sysfs参数判断,is_sysfs一直为0,所以执行stmvl53l1_get_mz_data_blocking_ioctl函数\r
- return is_sysfs ? stmvl53l1_get_mz_data_blocking_sysfs(data)\r
- : stmvl53l1_get_mz_data_blocking_ioctl(fd, data);\r
-}\r
-\r
-static int stmvl53l1_get_mz_data_blocking_sysfs(VL53L1_MultiRangingData_t *data)\r
-{\r
- ........\r
-}\r
-\r
-static int stmvl53l1_get_mz_data_blocking_ioctl(int fd, VL53L1_MultiRangingData_t *data)\r
-{\r
- int rc;\r
- //调用驱动提供的ioctl接口获取底层数据并将数据保存在VL53L1_MultiRangingData_t结构中。\r
- rc= ioctl(fd, VL53L1_IOCTL_MZ_DATA_BLOCKING, data);\r
- if( rc != 0){\r
- ioctl_error("%d %s", rc,strerror(errno));\r
- }\r
- return rc;\r
-}\r
-```\r
-\r
-在线程函数中进行主要的逻辑判断,并调用传入的回调函数实现结果上报给主程序。\r
-\r
-```\r
- while(stop){\r
- run_meas_loop(3);\r
- usleep(180 * 1000);\r
- //障碍物移开之后恢复到涂鸦下发的测量距离\r
- range = (int)dev_1xrange_data.RangeMilliMeter;\r
- if(range >= my_tof->default_range){\r
- is_fixe = 0;\r
- distanceThreshold = my_tof->default_range;\r
- }\r
- //在有障碍物的情况下判断障碍物是否移动\r
- if(is_fixe){\r
- run_meas_loop(3);\r
- usleep(180 * 1000);\r
- range = (int)dev_1xrange_data.RangeMilliMeter;\r
- if(range >= my_tof->default_range){\r
- is_fixe = 0;\r
- continue;\r
- }\r
- else if(range < distanceThreshold-5 || range > distanceThreshold+5){\r
- if(tof_event != NULL && my_info->status != TOF_ANYBODY){\r
- timer_flag = 1;\r
- my_info->distance = range;\r
- my_info->status = TOF_ANYBODY;\r
- printf("== 有 人 ==\n");\r
- tof_event(my_info);\r
- }\r
- }\r
- }\r
- //正常情况检测有人\r
- if(range < (distanceThreshold - 10)){\r
- TIMER_NOBODY = 1;\r
- if(tof_event != NULL && my_info->status != TOF_ANYBODY){\r
- timer_flag = 1;\r
- my_info->distance = range;\r
- my_info->status = TOF_ANYBODY;\r
- printf("== 有 人 ==\n");\r
- tof_event(my_info);\r
- }\r
- }\r
- //检测无人通过定时器控制有人到无人之间状态变化的时间\r
- if(range > my_tof->default_range){\r
- if(TIMER_NOBODY == 1){\r
- TIMER_NOBODY = 0;\r
- start_timer(1);\r
- }\r
- }\r
- //在检测到有人的前提下开启5s定时器检测障碍物\r
- if(timer_flag == 1)\r
- start_timer(0);\r
- }\r
-```\r
-\r
-### EIA485中间件\r
-\r
-路径:sdk/app/mg_app/eia485/\r
-\r
-```c\r
-src/485.c 主要控制逻辑\r
-\r
-mg_eia485_t * mg_eia485_open(uint32_t baud, uint32_t data_bits, uint32_t stop_bits, uint32_t parity )\r
-{\r
- ......\r
- //对串口进行基本设置\r
- //设置数据位长度\r
- switch( data_bits )\r
- {\r
- case 5:\r
- newtio.c_cflag |= CS5;\r
- break;\r
- case 6:\r
- newtio.c_cflag |= CS6;\r
- break;\r
- case 7:\r
- newtio.c_cflag |= CS7;\r
- break;\r
- case 8:\r
- newtio.c_cflag |= CS8;\r
- break;\r
- }\r
- //设置检验位\r
- switch( parity )\r
- {\r
- case '1':\r
- newtio.c_cflag |= PARENB;\r
- newtio.c_cflag |= PARODD;\r
- newtio.c_iflag |= (INPCK | ISTRIP);\r
- break;\r
- case '2': \r
- newtio.c_iflag |= (INPCK | ISTRIP);\r
- newtio.c_cflag |= PARENB;\r
- newtio.c_cflag &= ~PARODD;\r
- break;\r
- case '0': \r
- newtio.c_cflag &= ~PARENB;\r
- break;\r
- }\r
- //设置波特率\r
- switch( baud )\r
- {\r
- case 2400:\r
- cfsetispeed(&newtio, B2400);\r
- cfsetospeed(&newtio, B2400);\r
- break;\r
- case 4800:\r
- cfsetispeed(&newtio, B4800);\r
- cfsetospeed(&newtio, B4800);\r
- break;\r
- case 9600:\r
- cfsetispeed(&newtio, B9600);\r
- cfsetospeed(&newtio, B9600);\r
- break;\r
- case 115200:\r
- cfsetispeed(&newtio, B115200);\r
- cfsetospeed(&newtio, B115200);\r
- break;\r
- case 460800:\r
- cfsetispeed(&newtio, B460800);\r
- cfsetospeed(&newtio, B460800);\r
- break;\r
- case 921600:\r
- printf("Rate:921600\n");\r
- cfsetispeed(&newtio, B921600);\r
- cfsetospeed(&newtio, B921600);\r
- break;\r
- default:\r
- cfsetispeed(&newtio, B9600);\r
- cfsetospeed(&newtio, B9600);\r
- break;\r
- }\r
- //设置停止位\r
- if( stop_bits == 1 )\r
- newtio.c_cflag &= ~CSTOPB;\r
- else if ( stop_bits == 2 )\r
- newtio.c_cflag |= CSTOPB;\r
- ......\r
- //开启监听线程\r
- if( pthread_create( &uart5_thread, NULL, uart_task, NULL) != 0 ){\r
- perror("create 485 task!");\r
- goto error;\r
- }\r
- ......\r
-};\r
-```\r
-\r
-线程函数中主要进行接收数据,并将数据写入fifo\r
-\r
-```\r
-void* uart_task(void* data)\r
-{\r
- ......\r
- while (stop) {\r
- ......\r
- ret = select(my_485->uartFd + 1, &rfds, NULL, NULL,NULL);\r
- result = read(my_485->uartFd, &receiveData, 1);\r
- if (result > 0) {\r
- if (!writeToFifoQueue(&receiveQueue,receiveData))\r
- perror("Failed to write to FIFO queue\n");\r
- printf("receivedata 1----------->%c\n",receiveData);\r
- }else if(result == 0){\r
- lseek(my_485->uartFd, 0, SEEK_SET);\r
- }\r
- }\r
-}\r
-```\r
-\r
-fifo队列的实现\r
-\r
-```\r
-typedef struct {\r
- unsigned char* buffer;\r
- int capacity;\r
- int head;\r
- int tail;\r
- int count;\r
-} FifoQueue;\r
-FifoQueue receiveQueue;\r
-\r
-/*初始化fifo*/\r
-int initFifoQueue(FifoQueue* queue, int capacity) {\r
- queue->buffer = (unsigned char*)malloc(capacity * sizeof(unsigned char));\r
- if (queue->buffer == NULL) {\r
- perror("Failed to allocate memory for FIFO queue");\r
- return 0;\r
- }\r
-\r
- queue->capacity = capacity;\r
- queue->head = 0;\r
- queue->tail = 0;\r
- queue->count = 0;\r
-\r
- return 1;\r
-}\r
-\r
-/*销毁fifo*/\r
-void destroyFifoQueue(FifoQueue* queue) {\r
- if (queue->buffer != NULL) {\r
- free(queue->buffer);\r
- queue->buffer = NULL;\r
- }\r
- queue->capacity = 0;\r
- queue->head = 0;\r
- queue->tail = 0;\r
- queue->count = 0;\r
-}\r
-\r
-/*判断fifo是否已满*/\r
-int isFifoQueueFull(const FifoQueue* queue) {\r
- return (queue->count == queue->capacity);\r
-}\r
-\r
-/*判断fifo是否为空*/\r
-int isFifoQueueEmpty(const FifoQueue* queue) {\r
- return (queue->count == 0);\r
-}\r
-\r
-/*往fifo中写数据*/\r
-int writeToFifoQueue(FifoQueue* queue, unsigned char data) {\r
- if (isFifoQueueFull(queue)) {\r
- return 0;\r
- }\r
-\r
- queue->buffer[queue->tail] = data;\r
- queue->tail = (queue->tail + 1) % queue->capacity;\r
- queue->count++;\r
-\r
- return 1;\r
-}\r
-\r
-/*读取fifo的数据*/\r
-unsigned char readFromFifoQueue(FifoQueue* queue) {\r
- if (isFifoQueueEmpty(queue)) {\r
- return 0;\r
- }\r
-\r
- unsigned char data = queue->buffer[queue->head];\r
- queue->head = (queue->head + 1) % queue->capacity;\r
- queue->count--;\r
-\r
- return data;\r
-}\r
-\r
-/*清空fifo*/\r
-void clearFifoQueue(FifoQueue* queue) {\r
- if (queue == NULL) {\r
- return;\r
- }\r
-\r
- queue->head = 0;\r
- queue->tail = 0;\r
- queue->count = 0;\r
-}\r
-```\r
-\r
-### 环境光中间件\r
-\r
-路径:sdk/app/mg_app/als/\r
-\r
- als.c \r
-\r
-als设备接口\r
-\r
- static mg_als_t g_als = {\r
- .dev_path = "/sys/bus/iio/devices/iio:device0/in_voltage4_raw",\r
- };\r
-\r
-中间件调用open接口,该接口会打开als的设备文件节点获取文件描述符并启动一个task,周期性获取adc采集到的数据\r
-\r
- void* als_task( void* param )\r
- {\r
- ssize_t bytesRead;\r
- char buffer[BUFFER_SIZE];\r
- mg_als_t *p_als = ( mg_als_t*)param;\r
- \r
- while(!stop)\r
- {\r
- if(stop)\r
- break;\r
- //将文件指针移动到文件头位置\r
- lseek(p_als->fd,0,SEEK_SET); \r
- bytesRead = read(p_als->fd,buffer,BUFFER_SIZE -1);\r
- if(bytesRead < 0){\r
- MG_LOGE("read %s failed\n",p_als->fd);\r
- goto error;\r
- }\r
- //添加字符串结束符\r
- buffer[bytesRead] = '\0';\r
- //将字符串转换成整形数据\r
- p_als->data.ad_value = atoi(buffer);\r
- if(init)\r
- {\r
- //给定一个初始状态,(上限阈值/2)+(下限阈值/2)\r
- if(p_als->data.ad_value > ((p_als->data.threshold_high >> 1) + (p_als->data.threshold_low >> 1))){\r
- p_als->data.status = BRIGHT;\r
- }else{\r
- p_als->data.status = DARK;\r
- }\r
- init = 0;\r
- }else if(p_als->data.ad_value > (p_als->data.threshold_high)){\r
- p_als->data.status = BRIGHT;\r
- \r
- }else if(p_als->data.ad_value < (p_als->data.threshold_low)){\r
- p_als->data.status = DARK;\r
- }\r
- usleep(10000);\r
- }\r
- error:\r
- return NULL;\r
- }\r
-\r
-\r
-### 蜂鸣器中间件\r
-\r
-路径:sdk/app/mg_app/buzzer/\r
-\r
- buzzer.c \r
-\r
-buzzer设备接口\r
- \r
-\r
- mg_buzzer_t buzzer_init ={\r
- .enable = 0, //设备状态\r
- .dev_path[0] = "export",\r
- .dev_path[1] = "unexport",\r
- .dev_path[2] = "pwm0/period",\r
- .dev_path[3] = "pwm0/duty_cycle",\r
- .dev_path[4] = "pwm0/enable",\r
- };\r
-\r
-中间件调用open函数,open函数会检查pwm0节点是否存在如果不存在就调用system函数执行创建pwm0节点的操作,然后初始化定时器和返回蜂鸣器控制描述符\r
-\r
- mg_buzzer_t * mg_buzzer_open(void)\r
- {\r
- MG_LOGD( "tw8013 buzzer open...\n");\r
- if(access("/sys/class/pwm/pwmchip6/pwm0", 0))\r
- {\r
- if(mg_buzzer_start_t(0,buzzer_init.dev_path[0]))\r
- {\r
- MG_LOGE( "tw8013 buzzer open failed ...\n");\r
- return NULL;\r
- }\r
- } \r
- mg_buzzer_timer_init();\r
- return &buzzer_init;\r
- }\r
-\r
-应用中可以通过mg_buzzer_start函数设置蜂鸣器的参数使其播放声音\r
- \r
-\r
- mg_buzzer_start(buzzer, freq_hz ,duty_cycle , timer_ms);\r
-\r
-通过mg_buzzer_get函数可以获取当前蜂鸣器的状态及设置的相关参数(只有在蜂鸣器使能的情况下才能获取)\r
-\r
- mg_buzzer_get(buzzer,&c,&a,&b,&e);\r
-\r
-### 3.4 主应用\r
-\r
-#### 主流程\r
-\r
- 应用代码路径:sdk/app/mg_app/\r
-\r
-应用入口main函数:\r
- sdk/app/mg_app/app/src/main.c\r
-\r
-系统摄像头管理和手势识别算法,创建子进程来管理。\r
-\r
-父进程和子进程使用同一个应用程序,父进程中通过fork创建子进程后通过exec来执行子进程,进入main入口后首先检查是否子进程,如果是则调用算法进程模块的入口camera_process:\r
-\r
- 184 if( argc == 1 && strcmp( argv[0], "camera-ctrl" )==0 ){\r
- 185 //camera 控制 子进程\r
- 186 extern void camera_process( void );\r
- 187 camera_process();\r
- 188 exit(0);\r
- 189 }\r
-\r
-父进程继续运行,应用主程序只能运行一个实例,启动后先进行判断:\r
-\r
- 193 //检查程序是否已经运行\r
- 194 if( alone_runnind() ){\r
- 195 printf( "APP is alread runnig!\n" );\r
- 196 exit( -1 );\r
- 197 }\r
-\r
-初始化:\r
-\r
- 200 mg_log_init();\r
- 201 MG_LOGD( "mg app start..." );\r
- 202\r
- 203 //设备状态初始化\r
- 204 mg_device_init( &g_mg_dev );\r
- 205\r
- 206 //中间件初始化\r
- 207 btn_light_ctrl_init( &g_mg_dev );\r
- 208\r
- 209 //device_wifi_init();\r
- 210\r
- 211 // 启动wifi task;\r
- 212 //device_wifi_start();\r
- 213 device_netconfig_task_start( &g_mg_dev ); //start tuya bind and wificonfig\r
-启动背光按键控制子流程\r
-\r
- 214\r
- 215 //启动背光按键控制\r
- 216 btn_light_ctrl_start( &g_mg_dev );\r
-授权检查\r
-\r
- 218 //检查授权文件\r
- 219 while( load_auth_key( &g_mg_dev ) != 0 ){\r
- 220 //未授权,等待授权\r
- 221 mg_device_st_set( &g_mg_dev, DS_NO_AUTH );\r
- 222 MG_LOGD( "wait mg auth" );\r
- 223 sleep(5);\r
- 224 }\r
- 225\r
-配网检查:\r
-\r
- 226 //检查配网状态\r
- 227 if( !is_tuya_config( &g_mg_dev ) ){\r
- 228 netconfig_start( &g_mg_dev );\r
- 229 while( !is_tuya_config( &g_mg_dev ) ){\r
- 230 sleep(1);\r
- 231 }\r
- 232 netconfig_stop( &g_mg_dev );\r
- 233 }\r
- 234\r
-连接涂鸦\r
-\r
- 242 //连接涂鸦IOT平台\r
- 243 MG_LOGD( "iot start..");\r
- 244 iot_start();\r
-未激活则进行激活\r
-\r
- 261 //启动激活流程,堵塞,等待激活成功后返回\r
- 262 mg_device_active( &g_mg_dev );\r
-启动手势识别\r
-\r
- 282 if( !gesture_task_start( &g_mg_dev) ){\r
- 283 MG_LOGE( "start gesture task fail!\n" );\r
- 284 }\r
-主流程执行完成,各个子流程继续运行管理各自的逻辑\r
-#### 授权检查\r
-\r
-周期检查授权文件 mg_auth,如果无效,则是没有授权,等待授权\r
-\r
- 37 #define MG_AUTH_PATH "/customer/mg_auth"\r
-\r
-#### 涂鸦平台接入\r
-\r
-涂鸦接入需要接入key,需要预置到设备中的 /customer/tuya_auth 文件中\r
-接入的流程创建一个task,调用对应sdk接口连接到平台\r
-从文件中读取 接入key\r
-\r
- 97 void* iot_task( void * unused )\r
- 98 {\r
- ...\r
- 106 while( iot_key_load( &productId, &deviceId, &deviceSecret ) != 0){\r
- 107 MG_LOGE( "iot_task: load iot key fail!" );\r
- 108 sleep(5);\r
- 109 }\r
-初始化\r
-\r
- 111 ret = tuya_mqtt_init(client, &(const tuya_mqtt_config_t) {\r
- 112 .host = "m1.tuyacn.com",\r
- 113 .port = 8883,\r
- 114 .cacert = tuya_cacert_pem,\r
- 115 .cacert_len = sizeof(tuya_cacert_pem),\r
- 116 .device_id = deviceId,\r
- 117 .device_secret = deviceSecret,\r
- 118 .keepalive = 100,\r
- 119 .timeout_ms = 2000/10,\r
- 120 .on_connected = on_connected,\r
- 121 .on_disconnect = on_disconnect,\r
- 122 .on_messages = on_messages\r
- 123 });\r
-建立连接\r
-\r
- 128 ret = tuya_mqtt_connect(client);\r
-\r
-连接成功后就可以收发消息\r
-\r
-\r
-#### 激活流程\r
-\r
-连接涂鸦后,如果设备 没有激活则启动激活流程\r
-\r
- 221 int32_t mg_device_active( mg_dev_t *dev )\r
- 222 {\r
- ...\r
- 228 //read uuid;\r
- 229 if( !dev->uuid ){\r
- 230 read_device_uuid( dev );\r
- 231 }\r
- 232\r
- 233 sprintf( key_id, "%s%s", dev->auth_key_id, dev->uuid );\r
- 234\r
- 235 while( !dev->mg_active ){\r
- 236 //rx_key = 0;\r
- 237 dp_key_report( key_id );\r
- 238 //wait recv value\r
- 239 for( int i = 0; i<10; i++ ){\r
- 240 if( rx_key && !strcmp( dev->auth_key_value, received_key_value ) ){\r
- 241 dev->mg_active = 1;\r
- 242 if( mg_device_active_flag_write() ){\r
- 243 }\r
- 244 break;\r
- 245 }\r
- 246 sleep(1);\r
- 247 }\r
- 248 usleep(10);\r
- 249 }\r
- 250\r
- 251 return 0;\r
- 252 }\r
-\r
-从授权文件中读取key_id 拼接上系统uuid后,发送到涂鸦平台,然后等待接收到key_value消息,收到key_value 判断有效则完成激活流程。\r
-并创建已经激活标志文件 /customer/mg.active\r
-\r
-#### 配网流程\r
-\r
-配网目前有两个功能,一是配置wifi的ssid和密码,二是记录手机端已经执行了绑定操作\r
-设备端需要先预置有绑定码文件: \r
-\r
- /appconfigs/tuya.bind\r
-\r
-设备初始化时创建了配网的task\r
-\r
- void * device_netconfig_task( void * para )\r
-\r
-上电时没有配网或按下配网组合按键,调用到进入配网模式调用接口,开始配网流程:\r
-\r
- 18 int32_t netconfig_start( mg_dev_t *dev )\r
- 19 {\r
- 20 printf( "netconfig_start,now:%ld, , cfg:%d, s:%ld\n", device_uptime_sec(), dev->netconfig, dev->netconfig_start_time );\r
- 21 mg_dev_lock( dev );\r
- 22 dev->netconfig = 1;\r
- 23 dev->netconfig_start_time = device_uptime_sec();\r
- 24 mg_dev_unlock( dev );\r
- 25 return 0;\r
- 26 }\r
-\r
-配网task中检测到开始配网开启蓝牙广播和wifi udp服务\r
-\r
- 116 if( !ble_start && dev->netconfig ){\r
- 117 //启动配网\r
- 118 MG_LOGD( "ble start....\n" );\r
- 119 ble_get_local_ip( ip_str, sizeof( ip_str ) );\r
- 120 ble_start = dev->netconfig;\r
- 121 ble_wificonfig_start();\r
- 122 open_udp_listen();\r
-\r
-蓝牙广播设备名可以通过文件配置,手机端通过app连接后,可以发送ssid和密码到设备,设备保存到文件 /appconfigs/wifi.cfg 并更新到wpa_supplicant 的配置文件中。\r
-手机端可以通过蓝牙读取bindcode ,并发送绑定成功消息。设备接收到后即完成配网流程,关闭蓝牙和udp服务。手机端也可以通过udp连接来读取bindcode和发送bind完成消息。\r
-\r
-ble功能启动:\r
-```\r
-void * ble_wificonfig( void* p )\r
-```\r
-开始广播\r
-\r
- static void send_advertise( void )\r
-\r
-ble收到手机下发数据\r
-\r
- 1551 static DBusMessage *chr_write_value(DBusConnection *conn, DBusMessage *msg, void *user_data)\r
-\r
-ble上报数据到手机\r
-\r
- static DBusMessage *chr_read_value(DBusConnection *conn, DBusMessage *msg, void *user_data)\r
-\r
-#### 清洁模式\r
-\r
-长按组合键可以进入清洁模式,和退出清洁模式\r
-\r
-系统初始化时启动的控制任务用于管理按键和灯光等控制\r
-\r
- 18 //按键与背光子系统流程\r
- 19 void * btn_light_ctrl_task( void* para )\r
- \r
- 239 void btn_light_ctrl_start( mg_dev_t *dev )\r
- 240 {\r
- 241 if( pthread_create( &th, NULL, btn_light_ctrl_task, (void *)dev ) != 0 ){\r
- 242 MG_LOGE( "create button and light ctrl task fail!\n" );\r
- 243 }\r
- 244 }\r
- 245\r
-\r
-系统初始化时使用按键中间件的注册函数,注册了全部的组合按键\r
-\r
- 48 void device_button_init( mg_dev_t *dev )\r
- 49 {\r
- ......\r
- 55 ctrl = mg_button_open("/dev/input/by-path/platform-gpio_keys-event" );\r
- ......\r
- 57 mg_button_event_register( ctrl, 0xFF, EVENT_SINGLE_CLICK|EVENT_DOUBLE_CLICK|EVENT_LONG_PRESS|EVENT_LONG_PRESS_UP, button_single_cb );\r
- 58 mg_button_event_combonation_register( ctrl, BUTTON_7|BUTTON_8, EVENT_COMB_PRESS_5S, 0, button_comb_cb );\r
- 59 mg_button_event_combonation_register( ctrl, BUTTON_1|BUTTON_8, EVENT_COMB_PRESS_2S, 0, button_comb_cb );\r
- 60 mg_button_event_combonation_register( ctrl, BUTTON_2|BUTTON_7, EVENT_COMB_PRESS_2S, 0, button_comb_cb );\r
- ......\r
- 64 }\r
-\r
-BUTTON_1+BUTTON_8 长按2秒,和BUTTON_2+BUTTON_7长按2秒 已经注册,事件发生后就会调用button_comb_cb函数。\r
-在button_comb_cb中会创建一个消息发送到队列中,\r
-控制任务中读取到消息后检查是否进入清洁模式\r
-\r
- btn_msg_rx( &btn_msg ) \r
- to_clean_mode = is_btn_device_clean( &btn_msg );\r
-\r
-进入和退出cleanmode\r
-\r
- 57 if( !dev->clean_device && to_clean_mode ){\r
- 58\r
- 59 MG_LOGI( "enter clean mode ..." );\r
- 60 dev->clean_device = 1;\r
- 61 dev->clean_start_time = device_uptime_sec();\r
- 62\r
- 63 }else if( dev->clean_device && to_clean_mode_exit ){\r
- 64\r
- 65 MG_LOGI( "exit clean mode ..." );\r
- 66 dev->clean_device = 0;\r
- 67 dev->clean_start_time = 0;\r
-\r
-这里进入cleanmode时记录时间,用于超时退出\r
-\r
- 94 if( dev->clean_device ){\r
- 95 //检查清洁模式是否超时\r
- 96 if( dev->clean_start_time && device_uptime_sec() - dev->clean_start_time > CLEANMODE_TIMEOUT_SEC ){\r
- 97 mg_dev_lock( dev );\r
- 98 dev->clean_device = 0;\r
- 99 dev->clean_start_time = 0;\r
- 100 mg_dev_unlock( dev );\r
- 101 netconfig_stop( dev );\r
- 102 }\r
-\r
-#### LED灯管理\r
-\r
-在按键和led管理task中, 根据设备状态,切换LED的状态\r
-\r
- 18 //按键与背光子系统流程\r
- 19 void * btn_light_ctrl_task( void* para ){\r
- ......\r
- 128\r
- 129 dev_st_t st = dev->st;\r
- 130 if( dev->clean_device ){\r
- 131 light_mode_set( dev, LIGHT_MODE_CLEAN );\r
- 132 }else if( dev->netconfig ){\r
- 133 light_mode_set( dev, LIGHT_MODE_AUTH_WIFICONFIGING );\r
- 134 }else if( st == DS_INIT ){\r
- 135 light_mode_set( dev, LIGHT_MODE_INIT );\r
- 136 }else if( st == DS_NO_AUTH ){\r
- 137 light_mode_set( dev, LIGHT_MODE_NO_AUTH );\r
- 138 }else if( st == DS_AUTH_NO_WIFICONFIG ){\r
- 139 light_mode_set( dev, LIGHT_MODE_AUTH_NO_WIFICONFIG );\r
- 140 }else if( st == DS_AUTH_WIFICONFIGING ){\r
- 141 light_mode_set( dev, LIGHT_MODE_AUTH_WIFICONFIGING );\r
- 142 }else if( st == DS_AUTH_WIFICONFIG_NO_ACTIVE ){\r
- 143 light_mode_set( dev, LIGHT_MODE_AUTH_WIFICONFIG_NO_ACTIVE );\r
- 144 }else if( st == DS_ACTIVE ){\r
- 145\r
- 146 if( bl_manual ){\r
- ......\r
- }\r
-\r
-在激活状态,检查人感状态,控制对应的led显示\r
-背光为手动模式则停止tof监测,按dp状态显示LED灯\r
-背光为自动模式,则按人感检测周期,读取人感状态,如有变化,上报DP,更新led灯的状态\r
-\r
- 183 //检查周期到达,读取tof状态\r
- 184 if( mg_tof_read( dev->tof, &info )==0 ){\r
- 185 static tof_info_t dbg_info;\r
- 186 if( dbg_info.enable != info.enable || dbg_info.status != info.status || abs( dbg_info.distance-info.distance)>5 ){\r
- 187 memcpy( &dbg_info, &info, sizeof( dbg_info ) );\r
- 188 MG_LOGD( "read tof info, enable:%d, status:%d, dist:%d", info.enable, info.status, info.distance );\r
- 189 }\r
- 190 }else{\r
- 191 MG_LOGW( "read tof info fail, g_tof:%p", dev->tof );\r
- 192 }\r
- 193\r
- 194 if( !row_disabled && tof_sync ){\r
- 195 //联排功能,平台设置人感状态\r
- 196 light_mode_set( dev, LIGHT_MODE_TOF_ACTIVE );\r
- 197 }else if( info.enable && info.status == TOF_ANYBODY ){\r
- 198 light_mode_set( dev, LIGHT_MODE_TOF_ACTIVE );\r
- 199 }else{\r
- 200 light_mode_set( dev, LIGHT_MODE_TOF_DEACTIVE );\r
- 201 }\r
- 202 if( tof_st!= info.status ){\r
- 203 //状态变化,上报DP\r
- 204 tof_st= info.status;\r
- 205 dp_tof_status_report( tof_st== TOF_ANYBODY?1:0 );\r
- 206 MG_LOGI( "device tof status - > %d \n", tof_st );\r
- 207 }\r
-\r
-#### 手势识别流程\r
-\r
-算法和摄像头管理使用单独的进程管理\r
-\r
-子进程在main入口中直接调用\r
-\r
- 181 int main( int argc, char**argv )\r
- 182 {\r
- 183\r
- 184 if( argc == 1 && strcmp( argv[0], "camera-ctrl" )==0 ){\r
- 185 //camera 控制 子进程\r
- 186 extern void camera_process( void );\r
- 187 camera_process();\r
- 188 exit(0);\r
- 189 }\r
- ......\r
- }\r
-\r
-父进程和子进程通过共享内存通信\r
-\r
- 369 //子进程入口函数, 负责摄像头管理和手势识别\r
- 370 void camera_process( void )\r
- 371 {\r
- ......\r
- 389 // 开辟一段共享内存\r
- 390 mapfd = shm_open(CAM_SHM_NAME, O_RDWR, S_IRUSR | S_IWUSR);\r
-\r
-父进程可以通过共享内存发送摄像头切换指令,\r
-子进程循环执行, 控制摄像头拍照,识别手势,通过共享内存报告识别结果\r
-\r
-父进程中的gesture_task中启动子进程,并监测子进程的状态,如果子进程退出则重新启动子进程,如果子进程不响应超时1分钟则强制重启子进程。\r
-\r
- 532 //父进程\r
- 533 extern int32_t get_als_light( void );\r
- 534 void* gesture_task( void* param )\r
- 535 {\r
- ...... \r
- 595 while(1){\r
- ......\r
- fork创建子进程\r
- 604 cam_pid = fork();\r
- 605 if( cam_pid == -1 ){\r
- 606 perror("fork fail");\r
- 607 sleep(5);\r
- 608 continue;\r
- 609 }\r
- 610 if( cam_pid == 0 ){\r
- 611\r
- 612 extern char* program_name;\r
- 613 if( program_name )\r
- 614 program_name = strdup( "/app/mg_app" );\r
- 615\r
- 616 execl( program_name, "camera-ctrl" );\r
- 617 }\r
- 618\r
- \r
- ......\r
- 检测到子进程退出,重启子进程\r
- 622 while( 1 ){\r
- 623 usleep( 50*1000 );\r
- 624\r
- 625 if( cam_pid == waitpid(cam_pid, &status, WNOHANG) ){\r
- 626\r
- 627 printf( "waitpid pid:%d, status:%d, restart camer subprocess\n",cam_pid, status );\r
- 628 //重启子进程\r
- 629 break;\r
- 630 }\r
- ......\r
- 657 if( alive_err > 1*60*20 ){ //1*60*20*50ms -> 1min\r
- 658 alive_err = 0;\r
- 659 //子进程1分钟没有回应,关闭子进程\r
- 660 printf( "-----------kill sub process!\n" );\r
- 661 kill( cam_pid, SIGKILL ); //\r
- 662 }\r
-\r
-手势识别子流程在gr_task中完成\r
-\r
- void *gr_task(void *param)\r
-\r
-侦测到手掌并保持1秒,开启手势识别\r
-\r
- 559 if (gr_read_gesture() == GS_PAPER)\r
- 560 {\r
- 561 if (gr_ai_detect_palm() == 0)\r
- 562 {\r
- 563 printf("Enable gesture mode\n");\r
- 564 dp_recognition_running_report(1);\r
- 565 gr_ring_enable(p_gr->light_ctrl);\r
-\r
-超时退出手势识别:\r
-\r
- 588 if (device_uptime_sec() - gr_time > dp_timeout)\r
- 589 {\r
- 590 printf("gesture Time out\n");\r
- 591 reportdp_and_close_ring_gr(p_gr->light_ctrl);\r
- 592 break;\r
- 593 }\r
-\r
-侦测到手掌并保持1秒,退出手势识别\r
-\r
- 604 else if (ret == GS_PAPER)\r
- 605 {\r
- 606 if (gr_ai_detect_palm() == 0)\r
- 607 {\r
- 608 printf("Turn off gesture mode\n");\r
- 609 reportdp_and_close_ring_gr(p_gr->light_ctrl);\r
- 610 break;\r
- 611 }\r
- 612 }\r
-\r
-侦测到有效手势并上报\r
-\r
- 615 gr_detect_effective(ret);\r
-\r
-### 3.5 系统服务\r
-\r
-#### flash 分区和挂载\r
-系统分区表\r
-\r
- sdk/device/rockchip/rv1126_rv1109/parameter-tw8013.txt\r
- \r
- FIRMWARE_VER: 8.1\r
- MACHINE_MODEL: RV1126\r
- MACHINE_ID: 007\r
- MANUFACTURER: RV1126\r
- MAGIC: 0x5041524B\r
- ATAG: 0x00200800\r
- MACHINE: 0xffffffff\r
- CHECK_MASK: 0x80\r
- PWR_HLD: 0,0,A,0,1\r
- TYPE: GPT\r
- CMDLINE: mtdparts=rk29xxnand:0x00000800@0x00001000(vnvm),0x00002800@0x00001800(uboot),0x00008000@0x00004000(boot),0x00060000@0x0000C000(rootfs),0x00000400@0x0006C000(misc),0x00013C00@0x0006C400(recovery),0x00020000@0x00080000(userdata),0x00010000@0x000A0000(app),0x00008000@0x000B0000(appconfigs),0x00008000@0x000B8000(customer),-@0x000C0000(reserver:grow)\r
- uuid:rootfs=614e0000-0000-4b53-8000-1d28000054a9\r
-在SDK默认分区表上增加了app,appconfigs,customer, 最后分区reserver为保留空间未使用\r
-\r
-分区编译镜像要修改sdk配置文件\r
-\r
- sdk/device/rockchip/rv1126_rv1109/tw8013_defconfig\r
- \r
- RK_BUILDROOT_BASE_CFG="tw8013"\r
- RK_ROOTFS_TYPE="ubi"\r
- RK_UBOOT_CFG_FRAGMENTS="rk-sfc"\r
- RK_UBOOT_OPTS="--spl-new"\r
- RK_KERNEL_VERSION="4.19"\r
- RK_KERNEL_DTS_NAME="tw8013"\r
- RK_USE_FIT_IMG=y\r
- RK_RECOVERY_BASE_CFG="tw8013"\r
- RK_PARAMETER="parameter-tw8013.txt"\r
- RK_MISC_IMG="blank-misc.img"\r
- RK_EXTRA_PARTITION_NUM=4\r
- RK_EXTRA_PARTITION_1_DEV="userdata"\r
- RK_EXTRA_PARTITION_1_FSTYPE="ubi"\r
- RK_EXTRA_PARTITION_1_SIZE="60M"\r
- RK_EXTRA_PARTITION_2_DEV="app"\r
- RK_EXTRA_PARTITION_2_FSTYPE="ubi"\r
- RK_EXTRA_PARTITION_2_SIZE="28M"\r
- RK_EXTRA_PARTITION_3_DEV="appconfigs"\r
- RK_EXTRA_PARTITION_3_FSTYPE="ubi"\r
- RK_EXTRA_PARTITION_3_SIZE="10M"\r
- RK_EXTRA_PARTITION_3_SRC="normal"\r
- RK_EXTRA_PARTITION_4_DEV="customer"\r
- RK_EXTRA_PARTITION_4_FSTYPE="ubi"\r
- RK_EXTRA_PARTITION_4_SIZE="10M"\r
- RK_EXTRA_PARTITION_4_SRC="normal"\r
- \r
- RK_UBI_PAGE_SIZE=0x1000\r
- RK_UBI_BLOCK_SIZE=0x40000\r
-\r
-分区挂载:\r
-\r
- sdk/buildroot/board/rockchip/rv1126_rv1109/fs-overlay-tw8013cat etc/init.d/S09_mount_userdata\r
- \r
- #!/bin/sh\r
- #\r
- # Start init\r
- #\r
- \r
- start() {\r
- printf "Starting mount userdata parition...\n "\r
- ubiattach -p /dev/mtd6\r
- mount -t ubifs -o "rw" /dev/ubi1_0 /userdata\r
- ubiattach -p /dev/mtd7\r
- mount -t ubifs -o "rw" /dev/ubi2_0 /app\r
- ubiattach -p /dev/mtd8\r
- mount -t ubifs -o "rw" /dev/ubi3_0 /appconfigs\r
- ubiattach -p /dev/mtd9\r
- mount -t ubifs -o "rw" /dev/ubi4_0 /customer\r
- }\r
- \r
- case "$1" in\r
- start)\r
- start\r
- ;;\r
- stop)\r
- ;;\r
- restart|reload)\r
- ;;\r
- *)\r
- echo "Usage: $0 {start|stop|restart}"\r
- exit 1\r
- esac\r
- \r
- exit $?\r
-\r
-#### wifi 服务\r
-\r
-sdk/buildroot/board/rockchip/rv1126_rv1109/fs-overlay-tw8013/etc/init.d/S99_tw8013_wifi\r
-\r
-主要使用了wpa_cli提供的命令启动wifi服务,将链接上的wifi保存在/appconfigs/service/wpa_supplicant.conf目录中,也就是服务相关的配置文件。\r
-\r
-```\r
-#!/bin/sh\r
-\r
-start() {\r
- echo "wifi_test_activty"\r
- echo "tw8013 wifi up"\r
- CONF=/appconfigs/service/wpa_supplicant.conf\r
- killall wpa_supplicant\r
- sleep 1\r
- wpa_supplicant -D nl80211 -i wlan0 -c $CONF -B\r
-}\r
-\r
-case "$1" in\r
- start)\r
- start\r
- ;;\r
- stop)\r
- ;;\r
- *)\r
- echo "Usage:$0 [start|stop]"\r
- exit 1\r
- ;;\r
-esac\r
-\r
-exit 0\r
-```\r
-\r
-#### 守护进程\r
-\r
-sdk/buildroot/board/rockchip/rv1126_rv1109/fs-overlay-tw8013/usr/bin/mgd\r
-\r
-通过开机自启动脚本开启守护进程mgd并将mg_app启动,在脚本中每间隔10s通过ps系统命令去检测mg_app进程是否在运行,如果没有运行则再次启动它。\r
-\r
-```\r
-#!/bin/bash\r
- \r
- ......\r
- \r
-# 定义守护进程的名称和运行路径\r
-DAEMON_NAME="mg_app"\r
-DAEMON_PATH="/app"\r
-# 检查守护进程是否已经在运行\r
-is_running() {\r
- ps -ef | grep "./$DAEMON_NAME" | grep -v grep > /dev/null\r
-}\r
-\r
-......\r
-\r
-# 启动守护进程\r
-start() {\r
- if is_running; then\r
- echo "守护进程 $DAEMON_NAME 已经在运行。"\r
- exit 1\r
- fi\r
-\r
- echo "启动守护进程 $DAEMON_NAME ..."\r
- cd "$DAEMON_PATH"\r
- ./"$DAEMON_NAME" &\r
- echo "守护进程 $DAEMON_NAME 启动成功。"\r
-}\r
-\r
-# 监测守护进程并重新启动\r
-monitor() {\r
- while true; do\r
- if ! is_running; then\r
- echo "守护进程 $DAEMON_NAME 未在运行,重新启动..."\r
- start\r
- fi\r
- \r
- ......\r
- \r
- sleep 10\r
- done\r
-}\r
-\r
-# 检查命令行参数\r
-case "$1" in \r
- start)\r
- start\r
- monitor\r
- ;;\r
- *)\r
- echo "error"\r
- exit 1\r
- ;;\r
-esac\r
-```\r
-\r
-#### 看门狗\r
-\r
-添加看门狗服务\r
-\r
-sdk/buildroot/configs/rockchip_tw8013_defconfig\r
-\r
-```\r
-......\r
-BR2_PACKAGE_BLUEZ5_UTILS-5.50=y\r
-#添加看门狗\r
-BR2_PACKAGE_WATCHDOG=y\r
-BR2_PACKAGE_WATCHDOGD=y\r
-\r
-```\r
-\r
-watchdog.conf为看门狗服务配置文件,watchdogd.conf为看门狗服务的守护进程。\r
-\r
-sdk/buildroot/board/rockchip/rv1126_rv1109/fs-overlay-tw8013/etc/watchdog.conf\r
-\r
-```\r
-# ====================================================================\r
-# Configuration for the watchdog daemon. For more information on the\r
-# parameters in this file use the command 'man watchdog.conf'\r
-# ====================================================================\r
-\r
-.....\r
-\r
-# To see if they load, present /dev/watchdog, and are capable of\r
-# resetting the system on time-out.\r
-\r
-#pidfile = /var/run/rsyslogd.pid\r
-```\r
-\r
-sdk/buildroot/board/rockchip/rv1126_rv1109/fs-overlay-tw8013/etc/watchdogd.conf\r
-\r
-```\r
-# /etc/watchdogd.conf sample\r
-# Commented out values are program defaults.\r
-\r
-......\r
-\r
-# script = "/path/to/alt-reboot-action.sh"\r
-}\r
-```\r
-### 3.6 配置文件说明文档\r
- TW8013中间件接口定义.md\r
-\r
-### 3.7 中间件接口文档\r
- TW8013软件说明.md
\ No newline at end of file
+++ /dev/null
-# TW8013 软件说明\r
-## 1. 配置文件说明\r
-\r
-\r
-### 1.1 硬件版本\r
-文件路径\r
-\r
- /customer/hw_version\r
-文件内容:\r
-\r
- {\r
- "hw_version" : "V1.0"\r
- } \r
-\r
-### 1.2 摩根授权文件\r
-文件路径\r
-\r
- /customer/mg_auth\r
-文件内容:\r
-\r
- mg126d058eb378cc26be\r
- Qm3yoVX00JipFNgKUs5Rd5vTz9BW1jSP\r
-第一行是key ID,第二行是key value 用于摩根激活流程,\r
-激活成功时创建激活标志文件 /customer/mg.active\r
-\r
-### 1.3 摩根激活标志\r
-文件路径\r
-\r
- /customer/mg.active\r
-文件内容:\r
-\r
- 空文件,激活后建立这个文件,如果文件不存在则认为未激活\r
-\r
-### 1.4 涂鸦接入key文件\r
-文件路径\r
-\r
- /customer/tuya_auth\r
-文件内容:\r
-\r
- {\r
- "productID" : "3xeyrwyvbuyajz4a",\r
- "deviceID" : "2603f2bd3edca286d28wwz",\r
- "deviceSecret" : "Se6qN6Um7GdLvJAn"\r
- }\r
-用于接入涂鸦云平台的key\r
-### 1.5 涂鸦绑定二维码\r
-文件路径\r
-\r
- /customer/tuya_bindcode\r
-文件内容:\r
-\r
- {\r
- "bindcode":"https://smartapp.smart321.com/scandeviceId=12345678&appId="\r
- }\r
-\r
-涂鸦的设备绑定二维码的url字串,其中deviceID变量就是设备的bindcode\r
-\r
-### 1.6 设备参数配置文件\r
-文件路径\r
-\r
- /appconfigs/dev.cfg\r
-文件内容:\r
-\r
- 二进制数据,应用程序通过涂鸦接收到dp下发的设备参数存储在这个文件中\r
- 开机时自动加载\r
- 如果删除这个文件则各个参数恢复默认值\r
-\r
-### 1.7 涂鸦绑定标志\r
-文件路径\r
-\r
- /appconfigs/tuya.bind\r
-文件内容:\r
-\r
- 空文件,通过蓝牙ble或udp发送配网成功消息候app自动创建这个文件。\r
- 应用启动时,检查到wifi.cfg 和 tuya.bind 两个文件都有效,表示设备已经配网,否则直接进入配网模式。\r
-\r
-### 1.8 wifi配网标志\r
-文件路径\r
-\r
- /appconfigs/wifi.cfg\r
-文件内容:\r
-\r
- {\r
- "ssid":"XXXX",\r
- "password":"XXXXXXXX"\r
- }\r
- 手机端通过rockhome.apk,发送正确的ssid和password后,app创建这个文件,表示wifi配网成功\r
- 应用启动时,检查到wifi.cfg 和 tuya.bind 两个文件都有效,表示设备已经配网,否则直接进入配网模式。\r
-\r
-### 1.9 wifi服务配置文件\r
-文件路径\r
-\r
- /appconfigs/service/wpa_supplicant.conf\r
-文件内容:\r
-\r
- ctrl_interface=/var/run/wpa_supplicant\r
- update_config=1\r
- network={\r
- ssid="SSID"\r
- psk="PASSWORD"\r
- key_mgmt=WPA-PSK\r
- }\r
- wap 配置,配网模式下通过手机rockhome成功配置后自动修改这个文件中对应ssid和psk字段。\r
- 测试时可以通过手动修改后重启wpa_spplicant 服务来连接对应热点\r
-\r
-### 1.10 环境光阈值配置文件\r
-文件路径\r
-\r
- /appconfigs/als.cfg\r
-文件内容:\r
-\r
- {\r
- "high" : 1000,\r
- "low" : 400\r
- }\r
- 应用启动时,加载阈值,如果文件不存在,则使用默认值。\r
-\r
-### 1.11 人感检测配置文件\r
-文件路径\r
-\r
- /appconfigs/tof.cfg\r
-文件内容:\r
-\r
- {\r
- "nobody_timer" : 1,\r
- }\r
- 有人切换到无人状态延时值,单位秒,\r
- 应用启动时,加载阈值,如果文件不存在,则使用默认值 1秒。\r
-\r
-### 1.12 蓝牙BLE广播配置\r
-文件路径\r
-\r
- /appconfigs/ble_adv.cfg\r
-文件内容:\r
-\r
- {\r
- "local_name" : "ROCKCHIP",\r
- }\r
- 蓝牙广播名字\r
- 应用启动时加载,如果文件不存在,则使用默认值”MOORGEN“。\r
-\r
-### 1.13 LED配置\r
-文件路径\r
-\r
- /appconfigs/light.cfg\r
-文件内容:\r
-\r
- {\r
- "brightness" : [\r
- 0,\r
- 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,\r
- 11, 12, 13, 14, 15, 16, 17, 18, 19, 20,\r
- 21, 22, 23, 24, 25, 26, 27, 28, 29, 30,\r
- 32, 34, 36, 38, 40, 42, 34, 36, 38, 50,\r
- 52, 54, 56, 58, 60, 62, 64, 66, 68, 70,\r
- 72, 74, 76, 78, 80, 82, 84, 86, 88, 90,\r
- 92, 94, 96, 98, 100, 102, 104, 106, 108, 110,\r
- 112, 114, 116, 118, 120, 122, 124, 126, 128, 130,\r
- 132, 134, 136, 138, 140, 142, 144, 146, 148, 150,\r
- 160, 170, 180, 190, 200, 210, 220, 230, 240, 255\r
- ],\r
- "breath" : {\r
- "increase":600,\r
- "decrease":600,\r
- "apnea":300\r
- }\r
- }\r
- brightness 对应0--100各级亮度的值, 亮度取值范围是0-255,0:关闭, 255:最大亮度\r
- 应用启动时加载,如果文件不存在,则使用默认值\r
- breath 呼吸灯时间参数,分别为渐亮,渐暗,关闭的时间,单位毫秒.\r
-\r
-### 1.13 守护进程 mgd\r
-文件路径\r
-\r
- /usr/bin/mgd\r
-脚本文件,开机后调用ntp同步网络时间。检查mg_app的状态,如果mg_app终止会重启mg_app\r
-\r
-### 1.14 主程序 mg_app\r
-文件路径\r
- /app/mg_app\r
-\r
- 应用主程序\r
-\r
-### 1.15 flash 分区\r
-\r
- root@TW8013:/# cat /proc/mtd\r
- dev: size erasesize name\r
- mtd0: 00100000 00040000 "vnvm" ---- 1M\r
- mtd1: 00500000 00040000 "uboot" ---- 5M\r
- mtd2: 01000000 00040000 "boot" ---- 16M\r
- mtd3: 0c000000 00040000 "rootfs" ---- 192M\r
- mtd4: 00080000 00040000 "misc" ---- 0.5M\r
- mtd5: 02780000 00040000 "recovery" ---- 39.5M\r
- mtd6: 04000000 00040000 "userdata" ---- 64M\r
- mtd7: 02000000 00040000 "app" ---- 32M\r
- mtd8: 01000000 00040000 "appconfigs" ---- 16M\r
- mtd9: 01000000 00040000 "customer" ---- 16M\r
- mtd10: 07ec0000 00040000 "reserver" ---- 126.75M\r
-\r
- 分区配置文件:\r
- SDK/device/rockchip/rv1126_rv1109/parameter-tw8013.txt\r
- FIRMWARE_VER: 8.1\r
- MACHINE_MODEL: RV1126\r
- MACHINE_ID: 007\r
- MANUFACTURER: RV1126\r
- MAGIC: 0x5041524B\r
- ATAG: 0x00200800\r
- MACHINE: 0xffffffff\r
- CHECK_MASK: 0x80\r
- PWR_HLD: 0,0,A,0,1\r
- TYPE: GPT\r
- CMDLINE: mtdparts=rk29xxnand:0x00000800@0x00001000(vnvm),0x00002800@0x00001800(uboot),0x00008000@0x00004000(boot),0x00060000@0x0000C000(rootfs),0x00000400@0x0006C000(misc),0x00013C00@0x0006C400(recovery),0x00020000@0x00080000(userdata),0x00010000@0x000A0000(app),0x00008000@0x000B0000(appconfigs),0x00008000@0x000B8000(customer),-@0x000C0000(reserver:grow)\r
- uuid:rootfs=614e0000-0000-4b53-8000-1d28000054a9\r
-\r
-\r
cmake_minimum_required(VERSION 3.8)
-project(mg_app)
+project(rfjb_app)
add_definitions(-DRKAIQ)
aux_source_directory(common COMMON_SRCS)
${PROJECT_SOURCE_DIR}/./
${PROJECT_SOURCE_DIR}/src/
${PROJECT_SOURCE_DIR}/inc/
- ${PROJECT_SOURCE_DIR}/../tuya-iot-core-sdk/include/
- ${PROJECT_SOURCE_DIR}/../tuya/iot-core-sdk/interface/
- ${PROJECT_SOURCE_DIR}/../tuya/iot-core-sdk/middleware/
- ${PROJECT_SOURCE_DIR}/../tuya/iot-core-sdk/utils/
${PROJECT_SOURCE_DIR}/../button/inc/
${PROJECT_SOURCE_DIR}/../led/inc/
- ${PROJECT_SOURCE_DIR}/../tof/inc/
- ${PROJECT_SOURCE_DIR}/../als/inc/
- ${PROJECT_SOURCE_DIR}/../udp/inc/
- ${PROJECT_SOURCE_DIR}/../buzzer/inc/
${PROJECT_SOURCE_DIR}/../log/inc/
- ${PROJECT_SOURCE_DIR}/common/
- ${PROJECT_SOURCE_DIR}/../../rkmedia/include/rkmedia/
- ${PROJECT_SOURCE_DIR}/../../rkmedia/include/easymedia/
- ${PROJECT_SOURCE_DIR}/../../rkmedia/include/easymedia/
${CMAKE_SYSROOT}/usr/include/
- ${CMAKE_SYSROOT}/usr/include/rkaiq/algos
- ${CMAKE_SYSROOT}/usr/include/rkaiq/common
- ${CMAKE_SYSROOT}/usr/include/rkaiq/iq_parser
- ${CMAKE_SYSROOT}/usr/include/rkaiq/uAPI
- ${CMAKE_SYSROOT}/usr/include/rkaiq/xcore
)
link_directories(
target_link_libraries(
${PROJECT_NAME}
PUBLIC
- mg_button
- mg_led
- mg_buzzer
- mg_log
- mg_udp
+ rfjb_button
+ rfjb_led
+ rfjb_log
log4c
rt
- modbus
+ modbus
z
- ${GLIB2_LIBRARIES}
- ${DBUS_LIBRARIES}
+ ${GLIB2_LIBRARIES}
+ ${DBUS_LIBRARIES}
pthread
)
install(TARGETS ${PROJECT_NAME} RUNTIME DESTINATION /app)
-install(FILES ${PROJECT_SOURCE_DIR}/libsteria/libstasteria.so DESTINATION /usr/lib)
-install(DIRECTORY ${PROJECT_SOURCE_DIR}/st_model DESTINATION /usr/share )
-install(FILES ${PROJECT_SOURCE_DIR}/license.lic DESTINATION /customer )
-
+#install(FILES ${PROJECT_SOURCE_DIR}/libsteria/libstasteria.so DESTINATION /usr/lib)
--- /dev/null
+/*
+ Copyright (c) 2009-2017 Dave Gamble and cJSON contributors
+
+ Permission is hereby granted, free of charge, to any person obtaining a copy
+ of this software and associated documentation files (the "Software"), to deal
+ in the Software without restriction, including without limitation the rights
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ copies of the Software, and to permit persons to whom the Software is
+ furnished to do so, subject to the following conditions:
+
+ The above copyright notice and this permission notice shall be included in
+ all copies or substantial portions of the Software.
+
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ THE SOFTWARE.
+*/
+
+#ifndef cJSON__h
+#define cJSON__h
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+#if !defined(__WINDOWS__) && (defined(WIN32) || defined(WIN64) || defined(_MSC_VER) || defined(_WIN32))
+#define __WINDOWS__
+#endif
+
+#ifdef __WINDOWS__
+
+/* When compiling for windows, we specify a specific calling convention to avoid issues where we are being called from a project with a different default calling convention. For windows you have 3 define options:
+
+CJSON_HIDE_SYMBOLS - Define this in the case where you don't want to ever dllexport symbols
+CJSON_EXPORT_SYMBOLS - Define this on library build when you want to dllexport symbols (default)
+CJSON_IMPORT_SYMBOLS - Define this if you want to dllimport symbol
+
+For *nix builds that support visibility attribute, you can define similar behavior by
+
+setting default visibility to hidden by adding
+-fvisibility=hidden (for gcc)
+or
+-xldscope=hidden (for sun cc)
+to CFLAGS
+
+then using the CJSON_API_VISIBILITY flag to "export" the same symbols the way CJSON_EXPORT_SYMBOLS does
+
+*/
+
+#define CJSON_CDECL __cdecl
+#define CJSON_STDCALL __stdcall
+
+/* export symbols by default, this is necessary for copy pasting the C and header file */
+#if !defined(CJSON_HIDE_SYMBOLS) && !defined(CJSON_IMPORT_SYMBOLS) && !defined(CJSON_EXPORT_SYMBOLS)
+#define CJSON_EXPORT_SYMBOLS
+#endif
+
+#if defined(CJSON_HIDE_SYMBOLS)
+#define CJSON_PUBLIC(type) type CJSON_STDCALL
+#elif defined(CJSON_EXPORT_SYMBOLS)
+#define CJSON_PUBLIC(type) __declspec(dllexport) type CJSON_STDCALL
+#elif defined(CJSON_IMPORT_SYMBOLS)
+#define CJSON_PUBLIC(type) __declspec(dllimport) type CJSON_STDCALL
+#endif
+#else /* !__WINDOWS__ */
+#define CJSON_CDECL
+#define CJSON_STDCALL
+
+#if (defined(__GNUC__) || defined(__SUNPRO_CC) || defined (__SUNPRO_C)) && defined(CJSON_API_VISIBILITY)
+#define CJSON_PUBLIC(type) __attribute__((visibility("default"))) type
+#else
+#define CJSON_PUBLIC(type) type
+#endif
+#endif
+
+/* project version */
+#define CJSON_VERSION_MAJOR 1
+#define CJSON_VERSION_MINOR 7
+#define CJSON_VERSION_PATCH 12
+
+#include <stddef.h>
+
+/* cJSON Types: */
+#define cJSON_Invalid (0)
+#define cJSON_False (1 << 0)
+#define cJSON_True (1 << 1)
+#define cJSON_NULL (1 << 2)
+#define cJSON_Number (1 << 3)
+#define cJSON_String (1 << 4)
+#define cJSON_Array (1 << 5)
+#define cJSON_Object (1 << 6)
+#define cJSON_Raw (1 << 7) /* raw json */
+
+#define cJSON_IsReference 256
+#define cJSON_StringIsConst 512
+
+/* The cJSON structure: */
+typedef struct cJSON
+{
+ /* next/prev allow you to walk array/object chains. Alternatively, use GetArraySize/GetArrayItem/GetObjectItem */
+ struct cJSON *next;
+ struct cJSON *prev;
+ /* An array or object item will have a child pointer pointing to a chain of the items in the array/object. */
+ struct cJSON *child;
+
+ /* The type of the item, as above. */
+ int type;
+
+ /* The item's string, if type==cJSON_String and type == cJSON_Raw */
+ char *valuestring;
+ /* writing to valueint is DEPRECATED, use cJSON_SetNumberValue instead */
+ int valueint;
+ /* The item's number, if type==cJSON_Number */
+ double valuedouble;
+
+ /* The item's name string, if this item is the child of, or is in the list of subitems of an object. */
+ char *string;
+} cJSON;
+
+typedef struct cJSON_Hooks
+{
+ /* malloc/free are CDECL on Windows regardless of the default calling convention of the compiler, so ensure the hooks allow passing those functions directly. */
+ void *(CJSON_CDECL *malloc_fn)(size_t sz);
+ void (CJSON_CDECL *free_fn)(void *ptr);
+} cJSON_Hooks;
+
+typedef int cJSON_bool;
+
+/* Limits how deeply nested arrays/objects can be before cJSON rejects to parse them.
+ * This is to prevent stack overflows. */
+#ifndef CJSON_NESTING_LIMIT
+#define CJSON_NESTING_LIMIT 1000
+#endif
+
+/* Precision of double variables comparison */
+#ifndef CJSON_DOUBLE_PRECISION
+#define CJSON_DOUBLE_PRECISION .0000000000000001
+#endif
+
+/* returns the version of cJSON as a string */
+CJSON_PUBLIC(const char*) cJSON_Version(void);
+
+/* Supply malloc, realloc and free functions to cJSON */
+CJSON_PUBLIC(void) cJSON_InitHooks(cJSON_Hooks* hooks);
+
+/* Memory Management: the caller is always responsible to free the results from all variants of cJSON_Parse (with cJSON_Delete) and cJSON_Print (with stdlib free, cJSON_Hooks.free_fn, or cJSON_free as appropriate). The exception is cJSON_PrintPreallocated, where the caller has full responsibility of the buffer. */
+/* Supply a block of JSON, and this returns a cJSON object you can interrogate. */
+CJSON_PUBLIC(cJSON *) cJSON_Parse(const char *value);
+/* ParseWithOpts allows you to require (and check) that the JSON is null terminated, and to retrieve the pointer to the final byte parsed. */
+/* If you supply a ptr in return_parse_end and parsing fails, then return_parse_end will contain a pointer to the error so will match cJSON_GetErrorPtr(). */
+CJSON_PUBLIC(cJSON *) cJSON_ParseWithOpts(const char *value, const char **return_parse_end, cJSON_bool require_null_terminated);
+
+/* Render a cJSON entity to text for transfer/storage. */
+CJSON_PUBLIC(char *) cJSON_Print(const cJSON *item);
+/* Render a cJSON entity to text for transfer/storage without any formatting. */
+CJSON_PUBLIC(char *) cJSON_PrintUnformatted(const cJSON *item);
+/* Render a cJSON entity to text using a buffered strategy. prebuffer is a guess at the final size. guessing well reduces reallocation. fmt=0 gives unformatted, =1 gives formatted */
+CJSON_PUBLIC(char *) cJSON_PrintBuffered(const cJSON *item, int prebuffer, cJSON_bool fmt);
+/* Render a cJSON entity to text using a buffer already allocated in memory with given length. Returns 1 on success and 0 on failure. */
+/* NOTE: cJSON is not always 100% accurate in estimating how much memory it will use, so to be safe allocate 5 bytes more than you actually need */
+CJSON_PUBLIC(cJSON_bool) cJSON_PrintPreallocated(cJSON *item, char *buffer, const int length, const cJSON_bool format);
+/* Delete a cJSON entity and all subentities. */
+CJSON_PUBLIC(void) cJSON_Delete(cJSON *item);
+
+/* Returns the number of items in an array (or object). */
+CJSON_PUBLIC(int) cJSON_GetArraySize(const cJSON *array);
+/* Retrieve item number "index" from array "array". Returns NULL if unsuccessful. */
+CJSON_PUBLIC(cJSON *) cJSON_GetArrayItem(const cJSON *array, int index);
+/* Get item "string" from object. Case insensitive. */
+CJSON_PUBLIC(cJSON *) cJSON_GetObjectItem(const cJSON * const object, const char * const string);
+CJSON_PUBLIC(cJSON *) cJSON_GetObjectItemCaseSensitive(const cJSON * const object, const char * const string);
+CJSON_PUBLIC(cJSON_bool) cJSON_HasObjectItem(const cJSON *object, const char *string);
+/* For analysing failed parses. This returns a pointer to the parse error. You'll probably need to look a few chars back to make sense of it. Defined when cJSON_Parse() returns 0. 0 when cJSON_Parse() succeeds. */
+CJSON_PUBLIC(const char *) cJSON_GetErrorPtr(void);
+
+/* Check if the item is a string and return its valuestring */
+CJSON_PUBLIC(char *) cJSON_GetStringValue(const cJSON * const item);
+
+/* These functions check the type of an item */
+CJSON_PUBLIC(cJSON_bool) cJSON_IsInvalid(const cJSON * const item);
+CJSON_PUBLIC(cJSON_bool) cJSON_IsFalse(const cJSON * const item);
+CJSON_PUBLIC(cJSON_bool) cJSON_IsTrue(const cJSON * const item);
+CJSON_PUBLIC(cJSON_bool) cJSON_IsBool(const cJSON * const item);
+CJSON_PUBLIC(cJSON_bool) cJSON_IsNull(const cJSON * const item);
+CJSON_PUBLIC(cJSON_bool) cJSON_IsNumber(const cJSON * const item);
+CJSON_PUBLIC(cJSON_bool) cJSON_IsString(const cJSON * const item);
+CJSON_PUBLIC(cJSON_bool) cJSON_IsArray(const cJSON * const item);
+CJSON_PUBLIC(cJSON_bool) cJSON_IsObject(const cJSON * const item);
+CJSON_PUBLIC(cJSON_bool) cJSON_IsRaw(const cJSON * const item);
+
+/* These calls create a cJSON item of the appropriate type. */
+CJSON_PUBLIC(cJSON *) cJSON_CreateNull(void);
+CJSON_PUBLIC(cJSON *) cJSON_CreateTrue(void);
+CJSON_PUBLIC(cJSON *) cJSON_CreateFalse(void);
+CJSON_PUBLIC(cJSON *) cJSON_CreateBool(cJSON_bool boolean);
+CJSON_PUBLIC(cJSON *) cJSON_CreateNumber(double num);
+CJSON_PUBLIC(cJSON *) cJSON_CreateString(const char *string);
+/* raw json */
+CJSON_PUBLIC(cJSON *) cJSON_CreateRaw(const char *raw);
+CJSON_PUBLIC(cJSON *) cJSON_CreateArray(void);
+CJSON_PUBLIC(cJSON *) cJSON_CreateObject(void);
+
+/* Create a string where valuestring references a string so
+ * it will not be freed by cJSON_Delete */
+CJSON_PUBLIC(cJSON *) cJSON_CreateStringReference(const char *string);
+/* Create an object/array that only references it's elements so
+ * they will not be freed by cJSON_Delete */
+CJSON_PUBLIC(cJSON *) cJSON_CreateObjectReference(const cJSON *child);
+CJSON_PUBLIC(cJSON *) cJSON_CreateArrayReference(const cJSON *child);
+
+/* These utilities create an Array of count items.
+ * The parameter count cannot be greater than the number of elements in the number array, otherwise array access will be out of bounds.*/
+CJSON_PUBLIC(cJSON *) cJSON_CreateIntArray(const int *numbers, int count);
+CJSON_PUBLIC(cJSON *) cJSON_CreateFloatArray(const float *numbers, int count);
+CJSON_PUBLIC(cJSON *) cJSON_CreateDoubleArray(const double *numbers, int count);
+CJSON_PUBLIC(cJSON *) cJSON_CreateStringArray(const char *const *strings, int count);
+
+/* Append item to the specified array/object. */
+CJSON_PUBLIC(void) cJSON_AddItemToArray(cJSON *array, cJSON *item);
+CJSON_PUBLIC(void) cJSON_AddItemToObject(cJSON *object, const char *string, cJSON *item);
+/* Use this when string is definitely const (i.e. a literal, or as good as), and will definitely survive the cJSON object.
+ * WARNING: When this function was used, make sure to always check that (item->type & cJSON_StringIsConst) is zero before
+ * writing to `item->string` */
+CJSON_PUBLIC(void) cJSON_AddItemToObjectCS(cJSON *object, const char *string, cJSON *item);
+/* Append reference to item to the specified array/object. Use this when you want to add an existing cJSON to a new cJSON, but don't want to corrupt your existing cJSON. */
+CJSON_PUBLIC(void) cJSON_AddItemReferenceToArray(cJSON *array, cJSON *item);
+CJSON_PUBLIC(void) cJSON_AddItemReferenceToObject(cJSON *object, const char *string, cJSON *item);
+
+/* Remove/Detach items from Arrays/Objects. */
+CJSON_PUBLIC(cJSON *) cJSON_DetachItemViaPointer(cJSON *parent, cJSON * const item);
+CJSON_PUBLIC(cJSON *) cJSON_DetachItemFromArray(cJSON *array, int which);
+CJSON_PUBLIC(void) cJSON_DeleteItemFromArray(cJSON *array, int which);
+CJSON_PUBLIC(cJSON *) cJSON_DetachItemFromObject(cJSON *object, const char *string);
+CJSON_PUBLIC(cJSON *) cJSON_DetachItemFromObjectCaseSensitive(cJSON *object, const char *string);
+CJSON_PUBLIC(void) cJSON_DeleteItemFromObject(cJSON *object, const char *string);
+CJSON_PUBLIC(void) cJSON_DeleteItemFromObjectCaseSensitive(cJSON *object, const char *string);
+
+/* Update array items. */
+CJSON_PUBLIC(void) cJSON_InsertItemInArray(cJSON *array, int which, cJSON *newitem); /* Shifts pre-existing items to the right. */
+CJSON_PUBLIC(cJSON_bool) cJSON_ReplaceItemViaPointer(cJSON * const parent, cJSON * const item, cJSON * replacement);
+CJSON_PUBLIC(void) cJSON_ReplaceItemInArray(cJSON *array, int which, cJSON *newitem);
+CJSON_PUBLIC(void) cJSON_ReplaceItemInObject(cJSON *object,const char *string,cJSON *newitem);
+CJSON_PUBLIC(void) cJSON_ReplaceItemInObjectCaseSensitive(cJSON *object,const char *string,cJSON *newitem);
+
+/* Duplicate a cJSON item */
+CJSON_PUBLIC(cJSON *) cJSON_Duplicate(const cJSON *item, cJSON_bool recurse);
+/* Duplicate will create a new, identical cJSON item to the one you pass, in new memory that will
+ * need to be released. With recurse!=0, it will duplicate any children connected to the item.
+ * The item->next and ->prev pointers are always zero on return from Duplicate. */
+/* Recursively compare two cJSON items for equality. If either a or b is NULL or invalid, they will be considered unequal.
+ * case_sensitive determines if object keys are treated case sensitive (1) or case insensitive (0) */
+CJSON_PUBLIC(cJSON_bool) cJSON_Compare(const cJSON * const a, const cJSON * const b, const cJSON_bool case_sensitive);
+
+/* Minify a strings, remove blank characters(such as ' ', '\t', '\r', '\n') from strings.
+ * The input pointer json cannot point to a read-only address area, such as a string constant,
+ * but should point to a readable and writable adress area. */
+CJSON_PUBLIC(void) cJSON_Minify(char *json);
+
+/* Helper functions for creating and adding items to an object at the same time.
+ * They return the added item or NULL on failure. */
+CJSON_PUBLIC(cJSON*) cJSON_AddNullToObject(cJSON * const object, const char * const name);
+CJSON_PUBLIC(cJSON*) cJSON_AddTrueToObject(cJSON * const object, const char * const name);
+CJSON_PUBLIC(cJSON*) cJSON_AddFalseToObject(cJSON * const object, const char * const name);
+CJSON_PUBLIC(cJSON*) cJSON_AddBoolToObject(cJSON * const object, const char * const name, const cJSON_bool boolean);
+CJSON_PUBLIC(cJSON*) cJSON_AddNumberToObject(cJSON * const object, const char * const name, const double number);
+CJSON_PUBLIC(cJSON*) cJSON_AddStringToObject(cJSON * const object, const char * const name, const char * const string);
+CJSON_PUBLIC(cJSON*) cJSON_AddRawToObject(cJSON * const object, const char * const name, const char * const raw);
+CJSON_PUBLIC(cJSON*) cJSON_AddObjectToObject(cJSON * const object, const char * const name);
+CJSON_PUBLIC(cJSON*) cJSON_AddArrayToObject(cJSON * const object, const char * const name);
+
+/* When assigning an integer value, it needs to be propagated to valuedouble too. */
+#define cJSON_SetIntValue(object, number) ((object) ? (object)->valueint = (object)->valuedouble = (number) : (number))
+/* helper for the cJSON_SetNumberValue macro */
+CJSON_PUBLIC(double) cJSON_SetNumberHelper(cJSON *object, double number);
+#define cJSON_SetNumberValue(object, number) ((object != NULL) ? cJSON_SetNumberHelper(object, (double)number) : (number))
+
+/* Macro for iterating over an array or object */
+#define cJSON_ArrayForEach(element, array) for(element = (array != NULL) ? (array)->child : NULL; element != NULL; element = element->next)
+
+/* malloc/free objects using the malloc/free functions that have been set with cJSON_InitHooks */
+CJSON_PUBLIC(void *) cJSON_malloc(size_t size);
+CJSON_PUBLIC(void) cJSON_free(void *object);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
-#ifndef __MG_DEVICE_H__
-#define __MG_DEVICE_H__
+#ifndef __RFJB_DEVICE_H__
+#define __RFJB_DEVICE_H__
#include <stdint.h>
#include <time.h>
+#include <pthread.h>
-#include "iot.h"
-#include "mg_log.h"
-#include "mg_version.h"
-#include "led.h"
-#include "button.h"
+//#include "rfjb_iot.h"
+//#include "rfjb_log.h"
+//#include "rfjb_version.h"
+//#include "rfjb_led.h"
+//#include "rfjb_button.h"
#include "cQueue.h"
#include "cJSON.h"
#ifdef __x86_64__
//#warning "PC Version Debug"
-
-#define IOT_KEY_PATH "/customer/tuya_auth"
-#define DEV_CFG_PATH "dev.cfg"
-#define MG_AUTH_PATH "mg_auth"
-#define TUYA_BIND_PATH "tuya.bind"
-#define WIFI_CONFIG_PATH "wifi.cfg"
-#define MG_ACTIVE_PATH "mg.active"
-#define READ_UUID_CMD "cat cpuinfo | grep Serial"
-#define ALS_CFG_PATH "als.cfg"
-#define TOF_CFG_PATH "tof.cfg"
-#define LIGHT_CFG_PATH "light.cfg"
-
-#else
-
-#define IOT_KEY_PATH "/customer/tuya_auth"
-#define DEV_CFG_PATH "/appconfigs/dev.cfg"
-#define ALS_CFG_PATH "/appconfigs/als.cfg"
-#define TOF_CFG_PATH "/appconfigs/tof.cfg"
-
-#define MG_AUTH_PATH "/customer/mg_auth"
-#define TUYA_BINDCODE_PATH "/customer/tuya_bindcode"
-
-#define TUYA_BIND_PATH "/appconfigs/tuya.bind"
-#define WIFI_CONFIG_PATH "/appconfigs/wifi.cfg"
-#define MG_ACTIVE_PATH "/customer/mg.active"
-
-#define HW_VER_PATH "/customer/hw_version"
-#define BLE_ADV_CFG_PATH "/appconfigs/ble_adv.cfg"
-#define LIGHT_CFG_PATH "/appconfigs/light.cfg"
-
-#define READ_UUID_CMD "cat /proc/cpuinfo | grep Serial"
-
#endif
-#define NETCONFIG_TIMEOUT_SEC (2*60) //配网超时2分钟
-#define CLEANMODE_TIMEOUT_SEC (30) //清洁模式超时30秒
-
-//环境光传感器默认阈值
-#define ALS_THRESHOLD_HIGH_DEFAULT 1000
-#define ALS_THRESHOLD_LOW_DEFAULT 400
-
-//人感检测无人判断定时器周期,单位秒
-#define TOF_NOBODY_TIMER_SECS_DEFAULT 1 //默认1秒
-
-
-#define KEY_LED_MAX_DEF 100 //(0-100%)
-#define ATMOS_LED_MAX_DEF 100 //(0-100%)
-//#define RECOGNITION_MODE_DEF 0 //enum 0:"light_mode", 1:"dark_mode"
-#define RECOGNITION_LEVEL_DEF 6 //1--10
-#define RECOGNITION_DURATION_DEF 300 //5--1000 seconds
-#define LED_ATMOS_ON_DURATION_DEF 5 //1--20 seconds
-#define LED_TOF_THRESHOLD_DEF 150 //10--150 cm
-#define MG_TOF_INTERVAL_DEF 10 //10-20
-#define MG_DISALBE_ROW_DEF 0 //bool
-#define MG_KEY_ENABLE_DEF 0x1ff //bit0-8 -> btn1 - 9
-#define BL_MODE_DEF 0 //enum 0:"auto", 1"manual"
-//#define MG_TOF_STATUS_DEF 0 //bool
-#define MG_TOF_SYNC_DEF 0 //bool
-#define LED_ATMOS_OFF_DURATION_DEF 5 //1-20
-
+#define DEV_CFG_PATH "appconfigs/dev.cfg"
+#define FACTORY_CFG_PATH "appconfigs/factory.cfg"
+#define READ_UUID_CMD "cat /proc/cpuinfo | grep Serial"
-typedef enum{
- DS_INIT = 0,
- DS_NO_AUTH, //未授权:控制所有按键背光连续慢闪,装饰灯带常灭;不加载涂鸦 SDK应用程序轮询授权是否已写入,并校验写入长度符合要求;
- DS_AUTH_NO_WIFICONFIG, //已授权未配网:所有灯光常灭;
- DS_AUTH_WIFICONFIGING, //配网过程中 LED7 & LED8 连续慢闪, 2分钟超时后退出
- DS_AUTH_WIFICONFIG_NO_ACTIVE, //已授权已配网未激活:所有灯光常灭;
- DS_ACTIVE, //已授权已配网已激活:进入主流程,灯光根据 DP 设置处理。
- DS_INVALID
-}dev_st_t;
typedef struct{
-//dp info
- //key1 -- key8 //event
- uint32_t key_led_max;
- uint32_t atmos_led_max;
- //recognition_running bool ro
- //gesture_event event ro
- uint32_t recognition_mode; //手势识别补光
- uint32_t recognition_level; //手势识别灵敏度
- uint32_t recognition_duration; //手势识别关闭延时
- uint32_t privacy_mode; //true, 关闭手势识别功能
- //485_cmd; //action
- //active ro;
- uint32_t key;
- uint32_t mg_tof_threshold; //人感检测距离
- uint32_t mg_tof_interval; //人感检测周期
- uint32_t mg_disable_row; //关闭联排功能
- uint32_t mg_key_enable; //按键禁使能, 默认FF, 一个字节, bit0 是第一个按键, bit7是第八个按键
- uint32_t bl_mode; //背光模式 默认"自动", 自动模式: 氛围灯亮, 背光灭, 有人后反转. 手动模式: 氛围灯可调, 背光亮度可调, 两者无关联
- uint32_t mg_tof_status; //人感状态
- uint32_t mg_tof_sync; //人感状态同步, mg_disable_row 为false时,平台下发sync值, 人感状态由sync和本地传感器信号任意一个触发。
- uint32_t led_atmos_on_duration;//氛围灯打开时间
- uint32_t led_atmos_off_duration;//氛围灯关闭时间, 数值范围: 1-20, 间距: 1, 倍数: 0, 单位: 秒 默认5秒
-//
-}dev_cfg_t;
+ char serial[32];
+ char hw_version[32];
+}factory_cfg_t;
typedef struct{
- dev_st_t st;
- dev_cfg_t cfg;
-
- uint32_t iot_connect;
- uint32_t tof_somebody; //人感状态, 1: 有人,0:无人/障碍
- uint32_t tof_sync; //人感状态同步
-
- uint32_t mg_active; //moorgen 激活标志
- uint32_t mg_wificonfig; //wificonfig 标志
- uint32_t mg_tuyabind; //涂鸦绑定标志
-
- uint32_t auth; //auth
- char *auth_key_id;
- char *auth_key_value;
- char *uuid;
- //pthread_mutex_t lock;
-
- uint32_t clean_device;
- uint32_t clean_start_time; //clean 开始时间
-
- uint32_t netconfig; //wifi 配网 + tuya bind
- time_t netconfig_start_time; //配网开始时间
-
- uint32_t bl_manual;
-
- uint32_t mg_tof_status;
- pthread_mutex_t lock;
-
- //
- btn_ctrl_t btn;
- light_ctrl_t light;
-
-}mg_dev_t;
-
-
-//灯光模式
-typedef enum{
- //开机初始状态,所有灯常灭
- LIGHT_MODE_INIT = 0,
-
- //未授权:控制所有按键背光连续慢闪,装饰灯带常灭;不加载涂鸦 SDK应用程序轮询授权是否已写入,并校验写入长度符合要求;
- LIGHT_MODE_NO_AUTH,
-
- //已授权未配网:所有灯光常灭;
- LIGHT_MODE_AUTH_NO_WIFICONFIG,
-
- //配网过程中 LED7 & LED8 连续慢闪, 2分钟超时后退出
- LIGHT_MODE_AUTH_WIFICONFIGING,
-
- //已授权已配网未激活:所有灯光常灭;
- LIGHT_MODE_AUTH_WIFICONFIG_NO_ACTIVE,
-
- //已授权已配网已激活:进入主流程,灯光根据 DP 设置处理。
- LIGHT_MODE_ACTIVE,
-
-//单个按键触发,按键对应背光快闪 1s,并上报按键触发类型⾄相应 DP;
-//按 5s KEY7 + KEY8,进入配网模式,LED7 & LED8 连续慢闪;
-//按 2s KEY1 + KEY8,进入清洁模式,所有 LED 连续慢闪;
-//按 2s KEY7 + KEY2,退出清洁模式,所有 LED 恢复正常状态。
- LIGHT_MODE_CLEAN,
- LIGHT_MODE_TOF_ACTIVE,
- LIGHT_MODE_TOF_DEACTIVE,
-
-}light_mode_t;
+ char addr[128];
+ uint16_t port;
+}iot_cfg_t;
typedef struct{
- uint32_t increase_ms;
- uint32_t decrease_ms;
- uint32_t apnea_ms;
-} breath_cfg_t;
+ uint32_t addr;
+ uint32_t gw;
+ uint32_t srv;
+}lora_cfg_t;
+
typedef struct{
- uint8_t br[101]; //0--100亮度值
- breath_cfg_t breath;
-}light_cfg_t;
+ uint32_t addr;
+ uint32_t srv;
+}bd_cfg_t;
-void light_mode_set( mg_dev_t *dev, light_mode_t mode );
-//void light_brightness_set( led_id_t id, uint32_t br );
+typedef struct{
+ iot_cfg_t iot; //iot: srv_addr,srv_port
+ lora_cfg_t lora; //lora: local_addr, gw_addr, srv_addr
+ bd_cfg_t bd; //bd: local_addr, srv_addr
+}dev_cfg_t;
-void device_wifi_init( void );
-void device_wiwi_start( void );
+typedef struct{
+ factory_cfg_t factory_cfg;
+ dev_cfg_t cfg;
+ char* uuid;
+ pthread_mutex_t lock;
+}rfjb_dev_t;
-int32_t load_device_cfg( dev_cfg_t *cfg );
int32_t store_device_cfg( dev_cfg_t *cfg );
int32_t load_device_cfg( dev_cfg_t *cfg );
-int32_t load_auth_key( mg_dev_t *dev );
+int32_t store_factory_cfg( factory_cfg_t *cfg );
+int32_t load_factory_cfg( factory_cfg_t *cfg );
-int32_t is_device_active( mg_dev_t *dev );
-int32_t mg_device_active( mg_dev_t *dev );
-
-int32_t mg_device_run_st_init( mg_dev_t *dev );
//----------------------------------------------------------------------------
//cfg info
-int32_t cfg_key_led_max_read( mg_dev_t *dev );
-int32_t cfg_key_led_max_write( mg_dev_t *dev, int32_t br );
-
-int32_t cfg_atmos_led_max_read( mg_dev_t *dev );
-int32_t cfg_atmos_led_max_write( mg_dev_t *dev, int32_t br );
-
-int32_t cfg_recognition_level_read( mg_dev_t *dev );
-int32_t cfg_recognition_level_write( mg_dev_t *dev, int32_t level );
-
-int32_t cfg_recognition_duration_read( mg_dev_t *dev );
-int32_t cfg_recognition_duration_write( mg_dev_t *dev, int32_t dur_sec );
-
-int32_t cfg_privacy_mode_read( mg_dev_t *dev);
-int32_t cfg_privacy_mode_write( mg_dev_t *dev, int32_t mode );
-
-int32_t cfg_mg_tof_threshold_read( mg_dev_t *dev );
-int32_t cfg_mg_tof_threshold_write( mg_dev_t *dev, int32_t threshold_cm );
-
-int32_t cfg_mg_tof_interval_read( mg_dev_t *dev );
-int32_t cfg_mg_tof_interval_write( mg_dev_t *dev, int32_t interval_sec);
-
-int32_t cfg_mg_disable_row_read( mg_dev_t *dev );
-int32_t cfg_mg_disable_row_write( mg_dev_t *dev, int32_t disable );
-
-int32_t cfg_mg_key_enable_read( mg_dev_t *dev );
-int32_t cfg_mg_key_enable_write( mg_dev_t *dev, int32_t en_mask );
-
-int32_t cfg_bl_mode_read( mg_dev_t *dev );
-int32_t cfg_bl_mode_write( mg_dev_t *dev, int32_t mode ); //0:auto, 1-manual
-
-int32_t cfg_led_atmos_on_duration_read( mg_dev_t *dev );
-int32_t cfg_led_atmos_on_duration_write( mg_dev_t *dev, int32_t dur_sec );
-
-int32_t cfg_led_atmos_off_duration_read( mg_dev_t *dev );
-int32_t cfg_led_atmos_off_duration_write( mg_dev_t *dev, int32_t dur_sec );
-
-int32_t cfg_mg_tof_sync_read( mg_dev_t *dev);
-int32_t cfg_mg_tof_sync_write( mg_dev_t *dev, int32_t sync );
-
-//dp
-typedef enum{
- GS_GUN,
- GS_LITTLE_FINGER,
- GS_HORNED_HAND,
- GS_ILOVEYOU,
- GS_FOUR_FINGERS,
- GS_THREE_FINGERS,
- GS_WELL_PLAYED,
- GS_FINGERTIP,
- GS_FINGER_HEART,
- GS_ROCK,
- GS_PAPER,
- GS_THUMBS_UP,
- GS_SCISSORS,
- GS_OK,
- GS_NR
-}gesture_ev_t;
-
+int32_t cfg_key_led_max_read( rfjb_dev_t *dev );
+int32_t cfg_key_led_max_write( rfjb_dev_t *dev, int32_t br );
//-------------------------------------------------------------------------------------
-//mg_dev
-void mg_dev_lock( mg_dev_t *dev );
-void mg_dev_unlock( mg_dev_t *dev );
-mg_dev_t * mg_dev_get( void );
-
-//-------------------------------------------------------------------------------------
-//
-void btn_light_ctrl_init( mg_dev_t *dev );
-void btn_light_ctrl_start( mg_dev_t *dev );
+//rfjb_dev
+void rfjb_dev_lock( rfjb_dev_t *dev );
+void rfjb_dev_unlock( rfjb_dev_t *dev );
+rfjb_dev_t * rfjb_dev_get( void );
//-------------------------------------------------------------------------------------
//button
typedef struct{
- uint32_t code;
- uint32_t ev;
- uint32_t value;
+ uint32_t code;
+ uint32_t ev;
+ uint32_t value;
}btn_msg_t;
-void device_button_init( mg_dev_t *dev );
+void device_button_init( rfjb_dev_t *dev );
uint32_t get_single_click_code( btn_msg_t *msg );
uint32_t get_double_click_code( btn_msg_t *msg );
uint32_t get_long_press_code( btn_msg_t *msg );
int32_t wifi_config_store( char *ssid, char *passwd );
int32_t wifi_config_load( char *ssid, uint32_t ssid_max_len, char *passwd, uint32_t passwd_max_len );
-//-------------------------------------------------------------------------------------
-//light
-void device_light_init( mg_dev_t *dev );
-void led_flash_for_btn_single_click( mg_dev_t *dev, button_code_t btn_code );
-void light_set_key_br( mg_dev_t *dev, uint32_t id, uint32_t br );
-void light_set_atmos_br( mg_dev_t *dev, uint32_t id, uint32_t br );
-int32_t load_light_cfg( light_cfg_t * cfg );
-
-//-------------------------------------------------------------------------------------
-//net config
-int32_t netconfig_start( mg_dev_t *dev );
-int32_t netconfig_stop( mg_dev_t *dev );
-void device_netconfig_task_start( mg_dev_t *dev );
-
-//-------------------------------------------------------------------------------------
-//gesture
-int32_t gesture_recognition_start( mg_dev_t *dev );
-
-//-------------------------------------------------------------------------------------
-//涂鸦用户绑定设备标志
-int32_t is_tuya_bind( mg_dev_t *dev );
-//wifi配网标志
-int32_t is_wifi_config( mg_dev_t *dev );
-//检查是否已经配网,需要wifi配网而且设备绑定
-int32_t is_tuya_config( mg_dev_t *dev );
-
-//-------------------------------------------------------------------------------------
-int32_t tuya_bindcode_read( char * code, int32_t max_sz );
-int32_t fw_version_read( char * ver, int32_t max_sz );
-int32_t hw_version_read( char * ver, int32_t max_sz );
-int32_t tuya_productid_read( char * ver, int32_t max_sz );
-
-//-------------------------------------------------------------------------------------
-//ble广播配置文件
-char *load_ble_adv_local_name( void );
-
extern time_t device_uptime_sec( void );
extern time_t device_uptime_msec( void );
-#endif //__MG_DEVICE_H__
+#endif //__RFJB_DEVICE_H__
+
+//分区/目录
+////factory info
+// /config/dev
+// device_sn
+//
+// /config/iot
+// platform srv:port
+// lora id gw srv
+// bd id srv
+// camera enabled/disabled
+// dev_type: client lora-gw srv
+// controller_monitor: 0:control 1:monitor
+//
+// TODO: 串口作为RTU 从机,接受设置参数 和 监视器通信
+// 监视器按1秒发查询指令 读取状态, 配置指令修改参数
+// 定义监视器和控制器的协议按modbus寄存器方式
+//
+++ /dev/null
-#ifndef __MG_DEVICE_H__
-#define __MG_DEVICE_H__
-
-#include <stdint.h>
-#include <time.h>
-
-#include "iot.h"
-#include "mg_log.h"
-#include "mg_version.h"
-#include "led.h"
-#include "button.h"
-#include "cQueue.h"
-#include "cJSON.h"
-
-#ifdef __x86_64__
-//#warning "PC Version Debug"
-
-#define IOT_KEY_PATH "/customer/tuya_auth"
-#define DEV_CFG_PATH "dev.cfg"
-#define MG_AUTH_PATH "mg_auth"
-#define TUYA_BIND_PATH "tuya.bind"
-#define WIFI_CONFIG_PATH "wifi.cfg"
-#define MG_ACTIVE_PATH "mg.active"
-#define READ_UUID_CMD "cat cpuinfo | grep Serial"
-#define ALS_CFG_PATH "als.cfg"
-#define TOF_CFG_PATH "tof.cfg"
-#define LIGHT_CFG_PATH "light.cfg"
-
-#else
-
-#define IOT_KEY_PATH "/customer/tuya_auth"
-#define DEV_CFG_PATH "/appconfigs/dev.cfg"
-#define ALS_CFG_PATH "/appconfigs/als.cfg"
-#define TOF_CFG_PATH "/appconfigs/tof.cfg"
-
-#define MG_AUTH_PATH "/customer/mg_auth"
-#define TUYA_BINDCODE_PATH "/customer/tuya_bindcode"
-
-#define TUYA_BIND_PATH "/appconfigs/tuya.bind"
-#define WIFI_CONFIG_PATH "/appconfigs/wifi.cfg"
-#define MG_ACTIVE_PATH "/customer/mg.active"
-
-#define HW_VER_PATH "/customer/hw_version"
-#define BLE_ADV_CFG_PATH "/appconfigs/ble_adv.cfg"
-#define LIGHT_CFG_PATH "/appconfigs/light.cfg"
-
-#define READ_UUID_CMD "cat /proc/cpuinfo | grep Serial"
-
-#endif
-
-#define NETCONFIG_TIMEOUT_SEC (2*60) //配网超时2分钟
-#define CLEANMODE_TIMEOUT_SEC (30) //清洁模式超时30秒
-
-//环境光传感器默认阈值
-#define ALS_THRESHOLD_HIGH_DEFAULT 1000
-#define ALS_THRESHOLD_LOW_DEFAULT 400
-
-//人感检测无人判断定时器周期,单位秒
-#define TOF_NOBODY_TIMER_SECS_DEFAULT 1 //默认1秒
-
-
-#define KEY_LED_MAX_DEF 100 //(0-100%)
-#define ATMOS_LED_MAX_DEF 100 //(0-100%)
-//#define RECOGNITION_MODE_DEF 0 //enum 0:"light_mode", 1:"dark_mode"
-#define RECOGNITION_LEVEL_DEF 6 //1--10
-#define RECOGNITION_DURATION_DEF 300 //5--1000 seconds
-#define LED_ATMOS_ON_DURATION_DEF 5 //1--20 seconds
-#define LED_TOF_THRESHOLD_DEF 150 //10--150 cm
-#define MG_TOF_INTERVAL_DEF 10 //10-20
-#define MG_DISALBE_ROW_DEF 0 //bool
-#define MG_KEY_ENABLE_DEF 0x1ff //bit0-8 -> btn1 - 9
-#define BL_MODE_DEF 0 //enum 0:"auto", 1"manual"
-//#define MG_TOF_STATUS_DEF 0 //bool
-#define MG_TOF_SYNC_DEF 0 //bool
-#define LED_ATMOS_OFF_DURATION_DEF 5 //1-20
-
-
-typedef enum{
- DS_INIT = 0,
- DS_NO_AUTH, //未授权:控制所有按键背光连续慢闪,装饰灯带常灭;不加载涂鸦 SDK应用程序轮询授权是否已写入,并校验写入长度符合要求;
- DS_AUTH_NO_WIFICONFIG, //已授权未配网:所有灯光常灭;
- DS_AUTH_WIFICONFIGING, //配网过程中 LED7 & LED8 连续慢闪, 2分钟超时后退出
- DS_AUTH_WIFICONFIG_NO_ACTIVE, //已授权已配网未激活:所有灯光常灭;
- DS_ACTIVE, //已授权已配网已激活:进入主流程,灯光根据 DP 设置处理。
- DS_INVALID
-}dev_st_t;
-
-typedef struct{
-//dp info
- //key1 -- key8 //event
- uint32_t key_led_max;
- uint32_t atmos_led_max;
- //recognition_running bool ro
- //gesture_event event ro
- uint32_t recognition_mode; //手势识别补光
- uint32_t recognition_level; //手势识别灵敏度
- uint32_t recognition_duration; //手势识别关闭延时
- uint32_t privacy_mode; //true, 关闭手势识别功能
- //485_cmd; //action
- //active ro;
- uint32_t key;
- uint32_t mg_tof_threshold; //人感检测距离
- uint32_t mg_tof_interval; //人感检测周期
- uint32_t mg_disable_row; //关闭联排功能
- uint32_t mg_key_enable; //按键禁使能, 默认FF, 一个字节, bit0 是第一个按键, bit7是第八个按键
- uint32_t bl_mode; //背光模式 默认"自动", 自动模式: 氛围灯亮, 背光灭, 有人后反转. 手动模式: 氛围灯可调, 背光亮度可调, 两者无关联
- uint32_t mg_tof_status; //人感状态
- uint32_t mg_tof_sync; //人感状态同步, mg_disable_row 为false时,平台下发sync值, 人感状态由sync和本地传感器信号任意一个触发。
- uint32_t led_atmos_on_duration;//氛围灯打开时间
- uint32_t led_atmos_off_duration;//氛围灯关闭时间, 数值范围: 1-20, 间距: 1, 倍数: 0, 单位: 秒 默认5秒
-//
-}dev_cfg_t;
-
-typedef struct{
- dev_st_t st;
- dev_cfg_t cfg;
-
- uint32_t iot_connect;
- uint32_t tof_somebody; //人感状态, 1: 有人,0:无人/障碍
- uint32_t tof_sync; //人感状态同步
-
- uint32_t mg_active; //moorgen 激活标志
- uint32_t mg_wificonfig; //wificonfig 标志
- uint32_t mg_tuyabind; //涂鸦绑定标志
-
- uint32_t auth; //auth
- char *auth_key_id;
- char *auth_key_value;
- char *uuid;
- //pthread_mutex_t lock;
-
- uint32_t clean_device;
- uint32_t clean_start_time; //clean 开始时间
-
- uint32_t netconfig; //wifi 配网 + tuya bind
- time_t netconfig_start_time; //配网开始时间
-
- uint32_t bl_manual;
-
- uint32_t mg_tof_status;
- pthread_mutex_t lock;
-
- //
- btn_ctrl_t btn;
- light_ctrl_t light;
-
-}mg_dev_t;
-
-
-//灯光模式
-typedef enum{
- //开机初始状态,所有灯常灭
- LIGHT_MODE_INIT = 0,
-
- //未授权:控制所有按键背光连续慢闪,装饰灯带常灭;不加载涂鸦 SDK应用程序轮询授权是否已写入,并校验写入长度符合要求;
- LIGHT_MODE_NO_AUTH,
-
- //已授权未配网:所有灯光常灭;
- LIGHT_MODE_AUTH_NO_WIFICONFIG,
-
- //配网过程中 LED7 & LED8 连续慢闪, 2分钟超时后退出
- LIGHT_MODE_AUTH_WIFICONFIGING,
-
- //已授权已配网未激活:所有灯光常灭;
- LIGHT_MODE_AUTH_WIFICONFIG_NO_ACTIVE,
-
- //已授权已配网已激活:进入主流程,灯光根据 DP 设置处理。
- LIGHT_MODE_ACTIVE,
-
-//单个按键触发,按键对应背光快闪 1s,并上报按键触发类型⾄相应 DP;
-//按 5s KEY7 + KEY8,进入配网模式,LED7 & LED8 连续慢闪;
-//按 2s KEY1 + KEY8,进入清洁模式,所有 LED 连续慢闪;
-//按 2s KEY7 + KEY2,退出清洁模式,所有 LED 恢复正常状态。
- LIGHT_MODE_CLEAN,
- LIGHT_MODE_TOF_ACTIVE,
- LIGHT_MODE_TOF_DEACTIVE,
-
-}light_mode_t;
-
-typedef struct{
- uint32_t increase_ms;
- uint32_t decrease_ms;
- uint32_t apnea_ms;
-} breath_cfg_t;
-typedef struct{
- uint8_t br[101]; //0--100亮度值
- breath_cfg_t breath;
-}light_cfg_t;
-
-void light_mode_set( mg_dev_t *dev, light_mode_t mode );
-//void light_brightness_set( led_id_t id, uint32_t br );
-
-void device_wifi_init( void );
-void device_wiwi_start( void );
-
-
-int32_t load_device_cfg( dev_cfg_t *cfg );
-int32_t store_device_cfg( dev_cfg_t *cfg );
-int32_t load_device_cfg( dev_cfg_t *cfg );
-
-int32_t load_auth_key( mg_dev_t *dev );
-
-int32_t is_device_active( mg_dev_t *dev );
-int32_t mg_device_active( mg_dev_t *dev );
-
-int32_t mg_device_run_st_init( mg_dev_t *dev );
-
-//----------------------------------------------------------------------------
-//cfg info
-
-int32_t cfg_key_led_max_read( mg_dev_t *dev );
-int32_t cfg_key_led_max_write( mg_dev_t *dev, int32_t br );
-
-int32_t cfg_atmos_led_max_read( mg_dev_t *dev );
-int32_t cfg_atmos_led_max_write( mg_dev_t *dev, int32_t br );
-
-int32_t cfg_recognition_level_read( mg_dev_t *dev );
-int32_t cfg_recognition_level_write( mg_dev_t *dev, int32_t level );
-
-int32_t cfg_recognition_duration_read( mg_dev_t *dev );
-int32_t cfg_recognition_duration_write( mg_dev_t *dev, int32_t dur_sec );
-
-int32_t cfg_privacy_mode_read( mg_dev_t *dev);
-int32_t cfg_privacy_mode_write( mg_dev_t *dev, int32_t mode );
-
-int32_t cfg_mg_tof_threshold_read( mg_dev_t *dev );
-int32_t cfg_mg_tof_threshold_write( mg_dev_t *dev, int32_t threshold_cm );
-
-int32_t cfg_mg_tof_interval_read( mg_dev_t *dev );
-int32_t cfg_mg_tof_interval_write( mg_dev_t *dev, int32_t interval_sec);
-
-int32_t cfg_mg_disable_row_read( mg_dev_t *dev );
-int32_t cfg_mg_disable_row_write( mg_dev_t *dev, int32_t disable );
-
-int32_t cfg_mg_key_enable_read( mg_dev_t *dev );
-int32_t cfg_mg_key_enable_write( mg_dev_t *dev, int32_t en_mask );
-
-int32_t cfg_bl_mode_read( mg_dev_t *dev );
-int32_t cfg_bl_mode_write( mg_dev_t *dev, int32_t mode ); //0:auto, 1-manual
-
-int32_t cfg_led_atmos_on_duration_read( mg_dev_t *dev );
-int32_t cfg_led_atmos_on_duration_write( mg_dev_t *dev, int32_t dur_sec );
-
-int32_t cfg_led_atmos_off_duration_read( mg_dev_t *dev );
-int32_t cfg_led_atmos_off_duration_write( mg_dev_t *dev, int32_t dur_sec );
-
-int32_t cfg_mg_tof_sync_read( mg_dev_t *dev);
-int32_t cfg_mg_tof_sync_write( mg_dev_t *dev, int32_t sync );
-
-//dp
-typedef enum{
- GS_GUN,
- GS_LITTLE_FINGER,
- GS_HORNED_HAND,
- GS_ILOVEYOU,
- GS_FOUR_FINGERS,
- GS_THREE_FINGERS,
- GS_WELL_PLAYED,
- GS_FINGERTIP,
- GS_FINGER_HEART,
- GS_ROCK,
- GS_PAPER,
- GS_THUMBS_UP,
- GS_SCISSORS,
- GS_OK,
- GS_NR
-}gesture_ev_t;
-
-
-//-------------------------------------------------------------------------------------
-//mg_dev
-void mg_dev_lock( mg_dev_t *dev );
-void mg_dev_unlock( mg_dev_t *dev );
-mg_dev_t * mg_dev_get( void );
-
-//-------------------------------------------------------------------------------------
-//
-void btn_light_ctrl_init( mg_dev_t *dev );
-void btn_light_ctrl_start( mg_dev_t *dev );
-
-//-------------------------------------------------------------------------------------
-//button
-typedef struct{
- uint32_t code;
- uint32_t ev;
- uint32_t value;
-}btn_msg_t;
-
-void device_button_init( mg_dev_t *dev );
-uint32_t get_single_click_code( btn_msg_t *msg );
-uint32_t get_double_click_code( btn_msg_t *msg );
-uint32_t get_long_press_code( btn_msg_t *msg );
-uint32_t get_long_press_up_code( btn_msg_t *msg );
-int32_t is_btn_device_clean_exit( btn_msg_t *msg );
-int32_t is_btn_device_clean( btn_msg_t *msg );
-int32_t is_btn_netconfig( btn_msg_t *msg );
-int32_t btn_msg_rx( btn_msg_t *msg );
-
-//-------------------------------------------------------------------------------------
-//nv
-int32_t wifi_config_store( char *ssid, char *passwd );
-int32_t wifi_config_load( char *ssid, uint32_t ssid_max_len, char *passwd, uint32_t passwd_max_len );
-
-//-------------------------------------------------------------------------------------
-//light
-void device_light_init( mg_dev_t *dev );
-void led_flash_for_btn_single_click( mg_dev_t *dev, button_code_t btn_code );
-void light_set_key_br( mg_dev_t *dev, uint32_t id, uint32_t br );
-void light_set_atmos_br( mg_dev_t *dev, uint32_t id, uint32_t br );
-int32_t load_light_cfg( light_cfg_t * cfg );
-
-//-------------------------------------------------------------------------------------
-//net config
-int32_t netconfig_start( mg_dev_t *dev );
-int32_t netconfig_stop( mg_dev_t *dev );
-void device_netconfig_task_start( mg_dev_t *dev );
-
-//-------------------------------------------------------------------------------------
-//gesture
-int32_t gesture_recognition_start( mg_dev_t *dev );
-
-//-------------------------------------------------------------------------------------
-//涂鸦用户绑定设备标志
-int32_t is_tuya_bind( mg_dev_t *dev );
-//wifi配网标志
-int32_t is_wifi_config( mg_dev_t *dev );
-//检查是否已经配网,需要wifi配网而且设备绑定
-int32_t is_tuya_config( mg_dev_t *dev );
-
-//-------------------------------------------------------------------------------------
-int32_t tuya_bindcode_read( char * code, int32_t max_sz );
-int32_t fw_version_read( char * ver, int32_t max_sz );
-int32_t hw_version_read( char * ver, int32_t max_sz );
-int32_t tuya_productid_read( char * ver, int32_t max_sz );
-
-//-------------------------------------------------------------------------------------
-//ble广播配置文件
-char *load_ble_adv_local_name( void );
-
-extern time_t device_uptime_sec( void );
-extern time_t device_uptime_msec( void );
-#endif //__MG_DEVICE_H__
-
+++ /dev/null
-#ifndef __MG_IOT_H__
-#define __MG_IOT_H__
-
-#include <stdio.h>
-#include <stdint.h>
-#include <string.h>
-#include <stdlib.h>
-
-#include "cJSON.h"
-//#include "tuya_log.h"
-//#include "tuya_error_code.h"
-//#include "system_interface.h"
-//#include "mqtt_client_interface.h"
-//#include "tuyalink_core.h"
-
-typedef enum {
- DP_BUTTON_1 = 101, //101 按键1 事件 button_1
- DP_BUTTON_2 = 102, //102 按键2 事件 button_2
- DP_BUTTON_3 = 103, //103 按键3 事件 button_3
- DP_BUTTON_4 = 104, //104 按键4 事件 button_4
- DP_BUTTON_5 = 105, //105 按键5 事件 button_5
- DP_BUTTON_6 = 106, //106 按键6 事件 button_6
- DP_BUTTON_7 = 107, //107 按键7 事件 button_7
- DP_BUTTON_8 = 108, //108 按键8 事件 button_8
- DP_KEY_LED_MAX = 109,
- DP_ATMOS_LED_MAX = 110,
- DP_RECONGNITION_RUNNING = 111,
- DP_GESTURE_EVENT = 112,
- DP_RECOGNITION_MODE = 113,
- DP_RECOGNITION_LEVEL = 114,
- DP_RECOGNITION_DURATION = 115,
- DP_PRIVACY_MODE = 116,
- DP_485_CMD = 117,
- DP_ACTIVE = 120,
- DP_KEY = 121,
- DP_LED_ATMOS_ON_DURATION = 151,
- DP_MG_TOF_THRESHOLD = 152,
- DP_MG_TOF_INTERVAL = 153,
- DP_MG_DISABLE_ROW = 154,
- DP_MG_KEY_ENABLE = 155,
- DP_BL_MODE = 156,
- DP_MG_TOF_STATUS = 157,
- DP_MG_TOF_SYNC = 158,
- DP_LED_ATMOS_OFF_DURATION = 159,
-}dp_button_code_t;
-
-#if XXX
-
-typedef struct{
- uint32_t id;
- char name[32];
- uint32_t value_type; //0:int, 1:string
- uint32_t value_int;
- char* value_str;
- uint32_t ver;
-}point_t;
-
-typedef struct{
- //point_t button[8];
- //109 按键背光最大亮度 属性 key_led_max 数值型(Value) 可下发可上报(rw) 数值范围: 0-100, 间距: 1, 倍数: 0, 单位: % 默认100%
- point_t key_led_max;
- //110 氛围灯最大亮度 属性 atmos_led_max 数值型(Value) 可下发可上报(rw) 数值范围: 0-100, 间距: 1, 倍数: 0, 单位: % 默认100%
- point_t atmos_led_max;
- //111 手势开关状态 属性 recognition_running 布尔型(Bool) 只上报(ro)
- point_t recognition_running;
- //112 触发手势 事件 gesture_event - - -
- point_t gesture_event;
- //113 手势识别补光 属性 recognition_mode 枚举型(Enum) 可下发可上报(rw) 枚举值: light_mode, dark_mode 环境光亮模式, 环境光暗模式 编辑 删除
- point_t recognition_mode;
- //114 手势识别灵敏度 属性 recognition_level 数值型(Value) 可下发可上报(rw) 数值范围: 1-10, 间距: 1, 倍数: 0, 单位: 默认6, 1档最不灵敏, 10档最灵敏
- point_t recognition_level;
- //115 手势识别关闭延时 属性 recognition_duration 数值型(Value) 可下发可上报(rw) 数值范围: 5-1000, 间距: 1, 倍数: 0, 单位: 秒 默认300, 5分钟
- point_t recognition_duration;
- //116 隐私模式 属性 privacy_mode 布尔型(Bool) 只上报(ro) - 打开时关闭摄像头, 关闭手势识别功能, 但按键依然有效
- point_t privacy_mode;
- //117 485指令 动作 485_cmd - - -
- point_t _485_cmd;
- //120 active 属性 active 布尔型(Bool) 只上报(ro) -
- point_t active;
- //121 key 属性 key 字符型(String) 可下发可上报(rw) -
- point_t key;
- //151 氛围灯打开时间 属性 led_atmos_on_duration 数值型(Value) 可下发可上报(rw) 数值范围: 1-20, 间距: 1, 倍数: 0, 单位: 秒 默认5秒
- point_t led_atmos_on_duration;
- //152 人感检测距离 属性 mg_tof_threshold 数值型(Value) 可下发可上报(rw) 数值范围: 10-150, 间距: 1, 倍数: 0, 单位: 厘米 默认150
- point_t mg_tof_threshold;
- //153 人感检测周期 属性 mg_tof_interval 数值型(Value) 可下发可上报(rw) 数值范围: 10-20, 间距: 1, 倍数: 0, 单位: 秒 默认10秒
- point_t mg_tof_interval;
- //154 关闭联排功能 属性 mg_disalbe_row 布尔型(Bool) 可下发可上报(rw) -
- point_t mg_disalbe_row;
- //155 按键禁使能 属性 mg_key_enable 透传型(Raw) 可下发可上报(rw) - 默认FF, 一个字节, bit0 是第一个按键, bit7是第八个按键
- point_t mg_key_enable;
- //156 背光模式 属性 bl_mode 枚举型(Enum) 可下发可上报(rw) 枚举值: auto, manual 默认"自动", 自动模式: 氛围灯亮, 背光灭, 有人后反转. 手动模式: 氛围灯可调, 背光亮度可调, 两者无关联
- point_t bl_mode;
- //157 人感状态 属性 mg_tof_status 布尔型(Bool) 可下发可上报(rw) -
- point_t mg_tof_status;
- //158 人感状态同步 属性 mg_tof_sync 布尔型(Bool) 只下发(wr) -
- point_t mg_tof_sync;
- //159 氛围灯关闭时间 属性 led_atmos_off_duration 数值型(Value) 可下发可上报(rw) 数值范围: 1-20, 间距: 1, 倍数: 0, 单位: 秒 默认5秒
- point_t led_atmos_off_duration;
-} mg_dp_t;
-
-extern mg_dp_t g_mg_dp_remote;
-extern mg_dp_t g_mg_dp_local;
-
-g_mg_dp_local = {
- .key_led_max= { 109, "key_led_max", },
- .atoms_led_max={ 110, "atmos_led_max", },
-};
-
-#endif
-
-void iot_start(void);
-
-uint32_t dp_key_led_br_read( void );
-uint32_t dp_fun_led_br_read( void );
-uint32_t dp_bl_mode_read( void );
-uint32_t dp_tof_threshold_read( void );
-
-#endif //__MG_IOT_H__
+++ /dev/null
-#ifndef __MG_VERSION_H__
-#define __MG_VERSION_H__
-
-#define SW_VERSION "1.0.0"
-
-#endif //__MG_VERION_H__
-
+++ /dev/null
-\r
-const char tuya_cacert_pem[] = {\\r
-"-----BEGIN CERTIFICATE-----\n"\\r
-"MIIDxTCCAq2gAwIBAgIBADANBgkqhkiG9w0BAQsFADCBgzELMAkGA1UEBhMCVVMx\n"\\r
-"EDAOBgNVBAgTB0FyaXpvbmExEzARBgNVBAcTClNjb3R0c2RhbGUxGjAYBgNVBAoT\n"\\r
-"EUdvRGFkZHkuY29tLCBJbmMuMTEwLwYDVQQDEyhHbyBEYWRkeSBSb290IENlcnRp\n"\\r
-"ZmljYXRlIEF1dGhvcml0eSAtIEcyMB4XDTA5MDkwMTAwMDAwMFoXDTM3MTIzMTIz\n"\\r
-"NTk1OVowgYMxCzAJBgNVBAYTAlVTMRAwDgYDVQQIEwdBcml6b25hMRMwEQYDVQQH\n"\\r
-"EwpTY290dHNkYWxlMRowGAYDVQQKExFHb0RhZGR5LmNvbSwgSW5jLjExMC8GA1UE\n"\\r
-"AxMoR28gRGFkZHkgUm9vdCBDZXJ0aWZpY2F0ZSBBdXRob3JpdHkgLSBHMjCCASIw\n"\\r
-"DQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAL9xYgjx+lk09xvJGKP3gElY6SKD\n"\\r
-"E6bFIEMBO4Tx5oVJnyfq9oQbTqC023CYxzIBsQU+B07u9PpPL1kwIuerGVZr4oAH\n"\\r
-"/PMWdYA5UXvl+TW2dE6pjYIT5LY/qQOD+qK+ihVqf94Lw7YZFAXK6sOoBJQ7Rnwy\n"\\r
-"DfMAZiLIjWltNowRGLfTshxgtDj6AozO091GB94KPutdfMh8+7ArU6SSYmlRJQVh\n"\\r
-"GkSBjCypQ5Yj36w6gZoOKcUcqeldHraenjAKOc7xiID7S13MMuyFYkMlNAJWJwGR\n"\\r
-"tDtwKj9useiciAF9n9T521NtYJ2/LOdYq7hfRvzOxBsDPAnrSTFcaUaz4EcCAwEA\n"\\r
-"AaNCMEAwDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMCAQYwHQYDVR0OBBYE\n"\\r
-"FDqahQcQZyi27/a9BUFuIMGU2g/eMA0GCSqGSIb3DQEBCwUAA4IBAQCZ21151fmX\n"\\r
-"WWcDYfF+OwYxdS2hII5PZYe096acvNjpL9DbWu7PdIxztDhC2gV7+AJ1uP2lsdeu\n"\\r
-"9tfeE8tTEH6KRtGX+rcuKxGrkLAngPnon1rpN5+r5N9ss4UXnT3ZJE95kTXWXwTr\n"\\r
-"gIOrmgIttRD02JDHBHNA7XIloKmf7J6raBKZV8aPEjoJpL1E/QYVN8Gb5DKj7Tjo\n"\\r
-"2GTzLH4U/ALqn83/B2gX2yKQOC16jdFU8WnjXzPKej17CuPKf1855eJ1usV2GDPO\n"\\r
-"LPAvTK33sefOT6jEm0pUBsV/fdUID+Ic/n4XuKxe9tQWskMJDE32p2u0mYRlynqI\n"\\r
-"4uJEvlz36hz1\n"\\r
-"-----END CERTIFICATE-----\n"};\r
+++ /dev/null
-#ifndef ST_ASTERIA_MODEL_H
-#define ST_ASTERIA_MODEL_H
-
-//zf
-#define MODEL_FOLDER "/usr/share/st_model/"
-
-static const char *FACE_RECT_MODEL = MODEL_FOLDER "M_Detect_Hunter_smallFace_Gray_precompile_UINT8_RK_9.4.0.model";
-static const char *FACE_POINT_MODEL = MODEL_FOLDER "M_Align_occlusion_106_precompile_INT16_RK_1.16.6.model";
-static const char *FACE_POSE_MODEL = MODEL_FOLDER "M_Align_CalcPose_Ann_106_2.4.0.model";
-static const char *FACE_EYEBROW_MODEL = MODEL_FOLDER "M_eyebrow_staticnorm_nocompress_precompile_INT16_RK_1.7.0.model";
-static const char *FACE_EYELID_MODEL = MODEL_FOLDER "M_eyelid_2_6_0_relu_staticnorm_nocompress_INT16_RK_2.6.0.model";
-static const char *FACE_LIP_MODEL = MODEL_FOLDER "M_SenseAR_Landmark_Lips64ptCrop_FastV1_relu_nocompress_precompile_INT16_RK_1.0.3.model";
-static const char *FACE_ATTRIBUTE_MODEL = MODEL_FOLDER "M_TV_FaceAttribute_U8_RK_1.4.7.model";
-static const char *FACE_FEATURE_MODEL = MODEL_FOLDER "M_Verify_VehicleFace_Common_precompile_INT16_RK_2.48.0.model";
-static const char *BODY_PREALIGN_MODEL = MODEL_FOLDER "M_TV_Prealign_U8_RK_1.2.0.model";
-static const char *BODY_ATTRIBUTE_MODEL = MODEL_FOLDER "M_TV_Action_U8_RK_1.4.0.model";
-static const char *BODY_RECT_MODEL = MODEL_FOLDER "M_Body_Detect_AG_U8_RK_0.4.28.model";
-static const char *BODY_POINT_MODEL = MODEL_FOLDER "M_Detect_Light_Body_17_Keypoints_Simple_int8_RK_copied_RK_1.5.9.model";
-static const char *UPPER_BODY_RECT_MODEL = MODEL_FOLDER "M_Detect_UpperBody_Hunter_TV_U8_RK_1.0.11.model";
-static const char *UPPER_BODY_POINT_MODEL = MODEL_FOLDER "M_Pose_Embedding_precompile_UINT8_RK_1.0.4.model";
-static const char *HAND_RECT_MODEL = MODEL_FOLDER "M_Hand_Track_TV_U8_RK_1.5.8.model";
-static const char *HEAD_DISTANCE_RECT_MODEL = MODEL_FOLDER "M_Detect_Body_HS_Hunter_TV_U8_RK_0.2.26.model";
-static const char *HEAD_DISTANCE_POINT_MODEL= MODEL_FOLDER "M_Track_HS_INT8_RK_1.1.10.model";
-static const char *BACKGROUND_MODEL = MODEL_FOLDER "257_257_M_Segment_TV_RK_U8_4.17.0.model";
-static const char *MOTION_MODEL = MODEL_FOLDER "M_Detect_Body_Hunter_Adapt_TV_U8_RK_1.1.3.model";
-
-#endif //
+++ /dev/null
-#ifndef ST_ASTERIA_API_H
-#define ST_ASTERIA_API_H
-
-#include "st_asteria_common.h"
-
-/// 该文件中的接口不保证线程安全, 多线程调用时需要用户确保安全调用
-
-/// @brief 检测模式
-#define ST_DETECT_MODE_VIDEO 0x00000001 ///< 视频检测模式
-#define ST_DETECT_MODE_PICTURE 0x00000002 ///< 图片检测模式
-
-/// @brief 检测项
-#define ST_DETECT_FACE 0x00000001 ///< 检测人脸
-#define ST_DETECT_FACE_EYEBROW 0x00000002 ///< 检测眉毛细节. 需要开启人脸检测
-#define ST_DETECT_FACE_EYELID 0x00000004 ///< 检测眼睑细节. 需要开启人脸检测
-#define ST_DETECT_FACE_LIP 0x00000008 ///< 检测嘴唇细节. 需要开启人脸检测
-#define ST_DETECT_FACE_ACTION 0x00000010 ///< 检测人脸动作. 需要开始人脸检测
-#define ST_DETECT_FACE_DISTANCE 0x00000020 ///< 检测人脸距离. 需要开启人脸检测
-#define ST_DETECT_FACE_ATTRIBUTE 0x00000040 ///< 检测人脸属性. 需要开启人脸检测
-#define ST_DETECT_FACE_FEATURE 0x00000080 ///< 检测人脸特征值. 需要开启人脸检测
-#define ST_DETECT_HAND 0x00000100 ///< 检测手势
-#define ST_DETECT_BODY 0x00001000 ///< 检测肢体
-#define ST_DETECT_BODY_ATTRIBUTE 0x00002000 ///< 检测肢体属性. 需要开启肢体检测
-#define ST_DETECT_HEAD_DISTANCE 0x00010000 ///< 检测头肩距离. 双目测距检测
-#define ST_DETECT_BACKGROUND 0x00020000 ///< 检测背景
-#define ST_DETECT_MONOCULAR_HEAD_DISTANCE 0x00040000 ///< 检测头肩距离. 单目测距检测
-#define ST_DETECT_MOTION 0x00080000 ///< 检测图动
-
-/// @brief 模型类型
-typedef enum
-{
- ST_MODEL_FACE_RECT, ///< 人脸检测模型
- ST_MODEL_FACE_POINT, ///< 人脸关键点模型
- ST_MODEL_FACE_POSE, ///< 人脸姿态模型
- ST_MODEL_FACE_EYEBROW, ///< 眉毛模型
- ST_MODEL_FACE_EYELID, ///< 眼睑模型
- ST_MODEL_FACE_LIP, ///< 嘴唇模型
- ST_MODEL_FACE_ATTRIBUTE, ///< 人脸属性模型
- ST_MODEL_FACE_FEATURE, ///< 人脸特征值模型
- ST_MODEL_FACE_BLINK, ///< 眨眼模型. 眨眼检测耗时较长, 如不需要检测请勿加载眨眼模型
- ST_MODEL_HAND_RECT, ///< 手势框模型
- ST_MODEL_HAND_POINT, ///< 手势关键点模型
- ST_MODEL_BODY_RECT, ///< 肢体检测模型
- ST_MODEL_BODY_POINT, ///< 肢体关键点模型
- ST_MODEL_BODY_ATTRIBUTE, ///< 肢体属性模型
- ST_MODEL_BODY_PREAGLIN, ///< 肢体属性模型,针对有躺姿检测需求的场景
- ST_MODEL_HEAD_DISTANCE_RECT, ///< 头肩距离框模型(双目)
- ST_MODEL_HEAD_DISTANCE_POINT, ///< 头肩距离点模型(双目)
- ST_MODEL_MONOCULAR_HEAD_DISTANCE_RECT, ///< 单目头肩距离框模型
- ST_MODEL_MONOCULAR_HEAD_DISTANCE_POINT, ///< 单目头肩距离点模型
- ST_MODEL_UPPER_BODY_RECT, ///< 上半身肢体框模型
- ST_MODEL_UPPER_BODY_POINT, ///< 上半身肢体关键点模型
- ST_MODEL_BACKGROUND, ///< 背景检测模型
- ST_MODEL_MOTION_BODY_RECT ///< 图动肢体框检测模型
-} STModelType;
-
-/// @brief 参数类型
-typedef enum
-{
- ST_PARAMETER_FACE_DETECT_INTERVAL, ///< 人脸检测间隔: 设置每多少帧重新检测一次人脸. 有效值 [1, -), 默认值 20. 设置越短新人脸检出越快, CPU/NPU使用率越高
- ST_PARAMETER_FACE_COUNT_MAX, ///< 人脸最大检测个数. 有效值 [1, 32], 默认值 32. 已检测人脸数达到最大后将不再检测新的人脸 (图片模式不受该参数限制)
- ST_PARAMETER_FACE_ATTRIBUTE_THRESHOLD, ///< 检测人脸属性的人脸质量分阈值: 有效值 [0.0, 1.0], 默认值 0.6
- ST_PARAMETER_FACE_ATTRIBUTE_STEP, ///< 检测人脸属性的人脸质量分步长: 有效值 [0.0, 1.0], 默认值 0.1. 人脸质量分达到阈值时检测一次, 质量分每比上一次增加一个步长检测一次
- ST_PARAMETER_FACE_ATTRIBUTE_FRAMES, ///< 每多少帧检测一次人脸属性. 有效值 [0, -), 默认值 30. 设置为 0 时只根据人脸质量分阈值和步长判断. 会覆盖每多少秒检测一次人脸属性的设置
- ST_PARAMETER_FACE_ATTRIBUTE_SECONDS, ///< 每多少秒检测一次人脸属性. 有效值 [0.0, -), 默认值 0.0. 设置为 0 时只根据人脸质量分阈值和步长判断. 会覆盖每多少帧检测一次人脸属性的设置
- ST_PARAMETER_FACE_FEATURE_THRESHOLD, ///< 提取人脸特征值的人脸质量分阈值: 有效值 [0.0, 1.0], 默认值 0.6
- ST_PARAMETER_FACE_FEATURE_STEP, ///< 提取人脸特征值的人脸质量分阈值: 有效值 [0.0, 1.0], 默认值 0.1. 人脸质量分达到阈值时检测一次, 质量分每比上一次增加一个步长检测一次
- ST_PARAMETER_FACE_SPEAK_THRESHOLD, ///< 说话检测嘴唇距离阈值(毫米): 有效值 (0.0, -), 默认值 3.0.
- ST_PARAMETER_FACE_SPEAK_FRAME_COUNT, ///< 说话检测嘴唇距离缓存帧数: 有效值[1, -), 默认值 10.
- ST_PARAMETER_HAND_MULTIPLE, ///< 是否检测多只手: 有效值 {0(只检测一只手), 1(检测多只手)}, 默认值0
- ST_PARAMETER_BODY_DETECT_INTERVAL, ///< 肢体检测间隔: 设置每多少帧重新检测一次肢体. 有效值 [1, -), 默认值 20. 设置越短新肢体检出越快, CPU/NPU使用率越高
- ST_PARAMETER_BODY_COUNT_MAX, ///< 肢体最大检测个数. 有效值 [1, 32], 默认值 32. 已检测肢体数达到最大后将不再检测新的肢体 (图片模式不受该参数限制)
- ST_PARAMETER_BODY_ATTRIBUTE_THRESHOLD, ///< 检测肢体属性的肢体质量分阈值: 有效值 [0.0, 1.0], 默认值 0.4
- ST_PARAMETER_BODY_ATTRIBUTE_STEP, ///< 检测肢体属性的肢体质量分步长: 有效值 [0.0, 1.0], 默认值 0.1. 肢体质量分达到阈值时检测一次, 质量分每比上一次增加一个步长检测一次
- ST_PARAMETER_BODY_ATTRIBUTE_FRAMES, ///< 每多少帧检测一次肢体属性. 有效值 [0, -), 默认值 30. 设置为 0 时只根据肢体质量分阈值和步长判断. 会覆盖每多少秒检测一次肢体属性的设置
- ST_PARAMETER_BODY_ATTRIBUTE_SECONDS, ///< 每多少秒检测一次肢体属性. 有效值 [0.0, -), 默认值 0.0. 设置为 0 时只根据肢体质量分阈值和步长判断. 会覆盖每多少帧检测一次肢体属性的设置
- ST_PARAMETER_CAMERA_VERTICAL_FOV, ///< 摄像头垂直FOV: 默认值 40.0. 检测人脸距离时需要设置
- ST_PARAMETER_BINOCULAR_INTRINSIC_LEFT, ///< 双目相机左镜头内部参数
- ST_PARAMETER_BINOCULAR_INTRINSIC_RIGHT, ///< 双目相机右镜头内部参数
- ST_PARAMETER_BINOCULAR_DISTORTION_LEFT, ///< 双目相机左镜头畸变参数
- ST_PARAMETER_BINOCULAR_DISTORTION_RIGHT, ///< 双目相机右镜头畸变参数
- ST_PARAMETER_BINOCULAR_ROTATION_MATRIX, ///< 双目相机旋转矩阵
- ST_PARAMETER_BINOCULAR_TRANSLATION_MATRIX, ///< 双目相机平移矩阵
- ST_PARAMETER_ENHANCE_XU_GESTURE, ///< 增强嘘手势检测开关:有效值{1(打开增强),0(关闭增强)}默认值 0
- ST_PARAMETER_SEGMENT_POST_RESOLUTION, ///< 背景分割平滑分辨率:有效值 [360, 1280], 默认值 720
- ST_PARAMETER_SEGMENT_ENHANCE, ///< 增强背景分割检测开关:有效值{1(打开增强),0(关闭增强)}默认值 1, 开启可提升远景时效果
- ST_PARAMETER_MOTION_LOCAL, ///< 图动检测局部图动开关:有效值[0.0, 1.0], 默认值 0 启用图动肢体框模型检测肢体, 功能完整且耗时较高,适用于仅开图动检测项; 设置为 1 时,关闭图动肢体框模型检测肢体,耗时更低,支持检测局部肢体的图动,局部图动需同时开启肢体检测项
- ST_PARAMETER_MOTION_MINTHRES, ///< 图动检测最小阈值,有效值(0-255),默认值5. 像素变动高于最小阈值才可判定为差异像素,设置越高,图动触发率越低
- ST_PARAMETER_MOTION_MINDIFFNUM ///< 图动检测最小变动数量,有效值(0,-),默认值10. 像素差异量高于最小变动数量才可触发图动,设置越高,图动触发率越低
-} STParameterType;
-
-/// @brief 获取版本信息
-/// @param[out] major 主版本号. 不需要获取时传空
-/// @param[out] minor 子版本号. 不需要获取时传空
-/// @param[out] patch 修正版本号. 不需要获取时传空
-/// @return 版本信息字符串
-ST_API const char *STAsteriaVersion(int *major, int *minor, int *patch);
-
-/// @brief 设置授权芯片I2C总线号
-/// @param[in] number I2C总线号
-/// @return 设置成功时返回ST_OK, 否则返回错误码
-ST_API STResult STAsteriaSetI2CBusNumber(int number);
-
-/// @brief 获取设备唯一标识符. 只支持SigmaStar平台
-/// @param[in,out]
-/// @return 获取成功时返回ST_OK, 否则返回错误码
-ST_API STResult STAsteriaGetUDID(const char **udid);
-
-/// @brief 获取激活码
-/// @param[in] license 授权文件路径或内容
-/// @param[out] activationCode 激活码
-/// @return 获取成功时返回ST_OK, 否则返回错误码
-ST_API STResult STAsteriaGetActivationCode(const char *license, const char **activationCode);
-
-/// @brief 校验激活码
-/// @param[in] license 授权文件路径或内容
-/// @param[in] activationCode 激活码
-/// @return 激活码校验正确时返回ST_OK, 否则返回错误码
-ST_API STResult STAsteriaCheckActivationCode(const char *license, const char *activationCode);
-
-/// @brief 添加授权文件
-/// @param[in] license 授权文件路径或内容
-/// @return 授权文件正确时返回ST_OK, 否则返回错误码
-ST_API STResult STAsteriaAddLicense(const char *license);
-
-/// @brief 创建检测句柄
-/// @param[out] handle 创建的检测handle. 创建失败时为NULL
-/// @return 正确创建句柄时返回ST_OK, 否则返回错误码
-ST_API STResult STAsteriaCreate(STHandle *handle);
-
-/// @brief 添加检测模型
-/// @param[in] handle 检测句柄
-/// @param[in] detectMode 检测模式
-/// @param[in] modelType 模型类型
-/// @param[in] modelPath 模型路径
-/// @return 添加成功时返回ST_OK, 否则返回错误码
-ST_API STResult STAsteriaAddModel(STHandle handle, int detectMode, STModelType modelType, const char *modelPath);
-
-/// @brief 初始化检测模型
-/// @param[in] handle 检测句柄
-/// @param[in] detectMode 检测模式
-/// @return 初始化成功时返回ST_OK, 否则返回错误码
-ST_API STResult STAsteriaInitialize(STHandle handle, int detectMode);
-
-/// @brief 设置检测项
-/// @param[in] handle 检测句柄
-/// @param[in] detectMode 检测模式
-/// @param[in] detection 检测项
-/// @return 设置成功时返回ST_OK, 否则返回错误码
-ST_API STResult STAsteriaSetDetection(STHandle handle, int detectMode, int detection);
-
-/// @brief 设置参数
-/// @param[in] handle 检测句柄
-/// @param[in] type 参数类型
-/// @param[in] value 参数值
-/// @return 设置成功时返回ST_OK, 否则返回错误码
-ST_API STResult STAsteriaSetParameter(STHandle handle, STParameterType type, float value);
-
-/// @brief 设置双目镜头参数
-/// @param[in] handle 检测句柄
-/// @param[in] type 参数类型
-/// @param[in] value 参数值
-/// @return 设置成功时返回ST_OK, 否则返回错误码
-ST_API STResult STAsteriaSetParameterBinocular(STHandle handle, STParameterType type, const float *values, int count);
-
-/// @brief 设置单目镜头参数
-/// @param[in] handle 检测句柄
-/// @param[in] type 参数类型
-/// @param[in] value 参数值
-/// @return 设置成功时返回ST_OK, 否则返回错误码
-ST_API STResult STAsteriaSetParameterMonocular(STHandle handle, STParameterType type, const float *values, int count);
-
-/// @brief 初始化单目镜头参数
-/// @param[in] handle 检测句柄
-/// @param[in] modelPath 参数路径
-/// @return 设置成功时返回ST_OK, 否则返回错误码
-ST_API STResult STAsteriaInitParameterMonocular(STHandle handle, const char *parameterPath);
-
-/// @brief 对图像进行检测
-/// @param[in] handle 检测句柄
-/// @param[in] detectMode 检测模式
-/// @param[in] image 检测图像
-/// @param[out] detectResult 检测结果
-/// @note 需要在初始化完成后调用. 在初始化过程中调用可能会导致程序崩溃
-/// @return 检测成功时返回ST_OK, 否则返回错误码
-ST_API STResult STAsteriaDetect(STHandle handle, int detectMode, const STImage *image, const STDetectResult **detectResult);
-
-/// @brief 对双目图像进行检测
-/// @param[in] handle 检测句柄
-/// @param[in] detectMode 检测模式
-/// @param[in] left 双目相机左镜头图像
-/// @param[in] right 双目相机右镜头图像
-/// @param[out] detectResult 检测结果
-/// @return 检测成功时返回ST_OK, 否则返回错误码
-ST_API STResult STAsteriaDetectBinocular(STHandle handle, int detectMode, const STImage *left, const STImage *right, const STDetectResult **detectResult);
-
-/// @brief 比对特征值
-/// @param[in] feature1 特征值1
-/// @param[in] feature2 特征值2
-/// @param[in] featureLen 特征值长度
-/// @param[out] score 比对分值
-/// @return 比对成功时返回ST_OK, 否则返回错误码
-ST_API STResult STAsteriaCompare(const unsigned char *feature1, const unsigned char *feature2, int featureLen, float *score);
-
-/// @brief 深拷贝检测结果
-/// @param[in] detectResult 需要拷贝的检测结果
-/// @return 拷贝后的检测结果. 使用完后需要调用STAsteriaReleaseDetectResult释放, 否则会有内存泄露
-ST_API STDetectResult *STAsteriaCopyDetectResult(const STDetectResult *detectResult);
-
-/// @brief 释放深拷贝的检测结果
-/// @param[in] detectResult 需要释放的检测结果
-ST_API void STAsteriaReleaseDetectResult(STDetectResult *detectResult);
-
-/// @brief 镜像检测结果
-/// @param[in] image_width 检测图像宽度
-/// @param[in] detectResult 需要镜像的检测结果
-ST_API void STAsteriaMirrorDetectResult(int image_width, STDetectResult *detectResult);
-
-/// @brief 重置检测句柄. 视频模式下, 当前后两帧图像相差较大时(如切换两段不同的视频), 需要调用本接口, 清除缓存数据
-/// @param[in] handle 需要重置的检测句柄
-ST_API void STAsteriaReset(STHandle handle);
-
-/// @brief 释放检测句柄
-/// @param[in] handle 需要释放的检测句柄
-/// @note 需要在检测完成后调用. 在检测过程中调用可能会导致程序崩溃
-ST_API void STAsteriaDestroy(STHandle handle);
-
-/// @brief 获取执行结果的文字描述
-/// @param[in] result 执行结果
-/// @return 结果描述字符串
-ST_API const char *STAsteriaGetDescription(STResult result);
-
-#endif // ST_ASTERIA_API_H
+++ /dev/null
-#ifndef ST_ASTERIA_COMMON_H
-#define ST_ASTERIA_COMMON_H
-
-#ifdef _MSC_VER
-# ifdef SDK_EXPORTS
-# define ST_API_ __declspec(dllexport)
-# else
-# define ST_API_ __declspec(dllimport)
-# endif
-#else
-# ifdef SDK_EXPORTS
-# define ST_API_ __attribute__((visibility ("default")))
-# else
-# define ST_API_
-# endif
-#endif
-
-#ifdef __cplusplus
-# define ST_API extern "C" ST_API_
-#else
-# define ST_API ST_API_
-#endif
-
-#define ST_OK 0 ///< 运行正常
-#define ST_E_INVALID_ARG -1 ///< 无效参数
-#define ST_E_HANDLE -2 ///< 句柄错误
-#define ST_E_OUT_OF_MEMORY -3 ///< 内存不足
-#define ST_E_INTERNAL_ERROR -4 ///< 内部错误
-#define ST_E_INVALID_PIXEL_FORMAT -6 ///< 图像格式不支持
-#define ST_E_FILE_NOT_EXIST -7 ///< 文件不存在
-#define ST_E_INVALID_FILE_FORMAT -8 ///< 模型格式错误
-#define ST_E_INVALID_UDID -12 ///< 无效的UDID
-#define ST_E_INVALID_LICENSE -13 ///< 授权文件无效
-#define ST_E_INVALID_APP_ID -14 ///< 包名错误
-#define ST_E_LICENSE_EXPIRED -15 ///< 授权文件过期
-#define ST_E_UDID_MISMATCH -16 ///< UDID不匹配
-#define ST_E_LICENSE_IS_NOT_ACTIVABLE -20 ///< 授权文件不支持生成激活码
-#define ST_E_ACTIVATION_CODE_INVALID -22 ///< 离线激活码无效
-#define ST_E_NO_CAPABILITY -23 ///< 授权文件不包含该功能
-#define ST_E_PLATFORM_NOT_SUPPORTED -24 ///< 授权文件不支持该平台
-#define ST_E_ONLINE_ACTIVATION_FAILED -28 ///< 在线激活失败
-#define ST_E_ONLINE_ACTIVATION_CODE_INVALID -29 ///< 在线激活码无效
-#define ST_E_ONLINE_ACTIVATION_CONNECT_FAILED -30 ///< 在线激活连接失败
-#define ST_E_HARDWARE_AUTHORIZE_INIT_FAILED -32 ///< 加密芯片验证初始化失败
-#define ST_E_HARDWARE_AUTHORIZE_FAILED -33 ///< 加密芯片验证失败
-#define ST_E_UNSUPPORTED -1000 ///< 不支持的函数调用方式
-#define ST_E_DEVICE_NOT_CONNECTED_TO_NETWORK -196608 ///< 设备没有连接网络
-
-#define ST_FACE_ACTION_BLINK 0x00000002 ///< 眨眼 (需要加载眨眼模型. 检测耗时较长, 如不需要检测请勿加载眨眼模型)
-#define ST_FACE_ACTION_OPEN_MOUTH 0x00000004 ///< 张嘴
-#define ST_FACE_ACTION_SHAKE_HEAD 0x00000008 ///< 摇头
-#define ST_FACE_ACTION_NOD_HEAD 0x00000010 ///< 点头
-#define ST_FACE_ACTION_BROW_JUMP 0x00000020 ///< 挑眉
-#define ST_FACE_ACTION_LIPS_UP 0x00000040 ///< 嘴角上扬
-#define ST_FACE_ACTION_POUT 0x00000080 ///< 嘟嘴
-#define ST_FACE_ACTION_SPEAK 0x00000100 ///< 说话
-
-#define ST_HAND_ACTION_INVALID 0x00000000 ///< 无效手势
-#define ST_HAND_ACTION_THUMBS_UP 0x00000001 ///< 竖大拇指
-#define ST_HAND_ACTION_INDEX_FINGER 0x00000002 ///< 食指/一
-#define ST_HAND_ACTION_LITTLE_FINGER 0x00000004 ///< 小拇指
-#define ST_HAND_ACTION_V 0x00000008 ///< V/Yeah/二
-#define ST_HAND_ACTION_THREE 0x00000010 ///< 三
-#define ST_HAND_ACTION_FOUR 0x00000020 ///< 四
-#define ST_HAND_ACTION_SIX 0x00000040 ///< 六
-#define ST_HAND_ACTION_SHOOT 0x00000080 ///< 手枪/八
-#define ST_HAND_ACTION_FINGER_HEART 0x00000100 ///< 单手比心
-#define ST_HAND_ACTION_OK 0x00000200 ///< OK
-#define ST_HAND_ACTION_ROCK_ON 0x00000400 ///< 摇滚
-#define ST_HAND_ACTION_I_LOVE_YOU 0x00000800 ///< 我爱你
-#define ST_HAND_ACTION_PALM 0x00001000 ///< 手掌/五
-#define ST_HAND_ACTION_HOLD_UP 0x00002000 ///< 托手
-#define ST_HAND_ACTION_FIST 0x00004000 ///< 拳头
-#define ST_HAND_ACTION_HEART 0x00008000 ///< 双手比心
-#define ST_HAND_ACTION_PRAY 0x00010000 ///< 祈祷/双手合十
-#define ST_HAND_ACTION_CONGRATULATE 0x00020000 ///< 恭贺/抱拳
-
-#define ST_ATTRIBUTE_UNSURE "unsure"
-#define ST_ATTRIBUTE_AGE "age"
-#define ST_ATTRIBUTE_AGE_RANGE_JUDGE "age_range_judge"
-#define ST_ATTRIBUTE_IS_K12 "k12"
-#define ST_ATTRIBUTE_NOT_K12 "not_k12"
-#define ST_ATTRIBUTE_GENDER "gender"
-#define ST_ATTRIBUTE_GENDER_FEMALE "female"
-#define ST_ATTRIBUTE_GENDER_MALE "male"
-#define ST_ATTRIBUTE_RACE "race"
-#define ST_ATTRIBUTE_RACE_YELLOW "yellow"
-#define ST_ATTRIBUTE_RACE_BLACK "black"
-#define ST_ATTRIBUTE_RACE_WHITE "white"
-#define ST_ATTRIBUTE_BEARD "beard"
-#define ST_ATTRIBUTE_BEARD_NONE "none"
-#define ST_ATTRIBUTE_BEARD_HAVE "beard"
-#define ST_ATTRIBUTE_FACE_VALUE "face_value"
-#define ST_ATTRIBUTE_GLASSES "glasses"
-#define ST_ATTRIBUTE_GLASSES_NONE "none"
-#define ST_ATTRIBUTE_GLASSES_GLASSES "glasses"
-#define ST_ATTRIBUTE_GLASSES_SUNGLASSES "sunglasses"
-#define ST_ATTRIBUTE_MASK "mask"
-#define ST_ATTRIBUTE_MASK_NONE "none"
-#define ST_ATTRIBUTE_MASK_HAVE "mask"
-#define ST_ATTRIBUTE_EYE "eye"
-#define ST_ATTRIBUTE_EYE_OPEN "open"
-#define ST_ATTRIBUTE_EYE_CLOSE "close"
-#define ST_ATTRIBUTE_MOUTH "mouth"
-#define ST_ATTRIBUTE_MOUTH_OPEN "open"
-#define ST_ATTRIBUTE_MOUTH_CLOSE "close"
-#define ST_ATTRIBUTE_SMILE "smile"
-#define ST_ATTRIBUTE_EMOTION "emotion"
-#define ST_ATTRIBUTE_EMOTION_ANGRY "angry"
-#define ST_ATTRIBUTE_EMOTION_CALM "calm"
-#define ST_ATTRIBUTE_EMOTION_DISGUST "disgust"
-#define ST_ATTRIBUTE_EMOTION_HAPPY "happy"
-#define ST_ATTRIBUTE_EMOTION_SAD "sad"
-#define ST_ATTRIBUTE_EMOTION_SCARED "scared"
-#define ST_ATTRIBUTE_EMOTION_SURPRISE "surprise"
-#define ST_ATTRIBUTE_EMOTION_UNCLEAR "unclear"
-
-#define ST_ATTRIBUTE_POSTURE "posture"
-#define ST_ATTRIBUTE_POSTURE_STAND "stand"
-#define ST_ATTRIBUTE_POSTURE_SIT "sit"
-#define ST_ATTRIBUTE_POSTURE_LIE "lie"
-
-typedef int STResult;
-typedef void* STHandle;
-
-typedef enum {
- ST_PIXEL_FORMAT_GRAY, ///< GRAY 1 8bpp 单通道灰度
- ST_PIXEL_FORMAT_I420, ///< YUV 4:2:0 12bpp 3通道, 亮度通道, U分量通道, V分量通道. 所有通道都是连续的
- ST_PIXEL_FORMAT_NV12, ///< YUV 4:2:0 12bpp 2通道, 亮度通道和UV分量交错通道
- ST_PIXEL_FORMAT_NV21, ///< YUV 4:2:0 12bpp 2通道, 亮度通道和VU分量交错通道
- ST_PIXEL_FORMAT_BGRA, ///< BGRA 8:8:8:8 32bpp 4通道
- ST_PIXEL_FORMAT_BGR, ///< BGR 8:8:8 24bpp 3通道
- ST_PIXEL_FORMAT_RGBA, ///< RGBA 8:8:8:8 32bpp 4通道
- ST_PIXEL_FORMAT_RGB, ///< RGB 8:8:8 24bpp 3通道
- ST_PIXEL_FORMAT_GRAY_FLOAT, ///< GRAY 1 32bpp 单通道灰度,每个像素为一个4字节浮点数
-} STPixelFormat;
-
-typedef struct STPoint {
- float x;
- float y;
-} STPoint;
-
-typedef struct STRect {
- int left;
- int top;
- int right;
- int bottom;
-} STRect;
-
-typedef struct STImage {
- unsigned char *data; ///< 图像数据
- STPixelFormat format; ///< 像素格式
- int width; ///< 图像宽度 (单位: 像素)
- int height; ///< 图像高度 (单位: 像素)
- int reserved0; ///< 保留字段
- long reserved1; ///< 保留字段
- long reserved2; ///< 保留字段
- int reserved3; ///< 保留字段
- int reserved4; ///< 保留字段
- int reserved5; ///< 保留字段
-} STImage;
-
-typedef struct STAttribute {
- char *category; ///< 属性类别
- char *label; ///< 属性标签
- float score; ///< 属性置信度
-} STAttribute;
-
-typedef struct STFace {
- int id; ///< 人脸序号 (从1开始)
- STRect rect; ///< 人脸框
- STPoint *points; ///< 人脸关键点
- int pointCount; ///< 人脸关键点个数
- float *visibilities; ///< 人脸关键点可见度
- STPoint *extraPoints; ///< 眼睛(0~43), 眉毛(44~69), 嘴唇(70~133)细节关键点
- int extraPointCount; ///< 眉毛, 眼睛, 嘴唇细节关键点个数
- int action; ///< 人脸动作
- float yaw; ///< 水平转角
- float pitch; ///< 俯仰角
- float roll; ///< 旋转角
- float quality; ///< 人脸质量
- float distance; ///< 人脸距离
- STAttribute *attributes;///< 人脸属性
- int attributeCount; ///< 人脸属性个数
- unsigned char *feature; ///< 人脸特征值
- int featureLen; ///< 人脸特征值长度
-} STFace;
-
-typedef enum {
- ST_HAND_EVENT_NONE, ///< 无动态手势
- ST_HAND_EVENT_UP, ///< 向上手势
- ST_HAND_EVENT_DOWN, ///< 向下手势
- ST_HAND_EVENT_LEFT, ///< 向左手势
- ST_HAND_EVENT_RIGHT, ///< 向右手势
- ST_HAND_EVENT_CIRCLE, ///< 转圈手势
- ST_HAND_EVENT_HOLD, ///< 手势保持不动
- ST_HAND_EVENT_SILENT, ///< 静音(嘘)手势
-} STHandEventType;
-
-typedef struct STHandEvent {
- STHandEventType type; ///< 手势事件类型
- float velocity; ///< 手势事件速度
- float value; ///< 手势事件值
-} STHandEvent;
-
-typedef struct STHand {
- int id; ///< 手势序号
- int faceId; ///< 关联的人脸id. 没有关联的人脸时值为0 (无效人脸id)
- STRect rect; ///< 手势框
- STPoint *points; ///< 手势关键点
- int pointCount; ///< 手势关键点个数
- int action; ///< 手势类型
- int palmSide; ///< 手心朝向 0代表Frontward、1代表Backward、2代表Sideward
- int isHoldingObjects; ///< 手持物体判定 -1代表Unknown、1代表True、0代表False
- STHandEvent event; ///< 动态手势
-} STHand;
-
-typedef struct STBody {
- int id; ///< 肢体序号 (从1开始)
- int faceId; ///< 关联的人脸id. 没有关联的人脸时值为0 (无效人脸id)
- STRect rect; ///< 肢体框
- STPoint *points; ///< 肢体关键点
- float *visibilities; ///< 肢体关键点可见度
- int pointCount; ///< 肢体关键点个数
- float quality; ///< 肢体质量
- STAttribute *attributes;///< 肢体属性
- int attributeCount; ///< 肢体属性个数
-} STBody;
-
-typedef struct STHead {
- int id; ///< 头肩序号 (从1开始)
- int faceId; ///< 关联的人脸id. 没有关联的人脸时值为0 (无效人脸id)
- STRect rect; ///< 头肩框
- float distance; ///< 头肩距离
- float angle; ///< 头肩角度
-} STHead;
-
-typedef struct STSegment {
- STImage mask; ///< 前后背景分割结果图片信息,前景为0,背景为255,边缘部分有模糊(0-255之间),输出图像大小可以调节
- float minThreshold; ///< 前后背景最小阈值,与模型相关,取值范围0.0f-1.0f
- float maxThreshold; ///< 前后背景最大阈值,与模型相关,取值范围0.0f-2.0f
-} STSegment;
-
-typedef struct STMotion {
- STRect *motionRegion; ///< 图动框
- int motionCount; ///< 图动框个数
- STRect *bodyRect; ///< 肢体框
- int bodyCount; ///< 肢体框个数
-} STMotion;
-
-typedef struct STDetectResult {
- STFace *faces; ///< 人脸
- int faceCount; ///< 人脸个数
- STHead* heads; ///< 头肩
- int headCount; ///< 头肩个数
- STHand *hands; ///< 手势
- int handCount; ///< 手势个数
- STBody *bodys; ///< 肢体
- int bodyCount; ///< 肢体个数
- STSegment *backgrounds; ///< 背景
- STMotion *motion; ///< 图动
-} STDetectResult;
-
-#endif // ST_ASTERIA_COMMON_H
+++ /dev/null
-#ifndef ST_ASTERIA_UTILS_H
-#define ST_ASTERIA_UTILS_H
-#include <string.h>
-#include <sys/time.h>
-#include <sys/timeb.h>
-#include "model.h"
-
-#define STR_LEN 22
- static char* time_str()
-{
- //static const size_t STR_LEN = 22;
- static char time_str[STR_LEN] = {0};
-
- struct timeb tb;
- ftime(&tb);
- struct tm *t = NULL;
- t = localtime(&tb.time);
- snprintf(time_str, STR_LEN, "%04d%02d%02d %02d:%02d:%02d.%03d",
- t->tm_year + 1900, t->tm_mon + 1, t->tm_mday,
- t->tm_hour, t->tm_min, t->tm_sec, tb.millitm);
- return time_str;
-}
-
- double time_ms()
-{
- struct timeval tv;
- gettimeofday(&tv, NULL);
- return tv.tv_sec * 1000.0 + tv.tv_usec / 1000.0;
-}
-
-#define LOGE(fmt, ...) fprintf(stderr, "[%s] asteria error: " fmt "\n", time_str(), ## __VA_ARGS__)
-#define LOGI(fmt, ...) fprintf(stdout, "[%s] asteria info : " fmt "\n", time_str(), ## __VA_ARGS__)
-#define LOGD(fmt, ...) fprintf(stdout, "[%s] asteria debug: " fmt "\n", time_str(), ## __VA_ARGS__)
-
-#define TIME_S(tag) double time_##tag##_start = time_ms();
-#define TIME_E(tag) double time_##tag##_end = time_ms(); LOGD(#tag " time: %.2f ms", time_##tag##_end - time_##tag##_start);
-
-#define ST_CHECK_RET(msg) { \
- if (ret != ST_OK) { \
- LOGE(msg " failed: %d (%s)", ret, STAsteriaGetDescription(ret)); \
- return ret; \
- } \
-}
-
-#define ST_CHECK_RET_DESTROY_HANDLE(msg) { \
- if (ret != ST_OK) { \
- LOGE(msg " failed: %d (%s)", ret, STAsteriaGetDescription(ret)); \
- STAsteriaDestroy(g_SThandle); \
- return ret; \
- } \
-}
-
-void printDetectResult(const STDetectResult *detectResult)
-{
- if (!detectResult) return;
-
- LOGI("face count: %d", detectResult->faceCount);
- for (int i = 0; i < detectResult->faceCount; ++i)
- {
- LOGI(" id %d, head box[ %d %d %d %d], distance %.2f, attr count %d, feature len %d",
- detectResult->faces[i].id, detectResult->faces[i].rect.left,
- detectResult->faces[i].rect.top, detectResult->faces[i].rect.right,
- detectResult->faces[i].rect.bottom, detectResult->faces[i].distance,
- detectResult->faces[i].attributeCount, detectResult->faces[i].featureLen);
- }
-
-
- LOGI("body count: %d", detectResult->bodyCount);
- for(int i=0;i<detectResult->bodyCount;i++)
- {
- LOGI("body point count: %d", detectResult->bodys[i].pointCount);
- for(int k=0;k< detectResult->bodys[i].pointCount;k++)
- {
- int x=(int)detectResult->bodys[i].points[k].x;
- int y=(int)detectResult->bodys[i].points[k].y;
- LOGI(" point : %d,%d",x,y);
- }
-
- }
-
-}
-
-#endif // ST_ASTERIA_UTILS_H
+++ /dev/null
-############################################################
-# SenseTime License
-# License Product: SenseAsteriaRK
-# Expiration: 20230727~20230827
-# License SN: d1d40bd7-e79c-4484-80c5-97aba865ffc3
-############################################################
-sGfdd1s1qb3wA+Uwf0R19tc8k2SAM6zdyhws5TEollPbKQ3iDS+mo1f0YOxS
-t6IcTlIMlvOZnTOj6QLi2mDao0ePtVNpAHU6DzRW1VDzHHbV5GaPRaTRfKod
-B8Ax2wgoTqRIl1GurVbYmKc1Vydgj3BZfzXK//VlPz7Q4PEIXgCLvZdSAQAA
-AAEAAAAMga9rrsYWlSZKBdxBkaiHGHFfWdX/O3jUiBAmfD0wklukiC92n7/Z
-TmBQqe8P95nRfsrTbqMgjHKmuA5OUUvWEEpASJTmcz1nwGeLwZnDvKz1xb+P
-bHaRllsmak2JC4vfrUzzSQDRGr7qUG0YLpmHtC5uvVHMDYnRIQyVFmS/udgf
-HH9+8/WyL7sLoB+0rDbrn3RS1pRJKsenZf9t0+wHMRhEOOhsGyN9d6bA7UqM
-JJ86CLdRIJeWjCQLfm6kXP5jmwTCdid5hREGz1LlREAI5NQLkGW/iPhpYE4+
-0Z4jsAGfUBZw7l9bXiEYEoMFLxWglofrD3r2oaZ1jpT/MRj/AQABAAAAAAAD
-AAAAAAAAAAAAAABH96LapFP517TghAMRwj6cOdPXpzNPOyEb63vxYMt2fGTX
-XiSJ7nEF9CIUJozM32v3jyeBGKCqRrWuYL7pIuHPG96/GX1hdjlwIpIS/3qG
-zYlWo8nR5jvd1I8Xd/LiVAdQmiejfDwDino9z6KDuRzNFS6sz1CYSrXsaaP5
-lnVTC0KSyi0zIJcYaG5Aqa78KRE7NsdFifeYeXSDgu/01r0FHtKpG7vI4YAP
-9L2WKoFHw24KpRlcJcHxHAYEncame/UH/6voUIDpKZjMKYOW7ta8NIzlLrDv
-kkALyzbAUKsjdFzhviEkTwqRkYEfdfQ8sdZYt5gH88aOrT+KRd/0ClGNw1Dc
-YxeXilemFta42WjlayNnrUQfcGvhNXnNIpZKnYy9ALkC52C2BxO5XmLIP4Ou
-yJSFT57DalbqU2VDXY5fH0uv8SxerSsbQ1sRSbJ804tqZ5NyjTBjesdO2xWj
-F1cnH/JGyvJPAQ2W/PiEZ1PEpMdb5fDqDFOhfFspZ5v7wb+wLaRT97sBxV5V
-tGYUrgJSDHcU+h4Rzoy33/1RBwlZWjkci7okAGm/3jhzZ61sK8SAjFPeqZ3+
-DS6RzEbMtkOCLkWHU8yX5A1j0Nqx/3ku08zfgYhxs2qhC7uH5bD/T3wuCnQE
-NCKTWvbDO2U4uQbGMARd4B1s
-------------------------------------------------------------
-sGfdd5IBiQsMRlv2TssoIQwPT8nP+a16BVO3Kzed5488mUsR1TDL3NmnFAE0
-IrXfED9MP3ldDso7sY6a2MBSzHqmiVSZd5s61wc8seyYjuzUA7cpXpqZiOI5
-uYoMPFCYmrulLR4DmjSa2MlicL51nD2WZhHNw302mmaff6mo9akFHH3SAQAA
-AAIAAAA7mOZErIopiZx8+d9rRIfOQg3O2fSDzhXuL1vbK6Q4kt4osx0CvmsF
-1JAgkelQUWF+bcQSzpE/hF1LQLuSAbMFkXZ+VwZ7ZDCLNAwzktfFPohaNMBa
-ojND0F2XQNOzXdmyYvRLszD8p9u4c3JkakvupOhdY/2AERTNmUcwhiGeT9b5
-WIgnE4bPKQI+lMCKSF9PwyodMM/L/GyRAI+TcyC99Um4JoeKKb62FwgrcdIF
-JL3g5OXmzgstQZiKE9vqEm/RCStl57Z1ETMeW111fYVRu54hITIFK4GlDPBH
-vjregyH6FCW+Pg8kb3pGzjS/7WgAuAq5OqXTcQMIKwVwjhVTAAAAAAAAAAAA
-AAAAAAAAAAAAAABzU2AlR64j3aLkY4H5HHPE2VoaHyKzBhJalghHuqgun4IT
-M6jilujA18MOuRjTTqksw7L3q9SztWM8zCJLeCUxw38dUQFQsmB1mffMs64C
-c/9AgxEPuoQZsUShWyi2AEeq05AyF3hRCupczrmjTvOnabNj/l0HfqG3qNdA
-f3vH+45ElA+0Ge15fiEnHiD6rmIenSIWXU83w9AT/T+brDqAZPJ74NDMpvk6
-+AUiUwrKR85K0HR2epdA24iiKkphLtkKZM0iPFVyTxELNgwZJ/ZXOLBwNNAv
-36ybpCw3m84vh+zlm3+FeUmY1KoSiOQrMwtnx67nma4PDuQFxCsRhhhlQ58u
-zJLjNC5idjuEtBOg3UDZm035SKTLTojedzbqdDKr01XeVO6yB0hCYKn8GDTA
-ZMIGSi6AmPGVr/hBPIM3EGKXtoLIizs75ytnN60j08gG3xVFnoEfZCPnX+KO
-2N1u/W/ys/LBQTMO/qc2qft2JLGTMIbl8Nzs95FsjdD/VdVZm97OgzOCGpO2
-pfrrAQvKy+9tE1F0djrAVTbJ+JEP2isS51ETJDyGycxCHaJaevwynQ9mGfsS
-Wxnw6uKfVvqNOs/iDbPpK/a8ZZri981mkZAv8JqKC1MflBSeJX8+oL09DGm8
-B5khyVhFYpkjI5vuSQuLrC99H+E75aNaVRfvzvCSeMVTFxUM/Mk4EApiQQ47
-xTMJok8I8V5uCeHa5xIdV9qZLt7I/TdBt9ji9I+zVb8ZX1TX+FCZc7Plh84K
-xHZX7Mpk5Ux+Ym5Owt4us9MY9qRRoBUkt4Vj0px26g5X14xnN7gCK8obB39P
-AhRKonki2lpT+f0m//Lz6xbdT7KDeqREpJK1ruOsBEb4VjNCNuvXQnifS+El
-qy2ANLu5jB+jgqnfG/aN1MtXR5pc1Zr+9VSDJk4HW8+0Znl0VClgvaS1WVPn
-KAJ1vcNIeSBXBnAdam7VI6YUMGmHLiEoI4DWpyT1NUBg71QHKAdnKbU70GUg
-Al/o
-############################################################
\ No newline at end of file
+++ /dev/null
-#include <stdio.h>
-#include <stdint.h>
-#include <stdlib.h>
-#include <string.h>
-#include <unistd.h>
-#include <zlib.h>
-
-#include <sys/types.h>
-#include <sys/stat.h>
-#include <fcntl.h>
-#include <errno.h>
-
-//#include "button.h"
-//#include "led.h"
-//#include "iot.h"
-//#include "mg_log.h"
-
-#include "device.h"
-#include "version.h"
-#include "rk_ble_app.h"
-
-#define PID_FILE "/var/run/mg_app/mg_app.pid"
-
-extern int32_t read_device_uuid( mg_dev_t *dev );
-
-static mg_dev_t g_mg_dev;
-
-time_t device_uptime_msec( void )
-{
- struct timespec ts;
-
- clock_gettime( CLOCK_BOOTTIME, &ts );
-
- return (time_t )(ts.tv_sec*1000+ts.tv_nsec/1000/1000);
-}
-
-time_t device_uptime_sec( void )
-{
- //struct sysinfo info;
- //( sysinfo( &info ) ){
- //return info.uptime;
- struct timespec ts;
-
- clock_gettime( CLOCK_BOOTTIME, &ts );
-
- return ts.tv_sec;
-}
-
-char * dev_uuid_str( void )
-{
- return g_mg_dev.uuid;
-}
-
-mg_dev_t * mg_dev_get( void )
-{
- return &g_mg_dev;
-}
-
-char * mg_st_name( dev_st_t st )
-{
- if( st == DS_INIT ) return "DS_INIT";
- else if( st == DS_NO_AUTH ) return "DS_NO_AUTH";
- else if( st == DS_AUTH_NO_WIFICONFIG ) return "DS_AUTH_NO_WIFICONFIG";
- else if( st == DS_AUTH_WIFICONFIGING ) return "DS_AUTH_WIFICONFIGING";
- else if( st == DS_AUTH_WIFICONFIG_NO_ACTIVE ) return "DS_AUTH_WIFICONFIG_NO_ACTIVE";
- else if( st == DS_ACTIVE ) return "DS_ACTIVE";
- else if( st == DS_INVALID ) return "DS_INVALID";
- return "unkown";
-}
-
-dev_st_t mg_device_st_get( mg_dev_t *dev )
-{
- dev_st_t st = DS_INVALID;
- if( dev ){
- mg_dev_lock( dev );
- st = g_mg_dev.st;
- mg_dev_unlock( dev );
- }
- return st;
-}
-
-dev_st_t mg_device_st_set( mg_dev_t *dev, dev_st_t st )
-{
- dev_st_t old_st;
-
- if( !dev || st >= DS_INVALID)
- return DS_INVALID;
-
- mg_dev_lock( dev );
- old_st = dev->st;
- dev->st = st;
- mg_dev_unlock( dev );
-
- if( old_st != st ){
- MG_LOGD( "mg device st %s -> %s\n", mg_st_name( old_st ), mg_st_name( st ) );
- if( st == DS_INIT ){
- light_mode_set( dev, LIGHT_MODE_INIT );
- }else if( st == DS_NO_AUTH ){
- light_mode_set( dev, LIGHT_MODE_NO_AUTH );
- }else if( st == DS_AUTH_NO_WIFICONFIG){
- light_mode_set( dev, LIGHT_MODE_AUTH_NO_WIFICONFIG );
- }else if( st == DS_AUTH_WIFICONFIG_NO_ACTIVE ){
- light_mode_set( dev, LIGHT_MODE_AUTH_WIFICONFIG_NO_ACTIVE );
- }else if( st == DS_ACTIVE){
- light_mode_set( dev, LIGHT_MODE_ACTIVE );
- }
- }
-
- return old_st;
-}
-
-static int alone_runnind(void)
-{
- int fd;
- char buf[16];
- struct flock fl;
-
- fd = open(PID_FILE, O_RDWR | O_CREAT, 0666);
- if (fd < 0)
- {
- perror("open");
- exit(1);
- }
-
- fl.l_type = F_WRLCK;
- fl.l_start = 0;
- fl.l_whence = SEEK_SET;
- fl.l_len = 0;
-
- if(fcntl(fd, F_SETLK, &fl)<0)
- {
- if (errno == EACCES || errno == EAGAIN)
- {
- close(fd);
- //printf("alone runnind\n");
- return -1;
- }
-
- printf("can't lock %s: %s\n", PID_FILE, strerror(errno));
-
- }
-
- if( ftruncate(fd, 0) ){ //设置文件的大小为0
- }
-
- sprintf(buf, "%ld\n", (long)getpid());
- if( write(fd, buf, strlen(buf) + 1)){
- }
-
- //这里不关闭文件, 保持锁定状态
-
- return 0;
-}
-
-int32_t mg_device_init( mg_dev_t *dev )
-{
-
- if( !dev )
- return -1;
-
- memset( dev, 0, sizeof( mg_dev_t ) );
-
- read_device_uuid( dev );
-
- pthread_mutex_init( &dev->lock, NULL );
-
- //从配置文件读取参数
- load_device_cfg( &dev->cfg );
- //printf( "load cfg, key_led_max:%d, led_atmos_off_duration:%d\n", g_mg_dev.cfg.key_led_max, g_mg_dev.cfg.led_atmos_off_duration );
-
- dev->st = DS_INIT;
-
- //var/run/mg_app目录下输出信息
- mg_device_run_st_init( dev );
-
- return 0;
-}
-
-char* program_name = NULL;
-
-int main( int argc, char**argv )
-{
- if( argc > 1 ){
- printf( "\n\nmg_app version: %s\n\n", SW_VERSION );
- exit( 0 );
- }
-
- if( argc == 1 && strcmp( argv[0], "camera-ctrl" )==0 ){
- //camera 控制 子进程
- extern void camera_process( void );
- camera_process();
- exit(0);
- }
-
- program_name = strdup( argv[0] );
-
- //检查程序是否已经运行
- if( alone_runnind() ){
- printf( "APP is alread runnig!\n" );
- exit( -1 );
- }
-
-
- mg_log_init();
- MG_LOGD( "mg app start..." );
-
- //设备状态初始化
- mg_device_init( &g_mg_dev );
-
- //中间件初始化
- btn_light_ctrl_init( &g_mg_dev );
-
- //device_wifi_init();
-
- // 启动wifi task;
- //device_wifi_start();
- device_netconfig_task_start( &g_mg_dev ); //start tuya bind and wificonfig
-
- //启动背光按键控制
- btn_light_ctrl_start( &g_mg_dev );
-
- //检查授权文件
- while( load_auth_key( &g_mg_dev ) != 0 ){
- //未授权,等待授权
- mg_device_st_set( &g_mg_dev, DS_NO_AUTH );
- MG_LOGD( "wait mg auth" );
- sleep(5);
- }
-
- //检查配网状态
- if( !is_tuya_config( &g_mg_dev ) ){
- netconfig_start( &g_mg_dev );
- while( !is_tuya_config( &g_mg_dev ) ){
- sleep(1);
- }
- netconfig_stop( &g_mg_dev );
- }
-
- if( is_device_active( &g_mg_dev ) ){
- //已经激活
- mg_device_st_set( &g_mg_dev, DS_ACTIVE );
- }else{
- //未激活
- mg_device_st_set( &g_mg_dev, DS_AUTH_WIFICONFIG_NO_ACTIVE );
- }
- //连接涂鸦IOT平台
- MG_LOGD( "iot start..");
- iot_start();
-
- //等待涂鸦连接
- while( !is_iot_connected() ){
- //wait iot connect ...
- MG_LOGD( "wait iot connect...");
- sleep(2);
- }
-
- //上报激活状态
- dp_active_report( g_mg_dev.mg_active );
-
- //未激活则连接tuya等待激活完成
- if( !is_device_active( &g_mg_dev ) ){
-
- mg_device_st_set( &g_mg_dev, DS_AUTH_WIFICONFIG_NO_ACTIVE );
-
- //启动激活流程,堵塞,等待激活成功后返回
- mg_device_active( &g_mg_dev );
-
- //上报激活状态
- dp_active_report( g_mg_dev.mg_active );
- }
-
- //激活,正常运行
- mg_device_st_set( &g_mg_dev, DS_ACTIVE );
-
- //上报所有dp 信息。
- dp_report_all( &g_mg_dev );
-
- //启动手势识别子流程
-#if 0
- if( gesture_recognition_start( &g_mg_dev ) < 0 ){
- MG_LOGE( "start gesture task fail!\n" );
- }
-#else
- {
- int32_t gesture_task_start( mg_dev_t *dev );
- if( !gesture_task_start( &g_mg_dev) ){
- MG_LOGE( "start gesture task fail!\n" );
- }
- }
-#endif
-
-
- ///rk_ble_wifi_init( NULL );
- while(1){
- //TODO:
- sleep(5*1000);
- }
- return 0;
-
-}
-
-/*
-rfjb_main
-主入口
-系统初始化
-加载系统参数
-启动各个子任务
-
-命令行参数
---help: 显示help信息
---version: 显示版本号
-
-*/
-
-int32_t main( int32_t argc, char**argv )
-{
- dev_init(); //参数加载
-
- app_sensor_task_start(); //传感器采集数据任务
- app_audio_task_start(); //音频管理任务
- app_camera_task_start(); //摄像机管理
- app_ui_task_start(); //显示界面和按键任务
- app_iot_task_start(); //平台通信任务
- app_BD_task_start(); //北斗通信
- app_voip_task_start(); //voip通信
- app_alarm_task_start(); //报警控制
- app_device_status_task_start(); //系统状态检测
-
- while(1){
- //main_task
- //TODO: ...
- sleep(1);
- }
-
- return 0x00;
-}
-struct{
- uint8_t dummy;
- struct{
- float tem;
- float humdity;
- float volage;
- float current;
- float noise;
- }sensor_data_t;
- struct{
- uint32_t ctrl_dev_power;
- uint32_t speaker_power;
- }ctrl;
-} g_dev;
-
-void app_sensor_task( void *device )
-{
- //sensor init
- //SENSOR A-B-C
- //sensor A init
- //sensor B init
-
- for(;;){
- g_dev.sensor_data.a = sensor_a_get_data();
- g_dev.sensor_data.b = sensor_b_get_data();
- }
-
-}
-
-void app_sensor_task_start( void )
-{
- pthread_start( app_sensor_task, &g_dev );
-}
-
-/*
-接口定义
-
-1. 电压电流传感器, uart接口
-int32_t power_sensor_open( void );
-打开串口,配置参数,
-启动线程,实时更新数据,
-
-int32_t power_sensor_read( power_sensor_data_t read_data );
-读取数据,非堵塞方式,
-
-int32_t power_sensor_close( void );
-关闭,线程
-
-2. 环境温湿度传感器,uart/rs485接口
-int32_t temperature_sensor_open( void );
-打开串口,配置参数,
-启动线程,实时更新数据,
-
-int32_t temperature_sensor_read( power_sensor_data_t read_data );
-读取数据,非堵塞方式,
-
-int32_t temperature_sensor_close( void );
-关闭,线程
-
-3. 声压传感器
-int32_t noise_sensor_open( void );
-打开串口,配置参数,
-启动线程,实时更新数据,
-
-int32_t noise_sensor_read( power_sensor_data_t read_data );
-读取数据,非堵塞方式,
-
-int32_t noise_sensor_close( void );
-关闭,线程
-
-4. alarm control
-报警控制
-
-int32_t alarm_ctrl_init(void );
-初始化
-
-int32_t alarm_ctrl_start( alarm_type )
-启动指定报警音
-
-int32_t alarm_ctrl_keyboard_lock( enable )
-锁定/解锁按键
-
-int32 alarm_ctrl_stop();
-关闭全部报警
-
-int32_t alarm_ctrl_read_status( read_st );
-读取报警器状态
-
-int32_t alarm_ctrl_read_parameter( read_para );
-读取报警器配置参数
-
-int32_t alarm_ctrl_write_parameter( read_para );
-写入报警器配置参数
-
-5. voip
-
-6. ui
-
-7. BD
-
-8. Lora
-
-9. IOT
-
-10. camera
-
-11. ota
-
-*/
-
-
-/*
-设备功能描述
-1. 报警控制器
-1.1 系统结构
- 控制器连接电声警报器,4G/Lora/BD/超短波 四种方式连接平台
- 以下按 输出模块 输入模块 平台通信模块说明
-
-1.1.1 输入
- 接传感器,按键
- 键盘锁定状态下,按键禁用
- 解锁状态下, 通过 按键启动对应的警报声
- 麦克风
-
-1.1.2 输出
- LCD显示, 电声警报器
- 通过警报器接口,控制警报器发声
- LCD显示对应状态
- 喇叭
-
-1.1.3 平台
- 支持远程指令,警报控制,按键锁定,状态读取,语音对讲,语音广播。
- BD/Lora 通信速率低,传输数据量很小,不支持语音功能
-
-1.1.4 语音功能
- 4G通信方式支持, 部署VoIP服务 终端使用PJSIP
-
-需要接口: 需要电声警报器的控制接口定义,
-
-2. 报警系统监测
-2.1 系统结构
- 控制器连接电声警报器,4G/Lora/BD/超短波 四种方式连接平台
- 以下按 输出模块 输入模块 平台通信模块说明
-
-2.1.1 输入
- 接传感器:温湿度 电压电流 声压 拾音器 红外
- 摄像机
- BD定位
-
-2.1.2 输出
- LCD显示, 电声警报器
- 通过警报器接口,控制警报器发声
- LCD显示对应状态
-
-2.1.3 平台
- BD/Lora 通信速率低,传输数据量很小,只能支持有限的指令
- 4G 通信时支持完整功能,包括语音对讲等
-
-
-
-2. 报警系统监测
-
-
-3. 参数管理
-设备编号 16字节
-TCP/IP平台 地址 256字节 端口2字节
-Lora 本地地址16字节, 网关地址16字节, 平台地址16字节, Lora网关模式
-BD 本地地址16字节, 平台地址16字节
-MODE 设备工作模式: 控制器, 监控器,
-Locked 本地锁定
-camera_1 enabled
-camera_2 enabled
-
-g_dev.cfg
-
-4.事件记录
-报警记录, 时间 类型, 记录1年数据
-g_dev.history
-
-设备实时采集数据
- 传感器数据,采集频率1Hz,电压,电流,声压,温度,湿度,红外
-g_dev.measure
-
-设备控制数据
- 控制数据,警报种类,开始时间,控制方式(remote/local)
- 平台连接方式 4G/Lora/BD, 状态 连接/断开
-g_dev.ctrl
-
-控制器主程序 ctrl_main
-void ctrl_main( void )
-{
- device_init();
- while(1){
- sleep(1);
- }
-}
-
-ui.c
- lcd_init()
- keypad_init()
- while(1){
- poll( ui_event )
- switch( ui_event){
- case key_x:
- todo
- break;
- case ui_update:
- todo
- break;
- }
- }
-
- UI显示:
- 工作模式
- 第一行 IDLE 显示时间, 报警时显示状态,
- 第二行 显示电流,电压,温度,速度,
- 底部显示 本机编号 软件版本 网络状态Icon
-
- 长按设置键,进入设置模式
- 菜单, 1. 时间修改, 2. 本机编号
-
-iot.c
- iot_tx_req( char *data, int32_t len, tx_done_cb );
-
- iot_init();
- iot_task()
- while(1){
- if !tx_queue_empty( tx_q)
- tx_pkt = tx_queue_pop( &tx_q )
- iot_tx( tx_pkt )
- if tx_pkt.cb
- tx_pkt.cb()
- if get_iot_pkt( &pkt ) )
- iot_handle(&pkt);
- poll( tx_pkt, rx_pkt );
- }
-
-*/
-
--- /dev/null
+/*
+ Copyright (c) 2009-2017 Dave Gamble and cJSON contributors
+
+ Permission is hereby granted, free of charge, to any person obtaining a copy
+ of this software and associated documentation files (the "Software"), to deal
+ in the Software without restriction, including without limitation the rights
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ copies of the Software, and to permit persons to whom the Software is
+ furnished to do so, subject to the following conditions:
+
+ The above copyright notice and this permission notice shall be included in
+ all copies or substantial portions of the Software.
+
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ THE SOFTWARE.
+*/
+
+/* cJSON */
+/* JSON parser in C. */
+
+/* disable warnings about old C89 functions in MSVC */
+#if !defined(_CRT_SECURE_NO_DEPRECATE) && defined(_MSC_VER)
+#define _CRT_SECURE_NO_DEPRECATE
+#endif
+
+#ifdef __GNUC__
+#pragma GCC visibility push(default)
+#endif
+#if defined(_MSC_VER)
+#pragma warning (push)
+/* disable warning about single line comments in system headers */
+#pragma warning (disable : 4001)
+#endif
+
+#include <string.h>
+#include <stdio.h>
+#include <math.h>
+#include <stdlib.h>
+#include <limits.h>
+#include <ctype.h>
+
+#ifdef ENABLE_LOCALES
+#include <locale.h>
+#endif
+
+#if defined(_MSC_VER)
+#pragma warning (pop)
+#endif
+#ifdef __GNUC__
+#pragma GCC visibility pop
+#endif
+
+#include "cJSON.h"
+
+/* define our own boolean type */
+#ifdef true
+#undef true
+#endif
+#define true ((cJSON_bool)1)
+
+#ifdef false
+#undef false
+#endif
+#define false ((cJSON_bool)0)
+
+typedef struct {
+ const unsigned char *json;
+ size_t position;
+} error;
+static error global_error = { NULL, 0 };
+
+CJSON_PUBLIC(const char *) cJSON_GetErrorPtr(void)
+{
+ return (const char*) (global_error.json + global_error.position);
+}
+
+CJSON_PUBLIC(char *) cJSON_GetStringValue(const cJSON * const item) {
+ if (!cJSON_IsString(item)) {
+ return NULL;
+ }
+
+ return item->valuestring;
+}
+
+/* This is a safeguard to prevent copy-pasters from using incompatible C and header files */
+#if (CJSON_VERSION_MAJOR != 1) || (CJSON_VERSION_MINOR != 7) || (CJSON_VERSION_PATCH != 12)
+ #error cJSON.h and cJSON.c have different versions. Make sure that both have the same.
+#endif
+
+CJSON_PUBLIC(const char*) cJSON_Version(void)
+{
+ static char version[15];
+ sprintf(version, "%i.%i.%i", CJSON_VERSION_MAJOR, CJSON_VERSION_MINOR, CJSON_VERSION_PATCH);
+
+ return version;
+}
+
+/* Case insensitive string comparison, doesn't consider two NULL pointers equal though */
+static int case_insensitive_strcmp(const unsigned char *string1, const unsigned char *string2)
+{
+ if ((string1 == NULL) || (string2 == NULL))
+ {
+ return 1;
+ }
+
+ if (string1 == string2)
+ {
+ return 0;
+ }
+
+ for(; tolower(*string1) == tolower(*string2); (void)string1++, string2++)
+ {
+ if (*string1 == '\0')
+ {
+ return 0;
+ }
+ }
+
+ return tolower(*string1) - tolower(*string2);
+}
+
+typedef struct internal_hooks
+{
+ void *(CJSON_CDECL *allocate)(size_t size);
+ void (CJSON_CDECL *deallocate)(void *pointer);
+ void *(CJSON_CDECL *reallocate)(void *pointer, size_t size);
+} internal_hooks;
+
+#if defined(_MSC_VER)
+/* work around MSVC error C2322: '...' address of dllimport '...' is not static */
+static void * CJSON_CDECL internal_malloc(size_t size)
+{
+ return malloc(size);
+}
+static void CJSON_CDECL internal_free(void *pointer)
+{
+ free(pointer);
+}
+static void * CJSON_CDECL internal_realloc(void *pointer, size_t size)
+{
+ return realloc(pointer, size);
+}
+#else
+#define internal_malloc malloc
+#define internal_free free
+#define internal_realloc realloc
+#endif
+
+/* strlen of character literals resolved at compile time */
+#define static_strlen(string_literal) (sizeof(string_literal) - sizeof(""))
+
+static internal_hooks global_hooks = { internal_malloc, internal_free, internal_realloc };
+
+static unsigned char* cJSON_strdup(const unsigned char* string, const internal_hooks * const hooks)
+{
+ size_t length = 0;
+ unsigned char *copy = NULL;
+
+ if (string == NULL)
+ {
+ return NULL;
+ }
+
+ length = strlen((const char*)string) + sizeof("");
+ copy = (unsigned char*)hooks->allocate(length);
+ if (copy == NULL)
+ {
+ return NULL;
+ }
+ memcpy(copy, string, length);
+
+ return copy;
+}
+
+CJSON_PUBLIC(void) cJSON_InitHooks(cJSON_Hooks* hooks)
+{
+ if (hooks == NULL)
+ {
+ /* Reset hooks */
+ global_hooks.allocate = malloc;
+ global_hooks.deallocate = free;
+ global_hooks.reallocate = realloc;
+ return;
+ }
+
+ global_hooks.allocate = malloc;
+ if (hooks->malloc_fn != NULL)
+ {
+ global_hooks.allocate = hooks->malloc_fn;
+ }
+
+ global_hooks.deallocate = free;
+ if (hooks->free_fn != NULL)
+ {
+ global_hooks.deallocate = hooks->free_fn;
+ }
+
+ /* use realloc only if both free and malloc are used */
+ global_hooks.reallocate = NULL;
+ if ((global_hooks.allocate == malloc) && (global_hooks.deallocate == free))
+ {
+ global_hooks.reallocate = realloc;
+ }
+}
+
+/* Internal constructor. */
+static cJSON *cJSON_New_Item(const internal_hooks * const hooks)
+{
+ cJSON* node = (cJSON*)hooks->allocate(sizeof(cJSON));
+ if (node)
+ {
+ memset(node, '\0', sizeof(cJSON));
+ }
+
+ return node;
+}
+
+/* Delete a cJSON structure. */
+CJSON_PUBLIC(void) cJSON_Delete(cJSON *item)
+{
+ cJSON *next = NULL;
+ while (item != NULL)
+ {
+ next = item->next;
+ if (!(item->type & cJSON_IsReference) && (item->child != NULL))
+ {
+ cJSON_Delete(item->child);
+ }
+ if (!(item->type & cJSON_IsReference) && (item->valuestring != NULL))
+ {
+ global_hooks.deallocate(item->valuestring);
+ }
+ if (!(item->type & cJSON_StringIsConst) && (item->string != NULL))
+ {
+ global_hooks.deallocate(item->string);
+ }
+ global_hooks.deallocate(item);
+ item = next;
+ }
+}
+
+/* get the decimal point character of the current locale */
+static unsigned char get_decimal_point(void)
+{
+#ifdef ENABLE_LOCALES
+ struct lconv *lconv = localeconv();
+ return (unsigned char) lconv->decimal_point[0];
+#else
+ return '.';
+#endif
+}
+
+typedef struct
+{
+ const unsigned char *content;
+ size_t length;
+ size_t offset;
+ size_t depth; /* How deeply nested (in arrays/objects) is the input at the current offset. */
+ internal_hooks hooks;
+} parse_buffer;
+
+/* check if the given size is left to read in a given parse buffer (starting with 1) */
+#define can_read(buffer, size) ((buffer != NULL) && (((buffer)->offset + size) <= (buffer)->length))
+/* check if the buffer can be accessed at the given index (starting with 0) */
+#define can_access_at_index(buffer, index) ((buffer != NULL) && (((buffer)->offset + index) < (buffer)->length))
+#define cannot_access_at_index(buffer, index) (!can_access_at_index(buffer, index))
+/* get a pointer to the buffer at the position */
+#define buffer_at_offset(buffer) ((buffer)->content + (buffer)->offset)
+
+/* Parse the input text to generate a number, and populate the result into item. */
+static cJSON_bool parse_number(cJSON * const item, parse_buffer * const input_buffer)
+{
+ double number = 0;
+ unsigned char *after_end = NULL;
+ unsigned char number_c_string[64];
+ unsigned char decimal_point = get_decimal_point();
+ size_t i = 0;
+
+ if ((input_buffer == NULL) || (input_buffer->content == NULL))
+ {
+ return false;
+ }
+
+ /* copy the number into a temporary buffer and replace '.' with the decimal point
+ * of the current locale (for strtod)
+ * This also takes care of '\0' not necessarily being available for marking the end of the input */
+ for (i = 0; (i < (sizeof(number_c_string) - 1)) && can_access_at_index(input_buffer, i); i++)
+ {
+ switch (buffer_at_offset(input_buffer)[i])
+ {
+ case '0':
+ case '1':
+ case '2':
+ case '3':
+ case '4':
+ case '5':
+ case '6':
+ case '7':
+ case '8':
+ case '9':
+ case '+':
+ case '-':
+ case 'e':
+ case 'E':
+ number_c_string[i] = buffer_at_offset(input_buffer)[i];
+ break;
+
+ case '.':
+ number_c_string[i] = decimal_point;
+ break;
+
+ default:
+ goto loop_end;
+ }
+ }
+loop_end:
+ number_c_string[i] = '\0';
+
+ number = strtod((const char*)number_c_string, (char**)&after_end);
+ if (number_c_string == after_end)
+ {
+ return false; /* parse_error */
+ }
+
+ item->valuedouble = number;
+
+ /* use saturation in case of overflow */
+ if (number >= INT_MAX)
+ {
+ item->valueint = INT_MAX;
+ }
+ else if (number <= (double)INT_MIN)
+ {
+ item->valueint = INT_MIN;
+ }
+ else
+ {
+ item->valueint = (int)number;
+ }
+
+ item->type = cJSON_Number;
+
+ input_buffer->offset += (size_t)(after_end - number_c_string);
+ return true;
+}
+
+/* don't ask me, but the original cJSON_SetNumberValue returns an integer or double */
+CJSON_PUBLIC(double) cJSON_SetNumberHelper(cJSON *object, double number)
+{
+ if (number >= INT_MAX)
+ {
+ object->valueint = INT_MAX;
+ }
+ else if (number <= (double)INT_MIN)
+ {
+ object->valueint = INT_MIN;
+ }
+ else
+ {
+ object->valueint = (int)number;
+ }
+
+ return object->valuedouble = number;
+}
+
+typedef struct
+{
+ unsigned char *buffer;
+ size_t length;
+ size_t offset;
+ size_t depth; /* current nesting depth (for formatted printing) */
+ cJSON_bool noalloc;
+ cJSON_bool format; /* is this print a formatted print */
+ internal_hooks hooks;
+} printbuffer;
+
+/* realloc printbuffer if necessary to have at least "needed" bytes more */
+static unsigned char* ensure(printbuffer * const p, size_t needed)
+{
+ unsigned char *newbuffer = NULL;
+ size_t newsize = 0;
+
+ if ((p == NULL) || (p->buffer == NULL))
+ {
+ return NULL;
+ }
+
+ if ((p->length > 0) && (p->offset >= p->length))
+ {
+ /* make sure that offset is valid */
+ return NULL;
+ }
+
+ if (needed > INT_MAX)
+ {
+ /* sizes bigger than INT_MAX are currently not supported */
+ return NULL;
+ }
+
+ needed += p->offset + 1;
+ if (needed <= p->length)
+ {
+ return p->buffer + p->offset;
+ }
+
+ if (p->noalloc) {
+ return NULL;
+ }
+
+ /* calculate new buffer size */
+ if (needed > (INT_MAX / 2))
+ {
+ /* overflow of int, use INT_MAX if possible */
+ if (needed <= INT_MAX)
+ {
+ newsize = INT_MAX;
+ }
+ else
+ {
+ return NULL;
+ }
+ }
+ else
+ {
+ newsize = needed * 2;
+ }
+
+ if (p->hooks.reallocate != NULL)
+ {
+ /* reallocate with realloc if available */
+ newbuffer = (unsigned char*)p->hooks.reallocate(p->buffer, newsize);
+ if (newbuffer == NULL)
+ {
+ p->hooks.deallocate(p->buffer);
+ p->length = 0;
+ p->buffer = NULL;
+
+ return NULL;
+ }
+ }
+ else
+ {
+ /* otherwise reallocate manually */
+ newbuffer = (unsigned char*)p->hooks.allocate(newsize);
+ if (!newbuffer)
+ {
+ p->hooks.deallocate(p->buffer);
+ p->length = 0;
+ p->buffer = NULL;
+
+ return NULL;
+ }
+ if (newbuffer)
+ {
+ memcpy(newbuffer, p->buffer, p->offset + 1);
+ }
+ p->hooks.deallocate(p->buffer);
+ }
+ p->length = newsize;
+ p->buffer = newbuffer;
+
+ return newbuffer + p->offset;
+}
+
+/* calculate the new length of the string in a printbuffer and update the offset */
+static void update_offset(printbuffer * const buffer)
+{
+ const unsigned char *buffer_pointer = NULL;
+ if ((buffer == NULL) || (buffer->buffer == NULL))
+ {
+ return;
+ }
+ buffer_pointer = buffer->buffer + buffer->offset;
+
+ buffer->offset += strlen((const char*)buffer_pointer);
+}
+
+/* securely comparison of floating-point variables */
+static cJSON_bool compare_double(double a, double b)
+{
+ return (fabs(a - b) <= CJSON_DOUBLE_PRECISION);
+}
+
+/* Render the number nicely from the given item into a string. */
+static cJSON_bool print_number(const cJSON * const item, printbuffer * const output_buffer)
+{
+ unsigned char *output_pointer = NULL;
+ double d = item->valuedouble;
+ int length = 0;
+ size_t i = 0;
+ unsigned char number_buffer[26] = {0}; /* temporary buffer to print the number into */
+ unsigned char decimal_point = get_decimal_point();
+ double test = 0.0;
+
+ if (output_buffer == NULL)
+ {
+ return false;
+ }
+
+ /* This checks for NaN and Infinity */
+ if ((d * 0) != 0)
+ {
+ length = sprintf((char*)number_buffer, "null");
+ }
+ else
+ {
+ /* Try 15 decimal places of precision to avoid nonsignificant nonzero digits */
+ length = sprintf((char*)number_buffer, "%1.15g", d);
+
+ /* Check whether the original double can be recovered */
+ if ((sscanf((char*)number_buffer, "%lg", &test) != 1) || !compare_double((double)test, d))
+ {
+ /* If not, print with 17 decimal places of precision */
+ length = sprintf((char*)number_buffer, "%1.17g", d);
+ }
+ }
+
+ /* sprintf failed or buffer overrun occurred */
+ if ((length < 0) || (length > (int)(sizeof(number_buffer) - 1)))
+ {
+ return false;
+ }
+
+ /* reserve appropriate space in the output */
+ output_pointer = ensure(output_buffer, (size_t)length + sizeof(""));
+ if (output_pointer == NULL)
+ {
+ return false;
+ }
+
+ /* copy the printed number to the output and replace locale
+ * dependent decimal point with '.' */
+ for (i = 0; i < ((size_t)length); i++)
+ {
+ if (number_buffer[i] == decimal_point)
+ {
+ output_pointer[i] = '.';
+ continue;
+ }
+
+ output_pointer[i] = number_buffer[i];
+ }
+ output_pointer[i] = '\0';
+
+ output_buffer->offset += (size_t)length;
+
+ return true;
+}
+
+/* parse 4 digit hexadecimal number */
+static unsigned parse_hex4(const unsigned char * const input)
+{
+ unsigned int h = 0;
+ size_t i = 0;
+
+ for (i = 0; i < 4; i++)
+ {
+ /* parse digit */
+ if ((input[i] >= '0') && (input[i] <= '9'))
+ {
+ h += (unsigned int) input[i] - '0';
+ }
+ else if ((input[i] >= 'A') && (input[i] <= 'F'))
+ {
+ h += (unsigned int) 10 + input[i] - 'A';
+ }
+ else if ((input[i] >= 'a') && (input[i] <= 'f'))
+ {
+ h += (unsigned int) 10 + input[i] - 'a';
+ }
+ else /* invalid */
+ {
+ return 0;
+ }
+
+ if (i < 3)
+ {
+ /* shift left to make place for the next nibble */
+ h = h << 4;
+ }
+ }
+
+ return h;
+}
+
+/* converts a UTF-16 literal to UTF-8
+ * A literal can be one or two sequences of the form \uXXXX */
+static unsigned char utf16_literal_to_utf8(const unsigned char * const input_pointer, const unsigned char * const input_end, unsigned char **output_pointer)
+{
+ long unsigned int codepoint = 0;
+ unsigned int first_code = 0;
+ const unsigned char *first_sequence = input_pointer;
+ unsigned char utf8_length = 0;
+ unsigned char utf8_position = 0;
+ unsigned char sequence_length = 0;
+ unsigned char first_byte_mark = 0;
+
+ if ((input_end - first_sequence) < 6)
+ {
+ /* input ends unexpectedly */
+ goto fail;
+ }
+
+ /* get the first utf16 sequence */
+ first_code = parse_hex4(first_sequence + 2);
+
+ /* check that the code is valid */
+ if (((first_code >= 0xDC00) && (first_code <= 0xDFFF)))
+ {
+ goto fail;
+ }
+
+ /* UTF16 surrogate pair */
+ if ((first_code >= 0xD800) && (first_code <= 0xDBFF))
+ {
+ const unsigned char *second_sequence = first_sequence + 6;
+ unsigned int second_code = 0;
+ sequence_length = 12; /* \uXXXX\uXXXX */
+
+ if ((input_end - second_sequence) < 6)
+ {
+ /* input ends unexpectedly */
+ goto fail;
+ }
+
+ if ((second_sequence[0] != '\\') || (second_sequence[1] != 'u'))
+ {
+ /* missing second half of the surrogate pair */
+ goto fail;
+ }
+
+ /* get the second utf16 sequence */
+ second_code = parse_hex4(second_sequence + 2);
+ /* check that the code is valid */
+ if ((second_code < 0xDC00) || (second_code > 0xDFFF))
+ {
+ /* invalid second half of the surrogate pair */
+ goto fail;
+ }
+
+
+ /* calculate the unicode codepoint from the surrogate pair */
+ codepoint = 0x10000 + (((first_code & 0x3FF) << 10) | (second_code & 0x3FF));
+ }
+ else
+ {
+ sequence_length = 6; /* \uXXXX */
+ codepoint = first_code;
+ }
+
+ /* encode as UTF-8
+ * takes at maximum 4 bytes to encode:
+ * 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx */
+ if (codepoint < 0x80)
+ {
+ /* normal ascii, encoding 0xxxxxxx */
+ utf8_length = 1;
+ }
+ else if (codepoint < 0x800)
+ {
+ /* two bytes, encoding 110xxxxx 10xxxxxx */
+ utf8_length = 2;
+ first_byte_mark = 0xC0; /* 11000000 */
+ }
+ else if (codepoint < 0x10000)
+ {
+ /* three bytes, encoding 1110xxxx 10xxxxxx 10xxxxxx */
+ utf8_length = 3;
+ first_byte_mark = 0xE0; /* 11100000 */
+ }
+ else if (codepoint <= 0x10FFFF)
+ {
+ /* four bytes, encoding 1110xxxx 10xxxxxx 10xxxxxx 10xxxxxx */
+ utf8_length = 4;
+ first_byte_mark = 0xF0; /* 11110000 */
+ }
+ else
+ {
+ /* invalid unicode codepoint */
+ goto fail;
+ }
+
+ /* encode as utf8 */
+ for (utf8_position = (unsigned char)(utf8_length - 1); utf8_position > 0; utf8_position--)
+ {
+ /* 10xxxxxx */
+ (*output_pointer)[utf8_position] = (unsigned char)((codepoint | 0x80) & 0xBF);
+ codepoint >>= 6;
+ }
+ /* encode first byte */
+ if (utf8_length > 1)
+ {
+ (*output_pointer)[0] = (unsigned char)((codepoint | first_byte_mark) & 0xFF);
+ }
+ else
+ {
+ (*output_pointer)[0] = (unsigned char)(codepoint & 0x7F);
+ }
+
+ *output_pointer += utf8_length;
+
+ return sequence_length;
+
+fail:
+ return 0;
+}
+
+/* Parse the input text into an unescaped cinput, and populate item. */
+static cJSON_bool parse_string(cJSON * const item, parse_buffer * const input_buffer)
+{
+ const unsigned char *input_pointer = buffer_at_offset(input_buffer) + 1;
+ const unsigned char *input_end = buffer_at_offset(input_buffer) + 1;
+ unsigned char *output_pointer = NULL;
+ unsigned char *output = NULL;
+
+ /* not a string */
+ if (buffer_at_offset(input_buffer)[0] != '\"')
+ {
+ goto fail;
+ }
+
+ {
+ /* calculate approximate size of the output (overestimate) */
+ size_t allocation_length = 0;
+ size_t skipped_bytes = 0;
+ while (((size_t)(input_end - input_buffer->content) < input_buffer->length) && (*input_end != '\"'))
+ {
+ /* is escape sequence */
+ if (input_end[0] == '\\')
+ {
+ if ((size_t)(input_end + 1 - input_buffer->content) >= input_buffer->length)
+ {
+ /* prevent buffer overflow when last input character is a backslash */
+ goto fail;
+ }
+ skipped_bytes++;
+ input_end++;
+ }
+ input_end++;
+ }
+ if (((size_t)(input_end - input_buffer->content) >= input_buffer->length) || (*input_end != '\"'))
+ {
+ goto fail; /* string ended unexpectedly */
+ }
+
+ /* This is at most how much we need for the output */
+ allocation_length = (size_t) (input_end - buffer_at_offset(input_buffer)) - skipped_bytes;
+ output = (unsigned char*)input_buffer->hooks.allocate(allocation_length + sizeof(""));
+ if (output == NULL)
+ {
+ goto fail; /* allocation failure */
+ }
+ }
+
+ output_pointer = output;
+ /* loop through the string literal */
+ while (input_pointer < input_end)
+ {
+ if (*input_pointer != '\\')
+ {
+ *output_pointer++ = *input_pointer++;
+ }
+ /* escape sequence */
+ else
+ {
+ unsigned char sequence_length = 2;
+ if ((input_end - input_pointer) < 1)
+ {
+ goto fail;
+ }
+
+ switch (input_pointer[1])
+ {
+ case 'b':
+ *output_pointer++ = '\b';
+ break;
+ case 'f':
+ *output_pointer++ = '\f';
+ break;
+ case 'n':
+ *output_pointer++ = '\n';
+ break;
+ case 'r':
+ *output_pointer++ = '\r';
+ break;
+ case 't':
+ *output_pointer++ = '\t';
+ break;
+ case '\"':
+ case '\\':
+ case '/':
+ *output_pointer++ = input_pointer[1];
+ break;
+
+ /* UTF-16 literal */
+ case 'u':
+ sequence_length = utf16_literal_to_utf8(input_pointer, input_end, &output_pointer);
+ if (sequence_length == 0)
+ {
+ /* failed to convert UTF16-literal to UTF-8 */
+ goto fail;
+ }
+ break;
+
+ default:
+ goto fail;
+ }
+ input_pointer += sequence_length;
+ }
+ }
+
+ /* zero terminate the output */
+ *output_pointer = '\0';
+
+ item->type = cJSON_String;
+ item->valuestring = (char*)output;
+
+ input_buffer->offset = (size_t) (input_end - input_buffer->content);
+ input_buffer->offset++;
+
+ return true;
+
+fail:
+ if (output != NULL)
+ {
+ input_buffer->hooks.deallocate(output);
+ }
+
+ if (input_pointer != NULL)
+ {
+ input_buffer->offset = (size_t)(input_pointer - input_buffer->content);
+ }
+
+ return false;
+}
+
+/* Render the cstring provided to an escaped version that can be printed. */
+static cJSON_bool print_string_ptr(const unsigned char * const input, printbuffer * const output_buffer)
+{
+ const unsigned char *input_pointer = NULL;
+ unsigned char *output = NULL;
+ unsigned char *output_pointer = NULL;
+ size_t output_length = 0;
+ /* numbers of additional characters needed for escaping */
+ size_t escape_characters = 0;
+
+ if (output_buffer == NULL)
+ {
+ return false;
+ }
+
+ /* empty string */
+ if (input == NULL)
+ {
+ output = ensure(output_buffer, sizeof("\"\""));
+ if (output == NULL)
+ {
+ return false;
+ }
+ strcpy((char*)output, "\"\"");
+
+ return true;
+ }
+
+ /* set "flag" to 1 if something needs to be escaped */
+ for (input_pointer = input; *input_pointer; input_pointer++)
+ {
+ switch (*input_pointer)
+ {
+ case '\"':
+ case '\\':
+ case '\b':
+ case '\f':
+ case '\n':
+ case '\r':
+ case '\t':
+ /* one character escape sequence */
+ escape_characters++;
+ break;
+ default:
+ if (*input_pointer < 32)
+ {
+ /* UTF-16 escape sequence uXXXX */
+ escape_characters += 5;
+ }
+ break;
+ }
+ }
+ output_length = (size_t)(input_pointer - input) + escape_characters;
+
+ output = ensure(output_buffer, output_length + sizeof("\"\""));
+ if (output == NULL)
+ {
+ return false;
+ }
+
+ /* no characters have to be escaped */
+ if (escape_characters == 0)
+ {
+ output[0] = '\"';
+ memcpy(output + 1, input, output_length);
+ output[output_length + 1] = '\"';
+ output[output_length + 2] = '\0';
+
+ return true;
+ }
+
+ output[0] = '\"';
+ output_pointer = output + 1;
+ /* copy the string */
+ for (input_pointer = input; *input_pointer != '\0'; (void)input_pointer++, output_pointer++)
+ {
+ if ((*input_pointer > 31) && (*input_pointer != '\"') && (*input_pointer != '\\'))
+ {
+ /* normal character, copy */
+ *output_pointer = *input_pointer;
+ }
+ else
+ {
+ /* character needs to be escaped */
+ *output_pointer++ = '\\';
+ switch (*input_pointer)
+ {
+ case '\\':
+ *output_pointer = '\\';
+ break;
+ case '\"':
+ *output_pointer = '\"';
+ break;
+ case '\b':
+ *output_pointer = 'b';
+ break;
+ case '\f':
+ *output_pointer = 'f';
+ break;
+ case '\n':
+ *output_pointer = 'n';
+ break;
+ case '\r':
+ *output_pointer = 'r';
+ break;
+ case '\t':
+ *output_pointer = 't';
+ break;
+ default:
+ /* escape and print as unicode codepoint */
+ sprintf((char*)output_pointer, "u%04x", *input_pointer);
+ output_pointer += 4;
+ break;
+ }
+ }
+ }
+ output[output_length + 1] = '\"';
+ output[output_length + 2] = '\0';
+
+ return true;
+}
+
+/* Invoke print_string_ptr (which is useful) on an item. */
+static cJSON_bool print_string(const cJSON * const item, printbuffer * const p)
+{
+ return print_string_ptr((unsigned char*)item->valuestring, p);
+}
+
+/* Predeclare these prototypes. */
+static cJSON_bool parse_value(cJSON * const item, parse_buffer * const input_buffer);
+static cJSON_bool print_value(const cJSON * const item, printbuffer * const output_buffer);
+static cJSON_bool parse_array(cJSON * const item, parse_buffer * const input_buffer);
+static cJSON_bool print_array(const cJSON * const item, printbuffer * const output_buffer);
+static cJSON_bool parse_object(cJSON * const item, parse_buffer * const input_buffer);
+static cJSON_bool print_object(const cJSON * const item, printbuffer * const output_buffer);
+
+/* Utility to jump whitespace and cr/lf */
+static parse_buffer *buffer_skip_whitespace(parse_buffer * const buffer)
+{
+ if ((buffer == NULL) || (buffer->content == NULL))
+ {
+ return NULL;
+ }
+
+ while (can_access_at_index(buffer, 0) && (buffer_at_offset(buffer)[0] <= 32))
+ {
+ buffer->offset++;
+ }
+
+ if (buffer->offset == buffer->length)
+ {
+ buffer->offset--;
+ }
+
+ return buffer;
+}
+
+/* skip the UTF-8 BOM (byte order mark) if it is at the beginning of a buffer */
+static parse_buffer *skip_utf8_bom(parse_buffer * const buffer)
+{
+ if ((buffer == NULL) || (buffer->content == NULL) || (buffer->offset != 0))
+ {
+ return NULL;
+ }
+
+ if (can_access_at_index(buffer, 4) && (strncmp((const char*)buffer_at_offset(buffer), "\xEF\xBB\xBF", 3) == 0))
+ {
+ buffer->offset += 3;
+ }
+
+ return buffer;
+}
+
+/* Parse an object - create a new root, and populate. */
+CJSON_PUBLIC(cJSON *) cJSON_ParseWithOpts(const char *value, const char **return_parse_end, cJSON_bool require_null_terminated)
+{
+ parse_buffer buffer = { 0, 0, 0, 0, { 0, 0, 0 } };
+ cJSON *item = NULL;
+
+ /* reset error position */
+ global_error.json = NULL;
+ global_error.position = 0;
+
+ if (value == NULL)
+ {
+ goto fail;
+ }
+
+ buffer.content = (const unsigned char*)value;
+ buffer.length = strlen((const char*)value) + sizeof("");
+ buffer.offset = 0;
+ buffer.hooks = global_hooks;
+
+ item = cJSON_New_Item(&global_hooks);
+ if (item == NULL) /* memory fail */
+ {
+ goto fail;
+ }
+
+ if (!parse_value(item, buffer_skip_whitespace(skip_utf8_bom(&buffer))))
+ {
+ /* parse failure. ep is set. */
+ goto fail;
+ }
+
+ /* if we require null-terminated JSON without appended garbage, skip and then check for a null terminator */
+ if (require_null_terminated)
+ {
+ buffer_skip_whitespace(&buffer);
+ if ((buffer.offset >= buffer.length) || buffer_at_offset(&buffer)[0] != '\0')
+ {
+ goto fail;
+ }
+ }
+ if (return_parse_end)
+ {
+ *return_parse_end = (const char*)buffer_at_offset(&buffer);
+ }
+
+ return item;
+
+fail:
+ if (item != NULL)
+ {
+ cJSON_Delete(item);
+ }
+
+ if (value != NULL)
+ {
+ error local_error;
+ local_error.json = (const unsigned char*)value;
+ local_error.position = 0;
+
+ if (buffer.offset < buffer.length)
+ {
+ local_error.position = buffer.offset;
+ }
+ else if (buffer.length > 0)
+ {
+ local_error.position = buffer.length - 1;
+ }
+
+ if (return_parse_end != NULL)
+ {
+ *return_parse_end = (const char*)local_error.json + local_error.position;
+ }
+
+ global_error = local_error;
+ }
+
+ return NULL;
+}
+
+/* Default options for cJSON_Parse */
+CJSON_PUBLIC(cJSON *) cJSON_Parse(const char *value)
+{
+ return cJSON_ParseWithOpts(value, 0, 0);
+}
+
+#define cjson_min(a, b) ((a < b) ? a : b)
+
+static unsigned char *print(const cJSON * const item, cJSON_bool format, const internal_hooks * const hooks)
+{
+ static const size_t default_buffer_size = 256;
+ printbuffer buffer[1];
+ unsigned char *printed = NULL;
+
+ memset(buffer, 0, sizeof(buffer));
+
+ /* create buffer */
+ buffer->buffer = (unsigned char*) hooks->allocate(default_buffer_size);
+ buffer->length = default_buffer_size;
+ buffer->format = format;
+ buffer->hooks = *hooks;
+ if (buffer->buffer == NULL)
+ {
+ goto fail;
+ }
+
+ /* print the value */
+ if (!print_value(item, buffer))
+ {
+ goto fail;
+ }
+ update_offset(buffer);
+
+ /* check if reallocate is available */
+ if (hooks->reallocate != NULL)
+ {
+ printed = (unsigned char*) hooks->reallocate(buffer->buffer, buffer->offset + 1);
+ if (printed == NULL) {
+ goto fail;
+ }
+ buffer->buffer = NULL;
+ }
+ else /* otherwise copy the JSON over to a new buffer */
+ {
+ printed = (unsigned char*) hooks->allocate(buffer->offset + 1);
+ if (printed == NULL)
+ {
+ goto fail;
+ }
+ memcpy(printed, buffer->buffer, cjson_min(buffer->length, buffer->offset + 1));
+ printed[buffer->offset] = '\0'; /* just to be sure */
+
+ /* free the buffer */
+ hooks->deallocate(buffer->buffer);
+ }
+
+ return printed;
+
+fail:
+ if (buffer->buffer != NULL)
+ {
+ hooks->deallocate(buffer->buffer);
+ }
+
+ if (printed != NULL)
+ {
+ hooks->deallocate(printed);
+ }
+
+ return NULL;
+}
+
+/* Render a cJSON item/entity/structure to text. */
+CJSON_PUBLIC(char *) cJSON_Print(const cJSON *item)
+{
+ return (char*)print(item, true, &global_hooks);
+}
+
+CJSON_PUBLIC(char *) cJSON_PrintUnformatted(const cJSON *item)
+{
+ return (char*)print(item, false, &global_hooks);
+}
+
+CJSON_PUBLIC(char *) cJSON_PrintBuffered(const cJSON *item, int prebuffer, cJSON_bool fmt)
+{
+ printbuffer p = { 0, 0, 0, 0, 0, 0, { 0, 0, 0 } };
+
+ if (prebuffer < 0)
+ {
+ return NULL;
+ }
+
+ p.buffer = (unsigned char*)global_hooks.allocate((size_t)prebuffer);
+ if (!p.buffer)
+ {
+ return NULL;
+ }
+
+ p.length = (size_t)prebuffer;
+ p.offset = 0;
+ p.noalloc = false;
+ p.format = fmt;
+ p.hooks = global_hooks;
+
+ if (!print_value(item, &p))
+ {
+ global_hooks.deallocate(p.buffer);
+ return NULL;
+ }
+
+ return (char*)p.buffer;
+}
+
+CJSON_PUBLIC(cJSON_bool) cJSON_PrintPreallocated(cJSON *item, char *buffer, const int length, const cJSON_bool format)
+{
+ printbuffer p = { 0, 0, 0, 0, 0, 0, { 0, 0, 0 } };
+
+ if ((length < 0) || (buffer == NULL))
+ {
+ return false;
+ }
+
+ p.buffer = (unsigned char*)buffer;
+ p.length = (size_t)length;
+ p.offset = 0;
+ p.noalloc = true;
+ p.format = format;
+ p.hooks = global_hooks;
+
+ return print_value(item, &p);
+}
+
+/* Parser core - when encountering text, process appropriately. */
+static cJSON_bool parse_value(cJSON * const item, parse_buffer * const input_buffer)
+{
+ if ((input_buffer == NULL) || (input_buffer->content == NULL))
+ {
+ return false; /* no input */
+ }
+
+ /* parse the different types of values */
+ /* null */
+ if (can_read(input_buffer, 4) && (strncmp((const char*)buffer_at_offset(input_buffer), "null", 4) == 0))
+ {
+ item->type = cJSON_NULL;
+ input_buffer->offset += 4;
+ return true;
+ }
+ /* false */
+ if (can_read(input_buffer, 5) && (strncmp((const char*)buffer_at_offset(input_buffer), "false", 5) == 0))
+ {
+ item->type = cJSON_False;
+ input_buffer->offset += 5;
+ return true;
+ }
+ /* true */
+ if (can_read(input_buffer, 4) && (strncmp((const char*)buffer_at_offset(input_buffer), "true", 4) == 0))
+ {
+ item->type = cJSON_True;
+ item->valueint = 1;
+ input_buffer->offset += 4;
+ return true;
+ }
+ /* string */
+ if (can_access_at_index(input_buffer, 0) && (buffer_at_offset(input_buffer)[0] == '\"'))
+ {
+ return parse_string(item, input_buffer);
+ }
+ /* number */
+ if (can_access_at_index(input_buffer, 0) && ((buffer_at_offset(input_buffer)[0] == '-') || ((buffer_at_offset(input_buffer)[0] >= '0') && (buffer_at_offset(input_buffer)[0] <= '9'))))
+ {
+ return parse_number(item, input_buffer);
+ }
+ /* array */
+ if (can_access_at_index(input_buffer, 0) && (buffer_at_offset(input_buffer)[0] == '['))
+ {
+ return parse_array(item, input_buffer);
+ }
+ /* object */
+ if (can_access_at_index(input_buffer, 0) && (buffer_at_offset(input_buffer)[0] == '{'))
+ {
+ return parse_object(item, input_buffer);
+ }
+
+ return false;
+}
+
+/* Render a value to text. */
+static cJSON_bool print_value(const cJSON * const item, printbuffer * const output_buffer)
+{
+ unsigned char *output = NULL;
+
+ if ((item == NULL) || (output_buffer == NULL))
+ {
+ return false;
+ }
+
+ switch ((item->type) & 0xFF)
+ {
+ case cJSON_NULL:
+ output = ensure(output_buffer, 5);
+ if (output == NULL)
+ {
+ return false;
+ }
+ strcpy((char*)output, "null");
+ return true;
+
+ case cJSON_False:
+ output = ensure(output_buffer, 6);
+ if (output == NULL)
+ {
+ return false;
+ }
+ strcpy((char*)output, "false");
+ return true;
+
+ case cJSON_True:
+ output = ensure(output_buffer, 5);
+ if (output == NULL)
+ {
+ return false;
+ }
+ strcpy((char*)output, "true");
+ return true;
+
+ case cJSON_Number:
+ return print_number(item, output_buffer);
+
+ case cJSON_Raw:
+ {
+ size_t raw_length = 0;
+ if (item->valuestring == NULL)
+ {
+ return false;
+ }
+
+ raw_length = strlen(item->valuestring) + sizeof("");
+ output = ensure(output_buffer, raw_length);
+ if (output == NULL)
+ {
+ return false;
+ }
+ memcpy(output, item->valuestring, raw_length);
+ return true;
+ }
+
+ case cJSON_String:
+ return print_string(item, output_buffer);
+
+ case cJSON_Array:
+ return print_array(item, output_buffer);
+
+ case cJSON_Object:
+ return print_object(item, output_buffer);
+
+ default:
+ return false;
+ }
+}
+
+/* Build an array from input text. */
+static cJSON_bool parse_array(cJSON * const item, parse_buffer * const input_buffer)
+{
+ cJSON *head = NULL; /* head of the linked list */
+ cJSON *current_item = NULL;
+
+ if (input_buffer->depth >= CJSON_NESTING_LIMIT)
+ {
+ return false; /* to deeply nested */
+ }
+ input_buffer->depth++;
+
+ if (buffer_at_offset(input_buffer)[0] != '[')
+ {
+ /* not an array */
+ goto fail;
+ }
+
+ input_buffer->offset++;
+ buffer_skip_whitespace(input_buffer);
+ if (can_access_at_index(input_buffer, 0) && (buffer_at_offset(input_buffer)[0] == ']'))
+ {
+ /* empty array */
+ goto success;
+ }
+
+ /* check if we skipped to the end of the buffer */
+ if (cannot_access_at_index(input_buffer, 0))
+ {
+ input_buffer->offset--;
+ goto fail;
+ }
+
+ /* step back to character in front of the first element */
+ input_buffer->offset--;
+ /* loop through the comma separated array elements */
+ do
+ {
+ /* allocate next item */
+ cJSON *new_item = cJSON_New_Item(&(input_buffer->hooks));
+ if (new_item == NULL)
+ {
+ goto fail; /* allocation failure */
+ }
+
+ /* attach next item to list */
+ if (head == NULL)
+ {
+ /* start the linked list */
+ current_item = head = new_item;
+ }
+ else
+ {
+ /* add to the end and advance */
+ current_item->next = new_item;
+ new_item->prev = current_item;
+ current_item = new_item;
+ }
+
+ /* parse next value */
+ input_buffer->offset++;
+ buffer_skip_whitespace(input_buffer);
+ if (!parse_value(current_item, input_buffer))
+ {
+ goto fail; /* failed to parse value */
+ }
+ buffer_skip_whitespace(input_buffer);
+ }
+ while (can_access_at_index(input_buffer, 0) && (buffer_at_offset(input_buffer)[0] == ','));
+
+ if (cannot_access_at_index(input_buffer, 0) || buffer_at_offset(input_buffer)[0] != ']')
+ {
+ goto fail; /* expected end of array */
+ }
+
+success:
+ input_buffer->depth--;
+
+ item->type = cJSON_Array;
+ item->child = head;
+
+ input_buffer->offset++;
+
+ return true;
+
+fail:
+ if (head != NULL)
+ {
+ cJSON_Delete(head);
+ }
+
+ return false;
+}
+
+/* Render an array to text */
+static cJSON_bool print_array(const cJSON * const item, printbuffer * const output_buffer)
+{
+ unsigned char *output_pointer = NULL;
+ size_t length = 0;
+ cJSON *current_element = item->child;
+
+ if (output_buffer == NULL)
+ {
+ return false;
+ }
+
+ /* Compose the output array. */
+ /* opening square bracket */
+ output_pointer = ensure(output_buffer, 1);
+ if (output_pointer == NULL)
+ {
+ return false;
+ }
+
+ *output_pointer = '[';
+ output_buffer->offset++;
+ output_buffer->depth++;
+
+ while (current_element != NULL)
+ {
+ if (!print_value(current_element, output_buffer))
+ {
+ return false;
+ }
+ update_offset(output_buffer);
+ if (current_element->next)
+ {
+ length = (size_t) (output_buffer->format ? 2 : 1);
+ output_pointer = ensure(output_buffer, length + 1);
+ if (output_pointer == NULL)
+ {
+ return false;
+ }
+ *output_pointer++ = ',';
+ if(output_buffer->format)
+ {
+ *output_pointer++ = ' ';
+ }
+ *output_pointer = '\0';
+ output_buffer->offset += length;
+ }
+ current_element = current_element->next;
+ }
+
+ output_pointer = ensure(output_buffer, 2);
+ if (output_pointer == NULL)
+ {
+ return false;
+ }
+ *output_pointer++ = ']';
+ *output_pointer = '\0';
+ output_buffer->depth--;
+
+ return true;
+}
+
+/* Build an object from the text. */
+static cJSON_bool parse_object(cJSON * const item, parse_buffer * const input_buffer)
+{
+ cJSON *head = NULL; /* linked list head */
+ cJSON *current_item = NULL;
+
+ if (input_buffer->depth >= CJSON_NESTING_LIMIT)
+ {
+ return false; /* to deeply nested */
+ }
+ input_buffer->depth++;
+
+ if (cannot_access_at_index(input_buffer, 0) || (buffer_at_offset(input_buffer)[0] != '{'))
+ {
+ goto fail; /* not an object */
+ }
+
+ input_buffer->offset++;
+ buffer_skip_whitespace(input_buffer);
+ if (can_access_at_index(input_buffer, 0) && (buffer_at_offset(input_buffer)[0] == '}'))
+ {
+ goto success; /* empty object */
+ }
+
+ /* check if we skipped to the end of the buffer */
+ if (cannot_access_at_index(input_buffer, 0))
+ {
+ input_buffer->offset--;
+ goto fail;
+ }
+
+ /* step back to character in front of the first element */
+ input_buffer->offset--;
+ /* loop through the comma separated array elements */
+ do
+ {
+ /* allocate next item */
+ cJSON *new_item = cJSON_New_Item(&(input_buffer->hooks));
+ if (new_item == NULL)
+ {
+ goto fail; /* allocation failure */
+ }
+
+ /* attach next item to list */
+ if (head == NULL)
+ {
+ /* start the linked list */
+ current_item = head = new_item;
+ }
+ else
+ {
+ /* add to the end and advance */
+ current_item->next = new_item;
+ new_item->prev = current_item;
+ current_item = new_item;
+ }
+
+ /* parse the name of the child */
+ input_buffer->offset++;
+ buffer_skip_whitespace(input_buffer);
+ if (!parse_string(current_item, input_buffer))
+ {
+ goto fail; /* failed to parse name */
+ }
+ buffer_skip_whitespace(input_buffer);
+
+ /* swap valuestring and string, because we parsed the name */
+ current_item->string = current_item->valuestring;
+ current_item->valuestring = NULL;
+
+ if (cannot_access_at_index(input_buffer, 0) || (buffer_at_offset(input_buffer)[0] != ':'))
+ {
+ goto fail; /* invalid object */
+ }
+
+ /* parse the value */
+ input_buffer->offset++;
+ buffer_skip_whitespace(input_buffer);
+ if (!parse_value(current_item, input_buffer))
+ {
+ goto fail; /* failed to parse value */
+ }
+ buffer_skip_whitespace(input_buffer);
+ }
+ while (can_access_at_index(input_buffer, 0) && (buffer_at_offset(input_buffer)[0] == ','));
+
+ if (cannot_access_at_index(input_buffer, 0) || (buffer_at_offset(input_buffer)[0] != '}'))
+ {
+ goto fail; /* expected end of object */
+ }
+
+success:
+ input_buffer->depth--;
+
+ item->type = cJSON_Object;
+ item->child = head;
+
+ input_buffer->offset++;
+ return true;
+
+fail:
+ if (head != NULL)
+ {
+ cJSON_Delete(head);
+ }
+
+ return false;
+}
+
+/* Render an object to text. */
+static cJSON_bool print_object(const cJSON * const item, printbuffer * const output_buffer)
+{
+ unsigned char *output_pointer = NULL;
+ size_t length = 0;
+ cJSON *current_item = item->child;
+
+ if (output_buffer == NULL)
+ {
+ return false;
+ }
+
+ /* Compose the output: */
+ length = (size_t) (output_buffer->format ? 2 : 1); /* fmt: {\n */
+ output_pointer = ensure(output_buffer, length + 1);
+ if (output_pointer == NULL)
+ {
+ return false;
+ }
+
+ *output_pointer++ = '{';
+ output_buffer->depth++;
+ if (output_buffer->format)
+ {
+ *output_pointer++ = '\n';
+ }
+ output_buffer->offset += length;
+
+ while (current_item)
+ {
+ if (output_buffer->format)
+ {
+ size_t i;
+ output_pointer = ensure(output_buffer, output_buffer->depth);
+ if (output_pointer == NULL)
+ {
+ return false;
+ }
+ for (i = 0; i < output_buffer->depth; i++)
+ {
+ *output_pointer++ = '\t';
+ }
+ output_buffer->offset += output_buffer->depth;
+ }
+
+ /* print key */
+ if (!print_string_ptr((unsigned char*)current_item->string, output_buffer))
+ {
+ return false;
+ }
+ update_offset(output_buffer);
+
+ length = (size_t) (output_buffer->format ? 2 : 1);
+ output_pointer = ensure(output_buffer, length);
+ if (output_pointer == NULL)
+ {
+ return false;
+ }
+ *output_pointer++ = ':';
+ if (output_buffer->format)
+ {
+ *output_pointer++ = '\t';
+ }
+ output_buffer->offset += length;
+
+ /* print value */
+ if (!print_value(current_item, output_buffer))
+ {
+ return false;
+ }
+ update_offset(output_buffer);
+
+ /* print comma if not last */
+ length = ((size_t)(output_buffer->format ? 1 : 0) + (size_t)(current_item->next ? 1 : 0));
+ output_pointer = ensure(output_buffer, length + 1);
+ if (output_pointer == NULL)
+ {
+ return false;
+ }
+ if (current_item->next)
+ {
+ *output_pointer++ = ',';
+ }
+
+ if (output_buffer->format)
+ {
+ *output_pointer++ = '\n';
+ }
+ *output_pointer = '\0';
+ output_buffer->offset += length;
+
+ current_item = current_item->next;
+ }
+
+ output_pointer = ensure(output_buffer, output_buffer->format ? (output_buffer->depth + 1) : 2);
+ if (output_pointer == NULL)
+ {
+ return false;
+ }
+ if (output_buffer->format)
+ {
+ size_t i;
+ for (i = 0; i < (output_buffer->depth - 1); i++)
+ {
+ *output_pointer++ = '\t';
+ }
+ }
+ *output_pointer++ = '}';
+ *output_pointer = '\0';
+ output_buffer->depth--;
+
+ return true;
+}
+
+/* Get Array size/item / object item. */
+CJSON_PUBLIC(int) cJSON_GetArraySize(const cJSON *array)
+{
+ cJSON *child = NULL;
+ size_t size = 0;
+
+ if (array == NULL)
+ {
+ return 0;
+ }
+
+ child = array->child;
+
+ while(child != NULL)
+ {
+ size++;
+ child = child->next;
+ }
+
+ /* FIXME: Can overflow here. Cannot be fixed without breaking the API */
+
+ return (int)size;
+}
+
+static cJSON* get_array_item(const cJSON *array, size_t index)
+{
+ cJSON *current_child = NULL;
+
+ if (array == NULL)
+ {
+ return NULL;
+ }
+
+ current_child = array->child;
+ while ((current_child != NULL) && (index > 0))
+ {
+ index--;
+ current_child = current_child->next;
+ }
+
+ return current_child;
+}
+
+CJSON_PUBLIC(cJSON *) cJSON_GetArrayItem(const cJSON *array, int index)
+{
+ if (index < 0)
+ {
+ return NULL;
+ }
+
+ return get_array_item(array, (size_t)index);
+}
+
+static cJSON *get_object_item(const cJSON * const object, const char * const name, const cJSON_bool case_sensitive)
+{
+ cJSON *current_element = NULL;
+
+ if ((object == NULL) || (name == NULL))
+ {
+ return NULL;
+ }
+
+ current_element = object->child;
+ if (case_sensitive)
+ {
+ while ((current_element != NULL) && (current_element->string != NULL) && (strcmp(name, current_element->string) != 0))
+ {
+ current_element = current_element->next;
+ }
+ }
+ else
+ {
+ while ((current_element != NULL) && (case_insensitive_strcmp((const unsigned char*)name, (const unsigned char*)(current_element->string)) != 0))
+ {
+ current_element = current_element->next;
+ }
+ }
+
+ if ((current_element == NULL) || (current_element->string == NULL)) {
+ return NULL;
+ }
+
+ return current_element;
+}
+
+CJSON_PUBLIC(cJSON *) cJSON_GetObjectItem(const cJSON * const object, const char * const string)
+{
+ return get_object_item(object, string, false);
+}
+
+CJSON_PUBLIC(cJSON *) cJSON_GetObjectItemCaseSensitive(const cJSON * const object, const char * const string)
+{
+ return get_object_item(object, string, true);
+}
+
+CJSON_PUBLIC(cJSON_bool) cJSON_HasObjectItem(const cJSON *object, const char *string)
+{
+ return cJSON_GetObjectItem(object, string) ? 1 : 0;
+}
+
+/* Utility for array list handling. */
+static void suffix_object(cJSON *prev, cJSON *item)
+{
+ prev->next = item;
+ item->prev = prev;
+}
+
+/* Utility for handling references. */
+static cJSON *create_reference(const cJSON *item, const internal_hooks * const hooks)
+{
+ cJSON *reference = NULL;
+ if (item == NULL)
+ {
+ return NULL;
+ }
+
+ reference = cJSON_New_Item(hooks);
+ if (reference == NULL)
+ {
+ return NULL;
+ }
+
+ memcpy(reference, item, sizeof(cJSON));
+ reference->string = NULL;
+ reference->type |= cJSON_IsReference;
+ reference->next = reference->prev = NULL;
+ return reference;
+}
+
+static cJSON_bool add_item_to_array(cJSON *array, cJSON *item)
+{
+ cJSON *child = NULL;
+
+ if ((item == NULL) || (array == NULL))
+ {
+ return false;
+ }
+
+ child = array->child;
+
+ if (child == NULL)
+ {
+ /* list is empty, start new one */
+ array->child = item;
+ }
+ else
+ {
+ /* append to the end */
+ while (child->next)
+ {
+ child = child->next;
+ }
+ suffix_object(child, item);
+ }
+
+ return true;
+}
+
+/* Add item to array/object. */
+CJSON_PUBLIC(void) cJSON_AddItemToArray(cJSON *array, cJSON *item)
+{
+ add_item_to_array(array, item);
+}
+
+#if defined(__clang__) || (defined(__GNUC__) && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 5))))
+ #pragma GCC diagnostic push
+#endif
+#ifdef __GNUC__
+#pragma GCC diagnostic ignored "-Wcast-qual"
+#endif
+/* helper function to cast away const */
+static void* cast_away_const(const void* string)
+{
+ return (void*)string;
+}
+#if defined(__clang__) || (defined(__GNUC__) && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 5))))
+ #pragma GCC diagnostic pop
+#endif
+
+
+static cJSON_bool add_item_to_object(cJSON * const object, const char * const string, cJSON * const item, const internal_hooks * const hooks, const cJSON_bool constant_key)
+{
+ char *new_key = NULL;
+ int new_type = cJSON_Invalid;
+
+ if ((object == NULL) || (string == NULL) || (item == NULL))
+ {
+ return false;
+ }
+
+ if (constant_key)
+ {
+ new_key = (char*)cast_away_const(string);
+ new_type = item->type | cJSON_StringIsConst;
+ }
+ else
+ {
+ new_key = (char*)cJSON_strdup((const unsigned char*)string, hooks);
+ if (new_key == NULL)
+ {
+ return false;
+ }
+
+ new_type = item->type & ~cJSON_StringIsConst;
+ }
+
+ if (!(item->type & cJSON_StringIsConst) && (item->string != NULL))
+ {
+ hooks->deallocate(item->string);
+ }
+
+ item->string = new_key;
+ item->type = new_type;
+
+ return add_item_to_array(object, item);
+}
+
+CJSON_PUBLIC(void) cJSON_AddItemToObject(cJSON *object, const char *string, cJSON *item)
+{
+ add_item_to_object(object, string, item, &global_hooks, false);
+}
+
+/* Add an item to an object with constant string as key */
+CJSON_PUBLIC(void) cJSON_AddItemToObjectCS(cJSON *object, const char *string, cJSON *item)
+{
+ add_item_to_object(object, string, item, &global_hooks, true);
+}
+
+CJSON_PUBLIC(void) cJSON_AddItemReferenceToArray(cJSON *array, cJSON *item)
+{
+ if (array == NULL)
+ {
+ return;
+ }
+
+ add_item_to_array(array, create_reference(item, &global_hooks));
+}
+
+CJSON_PUBLIC(void) cJSON_AddItemReferenceToObject(cJSON *object, const char *string, cJSON *item)
+{
+ if ((object == NULL) || (string == NULL))
+ {
+ return;
+ }
+
+ add_item_to_object(object, string, create_reference(item, &global_hooks), &global_hooks, false);
+}
+
+CJSON_PUBLIC(cJSON*) cJSON_AddNullToObject(cJSON * const object, const char * const name)
+{
+ cJSON *null = cJSON_CreateNull();
+ if (add_item_to_object(object, name, null, &global_hooks, false))
+ {
+ return null;
+ }
+
+ cJSON_Delete(null);
+ return NULL;
+}
+
+CJSON_PUBLIC(cJSON*) cJSON_AddTrueToObject(cJSON * const object, const char * const name)
+{
+ cJSON *true_item = cJSON_CreateTrue();
+ if (add_item_to_object(object, name, true_item, &global_hooks, false))
+ {
+ return true_item;
+ }
+
+ cJSON_Delete(true_item);
+ return NULL;
+}
+
+CJSON_PUBLIC(cJSON*) cJSON_AddFalseToObject(cJSON * const object, const char * const name)
+{
+ cJSON *false_item = cJSON_CreateFalse();
+ if (add_item_to_object(object, name, false_item, &global_hooks, false))
+ {
+ return false_item;
+ }
+
+ cJSON_Delete(false_item);
+ return NULL;
+}
+
+CJSON_PUBLIC(cJSON*) cJSON_AddBoolToObject(cJSON * const object, const char * const name, const cJSON_bool boolean)
+{
+ cJSON *bool_item = cJSON_CreateBool(boolean);
+ if (add_item_to_object(object, name, bool_item, &global_hooks, false))
+ {
+ return bool_item;
+ }
+
+ cJSON_Delete(bool_item);
+ return NULL;
+}
+
+CJSON_PUBLIC(cJSON*) cJSON_AddNumberToObject(cJSON * const object, const char * const name, const double number)
+{
+ cJSON *number_item = cJSON_CreateNumber(number);
+ if (add_item_to_object(object, name, number_item, &global_hooks, false))
+ {
+ return number_item;
+ }
+
+ cJSON_Delete(number_item);
+ return NULL;
+}
+
+CJSON_PUBLIC(cJSON*) cJSON_AddStringToObject(cJSON * const object, const char * const name, const char * const string)
+{
+ cJSON *string_item = cJSON_CreateString(string);
+ if (add_item_to_object(object, name, string_item, &global_hooks, false))
+ {
+ return string_item;
+ }
+
+ cJSON_Delete(string_item);
+ return NULL;
+}
+
+CJSON_PUBLIC(cJSON*) cJSON_AddRawToObject(cJSON * const object, const char * const name, const char * const raw)
+{
+ cJSON *raw_item = cJSON_CreateRaw(raw);
+ if (add_item_to_object(object, name, raw_item, &global_hooks, false))
+ {
+ return raw_item;
+ }
+
+ cJSON_Delete(raw_item);
+ return NULL;
+}
+
+CJSON_PUBLIC(cJSON*) cJSON_AddObjectToObject(cJSON * const object, const char * const name)
+{
+ cJSON *object_item = cJSON_CreateObject();
+ if (add_item_to_object(object, name, object_item, &global_hooks, false))
+ {
+ return object_item;
+ }
+
+ cJSON_Delete(object_item);
+ return NULL;
+}
+
+CJSON_PUBLIC(cJSON*) cJSON_AddArrayToObject(cJSON * const object, const char * const name)
+{
+ cJSON *array = cJSON_CreateArray();
+ if (add_item_to_object(object, name, array, &global_hooks, false))
+ {
+ return array;
+ }
+
+ cJSON_Delete(array);
+ return NULL;
+}
+
+CJSON_PUBLIC(cJSON *) cJSON_DetachItemViaPointer(cJSON *parent, cJSON * const item)
+{
+ if ((parent == NULL) || (item == NULL))
+ {
+ return NULL;
+ }
+
+ if (item->prev != NULL)
+ {
+ /* not the first element */
+ item->prev->next = item->next;
+ }
+ if (item->next != NULL)
+ {
+ /* not the last element */
+ item->next->prev = item->prev;
+ }
+
+ if (item == parent->child)
+ {
+ /* first element */
+ parent->child = item->next;
+ }
+ /* make sure the detached item doesn't point anywhere anymore */
+ item->prev = NULL;
+ item->next = NULL;
+
+ return item;
+}
+
+CJSON_PUBLIC(cJSON *) cJSON_DetachItemFromArray(cJSON *array, int which)
+{
+ if (which < 0)
+ {
+ return NULL;
+ }
+
+ return cJSON_DetachItemViaPointer(array, get_array_item(array, (size_t)which));
+}
+
+CJSON_PUBLIC(void) cJSON_DeleteItemFromArray(cJSON *array, int which)
+{
+ cJSON_Delete(cJSON_DetachItemFromArray(array, which));
+}
+
+CJSON_PUBLIC(cJSON *) cJSON_DetachItemFromObject(cJSON *object, const char *string)
+{
+ cJSON *to_detach = cJSON_GetObjectItem(object, string);
+
+ return cJSON_DetachItemViaPointer(object, to_detach);
+}
+
+CJSON_PUBLIC(cJSON *) cJSON_DetachItemFromObjectCaseSensitive(cJSON *object, const char *string)
+{
+ cJSON *to_detach = cJSON_GetObjectItemCaseSensitive(object, string);
+
+ return cJSON_DetachItemViaPointer(object, to_detach);
+}
+
+CJSON_PUBLIC(void) cJSON_DeleteItemFromObject(cJSON *object, const char *string)
+{
+ cJSON_Delete(cJSON_DetachItemFromObject(object, string));
+}
+
+CJSON_PUBLIC(void) cJSON_DeleteItemFromObjectCaseSensitive(cJSON *object, const char *string)
+{
+ cJSON_Delete(cJSON_DetachItemFromObjectCaseSensitive(object, string));
+}
+
+/* Replace array/object items with new ones. */
+CJSON_PUBLIC(void) cJSON_InsertItemInArray(cJSON *array, int which, cJSON *newitem)
+{
+ cJSON *after_inserted = NULL;
+
+ if (which < 0)
+ {
+ return;
+ }
+
+ after_inserted = get_array_item(array, (size_t)which);
+ if (after_inserted == NULL)
+ {
+ add_item_to_array(array, newitem);
+ return;
+ }
+
+ newitem->next = after_inserted;
+ newitem->prev = after_inserted->prev;
+ after_inserted->prev = newitem;
+ if (after_inserted == array->child)
+ {
+ array->child = newitem;
+ }
+ else
+ {
+ newitem->prev->next = newitem;
+ }
+}
+
+CJSON_PUBLIC(cJSON_bool) cJSON_ReplaceItemViaPointer(cJSON * const parent, cJSON * const item, cJSON * replacement)
+{
+ if ((parent == NULL) || (replacement == NULL) || (item == NULL))
+ {
+ return false;
+ }
+
+ if (replacement == item)
+ {
+ return true;
+ }
+
+ replacement->next = item->next;
+ replacement->prev = item->prev;
+
+ if (replacement->next != NULL)
+ {
+ replacement->next->prev = replacement;
+ }
+ if (replacement->prev != NULL)
+ {
+ replacement->prev->next = replacement;
+ }
+ if (parent->child == item)
+ {
+ parent->child = replacement;
+ }
+
+ item->next = NULL;
+ item->prev = NULL;
+ cJSON_Delete(item);
+
+ return true;
+}
+
+CJSON_PUBLIC(void) cJSON_ReplaceItemInArray(cJSON *array, int which, cJSON *newitem)
+{
+ if (which < 0)
+ {
+ return;
+ }
+
+ cJSON_ReplaceItemViaPointer(array, get_array_item(array, (size_t)which), newitem);
+}
+
+static cJSON_bool replace_item_in_object(cJSON *object, const char *string, cJSON *replacement, cJSON_bool case_sensitive)
+{
+ if ((replacement == NULL) || (string == NULL))
+ {
+ return false;
+ }
+
+ /* replace the name in the replacement */
+ if (!(replacement->type & cJSON_StringIsConst) && (replacement->string != NULL))
+ {
+ cJSON_free(replacement->string);
+ }
+ replacement->string = (char*)cJSON_strdup((const unsigned char*)string, &global_hooks);
+ replacement->type &= ~cJSON_StringIsConst;
+
+ cJSON_ReplaceItemViaPointer(object, get_object_item(object, string, case_sensitive), replacement);
+
+ return true;
+}
+
+CJSON_PUBLIC(void) cJSON_ReplaceItemInObject(cJSON *object, const char *string, cJSON *newitem)
+{
+ replace_item_in_object(object, string, newitem, false);
+}
+
+CJSON_PUBLIC(void) cJSON_ReplaceItemInObjectCaseSensitive(cJSON *object, const char *string, cJSON *newitem)
+{
+ replace_item_in_object(object, string, newitem, true);
+}
+
+/* Create basic types: */
+CJSON_PUBLIC(cJSON *) cJSON_CreateNull(void)
+{
+ cJSON *item = cJSON_New_Item(&global_hooks);
+ if(item)
+ {
+ item->type = cJSON_NULL;
+ }
+
+ return item;
+}
+
+CJSON_PUBLIC(cJSON *) cJSON_CreateTrue(void)
+{
+ cJSON *item = cJSON_New_Item(&global_hooks);
+ if(item)
+ {
+ item->type = cJSON_True;
+ }
+
+ return item;
+}
+
+CJSON_PUBLIC(cJSON *) cJSON_CreateFalse(void)
+{
+ cJSON *item = cJSON_New_Item(&global_hooks);
+ if(item)
+ {
+ item->type = cJSON_False;
+ }
+
+ return item;
+}
+
+CJSON_PUBLIC(cJSON *) cJSON_CreateBool(cJSON_bool boolean)
+{
+ cJSON *item = cJSON_New_Item(&global_hooks);
+ if(item)
+ {
+ item->type = boolean ? cJSON_True : cJSON_False;
+ }
+
+ return item;
+}
+
+CJSON_PUBLIC(cJSON *) cJSON_CreateNumber(double num)
+{
+ cJSON *item = cJSON_New_Item(&global_hooks);
+ if(item)
+ {
+ item->type = cJSON_Number;
+ item->valuedouble = num;
+
+ /* use saturation in case of overflow */
+ if (num >= INT_MAX)
+ {
+ item->valueint = INT_MAX;
+ }
+ else if (num <= (double)INT_MIN)
+ {
+ item->valueint = INT_MIN;
+ }
+ else
+ {
+ item->valueint = (int)num;
+ }
+ }
+
+ return item;
+}
+
+CJSON_PUBLIC(cJSON *) cJSON_CreateString(const char *string)
+{
+ cJSON *item = cJSON_New_Item(&global_hooks);
+ if(item)
+ {
+ item->type = cJSON_String;
+ item->valuestring = (char*)cJSON_strdup((const unsigned char*)string, &global_hooks);
+ if(!item->valuestring)
+ {
+ cJSON_Delete(item);
+ return NULL;
+ }
+ }
+
+ return item;
+}
+
+CJSON_PUBLIC(cJSON *) cJSON_CreateStringReference(const char *string)
+{
+ cJSON *item = cJSON_New_Item(&global_hooks);
+ if (item != NULL)
+ {
+ item->type = cJSON_String | cJSON_IsReference;
+ item->valuestring = (char*)cast_away_const(string);
+ }
+
+ return item;
+}
+
+CJSON_PUBLIC(cJSON *) cJSON_CreateObjectReference(const cJSON *child)
+{
+ cJSON *item = cJSON_New_Item(&global_hooks);
+ if (item != NULL) {
+ item->type = cJSON_Object | cJSON_IsReference;
+ item->child = (cJSON*)cast_away_const(child);
+ }
+
+ return item;
+}
+
+CJSON_PUBLIC(cJSON *) cJSON_CreateArrayReference(const cJSON *child) {
+ cJSON *item = cJSON_New_Item(&global_hooks);
+ if (item != NULL) {
+ item->type = cJSON_Array | cJSON_IsReference;
+ item->child = (cJSON*)cast_away_const(child);
+ }
+
+ return item;
+}
+
+CJSON_PUBLIC(cJSON *) cJSON_CreateRaw(const char *raw)
+{
+ cJSON *item = cJSON_New_Item(&global_hooks);
+ if(item)
+ {
+ item->type = cJSON_Raw;
+ item->valuestring = (char*)cJSON_strdup((const unsigned char*)raw, &global_hooks);
+ if(!item->valuestring)
+ {
+ cJSON_Delete(item);
+ return NULL;
+ }
+ }
+
+ return item;
+}
+
+CJSON_PUBLIC(cJSON *) cJSON_CreateArray(void)
+{
+ cJSON *item = cJSON_New_Item(&global_hooks);
+ if(item)
+ {
+ item->type=cJSON_Array;
+ }
+
+ return item;
+}
+
+CJSON_PUBLIC(cJSON *) cJSON_CreateObject(void)
+{
+ cJSON *item = cJSON_New_Item(&global_hooks);
+ if (item)
+ {
+ item->type = cJSON_Object;
+ }
+
+ return item;
+}
+
+/* Create Arrays: */
+CJSON_PUBLIC(cJSON *) cJSON_CreateIntArray(const int *numbers, int count)
+{
+ size_t i = 0;
+ cJSON *n = NULL;
+ cJSON *p = NULL;
+ cJSON *a = NULL;
+
+ if ((count < 0) || (numbers == NULL))
+ {
+ return NULL;
+ }
+
+ a = cJSON_CreateArray();
+ for(i = 0; a && (i < (size_t)count); i++)
+ {
+ n = cJSON_CreateNumber(numbers[i]);
+ if (!n)
+ {
+ cJSON_Delete(a);
+ return NULL;
+ }
+ if(!i)
+ {
+ a->child = n;
+ }
+ else
+ {
+ suffix_object(p, n);
+ }
+ p = n;
+ }
+
+ return a;
+}
+
+CJSON_PUBLIC(cJSON *) cJSON_CreateFloatArray(const float *numbers, int count)
+{
+ size_t i = 0;
+ cJSON *n = NULL;
+ cJSON *p = NULL;
+ cJSON *a = NULL;
+
+ if ((count < 0) || (numbers == NULL))
+ {
+ return NULL;
+ }
+
+ a = cJSON_CreateArray();
+
+ for(i = 0; a && (i < (size_t)count); i++)
+ {
+ n = cJSON_CreateNumber((double)numbers[i]);
+ if(!n)
+ {
+ cJSON_Delete(a);
+ return NULL;
+ }
+ if(!i)
+ {
+ a->child = n;
+ }
+ else
+ {
+ suffix_object(p, n);
+ }
+ p = n;
+ }
+
+ return a;
+}
+
+CJSON_PUBLIC(cJSON *) cJSON_CreateDoubleArray(const double *numbers, int count)
+{
+ size_t i = 0;
+ cJSON *n = NULL;
+ cJSON *p = NULL;
+ cJSON *a = NULL;
+
+ if ((count < 0) || (numbers == NULL))
+ {
+ return NULL;
+ }
+
+ a = cJSON_CreateArray();
+
+ for(i = 0;a && (i < (size_t)count); i++)
+ {
+ n = cJSON_CreateNumber(numbers[i]);
+ if(!n)
+ {
+ cJSON_Delete(a);
+ return NULL;
+ }
+ if(!i)
+ {
+ a->child = n;
+ }
+ else
+ {
+ suffix_object(p, n);
+ }
+ p = n;
+ }
+
+ return a;
+}
+
+CJSON_PUBLIC(cJSON *) cJSON_CreateStringArray(const char *const *strings, int count)
+{
+ size_t i = 0;
+ cJSON *n = NULL;
+ cJSON *p = NULL;
+ cJSON *a = NULL;
+
+ if ((count < 0) || (strings == NULL))
+ {
+ return NULL;
+ }
+
+ a = cJSON_CreateArray();
+
+ for (i = 0; a && (i < (size_t)count); i++)
+ {
+ n = cJSON_CreateString(strings[i]);
+ if(!n)
+ {
+ cJSON_Delete(a);
+ return NULL;
+ }
+ if(!i)
+ {
+ a->child = n;
+ }
+ else
+ {
+ suffix_object(p,n);
+ }
+ p = n;
+ }
+
+ return a;
+}
+
+/* Duplication */
+CJSON_PUBLIC(cJSON *) cJSON_Duplicate(const cJSON *item, cJSON_bool recurse)
+{
+ cJSON *newitem = NULL;
+ cJSON *child = NULL;
+ cJSON *next = NULL;
+ cJSON *newchild = NULL;
+
+ /* Bail on bad ptr */
+ if (!item)
+ {
+ goto fail;
+ }
+ /* Create new item */
+ newitem = cJSON_New_Item(&global_hooks);
+ if (!newitem)
+ {
+ goto fail;
+ }
+ /* Copy over all vars */
+ newitem->type = item->type & (~cJSON_IsReference);
+ newitem->valueint = item->valueint;
+ newitem->valuedouble = item->valuedouble;
+ if (item->valuestring)
+ {
+ newitem->valuestring = (char*)cJSON_strdup((unsigned char*)item->valuestring, &global_hooks);
+ if (!newitem->valuestring)
+ {
+ goto fail;
+ }
+ }
+ if (item->string)
+ {
+ newitem->string = (item->type&cJSON_StringIsConst) ? item->string : (char*)cJSON_strdup((unsigned char*)item->string, &global_hooks);
+ if (!newitem->string)
+ {
+ goto fail;
+ }
+ }
+ /* If non-recursive, then we're done! */
+ if (!recurse)
+ {
+ return newitem;
+ }
+ /* Walk the ->next chain for the child. */
+ child = item->child;
+ while (child != NULL)
+ {
+ newchild = cJSON_Duplicate(child, true); /* Duplicate (with recurse) each item in the ->next chain */
+ if (!newchild)
+ {
+ goto fail;
+ }
+ if (next != NULL)
+ {
+ /* If newitem->child already set, then crosswire ->prev and ->next and move on */
+ next->next = newchild;
+ newchild->prev = next;
+ next = newchild;
+ }
+ else
+ {
+ /* Set newitem->child and move to it */
+ newitem->child = newchild;
+ next = newchild;
+ }
+ child = child->next;
+ }
+
+ return newitem;
+
+fail:
+ if (newitem != NULL)
+ {
+ cJSON_Delete(newitem);
+ }
+
+ return NULL;
+}
+
+static void skip_oneline_comment(char **input)
+{
+ *input += static_strlen("//");
+
+ for (; (*input)[0] != '\0'; ++(*input))
+ {
+ if ((*input)[0] == '\n') {
+ *input += static_strlen("\n");
+ return;
+ }
+ }
+}
+
+static void skip_multiline_comment(char **input)
+{
+ *input += static_strlen("/*");
+
+ for (; (*input)[0] != '\0'; ++(*input))
+ {
+ if (((*input)[0] == '*') && ((*input)[1] == '/'))
+ {
+ *input += static_strlen("*/");
+ return;
+ }
+ }
+}
+
+static void minify_string(char **input, char **output) {
+ (*output)[0] = (*input)[0];
+ *input += static_strlen("\"");
+ *output += static_strlen("\"");
+
+
+ for (; (*input)[0] != '\0'; (void)++(*input), ++(*output)) {
+ (*output)[0] = (*input)[0];
+
+ if ((*input)[0] == '\"') {
+ (*output)[0] = '\"';
+ *input += static_strlen("\"");
+ *output += static_strlen("\"");
+ return;
+ } else if (((*input)[0] == '\\') && ((*input)[1] == '\"')) {
+ (*output)[1] = (*input)[1];
+ *input += static_strlen("\"");
+ *output += static_strlen("\"");
+ }
+ }
+}
+
+CJSON_PUBLIC(void) cJSON_Minify(char *json)
+{
+ char *into = json;
+
+ if (json == NULL)
+ {
+ return;
+ }
+
+ while (json[0] != '\0')
+ {
+ switch (json[0])
+ {
+ case ' ':
+ case '\t':
+ case '\r':
+ case '\n':
+ json++;
+ break;
+
+ case '/':
+ if (json[1] == '/')
+ {
+ skip_oneline_comment(&json);
+ }
+ else if (json[1] == '*')
+ {
+ skip_multiline_comment(&json);
+ } else {
+ json++;
+ }
+ break;
+
+ case '\"':
+ minify_string(&json, (char**)&into);
+ break;
+
+ default:
+ into[0] = json[0];
+ json++;
+ into++;
+ }
+ }
+
+ /* and null-terminate. */
+ *into = '\0';
+}
+
+CJSON_PUBLIC(cJSON_bool) cJSON_IsInvalid(const cJSON * const item)
+{
+ if (item == NULL)
+ {
+ return false;
+ }
+
+ return (item->type & 0xFF) == cJSON_Invalid;
+}
+
+CJSON_PUBLIC(cJSON_bool) cJSON_IsFalse(const cJSON * const item)
+{
+ if (item == NULL)
+ {
+ return false;
+ }
+
+ return (item->type & 0xFF) == cJSON_False;
+}
+
+CJSON_PUBLIC(cJSON_bool) cJSON_IsTrue(const cJSON * const item)
+{
+ if (item == NULL)
+ {
+ return false;
+ }
+
+ return (item->type & 0xff) == cJSON_True;
+}
+
+
+CJSON_PUBLIC(cJSON_bool) cJSON_IsBool(const cJSON * const item)
+{
+ if (item == NULL)
+ {
+ return false;
+ }
+
+ return (item->type & (cJSON_True | cJSON_False)) != 0;
+}
+CJSON_PUBLIC(cJSON_bool) cJSON_IsNull(const cJSON * const item)
+{
+ if (item == NULL)
+ {
+ return false;
+ }
+
+ return (item->type & 0xFF) == cJSON_NULL;
+}
+
+CJSON_PUBLIC(cJSON_bool) cJSON_IsNumber(const cJSON * const item)
+{
+ if (item == NULL)
+ {
+ return false;
+ }
+
+ return (item->type & 0xFF) == cJSON_Number;
+}
+
+CJSON_PUBLIC(cJSON_bool) cJSON_IsString(const cJSON * const item)
+{
+ if (item == NULL)
+ {
+ return false;
+ }
+
+ return (item->type & 0xFF) == cJSON_String;
+}
+
+CJSON_PUBLIC(cJSON_bool) cJSON_IsArray(const cJSON * const item)
+{
+ if (item == NULL)
+ {
+ return false;
+ }
+
+ return (item->type & 0xFF) == cJSON_Array;
+}
+
+CJSON_PUBLIC(cJSON_bool) cJSON_IsObject(const cJSON * const item)
+{
+ if (item == NULL)
+ {
+ return false;
+ }
+
+ return (item->type & 0xFF) == cJSON_Object;
+}
+
+CJSON_PUBLIC(cJSON_bool) cJSON_IsRaw(const cJSON * const item)
+{
+ if (item == NULL)
+ {
+ return false;
+ }
+
+ return (item->type & 0xFF) == cJSON_Raw;
+}
+
+CJSON_PUBLIC(cJSON_bool) cJSON_Compare(const cJSON * const a, const cJSON * const b, const cJSON_bool case_sensitive)
+{
+ if ((a == NULL) || (b == NULL) || ((a->type & 0xFF) != (b->type & 0xFF)) || cJSON_IsInvalid(a))
+ {
+ return false;
+ }
+
+ /* check if type is valid */
+ switch (a->type & 0xFF)
+ {
+ case cJSON_False:
+ case cJSON_True:
+ case cJSON_NULL:
+ case cJSON_Number:
+ case cJSON_String:
+ case cJSON_Raw:
+ case cJSON_Array:
+ case cJSON_Object:
+ break;
+
+ default:
+ return false;
+ }
+
+ /* identical objects are equal */
+ if (a == b)
+ {
+ return true;
+ }
+
+ switch (a->type & 0xFF)
+ {
+ /* in these cases and equal type is enough */
+ case cJSON_False:
+ case cJSON_True:
+ case cJSON_NULL:
+ return true;
+
+ case cJSON_Number:
+ if (compare_double(a->valuedouble, b->valuedouble))
+ {
+ return true;
+ }
+ return false;
+
+ case cJSON_String:
+ case cJSON_Raw:
+ if ((a->valuestring == NULL) || (b->valuestring == NULL))
+ {
+ return false;
+ }
+ if (strcmp(a->valuestring, b->valuestring) == 0)
+ {
+ return true;
+ }
+
+ return false;
+
+ case cJSON_Array:
+ {
+ cJSON *a_element = a->child;
+ cJSON *b_element = b->child;
+
+ for (; (a_element != NULL) && (b_element != NULL);)
+ {
+ if (!cJSON_Compare(a_element, b_element, case_sensitive))
+ {
+ return false;
+ }
+
+ a_element = a_element->next;
+ b_element = b_element->next;
+ }
+
+ /* one of the arrays is longer than the other */
+ if (a_element != b_element) {
+ return false;
+ }
+
+ return true;
+ }
+
+ case cJSON_Object:
+ {
+ cJSON *a_element = NULL;
+ cJSON *b_element = NULL;
+ cJSON_ArrayForEach(a_element, a)
+ {
+ /* TODO This has O(n^2) runtime, which is horrible! */
+ b_element = get_object_item(b, a_element->string, case_sensitive);
+ if (b_element == NULL)
+ {
+ return false;
+ }
+
+ if (!cJSON_Compare(a_element, b_element, case_sensitive))
+ {
+ return false;
+ }
+ }
+
+ /* doing this twice, once on a and b to prevent true comparison if a subset of b
+ * TODO: Do this the proper way, this is just a fix for now */
+ cJSON_ArrayForEach(b_element, b)
+ {
+ a_element = get_object_item(a, b_element->string, case_sensitive);
+ if (a_element == NULL)
+ {
+ return false;
+ }
+
+ if (!cJSON_Compare(b_element, a_element, case_sensitive))
+ {
+ return false;
+ }
+ }
+
+ return true;
+ }
+
+ default:
+ return false;
+ }
+}
+
+CJSON_PUBLIC(void *) cJSON_malloc(size_t size)
+{
+ return global_hooks.allocate(size);
+}
+
+CJSON_PUBLIC(void) cJSON_free(void *object)
+{
+ global_hooks.deallocate(object);
+}
+++ /dev/null
-#include <stdio.h>
-#include <stdint.h>
-#include <stdlib.h>
-#include <string.h>
-#include <unistd.h>
-#include <pthread.h>
-#include "button.h"
-
-#include "device.h"
-
-static pthread_mutex_t btn_lock;
-static cQueue_t *btn_msg_q;
-
-static void button_single_cb( button_code_t btn_code, button_event_t btn_event, void* value );
-static void button_comb_cb( button_code_t btn_code, button_event_t btn_event, void* value );
-
-int32_t btn_msg_tx( btn_msg_t *msg )
-{
-
- MG_LOGD( "btn msg tx: %x, %d, %c\n", msg->code, msg->ev, msg->value );
- btn_msg_t *p;
- p = ( btn_msg_t *)malloc( sizeof(btn_msg_t) );
- memcpy( p, msg, sizeof( btn_msg_t ) );
- pthread_mutex_lock( &btn_lock );
- cQPost( btn_msg_q, ( void *)p );
- pthread_mutex_unlock( &btn_lock );
-}
-
-int32_t btn_msg_rx( btn_msg_t *msg )
-{
- btn_msg_t *p;
- char err;
- if( !msg || !btn_msg_q )
- return -1;
-
- pthread_mutex_lock( &btn_lock );
- p = cQRcv( btn_msg_q, &err );
- pthread_mutex_unlock( &btn_lock );
- if( p ){
- memcpy( msg, p, sizeof( btn_msg_t ) );
- MG_LOGD( "btn msg rx: %x, %d, %c\n", msg->code, msg->ev, msg->value );
- free(p);
- return 0;
- }
- return -1;
-}
-
-void device_button_init( mg_dev_t *dev )
-{
- btn_ctrl_t ctrl;
-
- MG_LOGE( "btn init" );
- pthread_mutex_init( &btn_lock, NULL );
- btn_msg_q = cQcreate( 100 );
- ctrl = mg_button_open("/dev/input/by-path/platform-gpio_keys-event" );
- if( ctrl ){
- dev->btn = ctrl;
- mg_button_event_register( ctrl, 0xFF, EVENT_SINGLE_CLICK|EVENT_DOUBLE_CLICK|EVENT_LONG_PRESS|EVENT_LONG_PRESS_UP, button_single_cb );
- mg_button_event_combonation_register( ctrl, BUTTON_7|BUTTON_8, EVENT_COMB_PRESS_5S, 0, button_comb_cb );
- mg_button_event_combonation_register( ctrl, BUTTON_1|BUTTON_8, EVENT_COMB_PRESS_2S, 0, button_comb_cb );
- mg_button_event_combonation_register( ctrl, BUTTON_2|BUTTON_7, EVENT_COMB_PRESS_2S, 0, button_comb_cb );
- }else{
- MG_LOGE( "mg_button_open fail\n" );
- }
-}
-
-
-static int32_t is_key_disabled( button_code_t btn_code )
-{
- uint32_t mask = cfg_mg_key_enable_read( mg_dev_get() );
- if( (btn_code & mask ) != btn_code ){
- MG_LOGD( "drop key, code %02X, mask:%02X\n", mask, btn_code );
- return 1;
- }else{
- return 0;
- }
-}
-
-static void button_single_cb( button_code_t btn_code, button_event_t btn_event, void* value )
-{
- //key_enable
- if( is_key_disabled( btn_code ) ){
- return;
- }
- btn_msg_t msg;
- msg.code = btn_code;
- msg.ev = btn_event;
- msg.value = (uint32_t)value;
- btn_msg_tx( &msg );
-}
-
-static void button_comb_cb( button_code_t btn_code, button_event_t btn_event, void* value )
-{
- if( is_key_disabled( btn_code ) ){
- return;
- }
- btn_msg_t msg;
- msg.code = btn_code;
- msg.ev = btn_event;
- msg.value = (uint32_t)value;
- btn_msg_tx( &msg );
- printf( "COMB BTN cb--code:%x, event:%x, value:%p\n", btn_code, btn_event, value );
-}
-
-int32_t is_btn_netconfig( btn_msg_t *msg )
-{
- if( msg->ev == EVENT_COMB_PRESS_5S && msg->code == BUTTON_7|BUTTON_8 )
- return 1;
- return 0;
-}
-
-int32_t is_btn_device_clean( btn_msg_t *msg )
-{
- if( msg->ev == EVENT_COMB_PRESS_2S && msg->code == BUTTON_1|BUTTON_8 )
- return 1;
- return 0;
-}
-
-int32_t is_btn_device_clean_exit( btn_msg_t *msg )
-{
- if( msg->ev == EVENT_COMB_PRESS_2S && msg->code == BUTTON_2|BUTTON_7 )
- return 1;
- return 0;
-}
-
-uint32_t get_single_click_code( btn_msg_t *msg )
-{
- uint32_t code = 0;
- if( msg->ev == EVENT_SINGLE_CLICK )
- code = msg->code;
- return code;
-}
-
-uint32_t get_double_click_code( btn_msg_t *msg )
-{
- uint32_t code = 0;
- if( msg->ev == EVENT_DOUBLE_CLICK )
- code = msg->code;
- return code;
-}
-
-uint32_t get_long_press_code( btn_msg_t *msg )
-{
- uint32_t code = 0;
- if( msg->ev == EVENT_LONG_PRESS )
- code = msg->code;
- return code;
-}
-
-uint32_t get_long_press_up_code( btn_msg_t *msg )
-{
- uint32_t code = 0;
- if( msg->ev == EVENT_LONG_PRESS_UP )
- code = msg->code;
- return code;
-}
-
#include <zlib.h>
#include <pthread.h>
-//#include "mg_log.h"
+#include "rfjb_log.h"
#include "cJSON.h"
#include "device.h"
-static const dev_cfg_t dev_cfg_default={
- //dp info
- .key_led_max = KEY_LED_MAX_DEF,
- .atmos_led_max = ATMOS_LED_MAX_DEF,
- //.recognition_mode = RECOGNITION_MODE_DEF, //手势识别补光
- .recognition_level = RECOGNITION_LEVEL_DEF, //手势识别灵敏度
- .recognition_duration = RECOGNITION_DURATION_DEF, //手势识别关闭延时
- .led_atmos_on_duration = LED_ATMOS_ON_DURATION_DEF, //氛围灯打开时间
- .mg_tof_threshold = LED_TOF_THRESHOLD_DEF, //人感检测距离
- .mg_tof_interval = MG_TOF_INTERVAL_DEF, //人感检测周期
- .mg_disable_row = MG_DISALBE_ROW_DEF, //关闭联排功能
- .mg_key_enable = MG_KEY_ENABLE_DEF, //按键禁使能, 默认FF, 一个字节, bit0 是第一个按键, bit7是第八个按键
- .bl_mode = BL_MODE_DEF, //背光模式 默认"自动", 自动模式: 氛围灯亮, 背光灭, 有人后反转. 手动模式: 氛围灯可调, 背光亮度可调, 两者无关联
- //.mg_tof_status; //人感状态
- .mg_tof_sync = MG_TOF_SYNC_DEF, //人感状态同步
- .led_atmos_off_duration = LED_ATMOS_OFF_DURATION_DEF, //氛围灯关闭时间, 数值范围: 1-20, 间距: 1, 倍数: 0, 单位: 秒 默认5秒
-};
-
-int32_t nv_read( char *path, uint8_t *read_data, uint32_t read_sz )
-{
- int32_t retval = -1;
- int32_t read_crc;
- FILE *fp;
-
- fp = fopen( path, "r" );
- if( fp ){
- if( fread( read_data, read_sz, 1, fp )==1 && fread( &read_crc, 4, 1, fp )==1){
- if( read_crc == crc32( 0, read_data, read_sz ) ){
- retval = 0;
- }else{
- MG_LOGI( "cfg file[%s] verify fail!", path );
- }
- }else{
- MG_LOGI( "read cfg file[%s] fail!", path );
- }
- fclose(fp );
- }else{
- MG_LOGI( "open cfg file[%s] fail!", path );
- }
-
-
- return retval;
-}
-
-int32_t nv_write( char *path, uint8_t *write_data, uint32_t write_sz )
-{
- int32_t retval = -1;
- int32_t wr_crc;
- FILE *fp;
- uint8_t * wr_buf;
-
-
- fp = fopen( path, "w" );
- if( fp ){
- wr_crc = crc32( 0, (char *)write_data, write_sz );
- fwrite( write_data, write_sz, 1, fp );
- fwrite( &wr_crc, sizeof( wr_crc ), 1, fp );
- fclose( fp );
- retval = 0;
- }else{
- MG_LOGE( "create cfg file[%s] fail!", path );
- }
-
- // write cfg
- // write crc(cfg)
- return retval;
-}
-
-int32_t load_device_cfg( dev_cfg_t *cfg )
-{
- //read file
- if( nv_read( DEV_CFG_PATH, (uint8_t*)cfg, sizeof( *cfg ) ) != 0 ){
- MG_LOGI( "load cfg file fail, use default cfg!" );
- memcpy( cfg, &dev_cfg_default, sizeof( *cfg ) );
- }
-
- return 0;
-}
-
-int32_t store_device_cfg( dev_cfg_t *cfg )
-{
- //write file
- return nv_write( DEV_CFG_PATH, (uint8_t*)cfg, sizeof(*cfg) );
-}
-
-
-int32_t load_auth_key( mg_dev_t *dev )
-{
- FILE * fp;
- char key[50];
- char value[50];
- int32_t auth = 0;
- int32_t retval = -1;
-
- fp = fopen( MG_AUTH_PATH, "r" );
- if( fp ){
- if( fgets( key, 50-1, fp ) && fgets( value, 50-1, fp ) ){
- strtok( key, "\r\n");
- strtok( value, "\n\r");
- char *s = strchr( key, '\r' );
- dev->auth_key_id = strdup( key );
- dev->auth_key_value = strdup( value );
- dev->auth = 1;
- MG_LOGI( "get auth key[ %s:%s ]", dev->auth_key_id, dev->auth_key_value );
- retval = 0;
- }
- fclose(fp);
- }else{
- MG_LOGE( "open auth file[%s] fail!", MG_AUTH_PATH );
- retval = -1;
- }
- if( retval != 0 ){
- if( dev->auth_key_id )
- free( dev->auth_key_id );
- if( dev->auth_key_value )
- free( dev->auth_key_value );
- dev->auth_key_id = NULL;
- dev->auth_key_value = NULL;
- dev->auth = 0;
- }
- return retval;
-}
-
-int32_t is_dev_auth( mg_dev_t *dev )
-{
- return dev->auth?1:0;
-}
-
-static int rx_key = 1;
-static char received_key_value[50];
-
-int32_t recv_dp_key_value_cb( char * value )
-{
- if( value ){
- strncpy( received_key_value, value, sizeof(received_key_value)-1 );
- rx_key= 1;
- }
-}
-
-int32_t is_device_active( mg_dev_t *dev )
-{
-
- int fd;
- if( dev->mg_active )
- return 1;
-
- fd = open( MG_ACTIVE_PATH, O_RDONLY );
- if( fd >= 0 ){
- dev->mg_active = 1;
- close(fd);
- }else{
- MG_LOGD( "open [%s] fail: %d", MG_ACTIVE_PATH, fd );
- }
-
- return dev->mg_active;
-}
+#define SERIAL_DEF "12345678"
+#define HW_VER_DEF "V1.0"
+#define IOT_SRV_ADDR_DEF "test.com"
+#define IOT_SRV_PORT 8888
-static int32_t touch_file( char * path )
-{
- char cmd[200];
- sprintf( cmd, "touch %s", path );
- if( system( cmd ) ){
- //MG_LOGE( "" );
- }
- return 0;
-}
+#define LORA_ADDR_DEF 0
+#define LORA_GW_DEF 0
+#define LORA_SRV_DEF 0
-int32_t mg_device_active_flag_write( void )
-{
-/// touch_file( MG_ACTIVE_PATH );
-}
-
-int32_t mg_device_bind_flag_write( void )
-{
-// touch_file( TUYA_BIND_PATH );
-}
-
-int32_t read_device_uuid( mg_dev_t *dev )
-{
- FILE *fp;
- char buf[200];
- char uuid[100];
- char *s;
-
- int32_t retval = -1;
-
- if( dev->uuid )
- free( dev->uuid );
-
- dev->uuid = NULL;
-
- fp = popen( READ_UUID_CMD, "r" );
- if( fp ){
- if( fgets( buf, sizeof( buf )-1, fp ) ){
- printf( "get cpu serial :[%s]\n", buf );
- s = strstr( buf, "Serial" );
- if( s && sscanf( s, "%*[^:]:%*[ ]%s", uuid ) == 1 ){
- dev->uuid = strdup( uuid );
- printf( "get uuid [%s] from [%s]\n", uuid, buf );
- retval = 0;
- }
- }
- fclose( fp );
- }
- return retval;
-}
-
-int32_t mg_device_active( mg_dev_t *dev )
-{
- return 0;
-}
-
-//----------------------------------------------------------------------------
-void mg_dev_lock( mg_dev_t *dev )
-{
- pthread_mutex_lock( &dev->lock );
-}
-
-void mg_dev_unlock( mg_dev_t *dev )
-{
- pthread_mutex_unlock( &dev->lock );
-}
-
-int32_t cfg_key_led_max_read( mg_dev_t *dev)
-{
- int32_t br = 0;
- mg_dev_lock( dev );
- br = dev->cfg.key_led_max;
- mg_dev_unlock( dev );
- return br;
-}
-
-int32_t cfg_key_led_max_write( mg_dev_t *dev, int br )
-{
- if( br != dev->cfg.key_led_max ){
- MG_LOGI( "key_led_max: %d -> %d\n", dev->cfg.key_led_max, br );
- }
- mg_dev_lock( dev );
- if( br != dev->cfg.key_led_max ){
- dev->cfg.key_led_max = br;
- store_device_cfg( &dev->cfg );
- }
- mg_dev_unlock( dev );
- return 0;
-}
-
-int32_t cfg_atmos_led_max_read( mg_dev_t *dev)
-{
- int32_t br = 0;
- mg_dev_lock( dev );
- br = dev->cfg.atmos_led_max;
- mg_dev_unlock( dev );
- return br;
-}
-
-int32_t cfg_atmos_led_max_write( mg_dev_t *dev, int br )
-{
- if( br != dev->cfg.atmos_led_max ){
- MG_LOGI( "atmos_led_max: %d -> %d\n", dev->cfg.atmos_led_max, br );
- }
- mg_dev_lock( dev );
- if( br != dev->cfg.atmos_led_max ){
- dev->cfg.atmos_led_max = br;
- store_device_cfg( &dev->cfg );
- }
- mg_dev_unlock( dev );
- return 0;
-}
-
-int32_t cfg_recognition_level_read( mg_dev_t *dev)
-{
- int32_t level;
- mg_dev_lock( dev );
- level = dev->cfg.recognition_level;
- mg_dev_unlock( dev );
- return level;
-}
-
-int32_t cfg_recognition_level_write( mg_dev_t *dev, int level )
-{
- if( level != dev->cfg.recognition_level ){
- MG_LOGI( ": %d -> %d\n", dev->cfg.recognition_level, level );
- }
- mg_dev_lock( dev );
- if( level != dev->cfg.recognition_level ){
- dev->cfg.recognition_level= level;
- store_device_cfg( &dev->cfg );
- }
- mg_dev_unlock( dev );
- return 0;
-}
-
-int32_t cfg_recognition_duration_read( mg_dev_t *dev)
-{
- int32_t dur_sec;
- mg_dev_lock( dev );
- dur_sec = dev->cfg.recognition_duration;
- mg_dev_unlock( dev );
- return dur_sec;
-}
-
-int32_t cfg_recognition_duration_write( mg_dev_t *dev, int32_t dur_sec )
-{
- if( dur_sec != dev->cfg.recognition_duration){
- MG_LOGI( "dur_sec: %d -> %d\n", dev->cfg.recognition_duration, dur_sec );
- }
- mg_dev_lock( dev );
- if( dur_sec != dev->cfg.recognition_duration){
- dev->cfg.recognition_duration = dur_sec;
- store_device_cfg( &dev->cfg );
- }
- mg_dev_unlock( dev );
- return 0;
-}
+#define BD_ADDR_DEF 0
+#define BD_SRV_DEF 0
-int32_t cfg_privacy_mode_read( mg_dev_t *dev)
-{
- int32_t mode;
- mg_dev_lock( dev );
- mode = dev->cfg.privacy_mode;
- mg_dev_unlock( dev );
- return mode;
-}
+static const factory_cfg_t factory_cfg_default={
+ .serial = SERIAL_DEF,
+ .hw_version = HW_VER_DEF,
+};
+static const dev_cfg_t dev_cfg_default={
+ .iot = {
+ .addr = IOT_SRV_ADDR_DEF,
+ .port = IOT_SRV_PORT,
+ },
+ .lora = {
+ .addr = LORA_ADDR_DEF,
+ .gw = LORA_GW_DEF,
+ .srv = LORA_SRV_DEF,
+ },
+ .bd = {
+ .addr = BD_ADDR_DEF,
+ .srv = BD_SRV_DEF,
+ },
+};
-int32_t cfg_privacy_mode_write( mg_dev_t *dev, int32_t mode )
+int32_t nv_read( char *path, uint8_t *read_data, uint32_t read_sz )
{
- if( mode != dev->cfg.privacy_mode ){
- MG_LOGI( "privacy_mode: %d -> %d\n", dev->cfg.privacy_mode, mode );
- }
- mg_dev_lock( dev );
- if( mode != dev->cfg.privacy_mode ){
- dev->cfg.privacy_mode = mode;
- store_device_cfg( &dev->cfg );
- }
- mg_dev_unlock( dev );
- return 0;
-}
+ int32_t retval = -1;
+ int32_t read_crc;
+ FILE *fp;
-int32_t cfg_mg_tof_threshold_read( mg_dev_t *dev)
-{
- int32_t threshold;
- mg_dev_lock( dev );
- threshold = dev->cfg.mg_tof_threshold;
- mg_dev_unlock( dev );
- return threshold;
-}
+ fp = fopen( path, "r" );
+ if( fp ){
+ if( fread( read_data, read_sz, 1, fp )==1 && fread( &read_crc, 4, 1, fp )==1){
+ if( read_crc == crc32( 0, read_data, read_sz ) ){
+ retval = 0;
+ }else{
+ RFJB_LOGI( "cfg file[%s] verify fail!", path );
+ }
+ }else{
+ RFJB_LOGI( "read cfg file[%s] fail!", path );
+ }
+ fclose(fp );
+ }else{
+ RFJB_LOGI( "open cfg file[%s] fail!", path );
+ }
-int32_t cfg_mg_tof_threshold_write( mg_dev_t *dev, int32_t threshold_cm )
-{
- if( threshold_cm != dev->cfg.mg_tof_threshold ){
- MG_LOGI( ": %d -> %d\n", dev->cfg.mg_tof_threshold, threshold_cm );
- }
- mg_dev_lock( dev );
- if( threshold_cm != dev->cfg.mg_tof_threshold ){
- dev->cfg.mg_tof_threshold = threshold_cm;
- store_device_cfg( &dev->cfg );
- }
- mg_dev_unlock( dev );
- return 0;
-}
-int32_t cfg_mg_tof_interval_read( mg_dev_t *dev)
-{
- int32_t interval;
- mg_dev_lock( dev );
- interval = dev->cfg.mg_tof_interval;
- mg_dev_unlock( dev );
- return interval;
+ return retval;
}
-int32_t cfg_mg_tof_interval_write( mg_dev_t *dev, int32_t interval_sec)
+int32_t nv_write( char *path, uint8_t *write_data, uint32_t write_sz )
{
- if( interval_sec != dev->cfg.mg_tof_interval ){
- MG_LOGI( "mg_tof_interval: %d -> %d\n", dev->cfg.mg_tof_interval, interval_sec );
- }
- mg_dev_lock( dev );
- if( interval_sec != dev->cfg.mg_tof_interval ){
- dev->cfg.mg_tof_interval = interval_sec;
- store_device_cfg( &dev->cfg );
- }
- mg_dev_unlock( dev );
- return 0;
-}
+ int32_t retval = -1;
+ int32_t wr_crc;
+ FILE *fp;
+ uint8_t * wr_buf;
-int32_t cfg_mg_disable_row_read( mg_dev_t *dev)
-{
- int32_t row_disable;
- mg_dev_lock( dev );
- row_disable = dev->cfg.mg_disable_row;
- mg_dev_unlock( dev );
- return row_disable;
-}
+ fp = fopen( path, "w" );
+ if( fp ){
+ wr_crc = crc32( 0, (char *)write_data, write_sz );
+ fwrite( write_data, write_sz, 1, fp );
+ fwrite( &wr_crc, sizeof( wr_crc ), 1, fp );
+ fclose( fp );
+ retval = 0;
+ }else{
+ RFJB_LOGE( "create cfg file[%s] fail!", path );
+ }
-int32_t cfg_mg_disable_row_write( mg_dev_t *dev, int32_t disable )
-{
- if( disable != dev->cfg.mg_disable_row ){
- MG_LOGI( "mg_disable_row: %d -> %d\n", dev->cfg.mg_disable_row, disable );
- }
- mg_dev_lock( dev );
- if( disable != dev->cfg.mg_disable_row ){
- dev->cfg.mg_disable_row = disable;
- store_device_cfg( &dev->cfg );
- }
- mg_dev_unlock( dev );
- return 0;
+ // write cfg
+ // write crc(cfg)
+ return retval;
}
-
-int32_t cfg_mg_key_enable_read( mg_dev_t *dev)
+int32_t load_device_cfg( dev_cfg_t *cfg )
{
- int32_t en_mask;
- mg_dev_lock( dev );
- en_mask = dev->cfg.mg_key_enable;
- mg_dev_unlock( dev );
- return en_mask;
-}
+ //read file
+ if( nv_read( DEV_CFG_PATH, (uint8_t*)cfg, sizeof( *cfg ) ) != 0 ){
+ RFJB_LOGI( "load cfg file fail, use default cfg!" );
+ memcpy( cfg, &dev_cfg_default, sizeof( *cfg ) );
+ }
-int32_t cfg_mg_key_enable_write( mg_dev_t *dev, int32_t en_mask )
-{
- if( en_mask != dev->cfg.mg_key_enable){
- MG_LOGI( "key enable: %02X -> %02X\n", dev->cfg.mg_key_enable, en_mask );
- }
- mg_dev_lock( dev );
- if( en_mask != dev->cfg.mg_key_enable){
- dev->cfg.mg_key_enable = en_mask;
- store_device_cfg( &dev->cfg );
- }
- mg_dev_unlock( dev );
- return 0;
+ return 0;
}
-int32_t cfg_bl_mode_read( mg_dev_t *dev) //0:auto, 1-manual
+int32_t store_device_cfg( dev_cfg_t *cfg )
{
- int32_t mode;
- mg_dev_lock( dev );
- mode = dev->cfg.bl_mode;
- mg_dev_unlock( dev );
- return mode;
+ //write file
+ return nv_write( DEV_CFG_PATH, (uint8_t*)cfg, sizeof(*cfg) );
}
-int32_t cfg_bl_mode_write( mg_dev_t *dev, int32_t mode ) //0:auto, 1-manual
+static int32_t touch_file( char * path )
{
- if( mode != dev->cfg.bl_mode){
- MG_LOGI( "bl_mode: %d -> %d\n", dev->cfg.bl_mode, mode );
- }
- mg_dev_lock( dev );
- if( mode != dev->cfg.bl_mode){
- dev->cfg.bl_mode = mode;
- store_device_cfg( &dev->cfg );
- }
- mg_dev_unlock( dev );
- return 0;
+ char cmd[200];
+ sprintf( cmd, "touch %s", path );
+ if( system( cmd ) ){
+ //RFJB_LOGE( "" );
+ }
+ return 0;
}
-int32_t cfg_led_atmos_on_duration_read( mg_dev_t *dev)
+int32_t read_device_uuid( rfjb_dev_t *dev )
{
- int32_t dur_sec;
- mg_dev_lock( dev );
- dur_sec = dev->cfg.led_atmos_on_duration;
- mg_dev_unlock( dev );
- return dur_sec;
-}
+ FILE *fp;
+ char buf[200];
+ char uuid[100];
+ char *s;
-int32_t cfg_led_atmos_on_duration_write( mg_dev_t *dev, int32_t dur_sec )
-{
- if( dur_sec != dev->cfg.led_atmos_on_duration ){
- MG_LOGI( "led_atmos_on_duration %d -> %d\n", dev->cfg.led_atmos_on_duration, dur_sec );
- }
- mg_dev_lock( dev );
- if( dur_sec != dev->cfg.led_atmos_on_duration ){
- dev->cfg.led_atmos_on_duration = dur_sec;
- store_device_cfg( &dev->cfg );
- }
- mg_dev_unlock( dev );
- return 0;
-}
+ int32_t retval = -1;
+ if( dev->uuid )
+ free( dev->uuid );
-int32_t cfg_led_atmos_off_duration_read( mg_dev_t *dev)
-{
- int32_t dur_sec;
- mg_dev_lock( dev );
- dur_sec = dev->cfg.led_atmos_off_duration;
- mg_dev_unlock( dev );
- return dur_sec;
-}
+ dev->uuid = NULL;
-int32_t cfg_led_atmos_off_duration_write( mg_dev_t *dev, int32_t dur_sec )
-{
- if( dur_sec != dev->cfg.led_atmos_off_duration ){
- MG_LOGI( "led_atmos_off_duration %d -> %d\n", dev->cfg.led_atmos_off_duration, dur_sec );
- }
- mg_dev_lock( dev );
- if( dur_sec != dev->cfg.led_atmos_off_duration ){
- dev->cfg.led_atmos_off_duration = dur_sec;
- store_device_cfg( &dev->cfg );
- }
- mg_dev_unlock( dev );
- return 0;
+ fp = popen( READ_UUID_CMD, "r" );
+ if( fp ){
+ if( fgets( buf, sizeof( buf )-1, fp ) ){
+ printf( "get cpu serial :[%s]\n", buf );
+ s = strstr( buf, "Serial" );
+ if( s && sscanf( s, "%*[^:]:%*[ ]%s", uuid ) == 1 ){
+ dev->uuid = strdup( uuid );
+ printf( "get uuid [%s] from [%s]\n", uuid, buf );
+ retval = 0;
+ }
+ }
+ fclose( fp );
+ }
+ return retval;
}
-int32_t cfg_mg_tof_sync_read( mg_dev_t *dev)
+//----------------------------------------------------------------------------
+void rfjb_dev_lock( rfjb_dev_t *dev )
{
- int32_t sync;
- mg_dev_lock( dev );
- sync = dev->cfg.mg_tof_sync;
- mg_dev_unlock( dev );
- return sync;
+ pthread_mutex_lock( &dev->lock );
}
-int32_t cfg_mg_tof_sync_write( mg_dev_t *dev, int32_t sync )
+void rfjb_dev_unlock( rfjb_dev_t *dev )
{
- if( sync!= dev->cfg.mg_tof_sync ){
- MG_LOGI( "mg_tof_sync: %d -> %d\n", dev->cfg.mg_tof_sync, sync);
- }
- mg_dev_lock( dev );
- if( dev->cfg.mg_tof_sync != sync ){
- dev->cfg.mg_tof_sync = sync;
- store_device_cfg( &dev->cfg );
- }
- mg_dev_unlock( dev );
-
- return 0;
+ pthread_mutex_unlock( &dev->lock );
}
cJSON * load_json_data_from_file( char *path )
{
- FILE *fd;
- char *json_data;
- cJSON *root = NULL;
- size_t file_size;
-
- fd = fopen( path, "r" );
- if( fd ){
- fseek(fd,0,SEEK_END);
- file_size = ftell(fd);
- fseek(fd,0,SEEK_SET);
- json_data = (char *)malloc( file_size+1 );
- if( json_data ){
- if(fread( json_data, file_size, 1, fd ) ){
- json_data[ file_size ] = 0;
- root = cJSON_Parse((const char *)json_data);
- if( !root ){
- printf( "parser json data fail!\r\n" );
- }
- }else{
- MG_LOGE( "read file[%s] fail!\n", path );
- }
- free( json_data );
- }else{
- MG_LOGE( "out of memory!\n");
- }
- fclose( fd );
- }else{
- MG_LOGE( "open file [%s] fail\n", path );
- }
-
- return root;
-}
-
-int32_t load_als_threshold( uint32_t *ts_high, uint32_t *ts_low)
-{
- FILE *fd;
- char json_data[200];
- size_t n;
- cJSON *root = NULL;
- cJSON *high = NULL;
- cJSON *low = NULL;
-
- root =load_json_data_from_file( ALS_CFG_PATH );
-
- if( root ){
-
- high =cJSON_GetObjectItem(root, "high");
- low =cJSON_GetObjectItem(root, "low");
-
- if( !cJSON_IsNumber(high) || !cJSON_IsNumber(low) ){
- MG_LOGD( "get threshold high:fail\r\n" );
- goto err_out;
- }
-
- if( high )
- *ts_high = high->valueint;
- if( ts_low )
- *ts_low = low->valueint;
-
-
- cJSON_Delete( root );
- return 0;
- }
-
-err_out:
- if( root ){
- cJSON_Delete( root );
- }
-
- if( ts_high )
- *ts_high = ALS_THRESHOLD_HIGH_DEFAULT;
- if( ts_low )
- *ts_low = ALS_THRESHOLD_LOW_DEFAULT;
- return -1;
-}
-
-//有人到无人判断时间
-uint32_t load_tof_nobody_timer_secs( void )
-{
- FILE *fd;
- char json_data[200];
- size_t n;
- cJSON *root = NULL;
- cJSON *nobody_timer = NULL;
- uint32_t secs;
-
- root =load_json_data_from_file( TOF_CFG_PATH );
-
- if( root ){
-
- nobody_timer = cJSON_GetObjectItem(root, "nobody_timer");
-
- if( !cJSON_IsNumber(nobody_timer ) ){
- MG_LOGD( "get tof nobody timer :fail\r\n" );
- secs = TOF_NOBODY_TIMER_SECS_DEFAULT;
- }else{
- secs = nobody_timer->valueint;
- }
-
- cJSON_Delete( root );
- }else{
- secs = TOF_NOBODY_TIMER_SECS_DEFAULT;
- }
-
- return secs;
-
-}
-
-int32_t wifi_config_store( char *ssid, char *passwd )
-{
- FILE *fd;
- int32_t ret = -1;
-
- if( ssid && passwd ){
- if( (fd = fopen( WIFI_CONFIG_PATH, "w" ) )){
- fprintf( fd, "{\n\t\"ssid\":\"%s\",\n\t\"password\":\"%s\"\n}", ssid, passwd );
- fclose( fd );
- ret = 0;
- }
- }
- return ret;
-}
-
-int32_t wifi_config_load( char *ssid, uint32_t ssid_max_len, char *passwd, uint32_t passwd_max_len )
-{
- cJSON *root;
- cJSON *json_ssid;
- cJSON *json_passwd;
- int32_t ret = -1;
-
- root = load_json_data_from_file( WIFI_CONFIG_PATH );
- if( root ){
- json_ssid =cJSON_GetObjectItem(root, "ssid");
- json_passwd =cJSON_GetObjectItem(root, "password");
- if( json_ssid && json_passwd ){
- if( ssid )
- strncpy( ssid, json_ssid->valuestring, ssid_max_len);
- if( passwd )
- strncpy( passwd, json_passwd->valuestring, passwd_max_len);
- ret = 0;
- }
-
- cJSON_Delete( root );
- }
-
- return ret;
-}
-
-//涂鸦用户绑定设备标志
-
-//wifi配网标志
-int32_t is_wifi_config( mg_dev_t *dev )
-{
-
- if( dev->mg_wificonfig)
- return 1;
- if( wifi_config_load( NULL, 0, NULL, 0 ) == 0 ){
- dev->mg_wificonfig = 1;
- }
-
- return dev->mg_wificonfig;
-}
-
-//检查是否已经配网,需要wifi配网而且设备绑定
-
-int32_t fw_version_read( char * ver, int32_t max_sz )
-{
- strncpy( ver, SW_VERSION, max_sz );
- return 0;
-}
-
-int32_t hw_version_read( char * ver, int32_t max_sz )
-{
- cJSON *root = NULL;
- cJSON *json_ver;
- int32_t ret = -1;
-
- //root = load_json_data_from_file( HW_VER_PATH );
- if( root ){
- json_ver = cJSON_GetObjectItem(root, "hw_version");
- if( json_ver ){
- if( ver && max_sz )
- strncpy( ver, json_ver->valuestring, max_sz );
- ret = 0;
- }
- cJSON_Delete( root );
- }
-
- return ret;
-}
-
-//BLE avertise device name
-char *load_ble_adv_local_name( void )
-{
- static char name_str[50];
- FILE *fd;
- size_t n;
- cJSON *root = NULL;
- cJSON *dev_name = NULL;
- uint32_t secs;
-
- strncpy( name_str, "MOORGEN", sizeof( name_str) );
-
- //root =load_json_data_from_file( BLE_ADV_CFG_PATH );
-
- if( root ){
-
- dev_name = cJSON_GetObjectItem(root, "local_name");
-
- if( !cJSON_IsString(dev_name) ){
- MG_LOGD( "get dev_name:fail\r\n" );
- }else{
- strncpy( name_str, dev_name->valuestring, sizeof( name_str) );
- }
-
- cJSON_Delete( root );
- }
-
- return name_str;
-
-}
-
-
-const light_cfg_t light_cfg_default = {
- .br = { //亮度0 到100, 对应到sysfs接口的0-255
- 0,
- 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
- 11, 12, 13, 14, 15, 16, 17, 18, 19, 20,
- 21, 22, 23, 24, 25, 26, 27, 28, 29, 30,
- 32, 34, 36, 38, 40, 42, 34, 36, 38, 50,
- 52, 54, 56, 58, 60, 62, 64, 66, 68, 70,
- 72, 74, 76, 78, 80, 82, 84, 86, 88, 90,
- 92, 94, 96, 98, 100, 102, 104, 106, 108, 110,
- 112, 114, 116, 118, 120, 122, 124, 126, 128, 130,
- 132, 134, 136, 138, 140, 142, 144, 146, 148, 150,
- 160, 170, 180, 190, 200, 210, 220, 230, 240, 255,
- },
- .breath={
- .increase_ms = 600,
- .decrease_ms = 600,
- .apnea_ms = 300,
- },
-};
-
-//light cfg
-int32_t load_light_cfg( light_cfg_t * cfg )
-{
- FILE *fd;
- size_t n;
- cJSON *root = NULL;
- cJSON *br = NULL;
- cJSON *breath = NULL;
- cJSON *item= NULL;
- light_cfg_t read_cfg;
-
- int32_t ret = 0;
- int i;
-
- memcpy( &read_cfg, &light_cfg_default, sizeof( read_cfg ) );
-
- root =load_json_data_from_file( LIGHT_CFG_PATH );
- if( root ){
- if((br = cJSON_GetObjectItem(root, "brightness"))){
- if( cJSON_IsArray(br) || cJSON_GetArraySize( br ) == 101 ){
- for( i=0; i<101; i++ ){
- item = cJSON_GetArrayItem( br, i );
- if( cJSON_IsNumber( item ) && item->valueint <= 255 ){
- read_cfg.br[i] = item->valueint;
- }else{
- printf( "load light cfg [%d] fail!\n", i );
- ret =-1;
- break;
- }
- }
- }
-
- }
-
- if((breath = cJSON_GetObjectItem(root, "breath") ) ){
-
- if((item = cJSON_GetObjectItem(breath, "increase")) && cJSON_IsNumber( item ) )
- read_cfg.breath.increase_ms = item->valueint;
-
- if((item = cJSON_GetObjectItem(breath, "decrease")) && cJSON_IsNumber( item ) )
- read_cfg.breath.decrease_ms = item->valueint;
-
- if((item = cJSON_GetObjectItem(breath, "apnea")) && cJSON_IsNumber( item ) )
- read_cfg.breath.apnea_ms = item->valueint;
-
- }
- cJSON_Delete( root );
- }
- memcpy( cfg, &read_cfg, sizeof( *cfg ) );
-
- //printf( "-----------------------------------------------\n" );
- //printf( "load light cfg:\n" );
- //for( i=0; i<101; i++ ){
- // printf( "%4d%s", read_cfg.br[i], (i%10)?" ":"\n" );
- //}
- //printf( "breath:%d, %d, %d\n", read_cfg.breath.increase_ms, read_cfg.breath.decrease_ms, read_cfg.breath.apnea_ms );
- //printf( "-----------------------------------------------\n" );
-
- return ret;
-
+ FILE *fd;
+ char *json_data;
+ cJSON *root = NULL;
+ size_t file_size;
+
+ fd = fopen( path, "r" );
+ if( fd ){
+ fseek(fd,0,SEEK_END);
+ file_size = ftell(fd);
+ fseek(fd,0,SEEK_SET);
+ json_data = (char *)malloc( file_size+1 );
+ if( json_data ){
+ if(fread( json_data, file_size, 1, fd ) ){
+ json_data[ file_size ] = 0;
+ root = cJSON_Parse((const char *)json_data);
+ if( !root ){
+ printf( "parser json data fail!\r\n" );
+ }
+ }else{
+ RFJB_LOGE( "read file[%s] fail!\n", path );
+ }
+ free( json_data );
+ }else{
+ RFJB_LOGE( "out of memory!\n");
+ }
+ fclose( fd );
+ }else{
+ RFJB_LOGE( "open file [%s] fail\n", path );
+ }
+
+ return root;
+}
+
+//json file factory.cfg: { "serial":"123456", "hw_verison":"HW_V1.0" }
+int32_t load_factory_cfg( factory_cfg_t * cfg )
+{
+ FILE *fd;
+ size_t n;
+ cJSON *root = NULL;
+ cJSON *dev_serial = NULL;
+ cJSON *hw_ver= NULL;
+ factory_cfg_t read_cfg;
+
+ int32_t ret = 0;
+ int i;
+
+ memcpy( &read_cfg, &factory_cfg_default, sizeof( read_cfg ) );
+
+ root =load_json_data_from_file( FACTORY_CFG_PATH );
+ if( root ){
+ if((dev_serial = cJSON_GetObjectItem(root, "serial"))){
+ if( cJSON_IsString( dev_serial ) ){
+ strncpy( read_cfg.serial, dev_serial->valuestring, sizeof( read_cfg.serial) );
+ }else{
+ printf( "load factory cfg [%d] fail!\n", i );
+ ret =-1;
+ }
+ }
+ if((hw_ver = cJSON_GetObjectItem(root, "hw_version"))){
+ if( cJSON_IsString( dev_serial ) ){
+ strncpy( read_cfg.hw_version, dev_serial->valuestring, sizeof( read_cfg.hw_version) );
+ }else{
+ printf( "load factory cfg [%d] fail!\n", i );
+ ret =-1;
+ }
+ }
+
+ cJSON_Delete( root );
+ }
+ memcpy( cfg, &read_cfg, sizeof( *cfg ) );
+
+ printf( "-----------------------------------------------\n" );
+ printf( "load factory cfg:\n" );
+ printf( "serial:%s, hw_version:%s\n", cfg->serial, cfg->hw_version );
+ printf( "-----------------------------------------------\n" );
+
+ return ret;
}
+++ /dev/null
-#include <stdio.h>
-#include <stdint.h>
-#include <stdlib.h>
-#include <string.h>
-#include <unistd.h>
-#include <pthread.h>
-#include "button.h"
-//#include "led.h"
-//#include "iot.h"
-//#include "mg_log.h"
-
-#include "cQueue.h"
-
-#include "device.h"
-//#include "tof.h"
-
-
-//按键与背光子系统流程
-void * btn_light_ctrl_task( void* para )
-{
- mg_dev_t *dev;
- btn_msg_t btn_msg;
- uint32_t to_net_config = 0;
- uint32_t to_clean_mode = 0;
- uint32_t to_clean_mode_exit = 0;
- uint32_t btn_code = 0;
- int32_t bl_manual = 0;
-
- MG_LOGI( "btn light ctrl task run..." );
-
- dev = ( mg_dev_t * )para;
- bl_manual = -1;
-
- while(1){
- usleep(100*1000);
- //读取按键信息
- if( btn_msg_rx( &btn_msg ) == 0 ){
- MG_LOGI( "get btn msg: %04X, %d, %d", btn_msg.code, btn_msg.ev, btn_msg.value );
-
- //如果是配网按键
- to_net_config = is_btn_netconfig( &btn_msg );
- to_clean_mode = is_btn_device_clean( &btn_msg );
- to_clean_mode_exit = is_btn_device_clean_exit( &btn_msg );
-
- if( !dev->clean_device && to_clean_mode ){
-
- MG_LOGI( "enter clean mode ..." );
- dev->clean_device = 1;
- dev->clean_start_time = device_uptime_sec();
-
- }else if( dev->clean_device && to_clean_mode_exit ){
-
- MG_LOGI( "exit clean mode ..." );
- dev->clean_device = 0;
- dev->clean_start_time = 0;
- }else if( !dev->clean_device && !dev->netconfig && to_net_config ){
- MG_LOGI( "enter net config mode ..." );
- printf( "pressed key -- start net config\n" );
- }
-
- if( !dev->clean_device && !dev->netconfig ){
- //获取单击按键的键值
- if( dev->st != DS_ACTIVE ){
- //未激活,不响应按键
- }else if((btn_code = get_single_click_code( &btn_msg ))){
- //MG_LOGD( "key led flash fast, btn_code:%04X\n", btn_code );
- led_flash_for_btn_single_click( dev, btn_code ); //单击,LED快闪
- }else if((btn_code = get_double_click_code( &btn_msg ))){
- led_flash_for_btn_single_click( dev, btn_code ); //双击,LED快闪
- }else if((btn_code = get_long_press_code( &btn_msg ))){
- led_flash_for_btn_single_click( dev, btn_code ); //长按,LED快闪
- }else if((btn_code = get_long_press_up_code( &btn_msg ))){
- }
- }
- }
-
- dev_st_t st = dev->st;
- if( dev->clean_device ){
- light_mode_set( dev, LIGHT_MODE_CLEAN );
- }
- }
- return 0;
-}
-
-static pthread_t th;
-
-void btn_light_ctrl_init( mg_dev_t *dev )
-{
- uint32_t tof_threshold_cm;
-
- device_button_init( dev );
- device_light_init( dev );
-}
-
-void btn_light_ctrl_start( mg_dev_t *dev )
-{
- if( pthread_create( &th, NULL, btn_light_ctrl_task, (void *)dev ) != 0 ){
- MG_LOGE( "create button and light ctrl task fail!\n" );
- }
-}
-
+++ /dev/null
-//led manage.c
-//#include "led.h"
-//#include "mg_log.h"
-//#include "button.h"
-#include "device.h"
-
-typedef struct{
- uint32_t key_led_max;
- uint32_t fun_led_max;
- uint32_t ir_led_max;
- uint32_t ring_led_max;
-
- //uint32_t ir_led_max;
- light_mode_t mode;
- uint32_t dev_clean;
- time_t clean_timeout;
-}lightinfo_t;
-
-static lightinfo_t g_lightinfo; //保存灯状态
-
-void device_light_init( mg_dev_t *dev )
-{
- MG_LOGI( "device light init" );
- g_lightinfo.mode = LIGHT_MODE_INIT;
- g_lightinfo.key_led_max = 100;
- g_lightinfo.fun_led_max = 100;
-
- dev->light= mg_led_open();
-
- //MG_LOGI( "device light init, g_led_ctrl:%p", g_led_ctrl );
- if( dev->light ){
- light_cfg_t cfg;
- load_light_cfg( &cfg );
- mg_led_br_set( dev->light, cfg.br );
- light_mode_set( dev, LIGHT_MODE_INIT );
- }else{
- MG_LOGE( "mg_led_open fail!" );
- }
-}
-/*
-char *light_mode_name[]={
- "led_off",
- "led_on",
- "led_flash_1hz",
- "led_flash_2hz",
- "led_flash_8hz",
- "led_flash",
- "led_gradual_on",
- "led_gradual_off",
- "led_breath",
- "led_nochange",
-};
-*/
-static const char* light_mode_name[] = {
- "LIGHT_MODE_INIT", //开机初始状态,所有灯常灭
- "LIGHT_MODE_NO_AUTH", //未授权:控制所有按键背光连续慢闪,装饰灯带常灭;不加载涂鸦 SDK应用程序轮询授权是否已写入,并校验写入长度符合要求;
- "LIGHT_MODE_AUTH_NO_WIFICONFIG", //已授权未配网:所有灯光常灭;
- "LIGHT_MODE_AUTH_WIFICONFIGING", //配网过程中 LED7 & LED8 连续慢闪, 2分钟超时后退出
- "LIGHT_MODE_AUTH_WIFICONFIG_NO_ACTIVE", //已授权已配网未激活:所有灯光常灭;
- "LIGHT_MODE_ACTIVE", //已授权已配网已激活:进入主流程,灯光根据 DP 设置处理。
- "LIGHT_MODE_CLEAN",
- "LIGHT_MODE_TOF_ACTIVE",
- "LIGHT_MODE_TOF_DEACTIVE"
-};
-
-void light_mode_set( mg_dev_t *dev, light_mode_t mode )
-{
- uint32_t dur_sec;
- uint32_t key_mask = cfg_mg_key_enable_read( dev );
- light_mode_t old_mode;
-
- if( g_lightinfo.mode == mode )
- return;
-
- MG_LOGI( "light mode %s -> %s", light_mode_name[g_lightinfo.mode], light_mode_name[mode] );
- old_mode = g_lightinfo.mode;
- g_lightinfo.mode = mode;
-
- if( old_mode == LIGHT_MODE_AUTH_WIFICONFIGING ){
- //退出配网,关闭led闪
- key_led_off( dev->light, LED_ID_KEY_ALL, 0, 0, 0);
- atmos_led_off( dev->light, LED_ID_ATMOS_ALL, 0, 0, 0);
- ring_led_off( dev->light, 0, 0, 0);
- usleep( 100*1000 ); //delay 100ms 等待led task关灯
- }
-
- switch( g_lightinfo.mode ){
- case LIGHT_MODE_INIT:
- key_led_off( dev->light, LED_ID_KEY_ALL, 0, 0, 0);
- atmos_led_off( dev->light, LED_ID_ATMOS_ALL, 0, 0, 0);
- ring_led_off( dev->light, 0, 0, 0);
- break;
- case LIGHT_MODE_NO_AUTH:
- key_led_flash( dev->light, LED_ID_KEY_ALL&key_mask, 1000, 0);
- atmos_led_off( dev->light, LED_ID_ATMOS_ALL, 0, 0, 0);
- ring_led_off( dev->light, 0, 0, 0);
- break;
- case LIGHT_MODE_CLEAN: //clean mode en
- //进入清洁模式,所有 LED 连续慢闪;
- key_led_flash( dev->light, LED_ID_KEY_ALL&key_mask, 1000, 0);
- atmos_led_flash( dev->light, LED_ID_ATMOS_ALL, 1000, 0);
- break;
-
- case LIGHT_MODE_AUTH_WIFICONFIGING : //wifi config
- key_led_off( dev->light, LED_ID_KEY_ALL&~(LED_ID_KEY_7|LED_ID_KEY_8), 0, 0, 0);
- key_led_flash( dev->light, LED_ID_KEY_7|LED_ID_KEY_8, 1000, 0);
- atmos_led_off( dev->light, LED_ID_ATMOS_ALL, 0, 0, 0);
- //进入配网模式,所有 LED7 LED8 连续慢闪;
- break;
-
- case LIGHT_MODE_AUTH_WIFICONFIG_NO_ACTIVE: //
- key_led_off( dev->light, LED_ID_KEY_ALL, 0, 0, 0);
- atmos_led_off( dev->light, LED_ID_ATMOS_ALL, 0, 0, 0);
- ring_led_off( dev->light, 0, 0, 0);
- break;
-
- case LIGHT_MODE_ACTIVE: //
- if( cfg_bl_mode_read( dev) ){
- //manual mode
- key_led_on( dev->light, LED_ID_KEY_ALL&key_mask, 0, cfg_key_led_max_read( dev ), 0);
- atmos_led_on( dev->light, LED_ID_ATMOS_ALL, 0, cfg_atmos_led_max_read( dev ), 0);
- }
- break;
-
- case LIGHT_MODE_TOF_ACTIVE: //
- dur_sec = cfg_led_atmos_off_duration_read( dev );
- key_led_on( dev->light, LED_ID_KEY_ALL&key_mask, 0, 100, dur_sec*1000 );
- atmos_led_off( dev->light, LED_ID_ATMOS_ALL, 100, 0, dur_sec*1000 );
- //ring_led_breath( dev->light, 4000, 10*1000 );
- break;
-
- case LIGHT_MODE_TOF_DEACTIVE: //
- dur_sec = cfg_led_atmos_on_duration_read( dev );
- key_led_off( dev->light, LED_ID_KEY_ALL, 100, 0, dur_sec*1000 );
- //atmos_led_on( dev->light, LED_ID_ATMOS_ALL, 0, 100, 3*1000 );
- atmos_led_on( dev->light, LED_ID_ATMOS_ALL, 0, 100, dur_sec*1000 );
- //ring_led_breath( dev->light, 2000, 0 );
- break;
-
- }
-}
-
-void light_set_atmos_br( mg_dev_t *dev, uint32_t id, uint32_t br )
-{
- atmos_led_br_update( dev->light, id, br );
-}
-void light_set_key_br( mg_dev_t *dev, uint32_t id, uint32_t br )
-{
- key_led_br_update( dev->light, id, br );
-}
-
-void led_flash_for_btn_single_click( mg_dev_t *dev, button_code_t btn_code )
-{
- uint32_t led_id = 0;
-
- if( btn_code & BUTTON_1 ) led_id = LED_ID_KEY_1;
- else if( btn_code & BUTTON_2 ) led_id = LED_ID_KEY_2;
- else if( btn_code & BUTTON_3 ) led_id = LED_ID_KEY_3;
- else if( btn_code & BUTTON_4 ) led_id = LED_ID_KEY_4;
- else if( btn_code & BUTTON_5 ) led_id = LED_ID_KEY_5;
- else if( btn_code & BUTTON_6 ) led_id = LED_ID_KEY_6;
- else if( btn_code & BUTTON_7 ) led_id = LED_ID_KEY_7;
- else if( btn_code & BUTTON_8 ) led_id = LED_ID_KEY_8;
-
- if( led_id ){
- key_led_flash( dev->light, led_id, 125, 1*1000 );
- }
-}
-
+++ /dev/null
-#include "device.h"
-#include "mg_version.h"
-
-#define MG_ST_PATH "/var/run/mg_app/"
-//#define MG_VER_PATH "/var/run/mg_app/version"
-
-static int32_t version_init( void )
-{
- if( system( "echo " SW_VERSION " > " MG_ST_PATH "version" ) ){
- //
- }
- return 0;
-}
-
-int32_t mg_device_run_st_init( mg_dev_t *dev )
-{
- version_init();
-
- return 0;
-}
-
-
#include <stdio.h>
#include <stdint.h>
-#include <stdlib.h>
-#include <string.h>
-#include <unistd.h>
-#include <zlib.h>
-#include <sys/types.h>
-#include <sys/stat.h>
-#include <fcntl.h>
-#include <errno.h>
-
-//#include "button.h"
-//#include "led.h"
-//#include "iot.h"
-//#include "mg_log.h"
+#include "button.h"
+#include "led.h"
+#include "rfjb_log.h"
#include "device.h"
-///#include "version.h"
-//#include "rk_ble_app.h"
-
-#include "modbus/modbus.h"
-
-#define PID_FILE "/var/run/mg_app/mg_app.pid"
-
-extern int32_t read_device_uuid( mg_dev_t *dev );
-
-static mg_dev_t g_mg_dev;
-
-time_t device_uptime_msec( void )
-{
- struct timespec ts;
-
- clock_gettime( CLOCK_BOOTTIME, &ts );
-
- return (time_t )(ts.tv_sec*1000+ts.tv_nsec/1000/1000);
-}
-
-time_t device_uptime_sec( void )
-{
- //struct sysinfo info;
- //( sysinfo( &info ) ){
- //return info.uptime;
- struct timespec ts;
-
- clock_gettime( CLOCK_BOOTTIME, &ts );
-
- return ts.tv_sec;
-}
-
-char * dev_uuid_str( void )
-{
- return g_mg_dev.uuid;
-}
-
-mg_dev_t * mg_dev_get( void )
-{
- return &g_mg_dev;
-}
-
-char * mg_st_name( dev_st_t st )
-{
- if( st == DS_INIT ) return "DS_INIT";
- else if( st == DS_NO_AUTH ) return "DS_NO_AUTH";
- else if( st == DS_AUTH_NO_WIFICONFIG ) return "DS_AUTH_NO_WIFICONFIG";
- else if( st == DS_AUTH_WIFICONFIGING ) return "DS_AUTH_WIFICONFIGING";
- else if( st == DS_AUTH_WIFICONFIG_NO_ACTIVE ) return "DS_AUTH_WIFICONFIG_NO_ACTIVE";
- else if( st == DS_ACTIVE ) return "DS_ACTIVE";
- else if( st == DS_INVALID ) return "DS_INVALID";
- return "unkown";
-}
-
-dev_st_t mg_device_st_get( mg_dev_t *dev )
-{
- dev_st_t st = DS_INVALID;
- if( dev ){
- mg_dev_lock( dev );
- st = g_mg_dev.st;
- mg_dev_unlock( dev );
- }
- return st;
-}
-
-dev_st_t mg_device_st_set( mg_dev_t *dev, dev_st_t st )
-{
- dev_st_t old_st;
-
- if( !dev || st >= DS_INVALID)
- return DS_INVALID;
-
- mg_dev_lock( dev );
- old_st = dev->st;
- dev->st = st;
- mg_dev_unlock( dev );
-
- if( old_st != st ){
- MG_LOGD( "mg device st %s -> %s\n", mg_st_name( old_st ), mg_st_name( st ) );
- if( st == DS_INIT ){
- light_mode_set( dev, LIGHT_MODE_INIT );
- }else if( st == DS_NO_AUTH ){
- light_mode_set( dev, LIGHT_MODE_NO_AUTH );
- }else if( st == DS_AUTH_NO_WIFICONFIG){
- light_mode_set( dev, LIGHT_MODE_AUTH_NO_WIFICONFIG );
- }else if( st == DS_AUTH_WIFICONFIG_NO_ACTIVE ){
- light_mode_set( dev, LIGHT_MODE_AUTH_WIFICONFIG_NO_ACTIVE );
- }else if( st == DS_ACTIVE){
- light_mode_set( dev, LIGHT_MODE_ACTIVE );
- }
- }
-
- return old_st;
-}
-
-static int alone_runnind(void)
-{
- int fd;
- char buf[16];
- struct flock fl;
-
- fd = open(PID_FILE, O_RDWR | O_CREAT, 0666);
- if (fd < 0)
- {
- perror("open");
- // exit(1);
- return 0;
- }
-
- fl.l_type = F_WRLCK;
- fl.l_start = 0;
- fl.l_whence = SEEK_SET;
- fl.l_len = 0;
-
- if(fcntl(fd, F_SETLK, &fl)<0)
- {
- if (errno == EACCES || errno == EAGAIN)
- {
- close(fd);
- //printf("alone runnind\n");
- return -1;
- }
-
- printf("can't lock %s: %s\n", PID_FILE, strerror(errno));
-
- }
-
- if( ftruncate(fd, 0) ){ //设置文件的大小为0
- }
-
- sprintf(buf, "%ld\n", (long)getpid());
- if( write(fd, buf, strlen(buf) + 1)){
- }
-
- //这里不关闭文件, 保持锁定状态
- return 0;
-}
-
-int32_t mg_device_init( mg_dev_t *dev )
-{
-
- if( !dev )
- return -1;
-
- memset( dev, 0, sizeof( mg_dev_t ) );
+#ifdef __x86_64__
+//#warning "PC Version Debug"
+#endif
- read_device_uuid( dev );
+static rfjb_dev_t g_rfjb_dev;
- pthread_mutex_init( &dev->lock, NULL );
-
- //从配置文件读取参数
- load_device_cfg( &dev->cfg );
- //printf( "load cfg, key_led_max:%d, led_atmos_off_duration:%d\n", g_mg_dev.cfg.key_led_max, g_mg_dev.cfg.led_atmos_off_duration );
-
- dev->st = DS_INIT;
-
- //var/run/mg_app目录下输出信息
- mg_device_run_st_init( dev );
-
- return 0;
-}
-
-char* program_name = NULL;
-
-int modbus_test( void )
+int32_t rfjb_device_init( rfjb_dev_t *dev )
{
- modbus_t *ctx = NULL;
- uint16_t tab_reg[64];
- int rc;
-
- // 创建Modbus RTU主机上下文
- ctx = modbus_new_rtu("/dev/ttyUSB0", 9600, 'N', 8, 1);
- if (ctx == NULL) {
-
- fprintf(stderr, "无法创建Modbus RTU主机上下文\n");
- exit(1);
- }
- // 设置Modbus主机从机地址
- modbus_set_slave(ctx, 1);
+ rfjb_log_init();
- // 打开Modbus RTU连接
- if (modbus_connect(ctx) == -1) {
+ if( !dev )
+ return -1;
- fprintf(stderr, "无法连接到Modbus RTU从机: %s\n", modbus_strerror(errno));
- modbus_free(ctx);
- exit(1);
- }
+ memset( dev, 0, sizeof( rfjb_dev_t ) );
- // 读取Modbus寄存器
- rc = modbus_read_registers(ctx, 0, 1, tab_reg);
- if (rc == -1) {
+ read_device_uuid( dev );
- fprintf(stderr, "无法读取Modbus寄存器: %s\n", modbus_strerror(errno));
- modbus_free(ctx);
- exit(1);
- }
+ pthread_mutex_init( &dev->lock, NULL );
- printf("从Modbus RTU从机读取的温度值是:%d\n", tab_reg[0]);
+ load_factory_cfg( &dev->factory_cfg);
+ //从配置文件读取参数
+ load_device_cfg( &dev->cfg );
- // 关闭Modbus连接
- modbus_close(ctx);
- modbus_free(ctx);
+ button_init();
+ led_init();
return 0;
}
-
-int main( int argc, char**argv )
+int main( void )
{
- if( argc > 1 ){
- printf( "\n\nmg_app version: %s\n\n", SW_VERSION );
- exit( 0 );
- }
-
- program_name = strdup( argv[0] );
-
- //检查程序是否已经运行
- if( alone_runnind() ){
- printf( "APP is alread runnig!\n" );
- exit( -1 );
- }
-
- MG_LOGD( "modbus test..." );
- printf( "modbus test......\n" );
- modbus_test();
-
-
- mg_log_init();
- MG_LOGD( "mg app start..." );
-
- //设备状态初始化
- mg_device_init( &g_mg_dev );
-
- //中间件初始化
- btn_light_ctrl_init( &g_mg_dev );
-
- //device_wifi_init();
-
- // 启动wifi task;
- //device_wifi_start();
-
- //启动背光按键控制
- btn_light_ctrl_start( &g_mg_dev );
-
- //检查授权文件
-
- //检查配网状态
-
- if( is_device_active( &g_mg_dev ) ){
- //已经激活
- mg_device_st_set( &g_mg_dev, DS_ACTIVE );
- }else{
- //未激活
- mg_device_st_set( &g_mg_dev, DS_AUTH_WIFICONFIG_NO_ACTIVE );
- }
- //连接涂鸦IOT平台
-
- //等待涂鸦连接
-
- //上报激活状态
-
- //未激活则连接tuya等待激活完成
- if( !is_device_active( &g_mg_dev ) ){
-
- mg_device_st_set( &g_mg_dev, DS_AUTH_WIFICONFIG_NO_ACTIVE );
-
- //启动激活流程,堵塞,等待激活成功后返回
- mg_device_active( &g_mg_dev );
-
- //上报激活状态
- }
-
- //激活,正常运行
- mg_device_st_set( &g_mg_dev, DS_ACTIVE );
-
- //上报所有dp 信息。
-
- //启动手势识别子流程
-
- ///rk_ble_wifi_init( NULL );
- while(1){
- //TODO:
- sleep(5*1000);
- }
+ printf( "rfjb app start ...\n" );
+ rfjb_device_init( &g_rfjb_dev );
+ RFJB_LOGI( "LOGI rfjb app quit...\n" );
return 0;
-
}
cmake_minimum_required(VERSION 3.8)
-project(mg_button)
+project(rfjb_button)
SET(CMAKE_BUILD_TYPE "Debug")
SET(CMAKE_CXX_FLAGS_DEBUG "$ENV{CXXFLAGS} -O0 -Wall -g2 -ggdb")
link_directories(
)
-add_executable( button_test test/button.c )
-target_link_libraries(
- button_test
- PUBLIC
- mg_button
- mg_log
- log4c
- pthread
-)
-
-install( TARGETS button_test RUNTIME DESTINATION /app/test )
+#add_executable( button_test test/button.c )
+#target_link_libraries(
+# button_test
+# PUBLIC
+# mg_button
+# mg_log
+# log4c
+# pthread
+#)
+
+#install( TARGETS button_test RUNTIME DESTINATION /app/test )
-#ifndef __BUTTON__H__
-#define __BUTTON__H__
-
-#include <stdio.h>
-#include <stdint.h>
-#include <stdlib.h>
-#include <string.h>
-
-#include <linux/input.h>
-#include <pthread.h>
-
-#define BUTTON_DEVICE_PATH "/dev/input/event2"
-
-typedef enum{
- BUTTON_1 = (1<<0),
- BUTTON_2 = (1<<1),
- BUTTON_3 = (1<<2),
- BUTTON_4 = (1<<3),
- BUTTON_5 = (1<<4),
- BUTTON_6 = (1<<5),
- BUTTON_7 = (1<<6),
- BUTTON_8 = (1<<7),
- BUTTON_9 = (1<<8),
- BUTTON_ALL = 0x1ff,
-}button_code_t;
-
-typedef enum{
- EVENT_SINGLE_CLICK = (1<<0),
- EVENT_DOUBLE_CLICK = (1<<1),
- EVENT_LONG_PRESS = (1<<2),
- EVENT_LONG_PRESS_2S = (1<<3),
- EVENT_LONG_PRESS_5S = (1<<4),
- EVENT_LONG_PRESS_UP = (1<<5),
- EVENT_COMB_PRESS = (1<<6),
- EVENT_COMB_PRESS_2S = (1<<7),
- EVENT_COMB_PRESS_5S = (1<<8),
-}button_event_t;
-
-typedef void* btn_ctrl_t;
-
-typedef void ( * button_event_cb_t )( button_code_t code, button_event_t evt, void * value );
-
-btn_ctrl_t mg_button_open( char * button_device_path );
-void mg_button_close( btn_ctrl_t btn_ctrl );
-int32_t mg_button_event_register( btn_ctrl_t btn_ctrl, button_code_t code, button_event_t event, button_event_cb_t cb );
-int32_t mg_button_event_combonation_register( btn_ctrl_t btn_ctrl, button_code_t code, button_event_t event, uint32_t time_ms, button_event_cb_t cb );
-
-uint32_t mg_button_pressed_code( btn_ctrl_t btn_ctrl ); //读取button按下状态,
-
-#endif //__BUTTON__H__
+#ifndef __BUTTON_H__
+#define __BUTTON_H__
+int button_init( void );
+#endif //__BUTTON_H__
-#include <stdio.h>
#include <stdint.h>
-#include <stdlib.h>
+#include <stdio.h>
#include <string.h>
-#include <sys/types.h>
-#include <sys/stat.h>
-#include <fcntl.h>
-#include <unistd.h>
-
-//#include <linux/input.h>
-#include <pthread.h>
#include "button.h"
-#include "mg_log.h"
-
-#define SINGLE_BTN_CB_MAX 50
-#define COMB_BTN_CB_MAX 50
-
-typedef struct{
- uint32_t code;
- uint32_t event;
- button_event_cb_t cb;
-} cb_item_t;
-
-typedef struct{
- cb_item_t single_cb[SINGLE_BTN_CB_MAX];
- cb_item_t comb_cb[COMB_BTN_CB_MAX];
- uint32_t single_nr;
- uint32_t comb_nr;
- pthread_mutex_t lock;
-}btn_cb_list_t;
-
-typedef struct mg_button{
- char dev_path[100];
- int32_t fd;
- int32_t lock;
- pthread_t btn_thread;
- btn_cb_list_t cb_list;
- uint32_t pressed_code;
-} mg_button_t;
-
-static btn_ctrl_t g_btn_ctrl;
-
-extern void btn_scan( btn_ctrl_t btn_ctrl, uint32_t btn_pressed_code );
-static void* button_task( void* param );
-
-uint32_t button_code( uint32_t key_code )
+int button_init( void )
{
- if( key_code == KEY_1 ) return BUTTON_1;
- else if( key_code == KEY_2 ) return BUTTON_2;
- else if( key_code == KEY_3 ) return BUTTON_3;
- else if( key_code == KEY_4 ) return BUTTON_4;
- else if( key_code == KEY_5 ) return BUTTON_5;
- else if( key_code == KEY_6 ) return BUTTON_6;
- else if( key_code == KEY_7 ) return BUTTON_7;
- else if( key_code == KEY_8 ) return BUTTON_8;
- else if( key_code == KEY_9 ) return BUTTON_9;
+ printf( "button init\n" );
return 0;
}
-
-void* button_task( void* param )
-{
- mg_button_t *p_button;
- struct input_event ev[64];
- int i, rd;
- fd_set rdfs;
- int32_t fd;
- int32_t retval;
-
- struct timeval timeout;
-
- p_button = ( mg_button_t*)param;
- if( !p_button ){
- goto error;
- }
- fd = p_button->fd;
-
-
- while (1) {
- timeout.tv_sec = 0;
- timeout.tv_usec = 10*1000;
- FD_ZERO(&rdfs);
- FD_SET(fd, &rdfs);
- retval = select(fd + 1, &rdfs, NULL, NULL, &timeout);
- if( retval == 0 ){
- //timeout call btn_scan
- btn_scan( (btn_ctrl_t)p_button, p_button->pressed_code );
- continue;
- }
-
- rd = read(fd, ev, sizeof(ev));
-
- if (rd < (int) sizeof(struct input_event)) {
- MG_LOGE( "Button read event err!expected %d bytes, got %d\n", (int) sizeof(struct input_event), rd);
- //TODO:
- return NULL;
- }
-
- for (i = 0; i < rd / sizeof(struct input_event); i++) {
- unsigned int type, code, value;
-
- type = ev[i].type;
- code = ev[i].code;
- value = ev[i].value;
-
- if( type==EV_KEY ){
- if( value == 0 ){
- p_button->pressed_code &= ~( 1<< (code - KEY_1 ) );
- //printf( "btn up...code:%x\n", pressed_code );
- }else if( value == 1 ){
- p_button->pressed_code |= ( 1<< (code - KEY_1 ) );
- //printf( "btn down...code:%x\n", pressed_code );
- }
-
- //printf( "EV_KEY : KEY_%d, value:%d\n", code - KEY_1 +1, ev[i].value );
- continue;
- }
- } //for
- } //while
-
- ioctl(fd, EVIOCGRAB, (void*)0);
-error:
- return NULL;
-}
-
-
-btn_ctrl_t mg_button_open( char * button_device_path )
-{
- int32_t fd;
- pthread_t btn_thread;
-
- mg_button_t *button;
-
- if( g_btn_ctrl ){
- //busy
- goto error;
- }
-
- button = ( mg_button_t *)malloc( sizeof( mg_button_t ) );
- if( !button ){
- goto error;
- }
- memset( button, 0, sizeof( mg_button_t ) );
-
- if( button_device_path)
- strcpy( button->dev_path, button_device_path );
- else
- strcpy( button->dev_path, BUTTON_DEVICE_PATH );
-
- if ((fd = open(button->dev_path, O_RDONLY)) < 0) {
- MG_LOGE( "open button device[%s] fail!", button->dev_path );
- goto error;
- }
-
- if( pthread_create( &btn_thread, NULL, button_task, (void *)button ) != 0 ){
- MG_LOGE( "create button task fail!" );
- perror("create button task!");
- goto error;
- }
-
- button->fd = fd;
- button->btn_thread = btn_thread;
-
- memset( &button->cb_list, 0, sizeof( button->cb_list ) );
- pthread_mutex_init( &button->cb_list.lock, NULL );
-
- g_btn_ctrl = (btn_ctrl_t)button;
-
- return g_btn_ctrl;
-error:
- return 0;
-}
-
-void mg_button_close( btn_ctrl_t btn_ctrl )
-{
- if( btn_ctrl && btn_ctrl == g_btn_ctrl ){
- g_btn_ctrl = 0;
- free( (void *)btn_ctrl );
- }
-}
-
-int32_t mg_button_event_register( btn_ctrl_t btn_ctrl, button_code_t code, button_event_t event, button_event_cb_t cb )
-{
- uint32_t found = 0;
- uint32_t i;
- btn_cb_list_t *p_list = &((mg_button_t*)btn_ctrl)->cb_list;
-
- MG_LOGI( "regiser single btn, code:%x, event:%x", code, event );
-
- pthread_mutex_lock( &p_list->lock );
- for( i=0; i < p_list->single_nr; i++ ){
- if( (p_list->single_cb[i].code & code )==code
- && (p_list->single_cb[i].event & event)==event ){
- found = 1;
-
- p_list->single_cb[i].cb = cb;
- break;
- }
- }
- if( !found && p_list->single_nr < SINGLE_BTN_CB_MAX ){
- i = p_list->single_nr;
- p_list->single_cb[i].code = code;
- p_list->single_cb[i].event = event;
- p_list->single_cb[i].cb = cb;
- p_list->single_nr+=1;
- }
- pthread_mutex_unlock( &p_list->lock );
-
- return 0;
-}
-
-int32_t mg_button_event_combonation_register( btn_ctrl_t btn_ctrl, button_code_t code, button_event_t event, uint32_t time_ms, button_event_cb_t cb )
-{
- uint32_t i;
- uint32_t found = 0;
- int32_t retval = 0;
- btn_cb_list_t *p_list = &((mg_button_t*)btn_ctrl)->cb_list;
-
- MG_LOGI( "regiser comb btn, code:%x, event:%x", code, event );
-
- pthread_mutex_lock( &p_list->lock );
- for( i=0; i < p_list->comb_nr; i++ ){
- if( p_list->comb_cb[i].code ==code
- && (p_list->comb_cb[i].event & event)==event ){
- found = 1;
- p_list->comb_cb[i].cb = cb;
- break;
- }
- }
- if( !found && p_list->comb_nr < COMB_BTN_CB_MAX ){
- i = p_list->comb_nr;
- p_list->comb_cb[i].code = code;
- p_list->comb_cb[i].event = event;
- p_list->comb_cb[i].cb = cb;
- p_list->comb_nr+=1;
- }else{
- retval = -1;
- }
- pthread_mutex_unlock( &p_list->lock );
- return retval;
-}
-
-button_event_cb_t find_single_cb( btn_ctrl_t btn_ctrl, uint32_t code, uint32_t event )
-{
- int32_t found = 0;
- uint32_t i;
- button_event_cb_t cb = NULL;
- btn_cb_list_t *p_list = &((mg_button_t*)btn_ctrl)->cb_list;
-
- pthread_mutex_lock( &p_list->lock );
- for( int i=0; i < p_list->single_nr; i++ ){
- if( (p_list->single_cb[i].code & code )==code
- && (p_list->single_cb[i].event & event)==event ){
- cb = p_list->single_cb[i].cb;
- break;
- }
- }
- pthread_mutex_unlock( &p_list->lock );
-
- return cb;
-}
-
-button_event_cb_t find_comb_cb( btn_ctrl_t btn_ctrl, uint32_t code, uint32_t event )
-{
- int32_t found = 0;
- uint32_t i;
- button_event_cb_t cb = NULL;
-
- btn_cb_list_t *p_list = &((mg_button_t*)btn_ctrl)->cb_list;
-
- pthread_mutex_lock( &p_list->lock );
- for( int i=0; i < p_list->comb_nr; i++ ){
- if( p_list->comb_cb[i].code ==code ){
- if( (p_list->comb_cb[i].event & event)==event ){
- cb = p_list->comb_cb[i].cb;
- }
- break;
- }
- }
- pthread_mutex_unlock( &p_list->lock );
-
- return cb;
-}
-//----------------------------------------------------------------------------------
-
-//读取button按下状态,
-uint32_t mg_button_pressed_code( btn_ctrl_t btn_ctrl )
-{
- mg_button_t *p_button;
- p_button = ( mg_button_t*)btn_ctrl;
- return p_button->pressed_code;
-}
-
+++ /dev/null
-
-#include <stdio.h>
-#include <stdlib.h>
-#include <stdint.h>
-#include <string.h>
-#include <time.h>
-#include <sys/time.h>
-#include <time.h>
-#include <unistd.h>
-
-#include "button.h"
-
-typedef struct {
- uint32_t st; //0:up idle, 1: pressed, 2:up wait 250ms for next pressed. 3: double_pressed 8:wait all key released
- uint32_t code; //btn_code
- uint32_t pressed_tick;
- uint32_t up_tick;
- uint32_t single_click;
- uint32_t double_click;
- uint32_t long_press_1s;
- uint32_t long_press_2s;
- uint32_t long_press_5s;
- uint32_t long_press_up;
-}single_btn_st_t;
-
-typedef struct{
- uint32_t st; //0 idle, 1:combo pressed, 2:wait all released
- uint32_t code;
- uint32_t pressed_tick;
- uint32_t long_press_1s;
- uint32_t long_press_2s;
- uint32_t long_press_5s;
-}comb_btn_st_t;
-
-
-extern button_event_cb_t find_single_cb( btn_ctrl_t btn_ctrl, uint32_t code, uint32_t event );
-extern button_event_cb_t find_comb_cb( btn_ctrl_t btn_ctrl, uint32_t code, uint32_t event );
-
-static single_btn_st_t single_st;
-static comb_btn_st_t comb_st;
-
-int32_t is_comb_code( btn_ctrl_t btn_ctrl, uint32_t code )
-{
- if( find_comb_cb( btn_ctrl, code, 0 ) )
- return 1;
- else
- return 0;
-}
-
-static uint32_t get_systime_ms( void )
-{
- //struct timeval tm;
- //gettimeofday( &tm, NULL );
- //return (uint32_t)(tm.tv_sec*1000+tm.tv_usec/1000);
- struct timespec ts;
-
- clock_gettime( CLOCK_BOOTTIME, &ts );
-
- return (time_t )(ts.tv_sec*1000+ts.tv_nsec/1000/1000);
-}
-
-void single_btn_report( btn_ctrl_t btn_ctrl, uint32_t code, button_event_t event )
-{
- button_event_cb_t cb;
-
- cb = find_single_cb( btn_ctrl, code, event );
- if( cb )
- cb( code, event, NULL );
-}
-
-void comb_btn_report( btn_ctrl_t btn_ctrl, uint32_t code, button_event_t event )
-{
- button_event_cb_t cb;
-
- cb = find_comb_cb( btn_ctrl, code, event );
- if( cb )
- cb( code, event, NULL );
-}
-
-void comb_btn_scan( btn_ctrl_t btn_ctrl, comb_btn_st_t *comb, uint32_t pressed_code )
-{
- uint32_t curr_time_ms = get_systime_ms();
- static uint32_t dbg_comb_code =0;
-#if 1
- //for debug
- if( dbg_comb_code != pressed_code ){
- printf( "comb_btn scan: pressed code: %02x -> %02x\n", dbg_comb_code, pressed_code );
- dbg_comb_code = pressed_code;
- }
-#endif
- switch( comb->st ){
- case 0: //idle
- if( is_comb_code( btn_ctrl, pressed_code ) ){
- comb->st = 1;
- comb->code = pressed_code;
- comb->pressed_tick = get_systime_ms();
- comb->long_press_1s = 0;
- comb->long_press_2s = 0;
- comb->long_press_5s = 0;
- }
- break;
-
- case 1:
- if( pressed_code != comb->code ){
- comb->st = 2; //wait all btn released;
- }else{
- if( !comb->long_press_1s && curr_time_ms - comb->pressed_tick > 1000 ){
- //printf( "---------------comb long press 1s ...%x, time:[%d - %d]\n", comb->code, curr_ms, comb->pressed_tick );
- comb->long_press_1s = 1;
- comb_btn_report( btn_ctrl, comb->code, EVENT_COMB_PRESS );
- }else if( !comb->long_press_2s && curr_time_ms - comb->pressed_tick > 2000 ){
- //printf( "---------------comb long press 2s ...%x\n", comb->code );
- comb->long_press_2s = 1;
- comb_btn_report( btn_ctrl, comb->code, EVENT_COMB_PRESS_2S );
- }else if( !comb->long_press_5s && curr_time_ms - comb->pressed_tick > 5000 ){
- //printf( "---------------comb long press 5s ...%x\n", comb->code );
- comb->long_press_5s = 1;
- comb->st = 2;
- comb_btn_report( btn_ctrl, comb->code, EVENT_COMB_PRESS_5S );
- }
- }
- break;
- case 2:
- if( pressed_code == 0 ){
- comb->st = 0;
- //printf( "comb st -> idle\n" );
- dbg_comb_code =0;
- }
- break;
- }
-}
-
-void single_btn_scan( btn_ctrl_t btn_ctrl, single_btn_st_t * btn, uint32_t pressed_code )
-{
- uint32_t curr_time_ms;
- uint32_t i;
-
- curr_time_ms = get_systime_ms();
-
-#if 1
- //for debug
- static uint32_t code =0;
- if( code != pressed_code ){
- printf( "scan pressed code: %02x -> %02x\n", code, pressed_code );
- code = pressed_code;
- }
-#endif
- switch( btn->st ){
- case 0: //idle
- if( pressed_code&0xff ){
- for( i=0; i<8; i++ ){
- if( pressed_code & (1<<i ) ){
- //记录第一个按键, 其它按键忽略
- btn->code = 1<<i;
- break;
- }
- }
- btn->st = 1;
- btn->single_click = 0;
- btn->double_click = 0;
- btn->long_press_1s = 0;
- btn->long_press_2s = 0;
- btn->long_press_5s = 0;
- btn->long_press_up = 0;
-
- btn->pressed_tick = curr_time_ms;
- btn->up_tick = curr_time_ms;
- }
- break;
- case 1: //first pressed
- if( btn->code & pressed_code ){
- //check long pressed
- if( !btn->long_press_1s && curr_time_ms - btn->pressed_tick > 1000 ){
- btn->long_press_1s = 1;
- //printf( "------------ long press event ...%x\n", btn->code );
- single_btn_report( btn_ctrl, btn->code, EVENT_LONG_PRESS );
- }else if( !btn->long_press_2s && curr_time_ms - btn->pressed_tick > 2000 ){
- btn->long_press_2s = 1;
- //printf( "------------ long press 2s event ...%x\n", btn->code );
- single_btn_report( btn_ctrl, btn->code, EVENT_LONG_PRESS_2S );
- }else if( !btn->long_press_5s && curr_time_ms - btn->pressed_tick > 5000 ){
- btn->long_press_5s = 1;
- //printf( "------------ long press 5s event ...%x\n", btn->code );
- single_btn_report( btn_ctrl, btn->code, EVENT_LONG_PRESS_5S );
- }
-
- }else{
- btn->up_tick = curr_time_ms;
- if( btn->long_press_1s ){
- btn->long_press_up = 1;
- //printf( "------------ long press up event ...%x\n", btn->code );
- btn->st = 8; //等待全部按键放开
- single_btn_report( btn_ctrl, btn->code, EVENT_LONG_PRESS_UP );
- }else{
- btn->st = 2; //wait 250ms
- }
- }
- break;
- case 2: //wait 250ms
- if( btn->code & pressed_code ){
- btn->pressed_tick = curr_time_ms;
- btn->st = 3;
- }else{
- if( curr_time_ms - btn->up_tick > 250 ){
- btn->single_click = 1;
- //printf( "------------------sing click event ...%x\n", btn->code );
- btn->st = 8; //wait all btn released
- single_btn_report( btn_ctrl, btn->code, EVENT_SINGLE_CLICK );
- }
- }
- break;
- case 3: //
- if( btn->code & pressed_code ){
-
- }else{
- btn->up_tick = curr_time_ms;
- btn->double_click = 1;
- //printf( "------------------double click event ...%x\n", btn->code );
- btn->st = 8;
- single_btn_report( btn_ctrl, btn->code, EVENT_DOUBLE_CLICK );
- }
- break;
- case 8:
- if( !pressed_code ){
- btn->code = 0;
- btn->st = 0; //idle
- //printf( "single btn st -> idle\n" );
- }
- break;
- }
-}
-
-void single_btn_init( void )
-{
- memset( &single_st, 0, sizeof( single_st ) );
-}
-
-void comb_btn_init( void )
-{
- memset( &comb_st, 0, sizeof( comb_st ) );
-}
-
-void btn_scan_init( void )
-{
- single_btn_init();
- comb_btn_init();
-}
-
-void btn_scan( btn_ctrl_t btn_ctrl, uint32_t btn_pressed_code )
-{
- uint32_t pressed_code = btn_pressed_code;
-
- if( single_st.st != 0 && single_st.long_press_1s != 0 ){
- //已经产生了长按事件,不检测组合按键
- comb_st.st = 0;
- }else{
- comb_btn_scan( btn_ctrl, &comb_st, pressed_code );
- }
-
- if( comb_st.st == 0 ){ //0:idle, 1:pressing 2: wait all btn releasd
- //非组合按键,扫描单按键
- single_btn_scan( btn_ctrl, &single_st, pressed_code );
- }else{
- //组合按键扫描,不扫描单按键
- single_st.st = 0;
- }
-}
-
+++ /dev/null
-#include <stdio.h>
-#include <stdint.h>
-#include "button.h"
-#include "mg_log.h"
-
-char * btn_name[]={
- "BUTTON_1",
- "BUTTON_2",
- "BUTTON_3",
- "BUTTON_4",
- "BUTTON_5",
- "BUTTON_6",
- "BUTTON_7",
- "BUTTON_8",
-};
-
-static char btn_code_str[100];
-static char btn_event_str[100];
-char * btn_code_name( uint32_t btn_code )
-{
- char *p;
- p = btn_code_str;
- *p = 0;
-
- if( btn_code&BUTTON_1 ){ if( strlen(p)) strcat( p, "+" ); strcat( p, "BUTTON_1" ); }
- if( btn_code&BUTTON_2 ){ if( strlen(p)) strcat( p, "+" ); strcat( p, "BUTTON_2" ); }
- if( btn_code&BUTTON_3 ){ if( strlen(p)) strcat( p, "+" ); strcat( p, "BUTTON_3" ); }
- if( btn_code&BUTTON_4 ){ if( strlen(p)) strcat( p, "+" ); strcat( p, "BUTTON_4" ); }
- if( btn_code&BUTTON_5 ){ if( strlen(p)) strcat( p, "+" ); strcat( p, "BUTTON_5" ); }
- if( btn_code&BUTTON_6 ){ if( strlen(p)) strcat( p, "+" ); strcat( p, "BUTTON_6" ); }
- if( btn_code&BUTTON_7 ){ if( strlen(p)) strcat( p, "+" ); strcat( p, "BUTTON_7" ); }
- if( btn_code&BUTTON_8 ){ if( strlen(p)) strcat( p, "+" ); strcat( p, "BUTTON_8" ); }
- return p;
-}
-
-char * btn_event_name( uint32_t btn_event )
-{
- char *p;
-
- p = btn_event_str;
- *p = 0;
-
- if( btn_event&EVENT_SINGLE_CLICK ){ if( strlen(p)) strcat( p, "+" ); strcat( p, "EVENT_SINGLE_CLICK" ); }
- if( btn_event&EVENT_DOUBLE_CLICK ){ if( strlen(p)) strcat( p, "+" ); strcat( p, "EVENT_DOUBLE_CLICK" ); }
- if( btn_event&EVENT_LONG_PRESS ){ if( strlen(p)) strcat( p, "+" ); strcat( p, "EVENT_LONG_PRESS" ); }
- if( btn_event&EVENT_LONG_PRESS_2S ){ if( strlen(p)) strcat( p, "+" ); strcat( p, "EVENT_LONG_PRESS_2S" ); }
- if( btn_event&EVENT_LONG_PRESS_5S ){ if( strlen(p)) strcat( p, "+" ); strcat( p, "EVENT_LONG_PRESS_5S" ); }
- if( btn_event&EVENT_LONG_PRESS_UP ){ if( strlen(p)) strcat( p, "+" ); strcat( p, "EVENT_LONG_PRESS_UP" ); }
- if( btn_event&EVENT_COMB_PRESS ){ if( strlen(p)) strcat( p, "+" ); strcat( p, "EVENT_COMB_PRESS" ); }
- if( btn_event&EVENT_COMB_PRESS_2S ){ if( strlen(p)) strcat( p, "+" ); strcat( p, "EVENT_COMB_PRESS_2S" ); }
- if( btn_event&EVENT_COMB_PRESS_5S ){ if( strlen(p)) strcat( p, "+" ); strcat( p, "EVENT_COMB_PRESS_5S" ); }
-
- return p;
-}
-
-static void button_single_cb( button_code_t btn_code, button_event_t btn_event, void* value )
-{
- printf( "Single BTN--code:[%s], event:[%s], value:%p\n", btn_code_name(btn_code), btn_event_name(btn_event), value );
-}
-
-static void button_comb_cb( button_code_t btn_code, button_event_t btn_event, void* value )
-{
- printf( "COMB BTN--code:%x, event:%x, value:%p\n", btn_code, btn_event, value );
-}
-
-int main( void )
-{
- btn_ctrl_t btn;
- btn = mg_button_open("/dev/input/by-path/platform-gpio_keys-event" );
- if( !btn ){
- perror( "open button fail!\n" );
- exit(0);
- }
-
- printf( "register all single button event!\n" );
- mg_button_event_register( btn, 0xFF, EVENT_SINGLE_CLICK|EVENT_DOUBLE_CLICK|EVENT_LONG_PRESS|EVENT_LONG_PRESS_UP, button_single_cb );
- printf( "register button_7+button_8 event!\n" );
- mg_button_event_combonation_register( btn, BUTTON_7|BUTTON_8, EVENT_COMB_PRESS_5S, 0, button_comb_cb );
- printf( "register button_2+button_7 event!\n" );
- mg_button_event_combonation_register( btn, BUTTON_2|BUTTON_7, EVENT_COMB_PRESS_2S, 0, button_comb_cb );
-
- while(1){
- sleep(2);
- }
- mg_button_close( btn );
- exit(0);
-}
-
+++ /dev/null
-cmake_minimum_required(VERSION 3.8)
-
-project(mg_buzzer)
-
-SET(CMAKE_BUILD_TYPE "Debug")
-SET(CMAKE_CXX_FLAGS_DEBUG "$ENV{CXXFLAGS} -O0 -Wall -g2 -ggdb")
-SET(CMAKE_CXX_FLAGS_RELEASE "$ENV{CXXFLAGS} -O3 -Wall")
-
-include_directories(
- ${PROJECT_SOURCE_DIR}/./
- ${PROJECT_SOURCE_DIR}/../log/inc/
- ${PROJECT_SOURCE_DIR}/src/
- ${PROJECT_SOURCE_DIR}/inc/
- ${CMAKE_SYSROOT}/usr/include/
- )
-
-aux_source_directory(./src/ SRCS)
-
-add_library( ${PROJECT_NAME} STATIC ${SRCS} )
-#add_library( ${PROJECT_NAME} ${SRCS} )
-#install( TARGETS ${PROJECT_NAME} RUNTIME DESTINATION /app/lib )
-#install( TARGETS ${PROJECT_NAME} LIBRARY DESTINATION /app/lib )
-#install( TARGETS ${PROJECT_NAME} ARCHIVE DESTINATION /app/lib )
-
-#install(FILES ${PROJECT_SOURCE_DIR}/test/buzzer_test DESTINATION /app/test/ )
-install(FILES ${PROJECT_SOURCE_DIR}/test/buzzer_test.txt DESTINATION /app/test/ )
-
-add_executable( buzzer_test test/buzzer_test.c )
-target_link_libraries(
- buzzer_test
- PUBLIC
- mg_buzzer
- mg_log
- log4c
- rt
- pthread
-)
-
-install( TARGETS buzzer_test RUNTIME DESTINATION /app/test )
+++ /dev/null
-#ifndef __BUZZER__H__
-#define __BUZZER__H__
-
-#include <stdio.h>
-#include <stdint.h>
-#include <time.h>
-
-
-struct buzzer_status{
- float freq_hz;
- int32_t duty_cycle;
-};
-
-typedef struct buzzer_status buzzer_status_t;
-
-struct mg_buzzer{
- char* dev_path[5];
- uint32_t enable;
- uint32_t time_ms;
- buzzer_status_t buzzer_x_t[2];
-};
-
-typedef struct mg_buzzer mg_buzzer_t;
-
-mg_buzzer_t * mg_buzzer_open(void);
-void mg_buzzer_close(mg_buzzer_t * buzzer_ctrl);
-void mg_buzzer_start( mg_buzzer_t * buzzer_ctrl, float freq_hz, uint32_t duty_cycle, uint32_t time_ms );
-void mg_buzzer_get( mg_buzzer_t * buzzer_ctrl, float *freq_hz, uint32_t *duty_cycle, uint32_t *time_ms, uint32_t* enable);
-
-#endif //__BUZZER__H__
-
+++ /dev/null
-#include <stdio.h>
-#include <signal.h>
-#include <string.h>
-#include <stdlib.h>
-#include <unistd.h>
-#include <math.h>
-#include "mg_log.h"
-#include "buzzer.h"
-
-
-
-static uint32_t init = 0;
-static timer_t timerid;
-
-
-mg_buzzer_t buzzer_init ={
- .enable = 0,
- .dev_path[0] = "export",
- .dev_path[1] = "unexport",
- .dev_path[2] = "pwm0/period",
- .dev_path[3] = "pwm0/duty_cycle",
- .dev_path[4] = "pwm0/enable",
-
-
-};
-
-static int32_t mg_buzzer_start_t(uint32_t parameter ,char* path)
-{
- char system_cmd[100];
-
- sprintf(system_cmd, "echo %d > /sys/class/pwm/pwmchip6/%s ", parameter, path);
- if(system(system_cmd)){
- MG_LOGE( "system set [%s] failed\r\n",path);
- return -1;
- }
- return 0;
-}
-
-
-
-static void mg_buzzer_enable( mg_buzzer_t *buzzer_x )
-{
- mg_buzzer_start_t(1 , buzzer_x->dev_path[4]);
- buzzer_x->enable = 1;
-}
-
-static int32_t mg_buzzer_disabled(mg_buzzer_t *buzzer_x )
-{
- mg_buzzer_start_t(0 , buzzer_x->dev_path[4]);
- buzzer_x->enable = 0;
- return 0;
-}
-
-static void buzzer_timer_thread(union sigval v)
-{
- MG_LOGD("timer_thread function! %d\n", v.sival_int);
- mg_buzzer_disabled(&buzzer_init);
-}
-
-
-static void mg_buzzer_timer_init()
-{
- struct sigevent evp;
- memset(&evp, 0, sizeof(struct sigevent));
-
- evp.sigev_value.sival_int = 1;
- evp.sigev_notify = SIGEV_THREAD;
- evp.sigev_notify_function = buzzer_timer_thread;
-
- if (timer_create(CLOCK_REALTIME, &evp, &timerid) == -1)
- {
- MG_LOGE("buzzer fail to timer_create! \r\n");
- }
- else{
- MG_LOGD( " buzzer create timer OK !\r\n");
- }
- return;
-}
-
-
-void mg_buzzer_get( mg_buzzer_t * buzzer_ctrl, float *freq_hz, uint32_t *duty_cycle, uint32_t *time_ms, uint32_t* enable)
-{
- MG_LOGD( "tw8013 buzzer get!\n" );
-
- if(buzzer_ctrl->enable)
- {
- *freq_hz = buzzer_ctrl->buzzer_x_t[1].freq_hz;
- *duty_cycle = buzzer_ctrl->buzzer_x_t[1].duty_cycle ;
- *time_ms = buzzer_ctrl->time_ms;
- *enable = buzzer_ctrl->enable;
- }else{
- *freq_hz = 0;
- *duty_cycle = 0;
- *time_ms = 0;
- *enable = 0;
- }
-}
-
-
-static int32_t mg_buzzer_set( mg_buzzer_t * buzzer_ctrl, buzzer_status_t* buzzer_t)
-{
- buzzer_status_t buzzer_x;
-
- buzzer_x.freq_hz = (1 / buzzer_t->freq_hz) * pow(10,9);
- buzzer_x.duty_cycle = buzzer_t->duty_cycle * (buzzer_x.freq_hz / 100);
-
- if(buzzer_ctrl->enable){
- mg_buzzer_disabled(buzzer_ctrl);
- }
-
- if(init){
- //clean duty_cycle
- if(mg_buzzer_start_t(0,buzzer_ctrl->dev_path[3]))
- goto err;
- }
- init = 1;
-
- if(mg_buzzer_start_t((int)buzzer_x.freq_hz,buzzer_ctrl->dev_path[2]))
- goto err;
-
- if(mg_buzzer_start_t(buzzer_x.duty_cycle,buzzer_ctrl->dev_path[3])){
- goto err;
- }else{
- mg_buzzer_enable(buzzer_ctrl);
- buzzer_ctrl->buzzer_x_t[1].freq_hz = buzzer_ctrl->buzzer_x_t[0].freq_hz;
- buzzer_ctrl->buzzer_x_t[1].duty_cycle = buzzer_ctrl->buzzer_x_t[0].duty_cycle;
- }
- return 0;
-err:
- MG_LOGE( "buzzer set failed \r\n");
- return -1;
-}
-
-
-void mg_buzzer_start( mg_buzzer_t * buzzer_ctrl, float freq_hz, uint32_t duty_cycle, uint32_t time_ms )
-{
- buzzer_status_t tmp;
-
- if(freq_hz == 0){
- if(buzzer_ctrl->enable){
- mg_buzzer_disabled(buzzer_ctrl);
- }
- buzzer_ctrl->buzzer_x_t[1].freq_hz = freq_hz;
- buzzer_ctrl->buzzer_x_t[1].duty_cycle = duty_cycle;
- buzzer_ctrl->time_ms = time_ms;
- }else if((freq_hz >= 1) && (freq_hz <= 10000)){
- //Duty cycle limitation
- if(duty_cycle > 100)
- duty_cycle = 100;
- else if(duty_cycle < 0)
- duty_cycle = 0;
-
- tmp.freq_hz = freq_hz;
- tmp.duty_cycle = duty_cycle;
-
- buzzer_ctrl->time_ms = time_ms;
- buzzer_ctrl->buzzer_x_t[0].freq_hz = freq_hz;
- buzzer_ctrl->buzzer_x_t[0].duty_cycle = duty_cycle;
-
- if( time_ms ){
- //start timer...
- struct itimerspec it;
-
- it.it_interval.tv_sec = 0;
- it.it_interval.tv_nsec = 0;
- it.it_value.tv_sec = time_ms/1000;
- it.it_value.tv_nsec = 1000*1000 *(time_ms%1000);
-
- if (timer_settime(timerid, 0, &it, NULL) == -1){
- MG_LOGE( "buzzer start timer fail!\r\n");
- }else{
- MG_LOGD( "buzzer timer start\r\n");
- }
- }
- mg_buzzer_set(buzzer_ctrl,&tmp);
- }else{
- MG_LOGE( "period Out of range Please enter within 1 to 10000\r\n");
- }
-}
-
-
-mg_buzzer_t * mg_buzzer_open(void)
-{
-
- MG_LOGD( "tw8013 buzzer open...\n");
-
- if(access("/sys/class/pwm/pwmchip6/pwm0", 0))
- {
- if(mg_buzzer_start_t(0,buzzer_init.dev_path[0]))
- {
- MG_LOGE( "tw8013 buzzer open failed ...\n");
- return NULL;
- }
- }
- mg_buzzer_timer_init();
- return &buzzer_init;
-}
-
-
-void mg_buzzer_close(mg_buzzer_t * buzzer_ctrl)
-{
- MG_LOGD( "tw8013 buzzer close...\n");
-
- init = 0;
- if(buzzer_ctrl){
- if(!access("/sys/class/pwm/pwmchip6/pwm0", 0))
- {
- mg_buzzer_disabled(buzzer_ctrl);
- mg_buzzer_start_t(0,buzzer_ctrl->dev_path[3]);
- mg_buzzer_start_t(0,buzzer_ctrl->dev_path[1]);
- }
- }
-}
\ No newline at end of file
+++ /dev/null
-#include <stdio.h>
-#include <stdint.h>
-#include <stdlib.h>
-#include <string.h>
-#include <unistd.h>
-#include <zlib.h>
-#include <sys/types.h>
-#include <sys/stat.h>
-#include <fcntl.h>
-#include <errno.h>
-#include "buzzer.h"
-
-
-static mg_buzzer_t* buzzer = NULL;
-
-
-int main(int argc, char *argv[])
-{
- int32_t duty_cycle,timer_ms;
- float period, c;
- int a ,b, e;
- if(argc == 1)
- {
- period = 200;
- duty_cycle = 50;
- timer_ms = 1000;
- }
- else if(argc == 4)
- {
- period = atof(argv[1]);
- duty_cycle = atoi(argv[2]);
- timer_ms = atoi(argv[3]);
- }
-
- if(period > 10000)
- period = 10000;
-
- buzzer = mg_buzzer_open();
- if( buzzer == NULL ){
- printf( "open buzzer failed \n");
- return -1;
- }
-
- mg_buzzer_start(buzzer, period ,duty_cycle , timer_ms);
- mg_buzzer_get(buzzer,&c,&a,&b,&e);
- printf( "1-------main get hz = %f du = %d time = %dms enable = %d\r\n",c,a,b,e);
- sleep(10);
- mg_buzzer_close(buzzer);
- return 0;
-}
\ No newline at end of file
+++ /dev/null
-#将buzzer_test_app测试程序push到板子中
- adb push buzzer_test_app /app/
- chmod a+x buzzer_test_app
-
-#测试程序只会运行10s,10s之后就会退出;
-#频率范围:1-10000HZ 占空比范围:0-100
-
-#使用示例:
- 1-采用默认参数运行
- (默认参数: 频率:200HZ 占空比:50% 播放时间:1000ms)
- ./buzzer_test_app
-
- 2-重新传入参数
- 100:频率HZ 40:占空比% 1000:播放时间ms
- ./buzzer_test_app 100 40 1000
\ No newline at end of file
+++ /dev/null
-cmake_minimum_required(VERSION 3.8)
-
-project(mg_485)
-
-include_directories(
- ${PROJECT_SOURCE_DIR}/./
- ${PROJECT_SOURCE_DIR}/src/
- ${PROJECT_SOURCE_DIR}/inc/
- ${CMAKE_SYSROOT}/usr/include/
- )
-
-aux_source_directory(./src/ SRCS)
-
-add_library( ${PROJECT_NAME} STATIC ${SRCS} )
-#add_library( ${PROJECT_NAME} ${SRCS} )
-#install( TARGETS ${PROJECT_NAME} RUNTIME DESTINATION /app/lib )
-#install( TARGETS ${PROJECT_NAME} LIBRARY DESTINATION /app/lib )
-#install( TARGETS ${PROJECT_NAME} ARCHIVE DESTINATION /app/lib )
+++ /dev/null
-#ifndef _485_H_
-#define _485_H_
-
-/*数据位长度*/
-enum{
- DATA_BITS_5 = 5,
- DATA_BITS_6,
- DATA_BITS_7,
- DATA_BITS_8,
-};
-
-/*停止位长度*/
-enum{
- STOP_BITS_1 = 1,
- DATA_BITS_2 = 2,
-};
-
-/*校验位*/
-enum{
- PARITY_NONE=0,
- PARITY_ODD,
- PARITY_EVEN,
-};
-
-struct mg_eia485{
- char *dev_path;
- int uartFd;
- char *ctl_path;
- int ctlFd;
-};
-typedef struct mg_eia485 mg_eia485_t;
-
-/*打开EIA485控制器*/
-mg_eia485_t * mg_eia485_open(uint32_t baud, uint32_t data_bits, uint32_t stop_bits, uint32_t parity );
-
-/*关闭控制器*/
-void mg_eia485_close( mg_eia485_t * eia485_ctrl );
-
-/*发送数据*/
-int32_t mg_eia485_write(mg_eia485_t * eia485_ctrl, uint8_t * tx_data, uint32_t tx_size );
-
-/*接收数据*/
-int32_t mg_eia485_read( mg_eia485_t * eia485_ctrl,uint8_t * rx_data, uint32_t rx_size, uint32_t timeout_ms );
-
-
-#endif
\ No newline at end of file
+++ /dev/null
-#include <stdio.h>
-#include <stdlib.h>
-#include <fcntl.h>
-#include <unistd.h>
-#include <termios.h>
-#include <string.h>
-#include <stdint.h>
-#include <unistd.h>
-#include <pthread.h>
-
-#include "485.h"
-
-#define UART_DEVICE "/dev/ttyS5" // UART设备文件路径
-#define CTL_DEVICE "/dev/rs485_txen" // UART设备文件路径
-#define FIFO_SIZE 50 // FIFO队列大小
-
-typedef struct {
- unsigned char* buffer;
- int capacity;
- int head;
- int tail;
- int count;
-} FifoQueue;
-
-int time_flag = 0;
-int uartFd = -1;
-int stop = -1;
-FifoQueue receiveQueue;
-
-mg_eia485_t *my_485 = NULL;
-
-
-/*初始化fifo*/
-int initFifoQueue(FifoQueue* queue, int capacity) {
- queue->buffer = (unsigned char*)malloc(capacity * sizeof(unsigned char));
- if (queue->buffer == NULL) {
- perror("Failed to allocate memory for FIFO queue");
- return 0;
- }
-
- queue->capacity = capacity;
- queue->head = 0;
- queue->tail = 0;
- queue->count = 0;
-
- return 1;
-}
-
-/*销毁fifo*/
-void destroyFifoQueue(FifoQueue* queue) {
- if (queue->buffer != NULL) {
- free(queue->buffer);
- queue->buffer = NULL;
- }
- queue->capacity = 0;
- queue->head = 0;
- queue->tail = 0;
- queue->count = 0;
-}
-
-/*判断fifo是否已满*/
-int isFifoQueueFull(const FifoQueue* queue) {
- return (queue->count == queue->capacity);
-}
-
-/*判断fifo是否为空*/
-int isFifoQueueEmpty(const FifoQueue* queue) {
- return (queue->count == 0);
-}
-
-/*往fifo中写数据*/
-int writeToFifoQueue(FifoQueue* queue, unsigned char data) {
- if (isFifoQueueFull(queue)) {
- return 0;
- }
-
- queue->buffer[queue->tail] = data;
- queue->tail = (queue->tail + 1) % queue->capacity;
- queue->count++;
-
- return 1;
-}
-
-/*读取fifo的数据*/
-unsigned char readFromFifoQueue(FifoQueue* queue) {
- if (isFifoQueueEmpty(queue)) {
- return 0;
- }
-
- unsigned char data = queue->buffer[queue->head];
- queue->head = (queue->head + 1) % queue->capacity;
- queue->count--;
-
- return data;
-}
-
-/*清空fifo*/
-void clearFifoQueue(FifoQueue* queue) {
- if (queue == NULL) {
- return;
- }
-
- queue->head = 0;
- queue->tail = 0;
- queue->count = 0;
-}
-
-
-int Pull_up_ctrl_pin()
-{
- int ret;
-
- ret = write(my_485->ctlFd, "1", 1);
- if(ret<0)
- {
- printf("max485 set ctl to low failed!\r\n");
-
- return -1;
- }
- else
- {
- return 0;
- }
-}
-
-int Pull_down_ctrl_pin()
-{
- int ret;
-
- ret = write(my_485->ctlFd, "0", 1);
- if(ret<0)
- {
- printf("max485 set ctl to high failed!\r\n");
-
- return -1;
- }
- else
- {
- return 0;
- }
-}
-
-/*
-发送数据
-参数定义:
- eia485_ctrl: EIA485控制器
- tx_data: 发送数据
- tx_size: 发送数据长度
-返回值:
- 0: 成功
- -1:失败
-*/
-int32_t mg_eia485_write(mg_eia485_t * eia485_ctrl,uint8_t * tx_data,uint32_t tx_size )
-{
- int rc = 0;
- if (my_485->uartFd == -1) {
- perror("UART device not open");
- goto error;;
- }
-
- Pull_up_ctrl_pin();
- usleep(1000);
- int result = write(my_485->uartFd, tx_data, tx_size);
- if (result < 0) {
- perror("Failed to write to UART device");
- goto error;
- }
- Pull_down_ctrl_pin();
- usleep(1000);
- return 0;
-error:
- return -1;
-}
-
-/*
-接收数据
-参数定义:
- eia485_ctrl: EIA485控制器
- tx_data: 接收buffer
- tx_size: 最大读取长度
- timeout_ms: 等待超时时间,单位毫秒,如果值是0则立即返回
-返回值:
- 大于0:读取到的数据长度
- 0: 无数据
- -1: 操作失败失败
-*/
-int32_t mg_eia485_read( mg_eia485_t * eia485_ctrl,uint8_t * rx_data, uint32_t rx_size,uint32_t timeout_ms )
-{
- unsigned char receiveData;
-
- if (my_485->uartFd == -1) {
- perror("UART device not open");
- goto error;
- }
- // 接收数据
- int bytesRead = 0;
- while (bytesRead < rx_size) {
-
- receiveData=readFromFifoQueue(&receiveQueue);
- rx_data[bytesRead] = receiveData;
- bytesRead++;
- printf("rx_data[bytesRead]----------->%c\n",receiveData);
- // if(time_flag == 1)
- // {
- // clearFifoQueue(&receiveQueue);
- // time_flag = 0;
- // }
- }
- return bytesRead;
-error:
- return -1;
-}
-
-void* uart_task(void* data)
-{
- int result = 0;
- fd_set rfds;
- int ret;
- FD_ZERO(&rfds);
- FD_SET(my_485->uartFd, &rfds);
- unsigned char receiveData,rData;
- printf("this is therad\n");
- while (stop) {
- struct timeval timeout;
-
- // 设置超时时间为2秒
- timeout.tv_sec = 2;
- timeout.tv_usec = 0;
- ret = select(my_485->uartFd + 1, &rfds, NULL, NULL,NULL);
- result = read(my_485->uartFd, &receiveData, 1);
- if (result > 0) {
- if (!writeToFifoQueue(&receiveQueue,receiveData))
- perror("Failed to write to FIFO queue\n");
- printf("receivedata 1----------->%c\n",receiveData);
- //rData=readFromFifoQueue(&receiveQueue);
- //printf("rdata 2----------->%c\n",rData);
- }else if(result == 0){
- lseek(my_485->uartFd, 0, SEEK_SET);
- }
- }
-}
-
-
-
-
-/*
-打开EIA485控制器
-参数定义:
- baud: 波特率
- data_bits:数据位长度
- stop_bits: 停止位长度
- parity: 校验位
-返回值:
- 打开失败,返回 NULL;
- 成功,返回TOF控制器指针。
-*/
-mg_eia485_t * mg_eia485_open(uint32_t baud, uint32_t data_bits, uint32_t stop_bits, uint32_t parity )
-{
- initFifoQueue(&receiveQueue, FIFO_SIZE);
-
- pthread_t uart5_thread;
- my_485 = (mg_eia485_t*)malloc(sizeof(mg_eia485_t));
- my_485->dev_path = UART_DEVICE;
- my_485->dev_path = CTL_DEVICE;
-
- stop = 1;
- my_485->ctlFd = open(CTL_DEVICE, O_RDWR | O_NOCTTY | O_NDELAY);
- if (my_485->uartFd == -1) {
- perror("Failed to open CTL");
- goto error;
- }
- my_485->uartFd = open(UART_DEVICE, O_RDWR | O_NOCTTY | O_NDELAY);
- if (my_485->uartFd == -1) {
- perror("Failed to open UART");
- goto error;
- }
-
- struct termios newtio,oldtio;
- if ( tcgetattr(my_485->uartFd,&oldtio) != 0) {
- perror("SetupSerial 1");
- goto error;
- }
- bzero( &newtio, sizeof( newtio ) );
- newtio.c_cflag |= CLOCAL | CREAD;
- newtio.c_cflag &= ~CSIZE;
-
- switch( data_bits )
- {
- case 5:
- newtio.c_cflag |= CS5;
- break;
- case 6:
- newtio.c_cflag |= CS6;
- break;
- case 7:
- newtio.c_cflag |= CS7;
- break;
- case 8:
- newtio.c_cflag |= CS8;
- break;
- }
-
- switch( parity )
- {
- case '1':
- newtio.c_cflag |= PARENB;
- newtio.c_cflag |= PARODD;
- newtio.c_iflag |= (INPCK | ISTRIP);
- break;
- case '2':
- newtio.c_iflag |= (INPCK | ISTRIP);
- newtio.c_cflag |= PARENB;
- newtio.c_cflag &= ~PARODD;
- break;
- case '0':
- newtio.c_cflag &= ~PARENB;
- break;
- }
-
- switch( baud )
- {
- case 2400:
- cfsetispeed(&newtio, B2400);
- cfsetospeed(&newtio, B2400);
- break;
- case 4800:
- cfsetispeed(&newtio, B4800);
- cfsetospeed(&newtio, B4800);
- break;
- case 9600:
- cfsetispeed(&newtio, B9600);
- cfsetospeed(&newtio, B9600);
- break;
- case 115200:
- cfsetispeed(&newtio, B115200);
- cfsetospeed(&newtio, B115200);
- break;
- case 460800:
- cfsetispeed(&newtio, B460800);
- cfsetospeed(&newtio, B460800);
- break;
- case 921600:
- printf("Rate:921600\n");
- cfsetispeed(&newtio, B921600);
- cfsetospeed(&newtio, B921600);
- break;
- default:
- cfsetispeed(&newtio, B9600);
- cfsetospeed(&newtio, B9600);
- break;
- }
- if( stop_bits == 1 )
- newtio.c_cflag &= ~CSTOPB;
- else if ( stop_bits == 2 )
- newtio.c_cflag |= CSTOPB;
-
- newtio.c_cc[VTIME] = 0;
- newtio.c_cc[VMIN] = 0;
- tcflush(my_485->uartFd,TCIFLUSH);
- if((tcsetattr(my_485->uartFd,TCSANOW,&newtio))!=0)
- {
- perror("com set error");
- return NULL;
- }
- if( pthread_create( &uart5_thread, NULL, uart_task, NULL) != 0 ){
- perror("create 485 task!");
- goto error;
- }
- return my_485;
-error:
- return NULL;
-};
-
-/*
-关闭控制器
-参数定义:
- eia485_ctrl: EIA485控制器
-返回值: 无
-*/
-void mg_eia485_close( mg_eia485_t * eia485_ctrl )
-{
- stop = 0;
- if (eia485_ctrl->uartFd != -1) {
- close(eia485_ctrl->uartFd);
- eia485_ctrl->uartFd = -1;
- }
-}
cmake_minimum_required(VERSION 3.8)
-project(mg_led)
+project(rfjb_led)
SET(CMAKE_BUILD_TYPE "Debug")
SET(CMAKE_CXX_FLAGS_DEBUG "$ENV{CXXFLAGS} -O0 -Wall -g2 -ggdb")
include_directories(
${PROJECT_SOURCE_DIR}/./
- ${PROJECT_SOURCE_DIR}/../log/inc/
${PROJECT_SOURCE_DIR}/src/
${PROJECT_SOURCE_DIR}/inc/
+ ${PROJECT_SOURCE_DIR}/../log/inc/
${CMAKE_SYSROOT}/usr/include/
)
aux_source_directory(./src/ SRCS)
add_library( ${PROJECT_NAME} STATIC ${SRCS} )
-
#add_library( ${PROJECT_NAME} ${SRCS} )
#install( TARGETS ${PROJECT_NAME} RUNTIME DESTINATION /app/lib )
#install( TARGETS ${PROJECT_NAME} LIBRARY DESTINATION /app/lib )
#install( TARGETS ${PROJECT_NAME} ARCHIVE DESTINATION /app/lib )
-link_directories( ${PROJECT_SOURCE_DIR}/. )
-
-#aux_source_directory(./test/ TEST_SRCS)
-#add_executable( led_test ${TEST_SRCS} )
-#target_link_libraries( led_test PUBLIC rt pthread mg_led mg_log log4c rt pthread )
-
-
-add_executable( light_test test/light.c )
-target_link_libraries(
- light_test
- PUBLIC
- mg_led
- mg_log
- log4c
- pthread
+link_directories(
)
-install( TARGETS light_test RUNTIME DESTINATION /app/test )
+#add_executable( button_test test/button.c )
+#target_link_libraries(
+# button_test
+# PUBLIC
+# mg_button
+# mg_log
+# log4c
+# pthread
+#)
+
+#install( TARGETS button_test RUNTIME DESTINATION /app/test )
-#ifndef __MG_LIGHT_H__
-#define __MG_LIGHT_H__
+#ifndef __LED_H__
+#define __LED_H__
+int led_init( void );
+#endif //__LED_H__
-#include <stdint.h>
-
-#define BR_MIN 0
-#define BR_MAX 100
-#define BR_CURR ((uint32_t)-1)
-
-#define LED_ID_KEY_1 (1<<0)
-#define LED_ID_KEY_2 (1<<1)
-#define LED_ID_KEY_3 (1<<2)
-#define LED_ID_KEY_4 (1<<3)
-#define LED_ID_KEY_5 (1<<4)
-#define LED_ID_KEY_6 (1<<5)
-#define LED_ID_KEY_7 (1<<6)
-#define LED_ID_KEY_8 (1<<7)
-#define LED_ID_KEY_ALL (0xff)
-
-#define LED_ID_ATMOS_1 (1<<0)
-#define LED_ID_ATMOS_2 (1<<1)
-#define LED_ID_ATMOS_3 (1<<2)
-#define LED_ID_ATMOS_4 (1<<3)
-#define LED_ID_ATMOS_5 (1<<4)
-#define LED_ID_ATMOS_ALL ( 0x1f )
-
-typedef void* light_ctrl_t;
-
-typedef struct{
- uint32_t on; //0:off, 1:on, 2:flash, 3:breath
- uint32_t period; //flash or breath period
- uint32_t br_max; //brightness
-} light_st_t;
-
-
-
-//key led api
-int32_t key_led_on( light_ctrl_t ctrl, uint32_t led_id, uint32_t br_from, uint32_t br_to, uint32_t transition_time );
-int32_t key_led_off( light_ctrl_t ctrl, uint32_t led_id, uint32_t br_from, uint32_t br_to, uint32_t transition_time );
-int32_t key_led_flash( light_ctrl_t ctrl, uint32_t led_id, uint32_t period_ms, uint32_t duration_ms );
-int32_t key_led_br_update( light_ctrl_t ctrl, uint32_t led_id, uint32_t br );
-int32_t key_led_st( light_ctrl_t ctrl, uint32_t led_id, light_st_t *st );
-
-//atmosphere led
-int32_t atmos_led_on( light_ctrl_t ctrl, uint32_t led_id, uint32_t br_from, uint32_t br_to, uint32_t transition_time );
-int32_t atmos_led_off( light_ctrl_t ctrl, uint32_t led_id, uint32_t br_from, uint32_t br_to, uint32_t transition_time );
-int32_t atmos_led_flash( light_ctrl_t ctrl, uint32_t led_id, uint32_t period_ms, uint32_t duration_ms );
-int32_t atmos_led_br_update( light_ctrl_t ctrl, uint32_t led_id, uint32_t br );
-int32_t atmos_led_st( light_ctrl_t ctrl, uint32_t led_id, light_st_t *st );
-
-//ring led
-int32_t ring_led_on( light_ctrl_t ctrl, uint32_t br_from, uint32_t br_to, uint32_t transition_time );
-int32_t ring_led_off( light_ctrl_t ctrl, uint32_t br_from, uint32_t br_to, uint32_t transition_time );
-int32_t ring_led_flash( light_ctrl_t ctrl, uint32_t period_ms, uint32_t duration_ms );
-int32_t ring_led_breath( light_ctrl_t ctrl, uint32_t increase_ms, uint32_t decrease_ms, uint32_t apnea_ms, uint32_t duration_ms );
-int32_t ring_led_br_update( light_ctrl_t ctrl, uint32_t br );
-int32_t ring_led_st( light_ctrl_t ctrl, light_st_t *st );
-
-//ir led
-int32_t ir_led_on( light_ctrl_t ctrl, uint32_t br );
-int32_t ir_led_off( light_ctrl_t ctrl );
-int32_t ir_led_br_update( light_ctrl_t ctrl, uint32_t br );
-int32_t ir_led_st( light_ctrl_t ctrl, light_st_t *st );
-
-
-void mg_led_br_set( light_ctrl_t ctrl, uint8_t brightness[101] );
-void mg_led_br_get( light_ctrl_t ctrl, uint8_t brightness[101] );
-
-light_ctrl_t mg_led_open( void );
-void mg_led_close( light_ctrl_t ctrl );
-
-#endif //__MG_LIGHT_H__
#include <stdint.h>
#include <stdio.h>
-#include <stdlib.h>
#include <string.h>
-#include <pthread.h>
-#include <sys/types.h>
-#include <sys/stat.h>
-#include <fcntl.h>
-#include <sys/time.h>
-#include <time.h>
#include "led.h"
-#include "mg_log.h"
-//-------------------------------------------------------------------------------------------------------------
-#define LED_KEY_1 (1<<0)
-#define LED_KEY_2 (1<<1)
-#define LED_KEY_3 (1<<2)
-#define LED_KEY_4 (1<<3)
-#define LED_KEY_5 (1<<4)
-#define LED_KEY_6 (1<<5)
-#define LED_KEY_7 (1<<6)
-#define LED_KEY_8 (1<<7)
-#define LED_ATMOS_1 (1<<8)
-#define LED_ATMOS_2 (1<<9)
-#define LED_ATMOS_3 (1<<10)
-#define LED_ATMOS_4 (1<<11)
-#define LED_ATMOS_5 (1<<12)
-#define LED_RING (1<<13)
-#define LED_IR (1<<14)
-#define LED_NR 15
-
-struct led_path{
- uint32_t id;
- const char * name;
- const char * path;
-};
-
-struct led_ctrl;
-typedef struct led_ctrl led_ctrl_t;
-typedef struct {
- //----------------------------------
- uint32_t id;
- const char *name;
- const char *sys_path;
- int32_t br_fd; //->sys/class/leds/xxxx/brightness
-
- //----------------------------------
- uint32_t on;
- uint32_t br_max;
- uint32_t br_from;
- uint32_t br_to;
- uint32_t br_curr;
- uint32_t trans_ms;
- uint32_t trans_start_ms;
- uint32_t trans_stop_ms;
-
- uint32_t flash; //0:off, 1:flash, 2:breath
- uint32_t period_ms;
- uint32_t duration_ms;
- uint32_t duration_start_ms;
- uint32_t duration_stop_ms;
-
- uint32_t increase_ms;
- uint32_t decrease_ms;
- uint32_t apnea_ms;
-
- //----------------------------------
- pthread_t led_thread; //LED控制线程
- pthread_mutex_t lock;
- //sem_t sem;
- led_ctrl_t *ctrl; //指向控制器
- uint32_t run;
- //----------------------------------
-}led_dev_t;
-
-struct led_ctrl{
- led_dev_t led[LED_NR];
-};
-
-static void led_dev_lock( led_dev_t *dev );
-static void led_dev_unlock( led_dev_t *dev );
-
-//--------------------------------------------------------------------------------------------------------------------------------
-
-//--------------------------------------------------------------------------------------------------------------------------------
-static int32_t mg_led_on( light_ctrl_t ctrl, uint32_t led_id, uint32_t br_from, uint32_t br_to, uint32_t transition_time );
-static int32_t mg_led_off( light_ctrl_t ctrl, uint32_t led_id, uint32_t br_from, uint32_t br_to, uint32_t transition_time );
-static int32_t mg_led_flash( light_ctrl_t ctrl, uint32_t led_id, uint32_t period_ms, uint32_t duration_ms );
-//static int32_t mg_led_breath( light_ctrl_t ctrl, uint32_t led_id, uint32_t period_ms );
-static int32_t mg_led_breath( light_ctrl_t ctrl, uint32_t led_id, uint32_t increas_ms, uint32_t decreas_ms, uint32_t apnea_ms, uint32_t duration_ms );
-static int32_t mg_led_br_update( light_ctrl_t ctrl, uint32_t led_id, uint32_t br );
-static int32_t mg_led_st( light_ctrl_t ctrl, uint32_t led_id, light_st_t *st );
-//--------------------------------------------------------------------------------------------------------------------------------
-
-static uint32_t now_msec( void )
-{
-// struct timeval tm;
-// gettimeofday( &tm, NULL );
-// return (uint32_t)(tm.tv_sec*1000+tm.tv_usec/1000 );
- struct timespec ts;
-
- clock_gettime( CLOCK_BOOTTIME, &ts );
- return (time_t )(ts.tv_sec*1000+ts.tv_nsec/1000/1000);
-}
-
-static uint32_t get_key_led_id( uint32_t key_led )
-{
- if( key_led &~0xff ){
- //MG_LOGE( );
- return 0;
- }
- return key_led;
-}
-
-static uint32_t get_atmos_led_id( uint32_t atmos_led )
-{
- if( atmos_led &~0x1f ){
- //MG_LOGE( );
- return 0;
- }
- return (atmos_led<<8);
-}
-
-//key led api
-int32_t key_led_on( light_ctrl_t ctrl, uint32_t led_id, uint32_t br_from, uint32_t br_to, uint32_t transition_time )
-{
-//printf( "key led on, id:%x, from:%d, to:%d, time:%d\n", led_id, br_from, br_to, transition_time );
- return mg_led_on( ctrl, get_key_led_id( led_id ), br_from, br_to, transition_time );
-}
-
-int32_t key_led_off( light_ctrl_t ctrl, uint32_t led_id, uint32_t br_from, uint32_t br_to, uint32_t transition_time )
-{
-//printf( "key led off, id:%x, from:%d, to:%d, time:%d\n", led_id, br_from, br_to, transition_time );
- return mg_led_off( ctrl, get_key_led_id( led_id ), br_from, br_to, transition_time );
-}
-
-int32_t key_led_flash( light_ctrl_t ctrl, uint32_t led_id, uint32_t period_ms, uint32_t duration_ms )
-{
-//printf( "key led flash, id:%x, period:%d, dur:%d\n", led_id, period_ms, duration_ms );
- return mg_led_flash( ctrl, get_key_led_id( led_id ), period_ms, duration_ms );
-}
-
-int32_t key_led_br_update( light_ctrl_t ctrl, uint32_t led_id, uint32_t br )
-{
-//printf( "key led br updete, id:%x, br:%d \n", led_id, br );
- return mg_led_br_update( ctrl, get_key_led_id( led_id ), br );
-}
-
-int32_t key_led_st( light_ctrl_t ctrl, uint32_t led_id, light_st_t *st )
-{
- return mg_led_st( ctrl, get_key_led_id( led_id ), st );
-}
-
-//atmos led api
-int32_t atmos_led_on( light_ctrl_t ctrl, uint32_t led_id, uint32_t br_from, uint32_t br_to, uint32_t transition_time )
-{
-//printf( "atmos led on, id:%x, from:%d, to:%d, time:%d\n", led_id, br_from, br_to, transition_time );
- return mg_led_on( ctrl, get_atmos_led_id( led_id ), br_from, br_to, transition_time );
-}
-
-int32_t atmos_led_off( light_ctrl_t ctrl, uint32_t led_id, uint32_t br_from, uint32_t br_to, uint32_t transition_time )
-{
-//printf( "atmos led off, id:%x, from:%d, to:%d, time:%d\n", led_id, br_from, br_to, transition_time );
- return mg_led_off( ctrl, get_atmos_led_id( led_id ), br_from, br_to, transition_time );
-}
-
-int32_t atmos_led_flash( light_ctrl_t ctrl, uint32_t led_id, uint32_t period_ms, uint32_t duration_ms )
-{
-//printf( "atmos led flash, id:%x, period:%d, dur:%d\n", led_id, period_ms, duration_ms );
- return mg_led_flash( ctrl, get_atmos_led_id( led_id ), period_ms, duration_ms );
-}
-
-int32_t atmos_led_br_update( light_ctrl_t ctrl, uint32_t led_id, uint32_t br )
-{
-//printf( "atmos led br updete, id:%x, br:%d \n", led_id, br );
- return mg_led_br_update( ctrl, get_atmos_led_id( led_id ), br );
-}
-
-int32_t atmos_led_st( light_ctrl_t ctrl, uint32_t led_id, light_st_t *st )
-{
- return mg_led_st( ctrl, get_atmos_led_id( led_id ), st );
-}
-
-//ring led
-int32_t ring_led_on( light_ctrl_t ctrl, uint32_t br_from, uint32_t br_to, uint32_t transition_time )
-{
- return mg_led_on( ctrl, LED_RING, br_from, br_to, transition_time );
-}
-
-int32_t ring_led_off( light_ctrl_t ctrl, uint32_t br_from, uint32_t br_to, uint32_t transition_time )
-{
- return mg_led_off( ctrl, LED_RING, br_from, br_to, transition_time );
-}
-
-int32_t ring_led_breath( light_ctrl_t ctrl, uint32_t increase_ms, uint32_t decrease_ms, uint32_t apnea_ms, uint32_t duration_ms )
-{
- return mg_led_breath( ctrl, LED_RING, increase_ms, decrease_ms, apnea_ms, duration_ms );
-}
-
-int32_t ring_led_flash( light_ctrl_t ctrl, uint32_t period_ms, uint32_t duration_ms )
-{
- return mg_led_flash( ctrl, LED_RING, period_ms, duration_ms );
-}
-
-int32_t ring_led_br_update( light_ctrl_t ctrl, uint32_t br )
-{
- return mg_led_br_update( ctrl, LED_RING, br );
-}
-
-int32_t ring_led_st( light_ctrl_t ctrl, light_st_t *st )
-{
- return mg_led_st( ctrl, LED_RING, st );
-}
-
-//ir led
-
-int32_t ir_led_on( light_ctrl_t ctrl, uint32_t br )
-{
- return mg_led_on( ctrl, LED_IR, br, br, 0 );
-}
-
-int32_t ir_led_off( light_ctrl_t ctrl )
-{
- return mg_led_on( ctrl, LED_IR, 0, 0, 0 );
-}
-
-int32_t ir_led_br_update( light_ctrl_t ctrl, uint32_t br )
-{
- return mg_led_br_update( ctrl, LED_IR, br );
-}
-
-int32_t ir_led_st( light_ctrl_t ctrl, light_st_t *st )
-{
- return mg_led_st( ctrl, LED_IR, st );
-}
-
-//-------------------------------------------------------------------------------------------------------------
-//mg led api
-
-void led_dev_lock( led_dev_t *dev )
-{
- pthread_mutex_lock( &dev->lock );
-}
-
-void led_dev_unlock( led_dev_t *dev )
-{
- pthread_mutex_unlock( &dev->lock );
-}
-
-
-static int32_t mg_led_on( light_ctrl_t ctrl, uint32_t led_id, uint32_t br_from, uint32_t br_to, uint32_t transition_time )
-{
- int32_t retval = 0;
- led_ctrl_t *led_ctrl;
- led_dev_t *dev;
- uint32_t now_ms;
-
- now_ms = now_msec();
-
- led_ctrl = (led_ctrl_t*)ctrl;
-
- for( int i=0; i<LED_NR; i ++ ){
- if( led_id & (1<<i) ){
-
- dev = &led_ctrl->led[i];
- led_dev_lock( dev );
- if( br_to ){
- //on
- dev->on = 1;
- dev->br_max = br_to;
- }else{
- //off
- dev->on = 0;
- //dev->br_max = br_to;
- }
- dev->br_from = br_from;
- if( br_from < 100 )
- dev->br_curr = br_from;
- dev->br_to = br_to;
- dev->trans_ms = transition_time;
-
- if( dev->trans_ms ){
- dev->trans_start_ms = now_ms;
- dev->trans_stop_ms = now_ms+dev->trans_ms;
- }
- dev->flash = 0;
- dev->period_ms = 0;
- dev->duration_ms = 0;
- dev->duration_start_ms = 0;
- dev->duration_stop_ms = 0;
- led_dev_unlock( dev );
- }
- }
- return retval;
-}
-
-int32_t mg_led_off( light_ctrl_t ctrl, uint32_t led_id, uint32_t br_from, uint32_t br_to, uint32_t transition_time )
-{
- //直接调用 led on, 通过 br_to是0 则是OFF, 否则为 on;
- return mg_led_on( ctrl, led_id, br_from, br_to, transition_time );
-}
-
-int32_t mg_led_flash( light_ctrl_t ctrl, uint32_t led_id, uint32_t period_ms, uint32_t duration_ms )
-{
- int32_t retval = 0;
- led_ctrl_t *led_ctrl;
- led_dev_t *dev;
- uint32_t now_ms;
-
- now_ms = now_msec();
-
- led_ctrl = (led_ctrl_t*)ctrl;
-
- for( int i=0; i<LED_NR; i ++ ){
- if( led_id & (1<<i) ){
- dev = &led_ctrl->led[i];
-
-printf( "LED_%d flash \n", i+1 );
- led_dev_lock( dev );
- dev->flash = 1;
- dev->period_ms = period_ms;
- dev->duration_ms = duration_ms;
- if( duration_ms ){
- dev->duration_start_ms = now_ms;
- dev->duration_stop_ms = now_ms + duration_ms;
- }
- led_dev_unlock( dev );
- }
- }
-
- return retval;
-}
-
-int32_t mg_led_breath( light_ctrl_t ctrl, uint32_t led_id, uint32_t increase_ms, uint32_t decrease_ms, uint32_t apnea_ms, uint32_t duration_ms )
-{
- int32_t retval = 0;
- led_ctrl_t *led_ctrl;
- led_dev_t *dev;
- uint32_t now_ms;
-
- now_ms = now_msec();
-
- led_ctrl = (led_ctrl_t*)ctrl;
-
- for( int i=0; i<LED_NR; i ++ ){
- if( led_id & (1<<i) ){
- //lock
- dev = &led_ctrl->led[i];
- dev->flash = 2;
- dev->duration_ms = duration_ms;
- if( duration_ms ){
- dev->duration_start_ms = now_ms;
- dev->duration_stop_ms = now_ms + duration_ms;
- }
- dev->apnea_ms = apnea_ms;
- dev->increase_ms = increase_ms;
- dev->decrease_ms = decrease_ms;
- dev->period_ms = increase_ms+decrease_ms+apnea_ms;
- //led_dev_unlock( dev );
- }
- }
-
- return retval;
-}
-
-int32_t mg_led_br_update( light_ctrl_t ctrl, uint32_t led_id, uint32_t br )
-{
- int32_t retval = 0;
- led_ctrl_t *led_ctrl;
- led_dev_t *dev;
-
- led_ctrl = (led_ctrl_t*)ctrl;
-
- for( int i=0; i<LED_NR; i ++ ){
- if( led_id & (1<<i) ){
- //lock
- dev = &led_ctrl->led[i];
- led_dev_lock( dev );
- dev->br_max = br;
- led_dev_unlock( dev );
- }
- }
-
- return retval;
-}
-
-int32_t mg_led_st( light_ctrl_t ctrl, uint32_t led_id, light_st_t *st )
-{
- int32_t retval = -1;
- led_ctrl_t *led_ctrl;
- led_dev_t *dev;
-
- led_ctrl = (led_ctrl_t*)ctrl;
-
- for( int i=0; i<LED_NR; i ++ ){
- if( led_id & (1<<i) ){
- //lock
- dev = &led_ctrl->led[i];
- led_dev_lock( dev );
- if( dev->flash == 2 )
- st->on = 3; //breath;
- else if( dev->flash == 1 )
- st->on = 3; //flash
- else if( dev->on == 1 )
- st->on = 1; //on
- else
- st->on = 0; //off
- st->br_max = dev->br_max;
- st->period = dev->period_ms;
- led_dev_unlock( dev );
- retval = 0;
- break;
- }
- }
-
- return retval;
-}
-
-static led_ctrl_t g_light;
-
-
-const struct led_path led_path_info[LED_NR] = {
- { LED_KEY_1, "KEY_LED_1", "/sys/class/leds/key_led1" },
- { LED_KEY_2, "KEY_LED_2", "/sys/class/leds/key_led2" },
- { LED_KEY_3, "KEY_LED_3", "/sys/class/leds/key_led3" },
- { LED_KEY_4, "KEY_LED_4", "/sys/class/leds/key_led4" },
- { LED_KEY_5, "KEY_LED_5", "/sys/class/leds/key_led5" },
- { LED_KEY_6, "KEY_LED_6", "/sys/class/leds/key_led6" },
- { LED_KEY_7, "KEY_LED_7", "/sys/class/leds/key_led7" },
- { LED_KEY_8, "KEY_LED_8", "/sys/class/leds/key_led8" },
- { LED_ATMOS_1, "FUN_LED_1", "/sys/class/leds/fun_led1" },
- { LED_ATMOS_2, "FUN_LED_2", "/sys/class/leds/fun_led2" },
- { LED_ATMOS_3, "FUN_LED_3", "/sys/class/leds/fun_led3" },
- { LED_ATMOS_4, "FUN_LED_4", "/sys/class/leds/fun_led4" },
- { LED_ATMOS_5, "FUN_LED_5", "/sys/class/leds/fun_led5" },
- { LED_RING, "RING_LED", "/sys/class/leds/ring_led" },
- { LED_IR, "IR_LED", "/sys/class/leds/ir_led" },
-};
-
-static uint8_t hw_br[101] = { //亮度0 到100, 对应到sysfs接口的0-255
- 0,
- 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
- 11, 12, 13, 14, 15, 16, 17, 18, 19, 20,
- 21, 22, 23, 24, 25, 26, 27, 28, 29, 30,
- 32, 34, 36, 38, 40, 42, 34, 36, 38, 50,
- 52, 54, 56, 58, 60, 62, 64, 66, 68, 70,
- 72, 74, 76, 78, 80, 82, 84, 86, 88, 90,
- 92, 94, 96, 98, 100, 102, 104, 106, 108, 110,
- 112, 114, 116, 118, 120, 122, 124, 126, 128, 130,
- 132, 134, 136, 138, 140, 142, 144, 146, 148, 150,
- 160, 170, 180, 190, 200, 210, 220, 230, 240, 255,
-};
-
-uint32_t get_hw_brightness( uint32_t br )
-{
- if( br > 100 )
- return 255;
- else
- return hw_br[br];
-}
-
-void hw_led_brignt( led_dev_t * dev, uint32_t br )
-{
- char br_str[10];
-
- uint32_t out_br = get_hw_brightness( br );
-
- if( br<= 100 ){
- //br = br_gamma[br];
- //sprintf( br_str, "%d\n", br*255/100 );
- sprintf( br_str, "%d\n", out_br );
- if( write(dev->br_fd, br_str, strlen( br_str ) ) < 0 ){
- MG_LOGE( "write %s br:%d fail!", dev->name, br );
- }
- }
-}
-
-void* led_thread_fun( void *led )
-{
- uint32_t br;
- uint32_t curr_br = 0;
- led_dev_t *dev;
- uint32_t now_ms;
-
- dev = (led_dev_t *)led;
-
- while(1){
- usleep( 50*1000 );
-
- now_ms = now_msec();
-
- led_dev_lock( dev );
-
- curr_br = dev->br_curr;
- if( dev->duration_ms && now_ms > dev->duration_stop_ms){
- //时间到,关闭闪烁或呼吸
- dev->flash = 0;
- dev->duration_ms = 0;
- curr_br = dev->br_max;
-
- }
-
- if( dev->flash == 1 ){
- static uint32_t flash_br = 0;
- //flash
- if( (now_ms % dev->period_ms) *2 > dev->period_ms )
- curr_br = dev->br_max;
- else
- curr_br = 0;
- if( curr_br != flash_br ){
- //printf( "[%d] %s thread, flash br %d -> %d\n", now_ms, dev->name, flash_br, curr_br );
- flash_br = curr_br;
- }
-
- }else if( dev->flash == 2 ){
- //breath;
- //呼吸周期计算
- uint32_t ms = now_ms%(dev->increase_ms + dev->decrease_ms + dev->apnea_ms);
- //static int8_t dir = 0;
-
- if( ms < dev->increase_ms ){
- //up
- br = ( 5 + 10 *100 * ms /dev->increase_ms)/10;
- if( br < curr_br )
- br = curr_br;
- //if( dir <= 0 ) printf( "[%s]breath inc: dir %d -> 1 , time_ms:%d/%d\n", dev->name, dir, ms, now_ms );
- //dir = 1;
- }else if( ms < dev->increase_ms + dev->decrease_ms ){
- //down
- br = ( 5 + 10 *100 * (dev->increase_ms + dev->decrease_ms -ms )/dev->decrease_ms)/10;
- if( br > curr_br )
- br = curr_br;
- //if( dir >= 0 ) printf( "[%s]breath dec: dir %d -> -1 , time_ms:%d/%d\n", dev->name, dir, ms, now_ms );
- //dir = -1;
- }else{
- //apnea , led off
- br = 0;
- //if( dir != 0 ) printf( "[%s]breath apnea: %d -> 0, time_ms:%d/%d\n", dev->name, dir, ms, now_ms );
- //dir = 0;
- }
- //if( br <1 ) br = 1;
- if( br >100 ) br = 100;
- //curr_br = br_gamma[br];
- curr_br = br;
- //printf( "[%d] breath br:%d\n", now_ms%100000, curr_br );
-
- }else if( dev->flash == 0 ){
- //on /off
- if( dev->trans_ms ){
- //渐变计算
- if( now_ms > dev->trans_stop_ms
- || ( dev->on && curr_br >= dev->br_to )
- || ( !dev->on&& curr_br <= dev->br_to )){
- dev->trans_ms = 0;
- br = dev->br_to;
- }else{
- if( dev->on ){
- //trans_ms 是 0-到100 的变化时间,
- //curr_br = dev->br_from + (now_ms - dev->trans_start_ms)*(dev->br_to - dev->br_from)/dev->trans_ms;
- br = dev->br_from + (now_ms - dev->trans_start_ms)*(100 - 0)/dev->trans_ms;
- }else{
- br = dev->br_from - (now_ms - dev->trans_start_ms)*(100 - 0)/dev->trans_ms;
- }
-
- //printf( "[%d] LED-%s br trans [ %d -> %d ], now br:%d\n", now_ms%100000, dev->name, dev->br_from, dev->br_to, curr_br );
- }
- if( br > 100 ) br = 100;
- //curr_br = br_gamma[ br ];
- curr_br = br;
-
- }else if( dev->on){
- //ON
- curr_br = dev->br_max;
- }else{
- //OFF
- curr_br = 0;
- }
- //write curr_mx -> br_fd;
- }
- dev->br_curr = curr_br;
- led_dev_unlock( dev );
-
- hw_led_brignt( dev, curr_br );
-
- }
- return NULL;
-}
-
-static void led_dev_init( led_dev_t *led, const struct led_path *path_info )
+int led_init( void )
{
- char led_path[100];
-
- if( !led ){
- MG_LOGE( "led x init fail, path:%s\n", path_info->name );
- return;
- }
-
- memset( led, 0, sizeof( *led ) );
-
- pthread_mutex_init( &led->lock, NULL );
-
- led->id = path_info->id;
- led->name = path_info->name;
- led->sys_path = path_info->path;
-
- sprintf( led_path, "%s/brightness", led->sys_path );
- led->br_fd = open( led_path, O_WRONLY );
- if( led->br_fd < 0 ){
- MG_LOGE( "[%s]open brightness file[%s/brightness] fail!", led->name, led->sys_path );
- return;
- }
-
- led->br_max = 100;
-
- led->ctrl = &g_light;
- led->run = 1;
- pthread_create( &led->led_thread, NULL, led_thread_fun, led );
-
- return;
-}
-
-static void led_dev_deinit( led_dev_t *led )
-{
- void * res;
-
- if( !led ){
- return;
- }
-
- if( led->br_fd >= 0 ){
- close( led->br_fd );
- }
-
- led->run = 0;
- pthread_cancel( led->led_thread );
- pthread_join( led->led_thread, &res );
- if( res == PTHREAD_CANCELED ){
- }else{
- MG_LOGE( "led[%s]cacnel pthread fail!\n", led->name );
- }
- pthread_mutex_destroy( &led->lock );
- return;
-}
-
-static void led_ctrl_init( led_ctrl_t *ctrl )
-{
- for( int i=0; i<LED_NR; i++ ){
- led_dev_init( &ctrl->led[i], &led_path_info[i] );
- }
-
-}
-
-//设置led的0到100各级亮度的值, 0为关闭,255为最大亮度。
-void mg_led_br_set( light_ctrl_t ctrl, uint8_t brightness[101] )
-{
- //led_ctrl_t *led_ctrl;
- //led_ctrl = (led_ctrl_t*)ctrl;
- if( ctrl != ( light_ctrl_t)&g_light )
- return;
-
- memcpy( hw_br, brightness, 101 );
- printf( "----------------------------\n" );
- printf( "mg_led_br_set:\n" );
- for( int i =0; i<101; i++ ){
- printf( "%4d%s", brightness[i], (i%10)?" ":"\n");
- }
- printf( "----------------------------\n" );
- printf( "\n" );
-}
-
-void mg_led_br_get( light_ctrl_t ctrl, uint8_t brightness[101] )
-{
- //led_ctrl_t *led_ctrl;
- //led_ctrl = (led_ctrl_t*)ctrl;
- if( ctrl != ( light_ctrl_t)&g_light )
- return;
-
- memcpy( brightness, hw_br, 101 );
-}
-
-light_ctrl_t mg_led_open( void )
-{
- MG_LOGI( "mg_led_open..." );
-
- led_ctrl_init( &g_light );
-
- return ( light_ctrl_t)&g_light;
-}
-
-void mg_led_close( light_ctrl_t ctrl )
-{
- led_ctrl_t *led_ctrl;
-
- MG_LOGI( "mg_led_close..." );
- led_ctrl = (led_ctrl_t*)ctrl;
- for( int i=0; i<LED_NR; i++ ){
- led_dev_deinit( &led_ctrl->led[i] );
- }
-
-}
-
-#if 0
-int main( void )
-{
- mg_log_init();
-
- light_ctrl_t ctrl;
- ctrl = mg_led_open();
- if( ctrl == 0 ){
- printf( "open led fail!\n" );
- exit(0);
- }
-
- printf( "led 1 on from 0 to 100 , in 5s ... \n" );
- key_led_flash( ctrl, 1, 1000, 5000 );
-
- sleep( 2 );
- key_led_br_update( ctrl, 1, 40 );
- sleep( 4 );
- exit(0);
-
- printf( "led 1 off from 100 to 0 , in 3s ... \n" );
- key_led_off( ctrl, 1, 100, 0, 3000 );
- sleep( 4 );
-
- ring_led_breath( ctrl, 1000, 5000 );
-
- sleep(25);
+ printf( "led init\n" );
return 0;
}
-#endif
+
+++ /dev/null
-
-#include <stdio.h>
-#include <stdint.h>
-#include <stdlib.h>
-#include <string.h>
-#include <signal.h>
-#include <time.h>
-#include "led.h"
-#include "mg_log.h"
-#include "pthread.h"
-#include "semaphore.h"
-
-#include <sys/types.h>
-#include <sys/stat.h>
-#include <fcntl.h>
-#include <getopt.h>
-
-#if 0
-char* usage_str = ""
-"Usage: light_test [option] ...\n"
-"Options:\n"
-"\t -t, --type n -- 0:KEY LED 1:ATMOS LED 2:IR LED 3: RING LED\n"
-"\t -i, --index n -- KEY LED:1-8, ATMOS LED:1-5, IR LED:0 RING LED:0\n"
-"\t -o, --output n -- 0:off, 1:on, 2:flash, 3:breath, 4:slow on, 5slow off\n"
-"\t --on_ms n -- \n"
-"\t --off_ms n -- \n"
-"\t --brightness n -- 0-100 \n"
-"\t -h, --help\n"
-"\n";
-
-
-void disp_usage( void )
-{
- printf( usage_str );
-}
-
-int lopt;
-struct option opts[] = {
- {"type", required_argument, 0, 't' },
- {"help", no_argument, NULL, 'h' },
- {},
-
-};
-#endif
-
-static uint8_t brs[101] = { //亮度0 到100, 对应到sysfs接口的0-255
- 0,
- 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
- 11, 12, 13, 14, 15, 16, 17, 18, 19, 20,
- 21, 22, 23, 24, 25, 26, 27, 28, 29, 30,
- 32, 34, 36, 38, 40, 42, 34, 36, 38, 50,
- 52, 54, 56, 58, 60, 62, 64, 66, 68, 70,
- 72, 74, 76, 78, 80, 82, 84, 86, 88, 90,
- 92, 94, 96, 98, 100, 102, 104, 106, 108, 110,
- 112, 114, 116, 118, 120, 122, 124, 126, 128, 130,
- 132, 134, 136, 138, 140, 142, 144, 146, 148, 150,
- 160, 170, 180, 190, 200, 210, 220, 230, 240, 255,
-};
-
-int main( int argc, char ** argv )
-{
- light_ctrl_t light = mg_led_open();
- if( !light ){
- perror( "open led fail!\n" );
- exit(0);
- }
-
- //mg_led_br_set( light, brs );
-
-#if 0
-while(1){
-
-printf( "open key led all -> on ...\n" );
- key_led_on( light, LED_ID_KEY_ALL, 0, 100, 10000 );
- atmos_led_on( light, LED_ID_ATMOS_ALL, 0, 100, 10000 );
- sleep(15 );
-printf( "open key led all -> off ...\n" );
- key_led_off( light, LED_ID_KEY_ALL, 100, 0, 10000 );
- atmos_led_off( light, LED_ID_ATMOS_ALL, 100, 0, 10000 );
- sleep(15 );
-}
-#endif
-printf( "open key led 1 ...\n" );
- key_led_on( light, LED_ID_KEY_1, 0, 100, 1000 );
- sleep(1);
-printf( "open key led 2 ...\n" );
- key_led_off( light, LED_ID_KEY_1, 100, 0, 1000 );
- key_led_on( light, LED_ID_KEY_2, 0, 100, 1000 );
- sleep(1);
-printf( "open key led 3 ...\n" );
- key_led_off( light, LED_ID_KEY_2, 100, 0, 1000 );
- key_led_on( light, LED_ID_KEY_3, 0, 100, 1000 );
- sleep(1);
-printf( "open key led 4 ...\n" );
- key_led_off( light, LED_ID_KEY_3, 100, 0, 1000 );
- key_led_on( light, LED_ID_KEY_4, 0, 100, 1000 );
- sleep(1);
-printf( "open key led 5 ...\n" );
- key_led_off( light, LED_ID_KEY_4, 100, 0, 1000 );
- key_led_on( light, LED_ID_KEY_5, 0, 100, 1000 );
- sleep(1);
-printf( "open key led 6 ...\n" );
- key_led_off( light, LED_ID_KEY_5, 100, 0, 1000 );
- key_led_on( light, LED_ID_KEY_6, 0, 100, 1000 );
- sleep(1);
-printf( "open key led 7 ...\n" );
- key_led_off( light, LED_ID_KEY_6, 100, 0, 1000 );
- key_led_on( light, LED_ID_KEY_7, 0, 100, 1000 );
- sleep(1);
-printf( "open key led 8 ...\n" );
- key_led_off( light, LED_ID_KEY_7, 100, 0, 1000 );
- key_led_on( light, LED_ID_KEY_8, 0, 100, 1000 );
- sleep(1);
- key_led_off( light, LED_ID_KEY_8, 100, 0, 1000 );
-
-printf( "open atmos led 1 ...\n" );
- atmos_led_on( light, LED_ID_ATMOS_1, 0, 100, 1000 );
- sleep(1);
-printf( "open atmos led 2 ...\n" );
- atmos_led_off( light, LED_ID_ATMOS_1, 100, 0, 1000 );
- atmos_led_on( light, LED_ID_ATMOS_2, 0, 100, 1000 );
- sleep(1);
-printf( "open atmos led 3 ...\n" );
- atmos_led_off( light, LED_ID_ATMOS_2, 100, 0, 1000 );
- atmos_led_on( light, LED_ID_ATMOS_3, 0, 100, 1000 );
- sleep(1);
-printf( "open atmos led 4 ...\n" );
- atmos_led_off( light, LED_ID_ATMOS_3, 100, 0, 1000 );
- atmos_led_on( light, LED_ID_ATMOS_4, 0, 100, 1000 );
- sleep(1);
-printf( "open atmos led 5 ...\n" );
- atmos_led_off( light, LED_ID_ATMOS_4, 100, 0, 1000 );
- atmos_led_on( light, LED_ID_ATMOS_5, 0, 100, 1000 );
- sleep(1);
- atmos_led_off( light, LED_ID_ATMOS_5, 100, 0, 1000 );
-
-printf( "key led flash period 1s ...\n" );
- atmos_led_flash( light, LED_ID_KEY_ALL, 1000, 0 );
-
-printf( "atmos led flash period 2s ...\n" );
- atmos_led_flash( light, LED_ID_ATMOS_ALL, 2000, 0 );
-
-printf( "open ir led ...\n" );
- ir_led_on( light, 100 );
- sleep(1);
- //ir_led_off( light, 100 );
-printf( "ring led flash period 1s ...\n" );
- ring_led_flash( light, 1000, 5000 );
- sleep(5);
-printf( "ring led breath period inc 2s, dec 3s, apnea 1s...\n" );
- ring_led_breath( light, 2000, 3000, 1000, 30000 );
-
- while( 1 ){
- key_led_off( light, LED_ID_KEY_ALL, 100, 0, 5000 );
- atmos_led_on( light, LED_ID_ATMOS_ALL, 0, 100, 5000 );
- sleep(8);
- key_led_on( light, LED_ID_KEY_ALL, 0, 100, 5000 );
- atmos_led_off( light, LED_ID_ATMOS_ALL, 100, 0, 5000 );
- sleep(8);
- }
-
- return 0;
-}
-
-
cmake_minimum_required(VERSION 3.8)
-project(mg_log)
+project(rfjb_log)
include_directories(
${PROJECT_SOURCE_DIR}/./
+++ /dev/null
-#ifndef __MG_LOG__H__
-#define __MG_LOG__H__
-
-#include <unistd.h>
-#include "log4c.h"
-
-extern log4c_category_t *mg_log_category;
-
-#define MG_LOG_CATEGORY mg_log_category
-
-#define MG_LOGF mg_log_fatal
-#define MG_LOGE mg_log_error
-#define MG_LOGW mg_log_warning
-#define MG_LOGN mg_log_notice
-#define MG_LOGI mg_log_info
-#define MG_LOGD mg_log_debug
-
-#define mg_log_fatal(...) log4c_category_log( MG_LOG_CATEGORY, LOG4C_PRIORITY_FATAL, __VA_ARGS__)
-#define mg_log_error(...) log4c_category_log( MG_LOG_CATEGORY, LOG4C_PRIORITY_ERROR, __VA_ARGS__)
-#define mg_log_warning(...) log4c_category_log( MG_LOG_CATEGORY, LOG4C_PRIORITY_WARN, __VA_ARGS__)
-#define mg_log_notice(...) log4c_category_log( MG_LOG_CATEGORY, LOG4C_PRIORITY_NOTICE, __VA_ARGS__)
-#define mg_log_info(...) log4c_category_log( MG_LOG_CATEGORY, LOG4C_PRIORITY_INFO, __VA_ARGS__)
-#define mg_log_debug(...) log4c_category_log( MG_LOG_CATEGORY, LOG4C_PRIORITY_DEBUG, __VA_ARGS__)
-
-
-void mg_log_init( void );
-void mg_log_deinit( void );
-
-#endif //__MG_LOG__H__
-
--- /dev/null
+#ifndef __RFJB_LOG__H__
+#define __RFJB_LOG__H__
+
+#include <unistd.h>
+#include "log4c.h"
+
+extern log4c_category_t *rfjb_log_category;
+
+#define RFJB_LOG_CATEGORY rfjb_log_category
+
+#define RFJB_LOGF rfjb_log_fatal
+#define RFJB_LOGE rfjb_log_error
+#define RFJB_LOGW rfjb_log_warning
+#define RFJB_LOGN rfjb_log_notice
+#define RFJB_LOGI rfjb_log_info
+#define RFJB_LOGD rfjb_log_debug
+
+#define rfjb_log_fatal(...) log4c_category_log( RFJB_LOG_CATEGORY, LOG4C_PRIORITY_FATAL, __VA_ARGS__)
+#define rfjb_log_error(...) log4c_category_log( RFJB_LOG_CATEGORY, LOG4C_PRIORITY_ERROR, __VA_ARGS__)
+#define rfjb_log_warning(...) log4c_category_log( RFJB_LOG_CATEGORY, LOG4C_PRIORITY_WARN, __VA_ARGS__)
+#define rfjb_log_notice(...) log4c_category_log( RFJB_LOG_CATEGORY, LOG4C_PRIORITY_NOTICE, __VA_ARGS__)
+#define rfjb_log_info(...) log4c_category_log( RFJB_LOG_CATEGORY, LOG4C_PRIORITY_INFO, __VA_ARGS__)
+#define rfjb_log_debug(...) log4c_category_log( RFJB_LOG_CATEGORY, LOG4C_PRIORITY_DEBUG, __VA_ARGS__)
+
+
+void rfjb_log_init( void );
+void rfjb_log_deinit( void );
+
+#endif //__RFJB_LOG__H__
+
<category name="root" priority="notice"/>
<!-- 输出到文件mylogfilename.x ========================================= -->
- <category name="mg_app" priority="debug" appender = "myrollingappender"/>
- <appender name="myrollingappender" type="rollingfile" logdir="./" prefix="mg_app-log" layout="dated" rollingpolicy="myrollingpolicy" />
+ <category name="rfjb_app" priority="debug" appender = "myrollingappender"/>
+ <appender name="myrollingappender" type="rollingfile" logdir="./" prefix="rfjb_app-log" layout="dated" rollingpolicy="myrollingpolicy" />
<rollingpolicy name="myrollingpolicy" type="sizewin" maxsize="102400" maxnum="3" />
<!-- default appenders ===================================== -->
+++ /dev/null
-#include <stdio.h>
-#include <stdint.h>
-#include <stdlib.h>
-#include <string.h>
-
-#include <unistd.h>
-#include "log4c.h"
-#include "mg_log.h"
-
-#define LOG_CATEGORY "mg_app"
-
-
-//log4c_category_log(mytest, LOG4C_PRIORITY_INFO, "hello, world! -- %d\r\n", i++ );
-
-log4c_category_t *mg_log_category = NULL;
-
-void mg_log_init( void )
-{
- /* 初始化 */
- if(log4c_init()){
- printf("log4c_init error!\n");
- goto err;
- }
-
- /* 获取已配置的category */
- mg_log_category = log4c_category_get( LOG_CATEGORY );
- printf("mg_log_init: log4c_category_get ret:%p\n", mg_log_category );
-
-err:
- return;
-}
-
-void mg_log_deinit( void )
-{
- log4c_fini();
- mg_log_category = 0;
-}
-
--- /dev/null
+#include <stdio.h>
+#include <stdint.h>
+#include <stdlib.h>
+#include <string.h>
+
+#include <unistd.h>
+#include "log4c.h"
+#include "rfjb_log.h"
+
+#define LOG_CATEGORY "rfjb_app"
+
+
+//log4c_category_log(mytest, LOG4C_PRIORITY_INFO, "hello, world! -- %d\r\n", i++ );
+
+log4c_category_t *rfjb_log_category = NULL;
+
+void rfjb_log_init( void )
+{
+ /* 初始化 */
+ if(log4c_init()){
+ printf("log4c_init error!\n");
+ goto err;
+ }
+
+ /* 获取已配置的category */
+ rfjb_log_category = log4c_category_get( LOG_CATEGORY );
+ printf("rfjb_log_init: log4c_category_get ret:%p\n", rfjb_log_category );
+
+err:
+ return;
+}
+
+void rfjb_log_deinit( void )
+{
+ log4c_fini();
+ rfjb_log_category = 0;
+}
+
+++ /dev/null
-Subproject commit 0208badefb2003d30e70b5b875395e3187c850d9
+++ /dev/null
-cmake_minimum_required(VERSION 3.8)
-
-project(mg_udp)
-
-include_directories(
- ${PROJECT_SOURCE_DIR}/./
- ${PROJECT_SOURCE_DIR}/../app/inc/
- ${PROJECT_SOURCE_DIR}/src/
- ${PROJECT_SOURCE_DIR}/inc/
- ${CMAKE_SYSROOT}/usr/include/
- )
-
-aux_source_directory(./src/ SRCS)
-
-add_library( ${PROJECT_NAME} STATIC ${SRCS} )
-
+++ /dev/null
-/*
- Copyright (c) 2009-2017 Dave Gamble and cJSON contributors
-
- Permission is hereby granted, free of charge, to any person obtaining a copy
- of this software and associated documentation files (the "Software"), to deal
- in the Software without restriction, including without limitation the rights
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
- copies of the Software, and to permit persons to whom the Software is
- furnished to do so, subject to the following conditions:
-
- The above copyright notice and this permission notice shall be included in
- all copies or substantial portions of the Software.
-
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
- THE SOFTWARE.
-*/
-
-#ifndef cJSON__h
-#define cJSON__h
-
-#ifdef __cplusplus
-extern "C"
-{
-#endif
-
-#if !defined(__WINDOWS__) && (defined(WIN32) || defined(WIN64) || defined(_MSC_VER) || defined(_WIN32))
-#define __WINDOWS__
-#endif
-
-#ifdef __WINDOWS__
-
-/* When compiling for windows, we specify a specific calling convention to avoid issues where we are being called from a project with a different default calling convention. For windows you have 3 define options:
-
-CJSON_HIDE_SYMBOLS - Define this in the case where you don't want to ever dllexport symbols
-CJSON_EXPORT_SYMBOLS - Define this on library build when you want to dllexport symbols (default)
-CJSON_IMPORT_SYMBOLS - Define this if you want to dllimport symbol
-
-For *nix builds that support visibility attribute, you can define similar behavior by
-
-setting default visibility to hidden by adding
--fvisibility=hidden (for gcc)
-or
--xldscope=hidden (for sun cc)
-to CFLAGS
-
-then using the CJSON_API_VISIBILITY flag to "export" the same symbols the way CJSON_EXPORT_SYMBOLS does
-
-*/
-
-#define CJSON_CDECL __cdecl
-#define CJSON_STDCALL __stdcall
-
-/* export symbols by default, this is necessary for copy pasting the C and header file */
-#if !defined(CJSON_HIDE_SYMBOLS) && !defined(CJSON_IMPORT_SYMBOLS) && !defined(CJSON_EXPORT_SYMBOLS)
-#define CJSON_EXPORT_SYMBOLS
-#endif
-
-#if defined(CJSON_HIDE_SYMBOLS)
-#define CJSON_PUBLIC(type) type CJSON_STDCALL
-#elif defined(CJSON_EXPORT_SYMBOLS)
-#define CJSON_PUBLIC(type) __declspec(dllexport) type CJSON_STDCALL
-#elif defined(CJSON_IMPORT_SYMBOLS)
-#define CJSON_PUBLIC(type) __declspec(dllimport) type CJSON_STDCALL
-#endif
-#else /* !__WINDOWS__ */
-#define CJSON_CDECL
-#define CJSON_STDCALL
-
-#if (defined(__GNUC__) || defined(__SUNPRO_CC) || defined (__SUNPRO_C)) && defined(CJSON_API_VISIBILITY)
-#define CJSON_PUBLIC(type) __attribute__((visibility("default"))) type
-#else
-#define CJSON_PUBLIC(type) type
-#endif
-#endif
-
-/* project version */
-#define CJSON_VERSION_MAJOR 1
-#define CJSON_VERSION_MINOR 7
-#define CJSON_VERSION_PATCH 12
-
-#include <stddef.h>
-
-/* cJSON Types: */
-#define cJSON_Invalid (0)
-#define cJSON_False (1 << 0)
-#define cJSON_True (1 << 1)
-#define cJSON_NULL (1 << 2)
-#define cJSON_Number (1 << 3)
-#define cJSON_String (1 << 4)
-#define cJSON_Array (1 << 5)
-#define cJSON_Object (1 << 6)
-#define cJSON_Raw (1 << 7) /* raw json */
-
-#define cJSON_IsReference 256
-#define cJSON_StringIsConst 512
-
-/* The cJSON structure: */
-typedef struct cJSON
-{
- /* next/prev allow you to walk array/object chains. Alternatively, use GetArraySize/GetArrayItem/GetObjectItem */
- struct cJSON *next;
- struct cJSON *prev;
- /* An array or object item will have a child pointer pointing to a chain of the items in the array/object. */
- struct cJSON *child;
-
- /* The type of the item, as above. */
- int type;
-
- /* The item's string, if type==cJSON_String and type == cJSON_Raw */
- char *valuestring;
- /* writing to valueint is DEPRECATED, use cJSON_SetNumberValue instead */
- int valueint;
- /* The item's number, if type==cJSON_Number */
- double valuedouble;
-
- /* The item's name string, if this item is the child of, or is in the list of subitems of an object. */
- char *string;
-} cJSON;
-
-typedef struct cJSON_Hooks
-{
- /* malloc/free are CDECL on Windows regardless of the default calling convention of the compiler, so ensure the hooks allow passing those functions directly. */
- void *(CJSON_CDECL *malloc_fn)(size_t sz);
- void (CJSON_CDECL *free_fn)(void *ptr);
-} cJSON_Hooks;
-
-typedef int cJSON_bool;
-
-/* Limits how deeply nested arrays/objects can be before cJSON rejects to parse them.
- * This is to prevent stack overflows. */
-#ifndef CJSON_NESTING_LIMIT
-#define CJSON_NESTING_LIMIT 1000
-#endif
-
-/* Precision of double variables comparison */
-#ifndef CJSON_DOUBLE_PRECISION
-#define CJSON_DOUBLE_PRECISION .0000000000000001
-#endif
-
-/* returns the version of cJSON as a string */
-CJSON_PUBLIC(const char*) cJSON_Version(void);
-
-/* Supply malloc, realloc and free functions to cJSON */
-CJSON_PUBLIC(void) cJSON_InitHooks(cJSON_Hooks* hooks);
-
-/* Memory Management: the caller is always responsible to free the results from all variants of cJSON_Parse (with cJSON_Delete) and cJSON_Print (with stdlib free, cJSON_Hooks.free_fn, or cJSON_free as appropriate). The exception is cJSON_PrintPreallocated, where the caller has full responsibility of the buffer. */
-/* Supply a block of JSON, and this returns a cJSON object you can interrogate. */
-CJSON_PUBLIC(cJSON *) cJSON_Parse(const char *value);
-/* ParseWithOpts allows you to require (and check) that the JSON is null terminated, and to retrieve the pointer to the final byte parsed. */
-/* If you supply a ptr in return_parse_end and parsing fails, then return_parse_end will contain a pointer to the error so will match cJSON_GetErrorPtr(). */
-CJSON_PUBLIC(cJSON *) cJSON_ParseWithOpts(const char *value, const char **return_parse_end, cJSON_bool require_null_terminated);
-
-/* Render a cJSON entity to text for transfer/storage. */
-CJSON_PUBLIC(char *) cJSON_Print(const cJSON *item);
-/* Render a cJSON entity to text for transfer/storage without any formatting. */
-CJSON_PUBLIC(char *) cJSON_PrintUnformatted(const cJSON *item);
-/* Render a cJSON entity to text using a buffered strategy. prebuffer is a guess at the final size. guessing well reduces reallocation. fmt=0 gives unformatted, =1 gives formatted */
-CJSON_PUBLIC(char *) cJSON_PrintBuffered(const cJSON *item, int prebuffer, cJSON_bool fmt);
-/* Render a cJSON entity to text using a buffer already allocated in memory with given length. Returns 1 on success and 0 on failure. */
-/* NOTE: cJSON is not always 100% accurate in estimating how much memory it will use, so to be safe allocate 5 bytes more than you actually need */
-CJSON_PUBLIC(cJSON_bool) cJSON_PrintPreallocated(cJSON *item, char *buffer, const int length, const cJSON_bool format);
-/* Delete a cJSON entity and all subentities. */
-CJSON_PUBLIC(void) cJSON_Delete(cJSON *item);
-
-/* Returns the number of items in an array (or object). */
-CJSON_PUBLIC(int) cJSON_GetArraySize(const cJSON *array);
-/* Retrieve item number "index" from array "array". Returns NULL if unsuccessful. */
-CJSON_PUBLIC(cJSON *) cJSON_GetArrayItem(const cJSON *array, int index);
-/* Get item "string" from object. Case insensitive. */
-CJSON_PUBLIC(cJSON *) cJSON_GetObjectItem(const cJSON * const object, const char * const string);
-CJSON_PUBLIC(cJSON *) cJSON_GetObjectItemCaseSensitive(const cJSON * const object, const char * const string);
-CJSON_PUBLIC(cJSON_bool) cJSON_HasObjectItem(const cJSON *object, const char *string);
-/* For analysing failed parses. This returns a pointer to the parse error. You'll probably need to look a few chars back to make sense of it. Defined when cJSON_Parse() returns 0. 0 when cJSON_Parse() succeeds. */
-CJSON_PUBLIC(const char *) cJSON_GetErrorPtr(void);
-
-/* Check if the item is a string and return its valuestring */
-CJSON_PUBLIC(char *) cJSON_GetStringValue(const cJSON * const item);
-
-/* These functions check the type of an item */
-CJSON_PUBLIC(cJSON_bool) cJSON_IsInvalid(const cJSON * const item);
-CJSON_PUBLIC(cJSON_bool) cJSON_IsFalse(const cJSON * const item);
-CJSON_PUBLIC(cJSON_bool) cJSON_IsTrue(const cJSON * const item);
-CJSON_PUBLIC(cJSON_bool) cJSON_IsBool(const cJSON * const item);
-CJSON_PUBLIC(cJSON_bool) cJSON_IsNull(const cJSON * const item);
-CJSON_PUBLIC(cJSON_bool) cJSON_IsNumber(const cJSON * const item);
-CJSON_PUBLIC(cJSON_bool) cJSON_IsString(const cJSON * const item);
-CJSON_PUBLIC(cJSON_bool) cJSON_IsArray(const cJSON * const item);
-CJSON_PUBLIC(cJSON_bool) cJSON_IsObject(const cJSON * const item);
-CJSON_PUBLIC(cJSON_bool) cJSON_IsRaw(const cJSON * const item);
-
-/* These calls create a cJSON item of the appropriate type. */
-CJSON_PUBLIC(cJSON *) cJSON_CreateNull(void);
-CJSON_PUBLIC(cJSON *) cJSON_CreateTrue(void);
-CJSON_PUBLIC(cJSON *) cJSON_CreateFalse(void);
-CJSON_PUBLIC(cJSON *) cJSON_CreateBool(cJSON_bool boolean);
-CJSON_PUBLIC(cJSON *) cJSON_CreateNumber(double num);
-CJSON_PUBLIC(cJSON *) cJSON_CreateString(const char *string);
-/* raw json */
-CJSON_PUBLIC(cJSON *) cJSON_CreateRaw(const char *raw);
-CJSON_PUBLIC(cJSON *) cJSON_CreateArray(void);
-CJSON_PUBLIC(cJSON *) cJSON_CreateObject(void);
-
-/* Create a string where valuestring references a string so
- * it will not be freed by cJSON_Delete */
-CJSON_PUBLIC(cJSON *) cJSON_CreateStringReference(const char *string);
-/* Create an object/array that only references it's elements so
- * they will not be freed by cJSON_Delete */
-CJSON_PUBLIC(cJSON *) cJSON_CreateObjectReference(const cJSON *child);
-CJSON_PUBLIC(cJSON *) cJSON_CreateArrayReference(const cJSON *child);
-
-/* These utilities create an Array of count items.
- * The parameter count cannot be greater than the number of elements in the number array, otherwise array access will be out of bounds.*/
-CJSON_PUBLIC(cJSON *) cJSON_CreateIntArray(const int *numbers, int count);
-CJSON_PUBLIC(cJSON *) cJSON_CreateFloatArray(const float *numbers, int count);
-CJSON_PUBLIC(cJSON *) cJSON_CreateDoubleArray(const double *numbers, int count);
-CJSON_PUBLIC(cJSON *) cJSON_CreateStringArray(const char *const *strings, int count);
-
-/* Append item to the specified array/object. */
-CJSON_PUBLIC(void) cJSON_AddItemToArray(cJSON *array, cJSON *item);
-CJSON_PUBLIC(void) cJSON_AddItemToObject(cJSON *object, const char *string, cJSON *item);
-/* Use this when string is definitely const (i.e. a literal, or as good as), and will definitely survive the cJSON object.
- * WARNING: When this function was used, make sure to always check that (item->type & cJSON_StringIsConst) is zero before
- * writing to `item->string` */
-CJSON_PUBLIC(void) cJSON_AddItemToObjectCS(cJSON *object, const char *string, cJSON *item);
-/* Append reference to item to the specified array/object. Use this when you want to add an existing cJSON to a new cJSON, but don't want to corrupt your existing cJSON. */
-CJSON_PUBLIC(void) cJSON_AddItemReferenceToArray(cJSON *array, cJSON *item);
-CJSON_PUBLIC(void) cJSON_AddItemReferenceToObject(cJSON *object, const char *string, cJSON *item);
-
-/* Remove/Detach items from Arrays/Objects. */
-CJSON_PUBLIC(cJSON *) cJSON_DetachItemViaPointer(cJSON *parent, cJSON * const item);
-CJSON_PUBLIC(cJSON *) cJSON_DetachItemFromArray(cJSON *array, int which);
-CJSON_PUBLIC(void) cJSON_DeleteItemFromArray(cJSON *array, int which);
-CJSON_PUBLIC(cJSON *) cJSON_DetachItemFromObject(cJSON *object, const char *string);
-CJSON_PUBLIC(cJSON *) cJSON_DetachItemFromObjectCaseSensitive(cJSON *object, const char *string);
-CJSON_PUBLIC(void) cJSON_DeleteItemFromObject(cJSON *object, const char *string);
-CJSON_PUBLIC(void) cJSON_DeleteItemFromObjectCaseSensitive(cJSON *object, const char *string);
-
-/* Update array items. */
-CJSON_PUBLIC(void) cJSON_InsertItemInArray(cJSON *array, int which, cJSON *newitem); /* Shifts pre-existing items to the right. */
-CJSON_PUBLIC(cJSON_bool) cJSON_ReplaceItemViaPointer(cJSON * const parent, cJSON * const item, cJSON * replacement);
-CJSON_PUBLIC(void) cJSON_ReplaceItemInArray(cJSON *array, int which, cJSON *newitem);
-CJSON_PUBLIC(void) cJSON_ReplaceItemInObject(cJSON *object,const char *string,cJSON *newitem);
-CJSON_PUBLIC(void) cJSON_ReplaceItemInObjectCaseSensitive(cJSON *object,const char *string,cJSON *newitem);
-
-/* Duplicate a cJSON item */
-CJSON_PUBLIC(cJSON *) cJSON_Duplicate(const cJSON *item, cJSON_bool recurse);
-/* Duplicate will create a new, identical cJSON item to the one you pass, in new memory that will
- * need to be released. With recurse!=0, it will duplicate any children connected to the item.
- * The item->next and ->prev pointers are always zero on return from Duplicate. */
-/* Recursively compare two cJSON items for equality. If either a or b is NULL or invalid, they will be considered unequal.
- * case_sensitive determines if object keys are treated case sensitive (1) or case insensitive (0) */
-CJSON_PUBLIC(cJSON_bool) cJSON_Compare(const cJSON * const a, const cJSON * const b, const cJSON_bool case_sensitive);
-
-/* Minify a strings, remove blank characters(such as ' ', '\t', '\r', '\n') from strings.
- * The input pointer json cannot point to a read-only address area, such as a string constant,
- * but should point to a readable and writable adress area. */
-CJSON_PUBLIC(void) cJSON_Minify(char *json);
-
-/* Helper functions for creating and adding items to an object at the same time.
- * They return the added item or NULL on failure. */
-CJSON_PUBLIC(cJSON*) cJSON_AddNullToObject(cJSON * const object, const char * const name);
-CJSON_PUBLIC(cJSON*) cJSON_AddTrueToObject(cJSON * const object, const char * const name);
-CJSON_PUBLIC(cJSON*) cJSON_AddFalseToObject(cJSON * const object, const char * const name);
-CJSON_PUBLIC(cJSON*) cJSON_AddBoolToObject(cJSON * const object, const char * const name, const cJSON_bool boolean);
-CJSON_PUBLIC(cJSON*) cJSON_AddNumberToObject(cJSON * const object, const char * const name, const double number);
-CJSON_PUBLIC(cJSON*) cJSON_AddStringToObject(cJSON * const object, const char * const name, const char * const string);
-CJSON_PUBLIC(cJSON*) cJSON_AddRawToObject(cJSON * const object, const char * const name, const char * const raw);
-CJSON_PUBLIC(cJSON*) cJSON_AddObjectToObject(cJSON * const object, const char * const name);
-CJSON_PUBLIC(cJSON*) cJSON_AddArrayToObject(cJSON * const object, const char * const name);
-
-/* When assigning an integer value, it needs to be propagated to valuedouble too. */
-#define cJSON_SetIntValue(object, number) ((object) ? (object)->valueint = (object)->valuedouble = (number) : (number))
-/* helper for the cJSON_SetNumberValue macro */
-CJSON_PUBLIC(double) cJSON_SetNumberHelper(cJSON *object, double number);
-#define cJSON_SetNumberValue(object, number) ((object != NULL) ? cJSON_SetNumberHelper(object, (double)number) : (number))
-
-/* Macro for iterating over an array or object */
-#define cJSON_ArrayForEach(element, array) for(element = (array != NULL) ? (array)->child : NULL; element != NULL; element = element->next)
-
-/* malloc/free objects using the malloc/free functions that have been set with cJSON_InitHooks */
-CJSON_PUBLIC(void *) cJSON_malloc(size_t size);
-CJSON_PUBLIC(void) cJSON_free(void *object);
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif
+++ /dev/null
-#ifndef _UDP_H_
-#define _UDP_H_
-#include <stdbool.h>
-
-//端口号
-#define PORT 12020
-#define ACK_PORT 12021
-//接收报文数组大小
-#define BUFFER_SIZE 100
-//PID文件存放路径
-//#define PID_FILE_PATH "/customer/tuya_auth"
-//网卡名称
-#define ETH_NAME "wlan0"
-//设置mac地址长度
-#define MAC_SIZE 18
-//联网状态
-bool IS_NETWORKING;
-
-//开启端口监听
-int open_udp_listen();
-//关闭端口监听
-int close_udp_listen();
-
-#endif
+++ /dev/null
-/*
- Copyright (c) 2009-2017 Dave Gamble and cJSON contributors
-
- Permission is hereby granted, free of charge, to any person obtaining a copy
- of this software and associated documentation files (the "Software"), to deal
- in the Software without restriction, including without limitation the rights
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
- copies of the Software, and to permit persons to whom the Software is
- furnished to do so, subject to the following conditions:
-
- The above copyright notice and this permission notice shall be included in
- all copies or substantial portions of the Software.
-
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
- THE SOFTWARE.
-*/
-
-/* cJSON */
-/* JSON parser in C. */
-
-/* disable warnings about old C89 functions in MSVC */
-#if !defined(_CRT_SECURE_NO_DEPRECATE) && defined(_MSC_VER)
-#define _CRT_SECURE_NO_DEPRECATE
-#endif
-
-#ifdef __GNUC__
-#pragma GCC visibility push(default)
-#endif
-#if defined(_MSC_VER)
-#pragma warning (push)
-/* disable warning about single line comments in system headers */
-#pragma warning (disable : 4001)
-#endif
-
-#include <string.h>
-#include <stdio.h>
-#include <math.h>
-#include <stdlib.h>
-#include <limits.h>
-#include <ctype.h>
-
-#ifdef ENABLE_LOCALES
-#include <locale.h>
-#endif
-
-#if defined(_MSC_VER)
-#pragma warning (pop)
-#endif
-#ifdef __GNUC__
-#pragma GCC visibility pop
-#endif
-
-#include "cJSON.h"
-
-/* define our own boolean type */
-#ifdef true
-#undef true
-#endif
-#define true ((cJSON_bool)1)
-
-#ifdef false
-#undef false
-#endif
-#define false ((cJSON_bool)0)
-
-typedef struct {
- const unsigned char *json;
- size_t position;
-} error;
-static error global_error = { NULL, 0 };
-
-CJSON_PUBLIC(const char *) cJSON_GetErrorPtr(void)
-{
- return (const char*) (global_error.json + global_error.position);
-}
-
-CJSON_PUBLIC(char *) cJSON_GetStringValue(const cJSON * const item) {
- if (!cJSON_IsString(item)) {
- return NULL;
- }
-
- return item->valuestring;
-}
-
-/* This is a safeguard to prevent copy-pasters from using incompatible C and header files */
-#if (CJSON_VERSION_MAJOR != 1) || (CJSON_VERSION_MINOR != 7) || (CJSON_VERSION_PATCH != 12)
- #error cJSON.h and cJSON.c have different versions. Make sure that both have the same.
-#endif
-
-CJSON_PUBLIC(const char*) cJSON_Version(void)
-{
- static char version[15];
- sprintf(version, "%i.%i.%i", CJSON_VERSION_MAJOR, CJSON_VERSION_MINOR, CJSON_VERSION_PATCH);
-
- return version;
-}
-
-/* Case insensitive string comparison, doesn't consider two NULL pointers equal though */
-static int case_insensitive_strcmp(const unsigned char *string1, const unsigned char *string2)
-{
- if ((string1 == NULL) || (string2 == NULL))
- {
- return 1;
- }
-
- if (string1 == string2)
- {
- return 0;
- }
-
- for(; tolower(*string1) == tolower(*string2); (void)string1++, string2++)
- {
- if (*string1 == '\0')
- {
- return 0;
- }
- }
-
- return tolower(*string1) - tolower(*string2);
-}
-
-typedef struct internal_hooks
-{
- void *(CJSON_CDECL *allocate)(size_t size);
- void (CJSON_CDECL *deallocate)(void *pointer);
- void *(CJSON_CDECL *reallocate)(void *pointer, size_t size);
-} internal_hooks;
-
-#if defined(_MSC_VER)
-/* work around MSVC error C2322: '...' address of dllimport '...' is not static */
-static void * CJSON_CDECL internal_malloc(size_t size)
-{
- return malloc(size);
-}
-static void CJSON_CDECL internal_free(void *pointer)
-{
- free(pointer);
-}
-static void * CJSON_CDECL internal_realloc(void *pointer, size_t size)
-{
- return realloc(pointer, size);
-}
-#else
-#define internal_malloc malloc
-#define internal_free free
-#define internal_realloc realloc
-#endif
-
-/* strlen of character literals resolved at compile time */
-#define static_strlen(string_literal) (sizeof(string_literal) - sizeof(""))
-
-static internal_hooks global_hooks = { internal_malloc, internal_free, internal_realloc };
-
-static unsigned char* cJSON_strdup(const unsigned char* string, const internal_hooks * const hooks)
-{
- size_t length = 0;
- unsigned char *copy = NULL;
-
- if (string == NULL)
- {
- return NULL;
- }
-
- length = strlen((const char*)string) + sizeof("");
- copy = (unsigned char*)hooks->allocate(length);
- if (copy == NULL)
- {
- return NULL;
- }
- memcpy(copy, string, length);
-
- return copy;
-}
-
-CJSON_PUBLIC(void) cJSON_InitHooks(cJSON_Hooks* hooks)
-{
- if (hooks == NULL)
- {
- /* Reset hooks */
- global_hooks.allocate = malloc;
- global_hooks.deallocate = free;
- global_hooks.reallocate = realloc;
- return;
- }
-
- global_hooks.allocate = malloc;
- if (hooks->malloc_fn != NULL)
- {
- global_hooks.allocate = hooks->malloc_fn;
- }
-
- global_hooks.deallocate = free;
- if (hooks->free_fn != NULL)
- {
- global_hooks.deallocate = hooks->free_fn;
- }
-
- /* use realloc only if both free and malloc are used */
- global_hooks.reallocate = NULL;
- if ((global_hooks.allocate == malloc) && (global_hooks.deallocate == free))
- {
- global_hooks.reallocate = realloc;
- }
-}
-
-/* Internal constructor. */
-static cJSON *cJSON_New_Item(const internal_hooks * const hooks)
-{
- cJSON* node = (cJSON*)hooks->allocate(sizeof(cJSON));
- if (node)
- {
- memset(node, '\0', sizeof(cJSON));
- }
-
- return node;
-}
-
-/* Delete a cJSON structure. */
-CJSON_PUBLIC(void) cJSON_Delete(cJSON *item)
-{
- cJSON *next = NULL;
- while (item != NULL)
- {
- next = item->next;
- if (!(item->type & cJSON_IsReference) && (item->child != NULL))
- {
- cJSON_Delete(item->child);
- }
- if (!(item->type & cJSON_IsReference) && (item->valuestring != NULL))
- {
- global_hooks.deallocate(item->valuestring);
- }
- if (!(item->type & cJSON_StringIsConst) && (item->string != NULL))
- {
- global_hooks.deallocate(item->string);
- }
- global_hooks.deallocate(item);
- item = next;
- }
-}
-
-/* get the decimal point character of the current locale */
-static unsigned char get_decimal_point(void)
-{
-#ifdef ENABLE_LOCALES
- struct lconv *lconv = localeconv();
- return (unsigned char) lconv->decimal_point[0];
-#else
- return '.';
-#endif
-}
-
-typedef struct
-{
- const unsigned char *content;
- size_t length;
- size_t offset;
- size_t depth; /* How deeply nested (in arrays/objects) is the input at the current offset. */
- internal_hooks hooks;
-} parse_buffer;
-
-/* check if the given size is left to read in a given parse buffer (starting with 1) */
-#define can_read(buffer, size) ((buffer != NULL) && (((buffer)->offset + size) <= (buffer)->length))
-/* check if the buffer can be accessed at the given index (starting with 0) */
-#define can_access_at_index(buffer, index) ((buffer != NULL) && (((buffer)->offset + index) < (buffer)->length))
-#define cannot_access_at_index(buffer, index) (!can_access_at_index(buffer, index))
-/* get a pointer to the buffer at the position */
-#define buffer_at_offset(buffer) ((buffer)->content + (buffer)->offset)
-
-/* Parse the input text to generate a number, and populate the result into item. */
-static cJSON_bool parse_number(cJSON * const item, parse_buffer * const input_buffer)
-{
- double number = 0;
- unsigned char *after_end = NULL;
- unsigned char number_c_string[64];
- unsigned char decimal_point = get_decimal_point();
- size_t i = 0;
-
- if ((input_buffer == NULL) || (input_buffer->content == NULL))
- {
- return false;
- }
-
- /* copy the number into a temporary buffer and replace '.' with the decimal point
- * of the current locale (for strtod)
- * This also takes care of '\0' not necessarily being available for marking the end of the input */
- for (i = 0; (i < (sizeof(number_c_string) - 1)) && can_access_at_index(input_buffer, i); i++)
- {
- switch (buffer_at_offset(input_buffer)[i])
- {
- case '0':
- case '1':
- case '2':
- case '3':
- case '4':
- case '5':
- case '6':
- case '7':
- case '8':
- case '9':
- case '+':
- case '-':
- case 'e':
- case 'E':
- number_c_string[i] = buffer_at_offset(input_buffer)[i];
- break;
-
- case '.':
- number_c_string[i] = decimal_point;
- break;
-
- default:
- goto loop_end;
- }
- }
-loop_end:
- number_c_string[i] = '\0';
-
- number = strtod((const char*)number_c_string, (char**)&after_end);
- if (number_c_string == after_end)
- {
- return false; /* parse_error */
- }
-
- item->valuedouble = number;
-
- /* use saturation in case of overflow */
- if (number >= INT_MAX)
- {
- item->valueint = INT_MAX;
- }
- else if (number <= (double)INT_MIN)
- {
- item->valueint = INT_MIN;
- }
- else
- {
- item->valueint = (int)number;
- }
-
- item->type = cJSON_Number;
-
- input_buffer->offset += (size_t)(after_end - number_c_string);
- return true;
-}
-
-/* don't ask me, but the original cJSON_SetNumberValue returns an integer or double */
-CJSON_PUBLIC(double) cJSON_SetNumberHelper(cJSON *object, double number)
-{
- if (number >= INT_MAX)
- {
- object->valueint = INT_MAX;
- }
- else if (number <= (double)INT_MIN)
- {
- object->valueint = INT_MIN;
- }
- else
- {
- object->valueint = (int)number;
- }
-
- return object->valuedouble = number;
-}
-
-typedef struct
-{
- unsigned char *buffer;
- size_t length;
- size_t offset;
- size_t depth; /* current nesting depth (for formatted printing) */
- cJSON_bool noalloc;
- cJSON_bool format; /* is this print a formatted print */
- internal_hooks hooks;
-} printbuffer;
-
-/* realloc printbuffer if necessary to have at least "needed" bytes more */
-static unsigned char* ensure(printbuffer * const p, size_t needed)
-{
- unsigned char *newbuffer = NULL;
- size_t newsize = 0;
-
- if ((p == NULL) || (p->buffer == NULL))
- {
- return NULL;
- }
-
- if ((p->length > 0) && (p->offset >= p->length))
- {
- /* make sure that offset is valid */
- return NULL;
- }
-
- if (needed > INT_MAX)
- {
- /* sizes bigger than INT_MAX are currently not supported */
- return NULL;
- }
-
- needed += p->offset + 1;
- if (needed <= p->length)
- {
- return p->buffer + p->offset;
- }
-
- if (p->noalloc) {
- return NULL;
- }
-
- /* calculate new buffer size */
- if (needed > (INT_MAX / 2))
- {
- /* overflow of int, use INT_MAX if possible */
- if (needed <= INT_MAX)
- {
- newsize = INT_MAX;
- }
- else
- {
- return NULL;
- }
- }
- else
- {
- newsize = needed * 2;
- }
-
- if (p->hooks.reallocate != NULL)
- {
- /* reallocate with realloc if available */
- newbuffer = (unsigned char*)p->hooks.reallocate(p->buffer, newsize);
- if (newbuffer == NULL)
- {
- p->hooks.deallocate(p->buffer);
- p->length = 0;
- p->buffer = NULL;
-
- return NULL;
- }
- }
- else
- {
- /* otherwise reallocate manually */
- newbuffer = (unsigned char*)p->hooks.allocate(newsize);
- if (!newbuffer)
- {
- p->hooks.deallocate(p->buffer);
- p->length = 0;
- p->buffer = NULL;
-
- return NULL;
- }
- if (newbuffer)
- {
- memcpy(newbuffer, p->buffer, p->offset + 1);
- }
- p->hooks.deallocate(p->buffer);
- }
- p->length = newsize;
- p->buffer = newbuffer;
-
- return newbuffer + p->offset;
-}
-
-/* calculate the new length of the string in a printbuffer and update the offset */
-static void update_offset(printbuffer * const buffer)
-{
- const unsigned char *buffer_pointer = NULL;
- if ((buffer == NULL) || (buffer->buffer == NULL))
- {
- return;
- }
- buffer_pointer = buffer->buffer + buffer->offset;
-
- buffer->offset += strlen((const char*)buffer_pointer);
-}
-
-/* securely comparison of floating-point variables */
-static cJSON_bool compare_double(double a, double b)
-{
- return (fabs(a - b) <= CJSON_DOUBLE_PRECISION);
-}
-
-/* Render the number nicely from the given item into a string. */
-static cJSON_bool print_number(const cJSON * const item, printbuffer * const output_buffer)
-{
- unsigned char *output_pointer = NULL;
- double d = item->valuedouble;
- int length = 0;
- size_t i = 0;
- unsigned char number_buffer[26] = {0}; /* temporary buffer to print the number into */
- unsigned char decimal_point = get_decimal_point();
- double test = 0.0;
-
- if (output_buffer == NULL)
- {
- return false;
- }
-
- /* This checks for NaN and Infinity */
- if ((d * 0) != 0)
- {
- length = sprintf((char*)number_buffer, "null");
- }
- else
- {
- /* Try 15 decimal places of precision to avoid nonsignificant nonzero digits */
- length = sprintf((char*)number_buffer, "%1.15g", d);
-
- /* Check whether the original double can be recovered */
- if ((sscanf((char*)number_buffer, "%lg", &test) != 1) || !compare_double((double)test, d))
- {
- /* If not, print with 17 decimal places of precision */
- length = sprintf((char*)number_buffer, "%1.17g", d);
- }
- }
-
- /* sprintf failed or buffer overrun occurred */
- if ((length < 0) || (length > (int)(sizeof(number_buffer) - 1)))
- {
- return false;
- }
-
- /* reserve appropriate space in the output */
- output_pointer = ensure(output_buffer, (size_t)length + sizeof(""));
- if (output_pointer == NULL)
- {
- return false;
- }
-
- /* copy the printed number to the output and replace locale
- * dependent decimal point with '.' */
- for (i = 0; i < ((size_t)length); i++)
- {
- if (number_buffer[i] == decimal_point)
- {
- output_pointer[i] = '.';
- continue;
- }
-
- output_pointer[i] = number_buffer[i];
- }
- output_pointer[i] = '\0';
-
- output_buffer->offset += (size_t)length;
-
- return true;
-}
-
-/* parse 4 digit hexadecimal number */
-static unsigned parse_hex4(const unsigned char * const input)
-{
- unsigned int h = 0;
- size_t i = 0;
-
- for (i = 0; i < 4; i++)
- {
- /* parse digit */
- if ((input[i] >= '0') && (input[i] <= '9'))
- {
- h += (unsigned int) input[i] - '0';
- }
- else if ((input[i] >= 'A') && (input[i] <= 'F'))
- {
- h += (unsigned int) 10 + input[i] - 'A';
- }
- else if ((input[i] >= 'a') && (input[i] <= 'f'))
- {
- h += (unsigned int) 10 + input[i] - 'a';
- }
- else /* invalid */
- {
- return 0;
- }
-
- if (i < 3)
- {
- /* shift left to make place for the next nibble */
- h = h << 4;
- }
- }
-
- return h;
-}
-
-/* converts a UTF-16 literal to UTF-8
- * A literal can be one or two sequences of the form \uXXXX */
-static unsigned char utf16_literal_to_utf8(const unsigned char * const input_pointer, const unsigned char * const input_end, unsigned char **output_pointer)
-{
- long unsigned int codepoint = 0;
- unsigned int first_code = 0;
- const unsigned char *first_sequence = input_pointer;
- unsigned char utf8_length = 0;
- unsigned char utf8_position = 0;
- unsigned char sequence_length = 0;
- unsigned char first_byte_mark = 0;
-
- if ((input_end - first_sequence) < 6)
- {
- /* input ends unexpectedly */
- goto fail;
- }
-
- /* get the first utf16 sequence */
- first_code = parse_hex4(first_sequence + 2);
-
- /* check that the code is valid */
- if (((first_code >= 0xDC00) && (first_code <= 0xDFFF)))
- {
- goto fail;
- }
-
- /* UTF16 surrogate pair */
- if ((first_code >= 0xD800) && (first_code <= 0xDBFF))
- {
- const unsigned char *second_sequence = first_sequence + 6;
- unsigned int second_code = 0;
- sequence_length = 12; /* \uXXXX\uXXXX */
-
- if ((input_end - second_sequence) < 6)
- {
- /* input ends unexpectedly */
- goto fail;
- }
-
- if ((second_sequence[0] != '\\') || (second_sequence[1] != 'u'))
- {
- /* missing second half of the surrogate pair */
- goto fail;
- }
-
- /* get the second utf16 sequence */
- second_code = parse_hex4(second_sequence + 2);
- /* check that the code is valid */
- if ((second_code < 0xDC00) || (second_code > 0xDFFF))
- {
- /* invalid second half of the surrogate pair */
- goto fail;
- }
-
-
- /* calculate the unicode codepoint from the surrogate pair */
- codepoint = 0x10000 + (((first_code & 0x3FF) << 10) | (second_code & 0x3FF));
- }
- else
- {
- sequence_length = 6; /* \uXXXX */
- codepoint = first_code;
- }
-
- /* encode as UTF-8
- * takes at maximum 4 bytes to encode:
- * 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx */
- if (codepoint < 0x80)
- {
- /* normal ascii, encoding 0xxxxxxx */
- utf8_length = 1;
- }
- else if (codepoint < 0x800)
- {
- /* two bytes, encoding 110xxxxx 10xxxxxx */
- utf8_length = 2;
- first_byte_mark = 0xC0; /* 11000000 */
- }
- else if (codepoint < 0x10000)
- {
- /* three bytes, encoding 1110xxxx 10xxxxxx 10xxxxxx */
- utf8_length = 3;
- first_byte_mark = 0xE0; /* 11100000 */
- }
- else if (codepoint <= 0x10FFFF)
- {
- /* four bytes, encoding 1110xxxx 10xxxxxx 10xxxxxx 10xxxxxx */
- utf8_length = 4;
- first_byte_mark = 0xF0; /* 11110000 */
- }
- else
- {
- /* invalid unicode codepoint */
- goto fail;
- }
-
- /* encode as utf8 */
- for (utf8_position = (unsigned char)(utf8_length - 1); utf8_position > 0; utf8_position--)
- {
- /* 10xxxxxx */
- (*output_pointer)[utf8_position] = (unsigned char)((codepoint | 0x80) & 0xBF);
- codepoint >>= 6;
- }
- /* encode first byte */
- if (utf8_length > 1)
- {
- (*output_pointer)[0] = (unsigned char)((codepoint | first_byte_mark) & 0xFF);
- }
- else
- {
- (*output_pointer)[0] = (unsigned char)(codepoint & 0x7F);
- }
-
- *output_pointer += utf8_length;
-
- return sequence_length;
-
-fail:
- return 0;
-}
-
-/* Parse the input text into an unescaped cinput, and populate item. */
-static cJSON_bool parse_string(cJSON * const item, parse_buffer * const input_buffer)
-{
- const unsigned char *input_pointer = buffer_at_offset(input_buffer) + 1;
- const unsigned char *input_end = buffer_at_offset(input_buffer) + 1;
- unsigned char *output_pointer = NULL;
- unsigned char *output = NULL;
-
- /* not a string */
- if (buffer_at_offset(input_buffer)[0] != '\"')
- {
- goto fail;
- }
-
- {
- /* calculate approximate size of the output (overestimate) */
- size_t allocation_length = 0;
- size_t skipped_bytes = 0;
- while (((size_t)(input_end - input_buffer->content) < input_buffer->length) && (*input_end != '\"'))
- {
- /* is escape sequence */
- if (input_end[0] == '\\')
- {
- if ((size_t)(input_end + 1 - input_buffer->content) >= input_buffer->length)
- {
- /* prevent buffer overflow when last input character is a backslash */
- goto fail;
- }
- skipped_bytes++;
- input_end++;
- }
- input_end++;
- }
- if (((size_t)(input_end - input_buffer->content) >= input_buffer->length) || (*input_end != '\"'))
- {
- goto fail; /* string ended unexpectedly */
- }
-
- /* This is at most how much we need for the output */
- allocation_length = (size_t) (input_end - buffer_at_offset(input_buffer)) - skipped_bytes;
- output = (unsigned char*)input_buffer->hooks.allocate(allocation_length + sizeof(""));
- if (output == NULL)
- {
- goto fail; /* allocation failure */
- }
- }
-
- output_pointer = output;
- /* loop through the string literal */
- while (input_pointer < input_end)
- {
- if (*input_pointer != '\\')
- {
- *output_pointer++ = *input_pointer++;
- }
- /* escape sequence */
- else
- {
- unsigned char sequence_length = 2;
- if ((input_end - input_pointer) < 1)
- {
- goto fail;
- }
-
- switch (input_pointer[1])
- {
- case 'b':
- *output_pointer++ = '\b';
- break;
- case 'f':
- *output_pointer++ = '\f';
- break;
- case 'n':
- *output_pointer++ = '\n';
- break;
- case 'r':
- *output_pointer++ = '\r';
- break;
- case 't':
- *output_pointer++ = '\t';
- break;
- case '\"':
- case '\\':
- case '/':
- *output_pointer++ = input_pointer[1];
- break;
-
- /* UTF-16 literal */
- case 'u':
- sequence_length = utf16_literal_to_utf8(input_pointer, input_end, &output_pointer);
- if (sequence_length == 0)
- {
- /* failed to convert UTF16-literal to UTF-8 */
- goto fail;
- }
- break;
-
- default:
- goto fail;
- }
- input_pointer += sequence_length;
- }
- }
-
- /* zero terminate the output */
- *output_pointer = '\0';
-
- item->type = cJSON_String;
- item->valuestring = (char*)output;
-
- input_buffer->offset = (size_t) (input_end - input_buffer->content);
- input_buffer->offset++;
-
- return true;
-
-fail:
- if (output != NULL)
- {
- input_buffer->hooks.deallocate(output);
- }
-
- if (input_pointer != NULL)
- {
- input_buffer->offset = (size_t)(input_pointer - input_buffer->content);
- }
-
- return false;
-}
-
-/* Render the cstring provided to an escaped version that can be printed. */
-static cJSON_bool print_string_ptr(const unsigned char * const input, printbuffer * const output_buffer)
-{
- const unsigned char *input_pointer = NULL;
- unsigned char *output = NULL;
- unsigned char *output_pointer = NULL;
- size_t output_length = 0;
- /* numbers of additional characters needed for escaping */
- size_t escape_characters = 0;
-
- if (output_buffer == NULL)
- {
- return false;
- }
-
- /* empty string */
- if (input == NULL)
- {
- output = ensure(output_buffer, sizeof("\"\""));
- if (output == NULL)
- {
- return false;
- }
- strcpy((char*)output, "\"\"");
-
- return true;
- }
-
- /* set "flag" to 1 if something needs to be escaped */
- for (input_pointer = input; *input_pointer; input_pointer++)
- {
- switch (*input_pointer)
- {
- case '\"':
- case '\\':
- case '\b':
- case '\f':
- case '\n':
- case '\r':
- case '\t':
- /* one character escape sequence */
- escape_characters++;
- break;
- default:
- if (*input_pointer < 32)
- {
- /* UTF-16 escape sequence uXXXX */
- escape_characters += 5;
- }
- break;
- }
- }
- output_length = (size_t)(input_pointer - input) + escape_characters;
-
- output = ensure(output_buffer, output_length + sizeof("\"\""));
- if (output == NULL)
- {
- return false;
- }
-
- /* no characters have to be escaped */
- if (escape_characters == 0)
- {
- output[0] = '\"';
- memcpy(output + 1, input, output_length);
- output[output_length + 1] = '\"';
- output[output_length + 2] = '\0';
-
- return true;
- }
-
- output[0] = '\"';
- output_pointer = output + 1;
- /* copy the string */
- for (input_pointer = input; *input_pointer != '\0'; (void)input_pointer++, output_pointer++)
- {
- if ((*input_pointer > 31) && (*input_pointer != '\"') && (*input_pointer != '\\'))
- {
- /* normal character, copy */
- *output_pointer = *input_pointer;
- }
- else
- {
- /* character needs to be escaped */
- *output_pointer++ = '\\';
- switch (*input_pointer)
- {
- case '\\':
- *output_pointer = '\\';
- break;
- case '\"':
- *output_pointer = '\"';
- break;
- case '\b':
- *output_pointer = 'b';
- break;
- case '\f':
- *output_pointer = 'f';
- break;
- case '\n':
- *output_pointer = 'n';
- break;
- case '\r':
- *output_pointer = 'r';
- break;
- case '\t':
- *output_pointer = 't';
- break;
- default:
- /* escape and print as unicode codepoint */
- sprintf((char*)output_pointer, "u%04x", *input_pointer);
- output_pointer += 4;
- break;
- }
- }
- }
- output[output_length + 1] = '\"';
- output[output_length + 2] = '\0';
-
- return true;
-}
-
-/* Invoke print_string_ptr (which is useful) on an item. */
-static cJSON_bool print_string(const cJSON * const item, printbuffer * const p)
-{
- return print_string_ptr((unsigned char*)item->valuestring, p);
-}
-
-/* Predeclare these prototypes. */
-static cJSON_bool parse_value(cJSON * const item, parse_buffer * const input_buffer);
-static cJSON_bool print_value(const cJSON * const item, printbuffer * const output_buffer);
-static cJSON_bool parse_array(cJSON * const item, parse_buffer * const input_buffer);
-static cJSON_bool print_array(const cJSON * const item, printbuffer * const output_buffer);
-static cJSON_bool parse_object(cJSON * const item, parse_buffer * const input_buffer);
-static cJSON_bool print_object(const cJSON * const item, printbuffer * const output_buffer);
-
-/* Utility to jump whitespace and cr/lf */
-static parse_buffer *buffer_skip_whitespace(parse_buffer * const buffer)
-{
- if ((buffer == NULL) || (buffer->content == NULL))
- {
- return NULL;
- }
-
- while (can_access_at_index(buffer, 0) && (buffer_at_offset(buffer)[0] <= 32))
- {
- buffer->offset++;
- }
-
- if (buffer->offset == buffer->length)
- {
- buffer->offset--;
- }
-
- return buffer;
-}
-
-/* skip the UTF-8 BOM (byte order mark) if it is at the beginning of a buffer */
-static parse_buffer *skip_utf8_bom(parse_buffer * const buffer)
-{
- if ((buffer == NULL) || (buffer->content == NULL) || (buffer->offset != 0))
- {
- return NULL;
- }
-
- if (can_access_at_index(buffer, 4) && (strncmp((const char*)buffer_at_offset(buffer), "\xEF\xBB\xBF", 3) == 0))
- {
- buffer->offset += 3;
- }
-
- return buffer;
-}
-
-/* Parse an object - create a new root, and populate. */
-CJSON_PUBLIC(cJSON *) cJSON_ParseWithOpts(const char *value, const char **return_parse_end, cJSON_bool require_null_terminated)
-{
- parse_buffer buffer = { 0, 0, 0, 0, { 0, 0, 0 } };
- cJSON *item = NULL;
-
- /* reset error position */
- global_error.json = NULL;
- global_error.position = 0;
-
- if (value == NULL)
- {
- goto fail;
- }
-
- buffer.content = (const unsigned char*)value;
- buffer.length = strlen((const char*)value) + sizeof("");
- buffer.offset = 0;
- buffer.hooks = global_hooks;
-
- item = cJSON_New_Item(&global_hooks);
- if (item == NULL) /* memory fail */
- {
- goto fail;
- }
-
- if (!parse_value(item, buffer_skip_whitespace(skip_utf8_bom(&buffer))))
- {
- /* parse failure. ep is set. */
- goto fail;
- }
-
- /* if we require null-terminated JSON without appended garbage, skip and then check for a null terminator */
- if (require_null_terminated)
- {
- buffer_skip_whitespace(&buffer);
- if ((buffer.offset >= buffer.length) || buffer_at_offset(&buffer)[0] != '\0')
- {
- goto fail;
- }
- }
- if (return_parse_end)
- {
- *return_parse_end = (const char*)buffer_at_offset(&buffer);
- }
-
- return item;
-
-fail:
- if (item != NULL)
- {
- cJSON_Delete(item);
- }
-
- if (value != NULL)
- {
- error local_error;
- local_error.json = (const unsigned char*)value;
- local_error.position = 0;
-
- if (buffer.offset < buffer.length)
- {
- local_error.position = buffer.offset;
- }
- else if (buffer.length > 0)
- {
- local_error.position = buffer.length - 1;
- }
-
- if (return_parse_end != NULL)
- {
- *return_parse_end = (const char*)local_error.json + local_error.position;
- }
-
- global_error = local_error;
- }
-
- return NULL;
-}
-
-/* Default options for cJSON_Parse */
-CJSON_PUBLIC(cJSON *) cJSON_Parse(const char *value)
-{
- return cJSON_ParseWithOpts(value, 0, 0);
-}
-
-#define cjson_min(a, b) ((a < b) ? a : b)
-
-static unsigned char *print(const cJSON * const item, cJSON_bool format, const internal_hooks * const hooks)
-{
- static const size_t default_buffer_size = 256;
- printbuffer buffer[1];
- unsigned char *printed = NULL;
-
- memset(buffer, 0, sizeof(buffer));
-
- /* create buffer */
- buffer->buffer = (unsigned char*) hooks->allocate(default_buffer_size);
- buffer->length = default_buffer_size;
- buffer->format = format;
- buffer->hooks = *hooks;
- if (buffer->buffer == NULL)
- {
- goto fail;
- }
-
- /* print the value */
- if (!print_value(item, buffer))
- {
- goto fail;
- }
- update_offset(buffer);
-
- /* check if reallocate is available */
- if (hooks->reallocate != NULL)
- {
- printed = (unsigned char*) hooks->reallocate(buffer->buffer, buffer->offset + 1);
- if (printed == NULL) {
- goto fail;
- }
- buffer->buffer = NULL;
- }
- else /* otherwise copy the JSON over to a new buffer */
- {
- printed = (unsigned char*) hooks->allocate(buffer->offset + 1);
- if (printed == NULL)
- {
- goto fail;
- }
- memcpy(printed, buffer->buffer, cjson_min(buffer->length, buffer->offset + 1));
- printed[buffer->offset] = '\0'; /* just to be sure */
-
- /* free the buffer */
- hooks->deallocate(buffer->buffer);
- }
-
- return printed;
-
-fail:
- if (buffer->buffer != NULL)
- {
- hooks->deallocate(buffer->buffer);
- }
-
- if (printed != NULL)
- {
- hooks->deallocate(printed);
- }
-
- return NULL;
-}
-
-/* Render a cJSON item/entity/structure to text. */
-CJSON_PUBLIC(char *) cJSON_Print(const cJSON *item)
-{
- return (char*)print(item, true, &global_hooks);
-}
-
-CJSON_PUBLIC(char *) cJSON_PrintUnformatted(const cJSON *item)
-{
- return (char*)print(item, false, &global_hooks);
-}
-
-CJSON_PUBLIC(char *) cJSON_PrintBuffered(const cJSON *item, int prebuffer, cJSON_bool fmt)
-{
- printbuffer p = { 0, 0, 0, 0, 0, 0, { 0, 0, 0 } };
-
- if (prebuffer < 0)
- {
- return NULL;
- }
-
- p.buffer = (unsigned char*)global_hooks.allocate((size_t)prebuffer);
- if (!p.buffer)
- {
- return NULL;
- }
-
- p.length = (size_t)prebuffer;
- p.offset = 0;
- p.noalloc = false;
- p.format = fmt;
- p.hooks = global_hooks;
-
- if (!print_value(item, &p))
- {
- global_hooks.deallocate(p.buffer);
- return NULL;
- }
-
- return (char*)p.buffer;
-}
-
-CJSON_PUBLIC(cJSON_bool) cJSON_PrintPreallocated(cJSON *item, char *buffer, const int length, const cJSON_bool format)
-{
- printbuffer p = { 0, 0, 0, 0, 0, 0, { 0, 0, 0 } };
-
- if ((length < 0) || (buffer == NULL))
- {
- return false;
- }
-
- p.buffer = (unsigned char*)buffer;
- p.length = (size_t)length;
- p.offset = 0;
- p.noalloc = true;
- p.format = format;
- p.hooks = global_hooks;
-
- return print_value(item, &p);
-}
-
-/* Parser core - when encountering text, process appropriately. */
-static cJSON_bool parse_value(cJSON * const item, parse_buffer * const input_buffer)
-{
- if ((input_buffer == NULL) || (input_buffer->content == NULL))
- {
- return false; /* no input */
- }
-
- /* parse the different types of values */
- /* null */
- if (can_read(input_buffer, 4) && (strncmp((const char*)buffer_at_offset(input_buffer), "null", 4) == 0))
- {
- item->type = cJSON_NULL;
- input_buffer->offset += 4;
- return true;
- }
- /* false */
- if (can_read(input_buffer, 5) && (strncmp((const char*)buffer_at_offset(input_buffer), "false", 5) == 0))
- {
- item->type = cJSON_False;
- input_buffer->offset += 5;
- return true;
- }
- /* true */
- if (can_read(input_buffer, 4) && (strncmp((const char*)buffer_at_offset(input_buffer), "true", 4) == 0))
- {
- item->type = cJSON_True;
- item->valueint = 1;
- input_buffer->offset += 4;
- return true;
- }
- /* string */
- if (can_access_at_index(input_buffer, 0) && (buffer_at_offset(input_buffer)[0] == '\"'))
- {
- return parse_string(item, input_buffer);
- }
- /* number */
- if (can_access_at_index(input_buffer, 0) && ((buffer_at_offset(input_buffer)[0] == '-') || ((buffer_at_offset(input_buffer)[0] >= '0') && (buffer_at_offset(input_buffer)[0] <= '9'))))
- {
- return parse_number(item, input_buffer);
- }
- /* array */
- if (can_access_at_index(input_buffer, 0) && (buffer_at_offset(input_buffer)[0] == '['))
- {
- return parse_array(item, input_buffer);
- }
- /* object */
- if (can_access_at_index(input_buffer, 0) && (buffer_at_offset(input_buffer)[0] == '{'))
- {
- return parse_object(item, input_buffer);
- }
-
- return false;
-}
-
-/* Render a value to text. */
-static cJSON_bool print_value(const cJSON * const item, printbuffer * const output_buffer)
-{
- unsigned char *output = NULL;
-
- if ((item == NULL) || (output_buffer == NULL))
- {
- return false;
- }
-
- switch ((item->type) & 0xFF)
- {
- case cJSON_NULL:
- output = ensure(output_buffer, 5);
- if (output == NULL)
- {
- return false;
- }
- strcpy((char*)output, "null");
- return true;
-
- case cJSON_False:
- output = ensure(output_buffer, 6);
- if (output == NULL)
- {
- return false;
- }
- strcpy((char*)output, "false");
- return true;
-
- case cJSON_True:
- output = ensure(output_buffer, 5);
- if (output == NULL)
- {
- return false;
- }
- strcpy((char*)output, "true");
- return true;
-
- case cJSON_Number:
- return print_number(item, output_buffer);
-
- case cJSON_Raw:
- {
- size_t raw_length = 0;
- if (item->valuestring == NULL)
- {
- return false;
- }
-
- raw_length = strlen(item->valuestring) + sizeof("");
- output = ensure(output_buffer, raw_length);
- if (output == NULL)
- {
- return false;
- }
- memcpy(output, item->valuestring, raw_length);
- return true;
- }
-
- case cJSON_String:
- return print_string(item, output_buffer);
-
- case cJSON_Array:
- return print_array(item, output_buffer);
-
- case cJSON_Object:
- return print_object(item, output_buffer);
-
- default:
- return false;
- }
-}
-
-/* Build an array from input text. */
-static cJSON_bool parse_array(cJSON * const item, parse_buffer * const input_buffer)
-{
- cJSON *head = NULL; /* head of the linked list */
- cJSON *current_item = NULL;
-
- if (input_buffer->depth >= CJSON_NESTING_LIMIT)
- {
- return false; /* to deeply nested */
- }
- input_buffer->depth++;
-
- if (buffer_at_offset(input_buffer)[0] != '[')
- {
- /* not an array */
- goto fail;
- }
-
- input_buffer->offset++;
- buffer_skip_whitespace(input_buffer);
- if (can_access_at_index(input_buffer, 0) && (buffer_at_offset(input_buffer)[0] == ']'))
- {
- /* empty array */
- goto success;
- }
-
- /* check if we skipped to the end of the buffer */
- if (cannot_access_at_index(input_buffer, 0))
- {
- input_buffer->offset--;
- goto fail;
- }
-
- /* step back to character in front of the first element */
- input_buffer->offset--;
- /* loop through the comma separated array elements */
- do
- {
- /* allocate next item */
- cJSON *new_item = cJSON_New_Item(&(input_buffer->hooks));
- if (new_item == NULL)
- {
- goto fail; /* allocation failure */
- }
-
- /* attach next item to list */
- if (head == NULL)
- {
- /* start the linked list */
- current_item = head = new_item;
- }
- else
- {
- /* add to the end and advance */
- current_item->next = new_item;
- new_item->prev = current_item;
- current_item = new_item;
- }
-
- /* parse next value */
- input_buffer->offset++;
- buffer_skip_whitespace(input_buffer);
- if (!parse_value(current_item, input_buffer))
- {
- goto fail; /* failed to parse value */
- }
- buffer_skip_whitespace(input_buffer);
- }
- while (can_access_at_index(input_buffer, 0) && (buffer_at_offset(input_buffer)[0] == ','));
-
- if (cannot_access_at_index(input_buffer, 0) || buffer_at_offset(input_buffer)[0] != ']')
- {
- goto fail; /* expected end of array */
- }
-
-success:
- input_buffer->depth--;
-
- item->type = cJSON_Array;
- item->child = head;
-
- input_buffer->offset++;
-
- return true;
-
-fail:
- if (head != NULL)
- {
- cJSON_Delete(head);
- }
-
- return false;
-}
-
-/* Render an array to text */
-static cJSON_bool print_array(const cJSON * const item, printbuffer * const output_buffer)
-{
- unsigned char *output_pointer = NULL;
- size_t length = 0;
- cJSON *current_element = item->child;
-
- if (output_buffer == NULL)
- {
- return false;
- }
-
- /* Compose the output array. */
- /* opening square bracket */
- output_pointer = ensure(output_buffer, 1);
- if (output_pointer == NULL)
- {
- return false;
- }
-
- *output_pointer = '[';
- output_buffer->offset++;
- output_buffer->depth++;
-
- while (current_element != NULL)
- {
- if (!print_value(current_element, output_buffer))
- {
- return false;
- }
- update_offset(output_buffer);
- if (current_element->next)
- {
- length = (size_t) (output_buffer->format ? 2 : 1);
- output_pointer = ensure(output_buffer, length + 1);
- if (output_pointer == NULL)
- {
- return false;
- }
- *output_pointer++ = ',';
- if(output_buffer->format)
- {
- *output_pointer++ = ' ';
- }
- *output_pointer = '\0';
- output_buffer->offset += length;
- }
- current_element = current_element->next;
- }
-
- output_pointer = ensure(output_buffer, 2);
- if (output_pointer == NULL)
- {
- return false;
- }
- *output_pointer++ = ']';
- *output_pointer = '\0';
- output_buffer->depth--;
-
- return true;
-}
-
-/* Build an object from the text. */
-static cJSON_bool parse_object(cJSON * const item, parse_buffer * const input_buffer)
-{
- cJSON *head = NULL; /* linked list head */
- cJSON *current_item = NULL;
-
- if (input_buffer->depth >= CJSON_NESTING_LIMIT)
- {
- return false; /* to deeply nested */
- }
- input_buffer->depth++;
-
- if (cannot_access_at_index(input_buffer, 0) || (buffer_at_offset(input_buffer)[0] != '{'))
- {
- goto fail; /* not an object */
- }
-
- input_buffer->offset++;
- buffer_skip_whitespace(input_buffer);
- if (can_access_at_index(input_buffer, 0) && (buffer_at_offset(input_buffer)[0] == '}'))
- {
- goto success; /* empty object */
- }
-
- /* check if we skipped to the end of the buffer */
- if (cannot_access_at_index(input_buffer, 0))
- {
- input_buffer->offset--;
- goto fail;
- }
-
- /* step back to character in front of the first element */
- input_buffer->offset--;
- /* loop through the comma separated array elements */
- do
- {
- /* allocate next item */
- cJSON *new_item = cJSON_New_Item(&(input_buffer->hooks));
- if (new_item == NULL)
- {
- goto fail; /* allocation failure */
- }
-
- /* attach next item to list */
- if (head == NULL)
- {
- /* start the linked list */
- current_item = head = new_item;
- }
- else
- {
- /* add to the end and advance */
- current_item->next = new_item;
- new_item->prev = current_item;
- current_item = new_item;
- }
-
- /* parse the name of the child */
- input_buffer->offset++;
- buffer_skip_whitespace(input_buffer);
- if (!parse_string(current_item, input_buffer))
- {
- goto fail; /* failed to parse name */
- }
- buffer_skip_whitespace(input_buffer);
-
- /* swap valuestring and string, because we parsed the name */
- current_item->string = current_item->valuestring;
- current_item->valuestring = NULL;
-
- if (cannot_access_at_index(input_buffer, 0) || (buffer_at_offset(input_buffer)[0] != ':'))
- {
- goto fail; /* invalid object */
- }
-
- /* parse the value */
- input_buffer->offset++;
- buffer_skip_whitespace(input_buffer);
- if (!parse_value(current_item, input_buffer))
- {
- goto fail; /* failed to parse value */
- }
- buffer_skip_whitespace(input_buffer);
- }
- while (can_access_at_index(input_buffer, 0) && (buffer_at_offset(input_buffer)[0] == ','));
-
- if (cannot_access_at_index(input_buffer, 0) || (buffer_at_offset(input_buffer)[0] != '}'))
- {
- goto fail; /* expected end of object */
- }
-
-success:
- input_buffer->depth--;
-
- item->type = cJSON_Object;
- item->child = head;
-
- input_buffer->offset++;
- return true;
-
-fail:
- if (head != NULL)
- {
- cJSON_Delete(head);
- }
-
- return false;
-}
-
-/* Render an object to text. */
-static cJSON_bool print_object(const cJSON * const item, printbuffer * const output_buffer)
-{
- unsigned char *output_pointer = NULL;
- size_t length = 0;
- cJSON *current_item = item->child;
-
- if (output_buffer == NULL)
- {
- return false;
- }
-
- /* Compose the output: */
- length = (size_t) (output_buffer->format ? 2 : 1); /* fmt: {\n */
- output_pointer = ensure(output_buffer, length + 1);
- if (output_pointer == NULL)
- {
- return false;
- }
-
- *output_pointer++ = '{';
- output_buffer->depth++;
- if (output_buffer->format)
- {
- *output_pointer++ = '\n';
- }
- output_buffer->offset += length;
-
- while (current_item)
- {
- if (output_buffer->format)
- {
- size_t i;
- output_pointer = ensure(output_buffer, output_buffer->depth);
- if (output_pointer == NULL)
- {
- return false;
- }
- for (i = 0; i < output_buffer->depth; i++)
- {
- *output_pointer++ = '\t';
- }
- output_buffer->offset += output_buffer->depth;
- }
-
- /* print key */
- if (!print_string_ptr((unsigned char*)current_item->string, output_buffer))
- {
- return false;
- }
- update_offset(output_buffer);
-
- length = (size_t) (output_buffer->format ? 2 : 1);
- output_pointer = ensure(output_buffer, length);
- if (output_pointer == NULL)
- {
- return false;
- }
- *output_pointer++ = ':';
- if (output_buffer->format)
- {
- *output_pointer++ = '\t';
- }
- output_buffer->offset += length;
-
- /* print value */
- if (!print_value(current_item, output_buffer))
- {
- return false;
- }
- update_offset(output_buffer);
-
- /* print comma if not last */
- length = ((size_t)(output_buffer->format ? 1 : 0) + (size_t)(current_item->next ? 1 : 0));
- output_pointer = ensure(output_buffer, length + 1);
- if (output_pointer == NULL)
- {
- return false;
- }
- if (current_item->next)
- {
- *output_pointer++ = ',';
- }
-
- if (output_buffer->format)
- {
- *output_pointer++ = '\n';
- }
- *output_pointer = '\0';
- output_buffer->offset += length;
-
- current_item = current_item->next;
- }
-
- output_pointer = ensure(output_buffer, output_buffer->format ? (output_buffer->depth + 1) : 2);
- if (output_pointer == NULL)
- {
- return false;
- }
- if (output_buffer->format)
- {
- size_t i;
- for (i = 0; i < (output_buffer->depth - 1); i++)
- {
- *output_pointer++ = '\t';
- }
- }
- *output_pointer++ = '}';
- *output_pointer = '\0';
- output_buffer->depth--;
-
- return true;
-}
-
-/* Get Array size/item / object item. */
-CJSON_PUBLIC(int) cJSON_GetArraySize(const cJSON *array)
-{
- cJSON *child = NULL;
- size_t size = 0;
-
- if (array == NULL)
- {
- return 0;
- }
-
- child = array->child;
-
- while(child != NULL)
- {
- size++;
- child = child->next;
- }
-
- /* FIXME: Can overflow here. Cannot be fixed without breaking the API */
-
- return (int)size;
-}
-
-static cJSON* get_array_item(const cJSON *array, size_t index)
-{
- cJSON *current_child = NULL;
-
- if (array == NULL)
- {
- return NULL;
- }
-
- current_child = array->child;
- while ((current_child != NULL) && (index > 0))
- {
- index--;
- current_child = current_child->next;
- }
-
- return current_child;
-}
-
-CJSON_PUBLIC(cJSON *) cJSON_GetArrayItem(const cJSON *array, int index)
-{
- if (index < 0)
- {
- return NULL;
- }
-
- return get_array_item(array, (size_t)index);
-}
-
-static cJSON *get_object_item(const cJSON * const object, const char * const name, const cJSON_bool case_sensitive)
-{
- cJSON *current_element = NULL;
-
- if ((object == NULL) || (name == NULL))
- {
- return NULL;
- }
-
- current_element = object->child;
- if (case_sensitive)
- {
- while ((current_element != NULL) && (current_element->string != NULL) && (strcmp(name, current_element->string) != 0))
- {
- current_element = current_element->next;
- }
- }
- else
- {
- while ((current_element != NULL) && (case_insensitive_strcmp((const unsigned char*)name, (const unsigned char*)(current_element->string)) != 0))
- {
- current_element = current_element->next;
- }
- }
-
- if ((current_element == NULL) || (current_element->string == NULL)) {
- return NULL;
- }
-
- return current_element;
-}
-
-CJSON_PUBLIC(cJSON *) cJSON_GetObjectItem(const cJSON * const object, const char * const string)
-{
- return get_object_item(object, string, false);
-}
-
-CJSON_PUBLIC(cJSON *) cJSON_GetObjectItemCaseSensitive(const cJSON * const object, const char * const string)
-{
- return get_object_item(object, string, true);
-}
-
-CJSON_PUBLIC(cJSON_bool) cJSON_HasObjectItem(const cJSON *object, const char *string)
-{
- return cJSON_GetObjectItem(object, string) ? 1 : 0;
-}
-
-/* Utility for array list handling. */
-static void suffix_object(cJSON *prev, cJSON *item)
-{
- prev->next = item;
- item->prev = prev;
-}
-
-/* Utility for handling references. */
-static cJSON *create_reference(const cJSON *item, const internal_hooks * const hooks)
-{
- cJSON *reference = NULL;
- if (item == NULL)
- {
- return NULL;
- }
-
- reference = cJSON_New_Item(hooks);
- if (reference == NULL)
- {
- return NULL;
- }
-
- memcpy(reference, item, sizeof(cJSON));
- reference->string = NULL;
- reference->type |= cJSON_IsReference;
- reference->next = reference->prev = NULL;
- return reference;
-}
-
-static cJSON_bool add_item_to_array(cJSON *array, cJSON *item)
-{
- cJSON *child = NULL;
-
- if ((item == NULL) || (array == NULL))
- {
- return false;
- }
-
- child = array->child;
-
- if (child == NULL)
- {
- /* list is empty, start new one */
- array->child = item;
- }
- else
- {
- /* append to the end */
- while (child->next)
- {
- child = child->next;
- }
- suffix_object(child, item);
- }
-
- return true;
-}
-
-/* Add item to array/object. */
-CJSON_PUBLIC(void) cJSON_AddItemToArray(cJSON *array, cJSON *item)
-{
- add_item_to_array(array, item);
-}
-
-#if defined(__clang__) || (defined(__GNUC__) && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 5))))
- #pragma GCC diagnostic push
-#endif
-#ifdef __GNUC__
-#pragma GCC diagnostic ignored "-Wcast-qual"
-#endif
-/* helper function to cast away const */
-static void* cast_away_const(const void* string)
-{
- return (void*)string;
-}
-#if defined(__clang__) || (defined(__GNUC__) && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 5))))
- #pragma GCC diagnostic pop
-#endif
-
-
-static cJSON_bool add_item_to_object(cJSON * const object, const char * const string, cJSON * const item, const internal_hooks * const hooks, const cJSON_bool constant_key)
-{
- char *new_key = NULL;
- int new_type = cJSON_Invalid;
-
- if ((object == NULL) || (string == NULL) || (item == NULL))
- {
- return false;
- }
-
- if (constant_key)
- {
- new_key = (char*)cast_away_const(string);
- new_type = item->type | cJSON_StringIsConst;
- }
- else
- {
- new_key = (char*)cJSON_strdup((const unsigned char*)string, hooks);
- if (new_key == NULL)
- {
- return false;
- }
-
- new_type = item->type & ~cJSON_StringIsConst;
- }
-
- if (!(item->type & cJSON_StringIsConst) && (item->string != NULL))
- {
- hooks->deallocate(item->string);
- }
-
- item->string = new_key;
- item->type = new_type;
-
- return add_item_to_array(object, item);
-}
-
-CJSON_PUBLIC(void) cJSON_AddItemToObject(cJSON *object, const char *string, cJSON *item)
-{
- add_item_to_object(object, string, item, &global_hooks, false);
-}
-
-/* Add an item to an object with constant string as key */
-CJSON_PUBLIC(void) cJSON_AddItemToObjectCS(cJSON *object, const char *string, cJSON *item)
-{
- add_item_to_object(object, string, item, &global_hooks, true);
-}
-
-CJSON_PUBLIC(void) cJSON_AddItemReferenceToArray(cJSON *array, cJSON *item)
-{
- if (array == NULL)
- {
- return;
- }
-
- add_item_to_array(array, create_reference(item, &global_hooks));
-}
-
-CJSON_PUBLIC(void) cJSON_AddItemReferenceToObject(cJSON *object, const char *string, cJSON *item)
-{
- if ((object == NULL) || (string == NULL))
- {
- return;
- }
-
- add_item_to_object(object, string, create_reference(item, &global_hooks), &global_hooks, false);
-}
-
-CJSON_PUBLIC(cJSON*) cJSON_AddNullToObject(cJSON * const object, const char * const name)
-{
- cJSON *null = cJSON_CreateNull();
- if (add_item_to_object(object, name, null, &global_hooks, false))
- {
- return null;
- }
-
- cJSON_Delete(null);
- return NULL;
-}
-
-CJSON_PUBLIC(cJSON*) cJSON_AddTrueToObject(cJSON * const object, const char * const name)
-{
- cJSON *true_item = cJSON_CreateTrue();
- if (add_item_to_object(object, name, true_item, &global_hooks, false))
- {
- return true_item;
- }
-
- cJSON_Delete(true_item);
- return NULL;
-}
-
-CJSON_PUBLIC(cJSON*) cJSON_AddFalseToObject(cJSON * const object, const char * const name)
-{
- cJSON *false_item = cJSON_CreateFalse();
- if (add_item_to_object(object, name, false_item, &global_hooks, false))
- {
- return false_item;
- }
-
- cJSON_Delete(false_item);
- return NULL;
-}
-
-CJSON_PUBLIC(cJSON*) cJSON_AddBoolToObject(cJSON * const object, const char * const name, const cJSON_bool boolean)
-{
- cJSON *bool_item = cJSON_CreateBool(boolean);
- if (add_item_to_object(object, name, bool_item, &global_hooks, false))
- {
- return bool_item;
- }
-
- cJSON_Delete(bool_item);
- return NULL;
-}
-
-CJSON_PUBLIC(cJSON*) cJSON_AddNumberToObject(cJSON * const object, const char * const name, const double number)
-{
- cJSON *number_item = cJSON_CreateNumber(number);
- if (add_item_to_object(object, name, number_item, &global_hooks, false))
- {
- return number_item;
- }
-
- cJSON_Delete(number_item);
- return NULL;
-}
-
-CJSON_PUBLIC(cJSON*) cJSON_AddStringToObject(cJSON * const object, const char * const name, const char * const string)
-{
- cJSON *string_item = cJSON_CreateString(string);
- if (add_item_to_object(object, name, string_item, &global_hooks, false))
- {
- return string_item;
- }
-
- cJSON_Delete(string_item);
- return NULL;
-}
-
-CJSON_PUBLIC(cJSON*) cJSON_AddRawToObject(cJSON * const object, const char * const name, const char * const raw)
-{
- cJSON *raw_item = cJSON_CreateRaw(raw);
- if (add_item_to_object(object, name, raw_item, &global_hooks, false))
- {
- return raw_item;
- }
-
- cJSON_Delete(raw_item);
- return NULL;
-}
-
-CJSON_PUBLIC(cJSON*) cJSON_AddObjectToObject(cJSON * const object, const char * const name)
-{
- cJSON *object_item = cJSON_CreateObject();
- if (add_item_to_object(object, name, object_item, &global_hooks, false))
- {
- return object_item;
- }
-
- cJSON_Delete(object_item);
- return NULL;
-}
-
-CJSON_PUBLIC(cJSON*) cJSON_AddArrayToObject(cJSON * const object, const char * const name)
-{
- cJSON *array = cJSON_CreateArray();
- if (add_item_to_object(object, name, array, &global_hooks, false))
- {
- return array;
- }
-
- cJSON_Delete(array);
- return NULL;
-}
-
-CJSON_PUBLIC(cJSON *) cJSON_DetachItemViaPointer(cJSON *parent, cJSON * const item)
-{
- if ((parent == NULL) || (item == NULL))
- {
- return NULL;
- }
-
- if (item->prev != NULL)
- {
- /* not the first element */
- item->prev->next = item->next;
- }
- if (item->next != NULL)
- {
- /* not the last element */
- item->next->prev = item->prev;
- }
-
- if (item == parent->child)
- {
- /* first element */
- parent->child = item->next;
- }
- /* make sure the detached item doesn't point anywhere anymore */
- item->prev = NULL;
- item->next = NULL;
-
- return item;
-}
-
-CJSON_PUBLIC(cJSON *) cJSON_DetachItemFromArray(cJSON *array, int which)
-{
- if (which < 0)
- {
- return NULL;
- }
-
- return cJSON_DetachItemViaPointer(array, get_array_item(array, (size_t)which));
-}
-
-CJSON_PUBLIC(void) cJSON_DeleteItemFromArray(cJSON *array, int which)
-{
- cJSON_Delete(cJSON_DetachItemFromArray(array, which));
-}
-
-CJSON_PUBLIC(cJSON *) cJSON_DetachItemFromObject(cJSON *object, const char *string)
-{
- cJSON *to_detach = cJSON_GetObjectItem(object, string);
-
- return cJSON_DetachItemViaPointer(object, to_detach);
-}
-
-CJSON_PUBLIC(cJSON *) cJSON_DetachItemFromObjectCaseSensitive(cJSON *object, const char *string)
-{
- cJSON *to_detach = cJSON_GetObjectItemCaseSensitive(object, string);
-
- return cJSON_DetachItemViaPointer(object, to_detach);
-}
-
-CJSON_PUBLIC(void) cJSON_DeleteItemFromObject(cJSON *object, const char *string)
-{
- cJSON_Delete(cJSON_DetachItemFromObject(object, string));
-}
-
-CJSON_PUBLIC(void) cJSON_DeleteItemFromObjectCaseSensitive(cJSON *object, const char *string)
-{
- cJSON_Delete(cJSON_DetachItemFromObjectCaseSensitive(object, string));
-}
-
-/* Replace array/object items with new ones. */
-CJSON_PUBLIC(void) cJSON_InsertItemInArray(cJSON *array, int which, cJSON *newitem)
-{
- cJSON *after_inserted = NULL;
-
- if (which < 0)
- {
- return;
- }
-
- after_inserted = get_array_item(array, (size_t)which);
- if (after_inserted == NULL)
- {
- add_item_to_array(array, newitem);
- return;
- }
-
- newitem->next = after_inserted;
- newitem->prev = after_inserted->prev;
- after_inserted->prev = newitem;
- if (after_inserted == array->child)
- {
- array->child = newitem;
- }
- else
- {
- newitem->prev->next = newitem;
- }
-}
-
-CJSON_PUBLIC(cJSON_bool) cJSON_ReplaceItemViaPointer(cJSON * const parent, cJSON * const item, cJSON * replacement)
-{
- if ((parent == NULL) || (replacement == NULL) || (item == NULL))
- {
- return false;
- }
-
- if (replacement == item)
- {
- return true;
- }
-
- replacement->next = item->next;
- replacement->prev = item->prev;
-
- if (replacement->next != NULL)
- {
- replacement->next->prev = replacement;
- }
- if (replacement->prev != NULL)
- {
- replacement->prev->next = replacement;
- }
- if (parent->child == item)
- {
- parent->child = replacement;
- }
-
- item->next = NULL;
- item->prev = NULL;
- cJSON_Delete(item);
-
- return true;
-}
-
-CJSON_PUBLIC(void) cJSON_ReplaceItemInArray(cJSON *array, int which, cJSON *newitem)
-{
- if (which < 0)
- {
- return;
- }
-
- cJSON_ReplaceItemViaPointer(array, get_array_item(array, (size_t)which), newitem);
-}
-
-static cJSON_bool replace_item_in_object(cJSON *object, const char *string, cJSON *replacement, cJSON_bool case_sensitive)
-{
- if ((replacement == NULL) || (string == NULL))
- {
- return false;
- }
-
- /* replace the name in the replacement */
- if (!(replacement->type & cJSON_StringIsConst) && (replacement->string != NULL))
- {
- cJSON_free(replacement->string);
- }
- replacement->string = (char*)cJSON_strdup((const unsigned char*)string, &global_hooks);
- replacement->type &= ~cJSON_StringIsConst;
-
- cJSON_ReplaceItemViaPointer(object, get_object_item(object, string, case_sensitive), replacement);
-
- return true;
-}
-
-CJSON_PUBLIC(void) cJSON_ReplaceItemInObject(cJSON *object, const char *string, cJSON *newitem)
-{
- replace_item_in_object(object, string, newitem, false);
-}
-
-CJSON_PUBLIC(void) cJSON_ReplaceItemInObjectCaseSensitive(cJSON *object, const char *string, cJSON *newitem)
-{
- replace_item_in_object(object, string, newitem, true);
-}
-
-/* Create basic types: */
-CJSON_PUBLIC(cJSON *) cJSON_CreateNull(void)
-{
- cJSON *item = cJSON_New_Item(&global_hooks);
- if(item)
- {
- item->type = cJSON_NULL;
- }
-
- return item;
-}
-
-CJSON_PUBLIC(cJSON *) cJSON_CreateTrue(void)
-{
- cJSON *item = cJSON_New_Item(&global_hooks);
- if(item)
- {
- item->type = cJSON_True;
- }
-
- return item;
-}
-
-CJSON_PUBLIC(cJSON *) cJSON_CreateFalse(void)
-{
- cJSON *item = cJSON_New_Item(&global_hooks);
- if(item)
- {
- item->type = cJSON_False;
- }
-
- return item;
-}
-
-CJSON_PUBLIC(cJSON *) cJSON_CreateBool(cJSON_bool boolean)
-{
- cJSON *item = cJSON_New_Item(&global_hooks);
- if(item)
- {
- item->type = boolean ? cJSON_True : cJSON_False;
- }
-
- return item;
-}
-
-CJSON_PUBLIC(cJSON *) cJSON_CreateNumber(double num)
-{
- cJSON *item = cJSON_New_Item(&global_hooks);
- if(item)
- {
- item->type = cJSON_Number;
- item->valuedouble = num;
-
- /* use saturation in case of overflow */
- if (num >= INT_MAX)
- {
- item->valueint = INT_MAX;
- }
- else if (num <= (double)INT_MIN)
- {
- item->valueint = INT_MIN;
- }
- else
- {
- item->valueint = (int)num;
- }
- }
-
- return item;
-}
-
-CJSON_PUBLIC(cJSON *) cJSON_CreateString(const char *string)
-{
- cJSON *item = cJSON_New_Item(&global_hooks);
- if(item)
- {
- item->type = cJSON_String;
- item->valuestring = (char*)cJSON_strdup((const unsigned char*)string, &global_hooks);
- if(!item->valuestring)
- {
- cJSON_Delete(item);
- return NULL;
- }
- }
-
- return item;
-}
-
-CJSON_PUBLIC(cJSON *) cJSON_CreateStringReference(const char *string)
-{
- cJSON *item = cJSON_New_Item(&global_hooks);
- if (item != NULL)
- {
- item->type = cJSON_String | cJSON_IsReference;
- item->valuestring = (char*)cast_away_const(string);
- }
-
- return item;
-}
-
-CJSON_PUBLIC(cJSON *) cJSON_CreateObjectReference(const cJSON *child)
-{
- cJSON *item = cJSON_New_Item(&global_hooks);
- if (item != NULL) {
- item->type = cJSON_Object | cJSON_IsReference;
- item->child = (cJSON*)cast_away_const(child);
- }
-
- return item;
-}
-
-CJSON_PUBLIC(cJSON *) cJSON_CreateArrayReference(const cJSON *child) {
- cJSON *item = cJSON_New_Item(&global_hooks);
- if (item != NULL) {
- item->type = cJSON_Array | cJSON_IsReference;
- item->child = (cJSON*)cast_away_const(child);
- }
-
- return item;
-}
-
-CJSON_PUBLIC(cJSON *) cJSON_CreateRaw(const char *raw)
-{
- cJSON *item = cJSON_New_Item(&global_hooks);
- if(item)
- {
- item->type = cJSON_Raw;
- item->valuestring = (char*)cJSON_strdup((const unsigned char*)raw, &global_hooks);
- if(!item->valuestring)
- {
- cJSON_Delete(item);
- return NULL;
- }
- }
-
- return item;
-}
-
-CJSON_PUBLIC(cJSON *) cJSON_CreateArray(void)
-{
- cJSON *item = cJSON_New_Item(&global_hooks);
- if(item)
- {
- item->type=cJSON_Array;
- }
-
- return item;
-}
-
-CJSON_PUBLIC(cJSON *) cJSON_CreateObject(void)
-{
- cJSON *item = cJSON_New_Item(&global_hooks);
- if (item)
- {
- item->type = cJSON_Object;
- }
-
- return item;
-}
-
-/* Create Arrays: */
-CJSON_PUBLIC(cJSON *) cJSON_CreateIntArray(const int *numbers, int count)
-{
- size_t i = 0;
- cJSON *n = NULL;
- cJSON *p = NULL;
- cJSON *a = NULL;
-
- if ((count < 0) || (numbers == NULL))
- {
- return NULL;
- }
-
- a = cJSON_CreateArray();
- for(i = 0; a && (i < (size_t)count); i++)
- {
- n = cJSON_CreateNumber(numbers[i]);
- if (!n)
- {
- cJSON_Delete(a);
- return NULL;
- }
- if(!i)
- {
- a->child = n;
- }
- else
- {
- suffix_object(p, n);
- }
- p = n;
- }
-
- return a;
-}
-
-CJSON_PUBLIC(cJSON *) cJSON_CreateFloatArray(const float *numbers, int count)
-{
- size_t i = 0;
- cJSON *n = NULL;
- cJSON *p = NULL;
- cJSON *a = NULL;
-
- if ((count < 0) || (numbers == NULL))
- {
- return NULL;
- }
-
- a = cJSON_CreateArray();
-
- for(i = 0; a && (i < (size_t)count); i++)
- {
- n = cJSON_CreateNumber((double)numbers[i]);
- if(!n)
- {
- cJSON_Delete(a);
- return NULL;
- }
- if(!i)
- {
- a->child = n;
- }
- else
- {
- suffix_object(p, n);
- }
- p = n;
- }
-
- return a;
-}
-
-CJSON_PUBLIC(cJSON *) cJSON_CreateDoubleArray(const double *numbers, int count)
-{
- size_t i = 0;
- cJSON *n = NULL;
- cJSON *p = NULL;
- cJSON *a = NULL;
-
- if ((count < 0) || (numbers == NULL))
- {
- return NULL;
- }
-
- a = cJSON_CreateArray();
-
- for(i = 0;a && (i < (size_t)count); i++)
- {
- n = cJSON_CreateNumber(numbers[i]);
- if(!n)
- {
- cJSON_Delete(a);
- return NULL;
- }
- if(!i)
- {
- a->child = n;
- }
- else
- {
- suffix_object(p, n);
- }
- p = n;
- }
-
- return a;
-}
-
-CJSON_PUBLIC(cJSON *) cJSON_CreateStringArray(const char *const *strings, int count)
-{
- size_t i = 0;
- cJSON *n = NULL;
- cJSON *p = NULL;
- cJSON *a = NULL;
-
- if ((count < 0) || (strings == NULL))
- {
- return NULL;
- }
-
- a = cJSON_CreateArray();
-
- for (i = 0; a && (i < (size_t)count); i++)
- {
- n = cJSON_CreateString(strings[i]);
- if(!n)
- {
- cJSON_Delete(a);
- return NULL;
- }
- if(!i)
- {
- a->child = n;
- }
- else
- {
- suffix_object(p,n);
- }
- p = n;
- }
-
- return a;
-}
-
-/* Duplication */
-CJSON_PUBLIC(cJSON *) cJSON_Duplicate(const cJSON *item, cJSON_bool recurse)
-{
- cJSON *newitem = NULL;
- cJSON *child = NULL;
- cJSON *next = NULL;
- cJSON *newchild = NULL;
-
- /* Bail on bad ptr */
- if (!item)
- {
- goto fail;
- }
- /* Create new item */
- newitem = cJSON_New_Item(&global_hooks);
- if (!newitem)
- {
- goto fail;
- }
- /* Copy over all vars */
- newitem->type = item->type & (~cJSON_IsReference);
- newitem->valueint = item->valueint;
- newitem->valuedouble = item->valuedouble;
- if (item->valuestring)
- {
- newitem->valuestring = (char*)cJSON_strdup((unsigned char*)item->valuestring, &global_hooks);
- if (!newitem->valuestring)
- {
- goto fail;
- }
- }
- if (item->string)
- {
- newitem->string = (item->type&cJSON_StringIsConst) ? item->string : (char*)cJSON_strdup((unsigned char*)item->string, &global_hooks);
- if (!newitem->string)
- {
- goto fail;
- }
- }
- /* If non-recursive, then we're done! */
- if (!recurse)
- {
- return newitem;
- }
- /* Walk the ->next chain for the child. */
- child = item->child;
- while (child != NULL)
- {
- newchild = cJSON_Duplicate(child, true); /* Duplicate (with recurse) each item in the ->next chain */
- if (!newchild)
- {
- goto fail;
- }
- if (next != NULL)
- {
- /* If newitem->child already set, then crosswire ->prev and ->next and move on */
- next->next = newchild;
- newchild->prev = next;
- next = newchild;
- }
- else
- {
- /* Set newitem->child and move to it */
- newitem->child = newchild;
- next = newchild;
- }
- child = child->next;
- }
-
- return newitem;
-
-fail:
- if (newitem != NULL)
- {
- cJSON_Delete(newitem);
- }
-
- return NULL;
-}
-
-static void skip_oneline_comment(char **input)
-{
- *input += static_strlen("//");
-
- for (; (*input)[0] != '\0'; ++(*input))
- {
- if ((*input)[0] == '\n') {
- *input += static_strlen("\n");
- return;
- }
- }
-}
-
-static void skip_multiline_comment(char **input)
-{
- *input += static_strlen("/*");
-
- for (; (*input)[0] != '\0'; ++(*input))
- {
- if (((*input)[0] == '*') && ((*input)[1] == '/'))
- {
- *input += static_strlen("*/");
- return;
- }
- }
-}
-
-static void minify_string(char **input, char **output) {
- (*output)[0] = (*input)[0];
- *input += static_strlen("\"");
- *output += static_strlen("\"");
-
-
- for (; (*input)[0] != '\0'; (void)++(*input), ++(*output)) {
- (*output)[0] = (*input)[0];
-
- if ((*input)[0] == '\"') {
- (*output)[0] = '\"';
- *input += static_strlen("\"");
- *output += static_strlen("\"");
- return;
- } else if (((*input)[0] == '\\') && ((*input)[1] == '\"')) {
- (*output)[1] = (*input)[1];
- *input += static_strlen("\"");
- *output += static_strlen("\"");
- }
- }
-}
-
-CJSON_PUBLIC(void) cJSON_Minify(char *json)
-{
- char *into = json;
-
- if (json == NULL)
- {
- return;
- }
-
- while (json[0] != '\0')
- {
- switch (json[0])
- {
- case ' ':
- case '\t':
- case '\r':
- case '\n':
- json++;
- break;
-
- case '/':
- if (json[1] == '/')
- {
- skip_oneline_comment(&json);
- }
- else if (json[1] == '*')
- {
- skip_multiline_comment(&json);
- } else {
- json++;
- }
- break;
-
- case '\"':
- minify_string(&json, (char**)&into);
- break;
-
- default:
- into[0] = json[0];
- json++;
- into++;
- }
- }
-
- /* and null-terminate. */
- *into = '\0';
-}
-
-CJSON_PUBLIC(cJSON_bool) cJSON_IsInvalid(const cJSON * const item)
-{
- if (item == NULL)
- {
- return false;
- }
-
- return (item->type & 0xFF) == cJSON_Invalid;
-}
-
-CJSON_PUBLIC(cJSON_bool) cJSON_IsFalse(const cJSON * const item)
-{
- if (item == NULL)
- {
- return false;
- }
-
- return (item->type & 0xFF) == cJSON_False;
-}
-
-CJSON_PUBLIC(cJSON_bool) cJSON_IsTrue(const cJSON * const item)
-{
- if (item == NULL)
- {
- return false;
- }
-
- return (item->type & 0xff) == cJSON_True;
-}
-
-
-CJSON_PUBLIC(cJSON_bool) cJSON_IsBool(const cJSON * const item)
-{
- if (item == NULL)
- {
- return false;
- }
-
- return (item->type & (cJSON_True | cJSON_False)) != 0;
-}
-CJSON_PUBLIC(cJSON_bool) cJSON_IsNull(const cJSON * const item)
-{
- if (item == NULL)
- {
- return false;
- }
-
- return (item->type & 0xFF) == cJSON_NULL;
-}
-
-CJSON_PUBLIC(cJSON_bool) cJSON_IsNumber(const cJSON * const item)
-{
- if (item == NULL)
- {
- return false;
- }
-
- return (item->type & 0xFF) == cJSON_Number;
-}
-
-CJSON_PUBLIC(cJSON_bool) cJSON_IsString(const cJSON * const item)
-{
- if (item == NULL)
- {
- return false;
- }
-
- return (item->type & 0xFF) == cJSON_String;
-}
-
-CJSON_PUBLIC(cJSON_bool) cJSON_IsArray(const cJSON * const item)
-{
- if (item == NULL)
- {
- return false;
- }
-
- return (item->type & 0xFF) == cJSON_Array;
-}
-
-CJSON_PUBLIC(cJSON_bool) cJSON_IsObject(const cJSON * const item)
-{
- if (item == NULL)
- {
- return false;
- }
-
- return (item->type & 0xFF) == cJSON_Object;
-}
-
-CJSON_PUBLIC(cJSON_bool) cJSON_IsRaw(const cJSON * const item)
-{
- if (item == NULL)
- {
- return false;
- }
-
- return (item->type & 0xFF) == cJSON_Raw;
-}
-
-CJSON_PUBLIC(cJSON_bool) cJSON_Compare(const cJSON * const a, const cJSON * const b, const cJSON_bool case_sensitive)
-{
- if ((a == NULL) || (b == NULL) || ((a->type & 0xFF) != (b->type & 0xFF)) || cJSON_IsInvalid(a))
- {
- return false;
- }
-
- /* check if type is valid */
- switch (a->type & 0xFF)
- {
- case cJSON_False:
- case cJSON_True:
- case cJSON_NULL:
- case cJSON_Number:
- case cJSON_String:
- case cJSON_Raw:
- case cJSON_Array:
- case cJSON_Object:
- break;
-
- default:
- return false;
- }
-
- /* identical objects are equal */
- if (a == b)
- {
- return true;
- }
-
- switch (a->type & 0xFF)
- {
- /* in these cases and equal type is enough */
- case cJSON_False:
- case cJSON_True:
- case cJSON_NULL:
- return true;
-
- case cJSON_Number:
- if (compare_double(a->valuedouble, b->valuedouble))
- {
- return true;
- }
- return false;
-
- case cJSON_String:
- case cJSON_Raw:
- if ((a->valuestring == NULL) || (b->valuestring == NULL))
- {
- return false;
- }
- if (strcmp(a->valuestring, b->valuestring) == 0)
- {
- return true;
- }
-
- return false;
-
- case cJSON_Array:
- {
- cJSON *a_element = a->child;
- cJSON *b_element = b->child;
-
- for (; (a_element != NULL) && (b_element != NULL);)
- {
- if (!cJSON_Compare(a_element, b_element, case_sensitive))
- {
- return false;
- }
-
- a_element = a_element->next;
- b_element = b_element->next;
- }
-
- /* one of the arrays is longer than the other */
- if (a_element != b_element) {
- return false;
- }
-
- return true;
- }
-
- case cJSON_Object:
- {
- cJSON *a_element = NULL;
- cJSON *b_element = NULL;
- cJSON_ArrayForEach(a_element, a)
- {
- /* TODO This has O(n^2) runtime, which is horrible! */
- b_element = get_object_item(b, a_element->string, case_sensitive);
- if (b_element == NULL)
- {
- return false;
- }
-
- if (!cJSON_Compare(a_element, b_element, case_sensitive))
- {
- return false;
- }
- }
-
- /* doing this twice, once on a and b to prevent true comparison if a subset of b
- * TODO: Do this the proper way, this is just a fix for now */
- cJSON_ArrayForEach(b_element, b)
- {
- a_element = get_object_item(a, b_element->string, case_sensitive);
- if (a_element == NULL)
- {
- return false;
- }
-
- if (!cJSON_Compare(b_element, a_element, case_sensitive))
- {
- return false;
- }
- }
-
- return true;
- }
-
- default:
- return false;
- }
-}
-
-CJSON_PUBLIC(void *) cJSON_malloc(size_t size)
-{
- return global_hooks.allocate(size);
-}
-
-CJSON_PUBLIC(void) cJSON_free(void *object)
-{
- global_hooks.deallocate(object);
-}
+++ /dev/null
-#include <stdio.h>
-#include <stdlib.h>
-#include <unistd.h>
-#include <fcntl.h>
-#include <string.h>
-#include <sys/socket.h>
-#include <netinet/in.h>
-#include <pthread.h>
-#include <net/if.h>
-#include <sys/ioctl.h>
-#include <arpa/inet.h>
-
-#include "cJSON.h"
-#include "udp.h"
-#include "mg_version.h"
-
-extern int32_t tuya_productid_read( char * ver, int32_t max_sz );
-extern int32_t tuya_bindcode_read( char * code, int32_t max_sz );
-extern int32_t netconfig_success_notify_cb( void );
-
-//套接字FD
-static int sockfd = 0;
-static int ack_sockfd = 0;
-//select选择套接字
-static int nfds = 0;
-//标志位
-static int FLAG = 0;
-//接收客户端报文
-static char rec_buffer[BUFFER_SIZE];
-static char rec_ack_buffer[BUFFER_SIZE];
-//存放上报msgtype
-static cJSON* msgType;
-//存放上报PID
-static cJSON* productId;
-static char rec_pid[30];
-//存放上报的状态
-static cJSON* statusResult;
-//存放读取的板级PID
-static cJSON* on_board_PID;
-static char board_pid[30];
-//存放MAC地址
-static char local_mac[18];
-//存放下发的JSON报文
-static char* res_json = NULL;
-static char* res_ack_json = NULL;
-//定义线程
-static pthread_t udp_thread;
-
-//函数声明
-static int read_the_system_PID();
-
-/*
- * 获取本地mac地址
- * 参数:无
- * 返回值:成功 0 失败-1
- */
-static int get_local_mac()
-{
- int sock;
- struct ifreq ifr;
-
- bzero(&ifr, sizeof(struct ifreq));
- if( (sock = socket(AF_INET, SOCK_STREAM, 0)) < 0)
- {
- perror("socket error !");
- return -1;
- }
-
- strncpy(ifr.ifr_name, ETH_NAME, sizeof(ifr.ifr_name) - 1);
-
- if(ioctl(sock, SIOCGIFHWADDR, &ifr) < 0)
- {
- perror("ioctl error !");
- close(sock);
- return -1;
- }
-
- snprintf(local_mac, MAC_SIZE, "%02x:%02x:%02x:%02x:%02x:%02x",
- (unsigned char)ifr.ifr_hwaddr.sa_data[0],
- (unsigned char)ifr.ifr_hwaddr.sa_data[1],
- (unsigned char)ifr.ifr_hwaddr.sa_data[2],
- (unsigned char)ifr.ifr_hwaddr.sa_data[3],
- (unsigned char)ifr.ifr_hwaddr.sa_data[4],
- (unsigned char)ifr.ifr_hwaddr.sa_data[5]);
- close(sock);
- return 0;
-}
-
-/*
- * 获取本地IP地址
- * 参数:无
- * 返回值:成功 IP地址 失败 NULL
- */
-static char* get_local_ip()
-{
- int sock;
- struct sockaddr_in sin;
- struct ifreq ifr;
- sock = socket(AF_INET, SOCK_DGRAM, 0);
- if (sock == -1) {
- perror("socket");
- return NULL;
- }
- strncpy(ifr.ifr_name, ETH_NAME, IFNAMSIZ);
- ifr.ifr_name[IFNAMSIZ - 1] = 0;
- if (ioctl(sock, SIOCGIFADDR, &ifr) < 0) {
- //perror("ioctl");
- return NULL;
- }
- close(sock);
- memcpy(&sin, &ifr.ifr_addr, sizeof(sin));
- return inet_ntoa(sin.sin_addr);
-}
-
-/*
- * 构建JSON报文
- * 参数:无
- * 返回值:成功 0 失败-1
- */
-static int build_a_response_message( void )
-{
- char qrcode[ 256];
- cJSON* root = cJSON_CreateObject();
-
- if( root ){
- get_local_mac();
- //read_the_system_PID();
-
- if( tuya_productid_read( board_pid, sizeof( board_pid ) ) ){
- strcpy( board_pid, "error" );
- }
-
- if( tuya_bindcode_read( qrcode, sizeof( qrcode ) ) ){
- strcpy( qrcode, "null" );
- }
-
- cJSON_AddStringToObject(root, "msgType", "SEARCH_ACK");
- cJSON_AddNumberToObject(root, "ret", 1);
-
- cJSON* device = cJSON_CreateObject();
- cJSON_AddStringToObject(device, "mac", local_mac);
- cJSON_AddStringToObject(device, "productId", board_pid);
- cJSON_AddStringToObject(device, "version", SW_VERSION);
- cJSON_AddStringToObject(device, "ip", get_local_ip());
- cJSON_AddNumberToObject(device, "status", 0);
- cJSON_AddStringToObject(device, "qrCode", qrcode );
-
- cJSON_AddItemToObject(root, "device", device);
-
- // 将 cJSON 对象转换为 JSON 字符串
- res_json = cJSON_Print(root);
-
- cJSON_Delete(root);
- }
- if(res_json == NULL)
- return -1;
- return 0;
-}
-
-/*
- * 截取客户端报文,msgtype和productID
- * 参数:客户端上报的数据
- * 返回值:无
- */
-static int string_interception(char* buffer)
-{
- cJSON *root = cJSON_Parse(buffer);
- msgType = cJSON_GetObjectItem(root, "msgType");
- if (msgType == NULL)
- printf("msgType not found\n");
- productId = cJSON_GetObjectItem(root, "productId");
- if (productId == NULL){
- FLAG = 1;
- cJSON_Delete(root);
- return 0;
- }
- else
- {
- strcpy(rec_pid,productId->valuestring);
- cJSON_Delete(root);
- return 1;
- }
-}
-
-/*
- *截取ACK内容
- */
-static void get_statusResult(char* buffer)
-{
- cJSON *root = cJSON_Parse(buffer);
- statusResult = cJSON_GetObjectItem(root, "statusResult");
-
- if (statusResult == NULL)
- printf("statusResult not found\n");
- else if (statusResult->valueint == 1)
- IS_NETWORKING = true;
- else
- IS_NETWORKING = false;
-
- cJSON_Delete(root);
-}
-
-/*
- * 构建应答报文
- */
-static int build_ACK_message( void )
-{
- cJSON* root = cJSON_CreateObject();
-
- if( root ){
- cJSON_AddStringToObject(root, "msgType", "SUCCESS_ACK");
-
- // 将 cJSON 对象转换为 JSON 字符串
- res_ack_json = cJSON_Print(root);
- cJSON_Delete(root);
- }
- if(res_ack_json == NULL)
- return -1;
- return 0;
-}
-
-/*
- * 截取板级文件的productID
- * 参数:读取板级文件的内容
- * 返回值:无
- */
-static void extract_product_id(const char* input_string)
-{
- cJSON *root = cJSON_Parse(input_string);
- on_board_PID = cJSON_GetObjectItem(root, "productID");
-
- if (on_board_PID == NULL) {
- printf("on_board_PID not found\n");
- }
- strcpy(board_pid,on_board_PID->valuestring);
- cJSON_Delete(root);
-}
-
-#if 0
-/*
- * 读取板级文件tuya_key
- * 参数:无
- * 返回值:成功 0 失败-1
- */
-static int read_the_system_PID()
-{
- int fd = 0;
- int ret = 0;
- char* pid = NULL;
- char file_buff[150];
- fd=open(PID_FILE_PATH,O_RDONLY);
- if(fd == -1) {
- perror("open file failed!\n");
- goto open_error;
- }
- ret = read(fd,file_buff,sizeof(file_buff));
- if(ret ==-1)
- {
- perror("read file failed!\n");
- goto open_error;
- }
- extract_product_id(file_buff);
- close(fd);
- return 0;
- open_error:
- return -1;
-}
-#endif
-
-/*
- * 监听端口线程
- * 参数:无
- * 返回值:无
- */
-static void* udp_task(void*data)
-{
- int ret = 0;
- struct sockaddr_in client_addr;
- socklen_t client_addr_len;
- struct sockaddr_in ack_client_addr;
- socklen_t ack_client_addr_len;
- fd_set readfds;
- while (1) {
- usleep(500);
- client_addr_len = sizeof( client_addr );
- ack_client_addr_len = sizeof( ack_client_addr );
- //用于存储多个socket
- FD_ZERO(&readfds);//初始化select对象,用来清空readfds集合,即readfds集合不再包含任何文件句柄。
- //把创建的两个套接字文件描述符加入集合中
- FD_SET(sockfd, &readfds);
- FD_SET(ack_sockfd, &readfds);
- //确定select对象中最大的文件描述符值加1
- nfds = ack_sockfd + 1;
- // 使用select监测多个UDP socket
- if (select(nfds, &readfds, NULL, NULL, NULL) < 0) {
- perror("select");
-
- }
- if (FD_ISSET(sockfd, &readfds)) {//使用FD_ISSET判断是否就绪也就有无数据
- // 接收数据报文存放到rec_buffer
- ssize_t recv_len = recvfrom(sockfd, rec_buffer, BUFFER_SIZE, 0, (struct sockaddr*)&client_addr,
- &client_addr_len);
- printf("%s:\n %s",__func__ ,rec_buffer);
- if (recv_len < 0 ) {
- perror("Error in recvfrom!\n");
- }
- //解析数据
- string_interception(rec_buffer);
- //build_a_response_message();
- if( tuya_productid_read( board_pid, sizeof( board_pid ) ) ){
- strcpy( board_pid, "" );
- }
- printf( "cmp str board_pid:[%s], rec_pid[%s]\n", board_pid, rec_pid );
- ret = strcmp(board_pid,rec_pid);
- if(ret == 0 || FLAG == 1){
- FLAG = 0;
- //下发构建好的JSON报文
- build_a_response_message();
- if( res_json ){
- ssize_t send_len = sendto(sockfd, res_json, strlen(res_json), 0,
- (struct sockaddr*)&client_addr, client_addr_len);
- free( res_json );
- res_json = 0;
- }
- memset(rec_buffer,0,sizeof(rec_buffer));
- }
- }
- if (FD_ISSET(ack_sockfd, &readfds)) {
- ssize_t ack_recv_len = recvfrom(ack_sockfd, rec_ack_buffer, BUFFER_SIZE, 0,
- (struct sockaddr*)&ack_client_addr,&ack_client_addr_len);
- printf("%s: %s",__func__ ,rec_ack_buffer);
- if (ack_recv_len < 0 )
- perror("Error in recvfrom!\n");
- //解析数据
- get_statusResult(rec_ack_buffer);
- //构建应答json报文
- build_ACK_message();
- if( res_ack_json ){
-
- ssize_t send_len = sendto(ack_sockfd, res_ack_json, strlen(res_ack_json), 0,
- (struct sockaddr*)&ack_client_addr, ack_client_addr_len);
- free( res_ack_json );
- res_ack_json = NULL;
- }
- memset(rec_ack_buffer,0,sizeof(rec_ack_buffer));
-
- if( IS_NETWORKING ){
- //配网结束
- usleep(100);
- netconfig_success_notify_cb();
- }
- }
-
- }
- pthread_exit(NULL);
-}
-
-/*
- * 开启端口监听
- * 参数:无
- * 返回值:成功 0 失败-1
- */
-int open_udp_listen()
-{
- char* ip_addrs = NULL;
- struct sockaddr_in server_addr;
- struct sockaddr_in ack_server_addr;
-#if 0
- ip_addrs=get_local_ip();
- if(ip_addrs==NULL)
- {
- perror("Get IP addr failed!");
- return -1;
- }
-#endif
- // 创建套接字
- sockfd = socket(AF_INET, SOCK_DGRAM, 0);
- ack_sockfd = socket(AF_INET, SOCK_DGRAM, 0);
- if (sockfd < 0 || ack_sockfd < 0) {
- perror("Error in socket!\n");
- goto error;
- }
-
- int reuse=1;
- setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(reuse));
- setsockopt(ack_sockfd, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(reuse));
-
- // 设置服务器地址和端口
- server_addr.sin_family = AF_INET;
- server_addr.sin_addr.s_addr = htonl(INADDR_ANY);
- server_addr.sin_port = htons(PORT);
-
- // 设置服务器地址和端口
- ack_server_addr.sin_family = AF_INET;
- ack_server_addr.sin_addr.s_addr = htonl(INADDR_ANY);
- ack_server_addr.sin_port = htons(ACK_PORT);
-
- // 绑定套接字到地址和端口
- if (bind(sockfd, (struct sockaddr*)&server_addr, sizeof(server_addr)) < 0) {
- perror("Error in bind!\n");
- goto error;
- }
-
- // 绑定套接字到地址和端口
- if (bind(ack_sockfd, (struct sockaddr*)&ack_server_addr, sizeof(ack_server_addr)) < 0) {
- perror("Error in bind!\n");
- goto error;
- }
-
- printf("Server listening on port %d and %d\n", PORT,ACK_PORT);
- if( pthread_create( &udp_thread, NULL, udp_task, NULL) != 0 ){
- perror("create udp task!");
- goto error;
- }
-
- return 0;
-error :
- if( sockfd >= 0 )
- close(sockfd);
- if( ack_sockfd >= 0 )
- close(ack_sockfd);
- return -1;
-}
-
-/*
- * 关闭端口监听
- * 参数:无
- * 返回值:成功 0 失败-1
- */
-int close_udp_listen()
-{
- int ret = 0;
- close(sockfd);
- close(ack_sockfd);
- ret = pthread_cancel(udp_thread);
- if(ret != 0)
- return -1;
- ret = pthread_join(udp_thread,NULL);
- if(ret != 0)
- return -1;
- return 0;
-}