From 93da707c258427ace57b8e405d24e96fe947226b Mon Sep 17 00:00:00 2001 From: kyz Date: Sat, 25 Oct 2025 14:46:34 +0800 Subject: [PATCH] :add web server --- CMakeLists.txt | 12 +- nginx-pcs | 49 + pcs.md | 321 +++++ src/cJSON.c | 2979 ----------------------------------------- src/cJSON.h | 293 ---- src/http-server.c | 159 --- src/main.c | 16 +- src/user.h | 19 + src/user_bms.c | 100 +- src/user_bms.h | 8 +- src/user_mb.c | 5 - src/user_pcs.c | 233 ++-- src/user_pcs.h | 17 +- src/user_web.h | 0 src/user_web_data.c | 305 +++++ src/user_web_server.c | 837 ++++++++++++ test.html | 488 +++++++ 17 files changed, 2226 insertions(+), 3615 deletions(-) create mode 100644 nginx-pcs create mode 100644 pcs.md delete mode 100644 src/cJSON.c delete mode 100644 src/cJSON.h delete mode 100644 src/http-server.c create mode 100644 src/user.h create mode 100644 src/user_web.h create mode 100644 src/user_web_data.c create mode 100644 src/user_web_server.c create mode 100644 test.html diff --git a/CMakeLists.txt b/CMakeLists.txt index a722d4c..5ef8191 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -31,19 +31,19 @@ pkg_check_modules (DBUS dbus-1 REQUIRED) target_link_libraries( ${PROJECT_NAME} PUBLIC - curl log4c rt modbus z - websockets + websockets + cjson ${GLIB2_LIBRARIES} ${DBUS_LIBRARIES} - sqlite3 - ssl - crypto + sqlite3 + ssl + crypto pthread - ) +) install(TARGETS ${PROJECT_NAME} RUNTIME DESTINATION /app) install(FILES ${PROJECT_SOURCE_DIR}/log4crc DESTINATION /app) diff --git a/nginx-pcs b/nginx-pcs new file mode 100644 index 0000000..23399a5 --- /dev/null +++ b/nginx-pcs @@ -0,0 +1,49 @@ +# Nginx配置文件示例 + +server { + listen 80; + server_name localhost; + + # 设置访问日志 + access_log /var/log/nginx/access.log; + error_log /var/log/nginx/error.log; + + # 静态文件根目录 + #root /home/yn/websocket_server; + #root /var/www/html; + #root /home/kyz/study/todo/minimal-http-websocket-combined/mount-origin; + root /var/www2/html; + index index.html; + + # 静态文件服务 + location / { + try_files $uri $uri/ =404; + } + + # HTTP API 反向代理 + location /api/ { + proxy_pass http://localhost:7681; + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_set_header X-Forwarded-Proto $scheme; + + proxy_buffers 8 32k; + proxy_buffer_size 64k; + } + + # 修改WebSocket代理配置 + location /ws/ { + proxy_pass http://localhost:7681/; # 添加尾部斜杠,确保路径正确映射 + proxy_http_version 1.1; + proxy_set_header Upgrade $http_upgrade; + proxy_set_header Connection "upgrade"; + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_set_header X-Forwarded-Proto $scheme; + + proxy_read_timeout 86400; + proxy_send_timeout 86400; + } +} diff --git a/pcs.md b/pcs.md new file mode 100644 index 0000000..bd38f2c --- /dev/null +++ b/pcs.md @@ -0,0 +1,321 @@ +# PCS与BMS系统Web通信协议 + +## 1. 协议概述 + +本协议定义了PCS(储能变流器)与BMS(电池管理系统)通过Web API进行通信的接口规范,包括数据格式、请求/响应机制以及数据字段说明。 + +## 2. 接口说明 + +### 2.1 获取PCS信息 + +- **请求地址**:http://192.168.1.1/api/pcs_info +- **请求方式**:POST +- **请求参数**: +```json +{ + "code": 0, + "msg": "get_pcs_info" +} +``` +- **服务器回应**: + +```json +{ + "code": 0, + "msg": "get_pcs_info", + "data": { + "firmware_version": 100, + "hardware_version": 200, + "dc_voltage_p1v": 5600, + "dc_pos_voltage_p1v": 2800, + "dc_neg_voltage_p1v": 2800, + "dc_current_p1a": 150, + "dc_power_p1kw": 840, + "line_voltage_ab_p1v": 3800, + "line_voltage_bc_p1v": 3800, + "line_voltage_ca_p1v": 3800, + "phase_current_a_p1a": 100, + "phase_current_b_p1a": 100, + "phase_current_c_p1a": 100, + "apparent_power_p1kva": 1000, + "active_power_p1kw": 800, + "reactive_power_p1kvar": 600, + "power_factor_p3": 800, + "grid_frequency_p1hz": 5000, + "module_temperature_p1c": 450, + "ambient_temperature_p1c": 250, + "leakage_current_p1a": 5, + "running_state": 1, + "operation_mode": 2, + "error_code": 0, + "error_code2": 0, + "grid_voltage_a_p1v": 2200, + "grid_voltage_b_p1v": 2200, + "grid_voltage_c_p1v": 2200, + "on_off_setting": 1, + "work_mode_setting": 1, + "reactive_power_mode": 1, + "power_factor_setting_p3": 900, + "reactive_current_setting_p1a": 0, + "target_current_p1a": 100, + "target_voltage_p1v": 5600, + "voltage_limit_current_p1a": 150, + "target_power_p1kw": 800, + "offline_voltage": 380, + "offline_frequency": 50, + "grid_voltage": 380, + "grid_frequency": 50, + "grid_overvoltage_threshold_p1v": 4200, + "grid_undervoltage_threshold_p1v": 3400, + "grid_overfrequency_threshold_p1hz": 5150, + "grid_underfrequency_threshold_p1hz": 4850, + "dc_overvoltage_threshold_p1v": 6000, + "dc_overvoltage_recover_p1v": 5800, + "dc_undervoltage_threshold_p1v": 5000, + "dc_undervoltage_recover_p1v": 5200, + "heartbeat_enable": 120, + "clear_fault": 0 + } +} +``` +### 2.2 获取BMS信息 + +- **请求地址**:http://192.168.1.1/api/bms_info +- **请求方式**:POST +- **请求参数**: +```json +{ + "code": 0, + "msg": "get_bms_info" +} +``` +- **服务器回应**: +```json +{ + "code": 0, + "msg": "get_bms_info", + "data": { + "max_charge_current_p1a": 100, + "max_discharge_current_p1a": 100, + "total_voltage_p1v": 5600, + "total_current_p1a": 150, + "total_soc_p1": 80, + "total_soh_p1": 95, + "max_charge_voltage_p1v": 5800, + "battery_status": 1, + "light_alarm": 0, + "medium_alarm": 0, + "serious_alarm": 0, + "min_cell_voltage_p3v": 3200, + "min_cell_num": 10, + "max_cell_voltage_p3v": 3400, + "max_cell_num": 5, + "min_cell_temp_p1c": 250, + "min_temp_num": 3, + "max_cell_temp_p1c": 300, + "max_temp_num": 15 + } +} +``` + +### 2.3 配置PCS参数 + +**请求地址**:http://192.168.1.1/api/pcs_config + +**请求方式**:POST + +**请求参数**: +```json +{ + "code": 0, + "msg": "set_pcs_parameter", + "data": { + "on_off_setting": 1, + "work_mode_setting": 1, + "reactive_power_mode": 1, + "power_factor_setting_p3": 900, + "reactive_current_setting_p1a": 0, + "target_current_p1a": 100, + "target_voltage_p1v": 5600, + "voltage_limit_current_p1a": 150, + "target_power_p1kw": 800, + "offline_voltage": 380, + "offline_frequency": 50, + "grid_voltage": 380, + "grid_frequency": 50, + "grid_overvoltage_threshold_p1v": 4200, + "grid_undervoltage_threshold_p1v": 3400, + "grid_overfrequency_threshold_p1hz": 5150, + "grid_underfrequency_threshold_p1hz": 4850, + "dc_overvoltage_threshold_p1v": 6000, + "dc_overvoltage_recover_p1v": 5800, + "dc_undervoltage_threshold_p1v": 5000, + "dc_undervoltage_recover_p1v": 5200, + "heartbeat_enable": 120, + "clear_fault": 0 + } +} +``` +- **服务器回应**: +```json +{ + "code": 0, + "msg": "set_pcs_parameter" +} +``` + +## 3. 数据字段说明 + +### 3.1 pcs_info数据字段说明 + +| 字段名称 | 数据类型 | 单位 | 精度 | 功能描述 | 地址 | +|---------|---------|------|------|---------|------| +| firmware_version | uint16_t | 版本号 | - | 软件版本 | 0 | +| hardware_version | uint16_t | 版本号 | - | 硬件版本 | 1 | +| dc_voltage_p1v | uint16_t | V | 0.1 | 直流电压 | 2 | +| dc_pos_voltage_p1v | uint16_t | V | 0.1 | 直流正电压 | 3 | +| dc_neg_voltage_p1v | uint16_t | V | 0.1 | 直流负电压 | 4 | +| dc_current_p1a | int16_t | A | 0.1 | 直流电流 | 5 | +| dc_power_p1kw | int16_t | kW | 0.1 | 直流功率 | 6 | +| line_voltage_ab_p1v | uint16_t | V | 0.1 | AB线电压 | 7 | +| line_voltage_bc_p1v | uint16_t | V | 0.1 | BC线电压 | 8 | +| line_voltage_ca_p1v | uint16_t | V | 0.1 | CA线电压 | 9 | +| phase_current_a_p1a | int16_t | A | 0.1 | A相电流 | 10 | +| phase_current_b_p1a | int16_t | A | 0.1 | B相电流 | 11 | +| phase_current_c_p1a | int16_t | A | 0.1 | C相电流 | 12 | +| apparent_power_p1kva | int16_t | kVA | 0.1 | 视在功率 | 13 | +| active_power_p1kw | int16_t | kW | 0.1 | 有功功率 | 14 | +| reactive_power_p1kvar | int16_t | kVar | 0.1 | 无功功率 | 15 | +| power_factor_p3 | int16_t | - | 0.001 | 功率因数 | 16 | +| grid_frequency_p1hz | uint16_t | Hz | 0.01 | 电网频率 | 17 | +| module_temperature_p1c | int16_t | ℃ | 0.1 | 模块温度 | 18 | +| reserved_19 | uint16_t | - | - | 保留 | 19 | +| ambient_temperature_p1c | int16_t | ℃ | 0.1 | 环境温度 | 20 | +| reserved_21 | uint16_t | - | - | 保留 | 21 | +| reserved_22 | uint16_t | - | - | 保留 | 22 | +| leakage_current_p1a | int16_t | A | 0.01 | 漏电流 | 23 | +| reserved_24 | uint16_t | - | - | 保留 | 24 | +| reserved_25 | uint16_t | - | - | 保留 | 25 | +| reserved_26 | uint16_t | - | - | 保留 | 26 | +| running_state | uint16_t | - | - | 工作状态 | 27 | +| operation_mode | uint16_t | - | - | 运行模式显示 | 28 | +| error_code | uint16_t | - | - | 故障1 | 29 | +| error_code2 | uint16_t | - | - | 故障2 | 30 | +| reserved_31 | uint16_t | - | - | 保留 | 31 | +| grid_voltage_a_p1v | uint16_t | V | 0.1 | 电网A相电压 | 32 | +| grid_voltage_b_p1v | uint16_t | V | 0.1 | 电网B相电压 | 33 | +| grid_voltage_c_p1v | uint16_t | V | 0.1 | 电网C相电压 | 34 | +| on_off_setting | uint16_t | - | - | 开关机设置 | 35 | +| work_mode_setting | uint16_t | - | - | 工作模式设置 | 36 | +| reactive_power_mode | uint16_t | - | - | 无功调节方式 | 37 | +| power_factor_setting_p3 | int16_t | - | 0.001 | 功率因数设置 | 38 | +| reactive_current_setting_p1a | int16_t | A | 0.1 | 无功电流设置 | 39 | +| target_current_p1a | int16_t | A | 0.1 | 恒流电流值 | 46 | +| target_voltage_p1v | uint16_t | V | 0.1 | 恒压电压值 | 48 | +| voltage_limit_current_p1a | uint16_t | A | 0.1 | 恒压限流值 | 49 | +| target_power_p1kw | int16_t | kW | 0.1 | 恒功率目标值 | 51 | +| offline_voltage | uint16_t | - | - | 离网逆变电压设置 | 53 | +| offline_frequency | uint16_t | - | - | 离网逆变频率设置 | 54 | +| grid_voltage | uint16_t | - | - | 电网额定电压 | 55 | +| grid_frequency | uint16_t | - | - | 电网额定频率 | 56 | +| grid_overvoltage_threshold_p1v | uint16_t | V | 0.1 | 电网过压保护值 | 57 | +| grid_undervoltage_threshold_p1v | uint16_t | V | 0.1 | 电网欠压保护值 | 58 | +| grid_overfrequency_threshold_p1hz | uint16_t | Hz | 0.01 | 电网过频保护值 | 59 | +| grid_underfrequency_threshold_p1hz | uint16_t | Hz | 0.01 | 电网欠频保护值 | 60 | +| dc_overvoltage_threshold_p1v | uint16_t | V | 0.1 | 直流过压保护值 | 61 | +| dc_overvoltage_recover_p1v | uint16_t | V | 0.1 | 直流过压恢复值 | 62 | +| dc_undervoltage_threshold_p1v | uint16_t | V | 0.1 | 直流欠压保护值 | 63 | +| dc_undervoltage_recover_p1v | uint16_t | V | 0.1 | 直流欠压恢复值 | 64 | +| heartbeat_enable | uint16_t | S | - | 心跳检测及使能 | 67 | +| clear_fault | uint16_t | - | - | 清除故障 | 70 | + +### 3.2 bms_info数据字段说明 + +| 字段名称 | 数据类型 | 单位 | 精度 | 功能描述 | 来源帧 | +|---------|---------|------|------|---------|-------| +| max_charge_current_p1a | uint16_t | A | 0.1 | 最大允许充电电流 | BMS_FRAME1_ID | +| max_discharge_current_p1a | uint16_t | A | 0.1 | 最大允许放电电流 | BMS_FRAME1_ID | +| total_voltage_p1v | uint16_t | V | 0.1 | 总电压 | BMS_FRAME1_ID | +| total_current_p1a | int16_t | A | 0.1 | 总电流 | BMS_FRAME1_ID | +| total_soc_p1 | uint16_t | % | 0.1 | 总SOC | BMS_FRAME2_ID | +| total_soh_p1 | uint16_t | % | 0.1 | 总SOH | BMS_FRAME2_ID | +| max_charge_voltage_p1v | uint16_t | V | 0.1 | 最大允许充电电压 | BMS_FRAME2_ID | +| reserve_2 | uint16_t | - | - | 保留 | BMS_FRAME2_ID | +| battery_status | uint16_t | - | - | 电池状态 | BMS_FRAME3_ID | +| light_alarm | uint16_t | - | - | 轻度告警 | BMS_FRAME3_ID | +| medium_alarm | uint16_t | - | - | 中度告警 | BMS_FRAME3_ID | +| serious_alarm | uint16_t | - | - | 严重告警 | BMS_FRAME3_ID | +| min_cell_voltage_p3v | uint16_t | V | 0.001 | 单体最低电池电压 | BMS_FRAME4_ID | +| min_cell_num | uint16_t | - | - | 单体最低电池电压编号 | BMS_FRAME4_ID | +| max_cell_voltage_p3v | uint16_t | V | 0.001 | 单体最高电池电压 | BMS_FRAME4_ID | +| max_cell_num | uint16_t | - | - | 单体最高电池电压编号 | BMS_FRAME4_ID | +| min_cell_temp_p1c | int16_t | ℃ | 0.1 | 单体最低电池温度 | BMS_FRAME5_ID | +| min_temp_num | uint16_t | - | - | 单体最低电池温度编号 | BMS_FRAME5_ID | +| max_cell_temp_p1c | int16_t | ℃ | 0.1 | 单体最高电池温度 | BMS_FRAME5_ID | +| max_temp_num | uint16_t | - | - | 单体最高电池温度编号 | BMS_FRAME5_ID | + +### 3.3 pcs_config配置参数说明 + +| 字段名称 | 数据类型 | 单位 | 精度 | 功能描述 | 地址 | +|---------|---------|------|------|---------|------| +| on_off_setting | uint16_t | - | - | 开关机设置 | 35 | +| work_mode_setting | uint16_t | - | - | 工作模式设置 | 36 | +| reactive_power_mode | uint16_t | - | - | 无功调节方式 | 37 | +| power_factor_setting_p3 | int16_t | - | 0.001 | 功率因数设置 | 38 | +| reactive_current_setting_p1a | int16_t | A | 0.1 | 无功电流设置 | 39 | +| target_current_p1a | int16_t | A | 0.1 | 恒流电流值 | 46 | +| target_voltage_p1v | uint16_t | V | 0.1 | 恒压电压值 | 48 | +| voltage_limit_current_p1a | uint16_t | A | 0.1 | 恒压限流值 | 49 | +| target_power_p1kw | int16_t | kW | 0.1 | 恒功率目标值 | 51 | +| offline_voltage | uint16_t | - | - | 离网逆变电压设置 | 53 | +| offline_frequency | uint16_t | - | - | 离网逆变频率设置 | 54 | +| grid_voltage | uint16_t | - | - | 电网额定电压 | 55 | +| grid_frequency | uint16_t | - | - | 电网额定频率 | 56 | +| grid_overvoltage_threshold_p1v | uint16_t | V | 0.1 | 电网过压保护值 | 57 | +| grid_undervoltage_threshold_p1v | uint16_t | V | 0.1 | 电网欠压保护值 | 58 | +| grid_overfrequency_threshold_p1hz | uint16_t | Hz | 0.01 | 电网过频保护值 | 59 | +| grid_underfrequency_threshold_p1hz | uint16_t | Hz | 0.01 | 电网欠频保护值 | 60 | +| dc_overvoltage_threshold_p1v | uint16_t | V | 0.1 | 直流过压保护值 | 61 | +| dc_overvoltage_recover_p1v | uint16_t | V | 0.1 | 直流过压恢复值 | 62 | +| dc_undervoltage_threshold_p1v | uint16_t | V | 0.1 | 直流欠压保护值 | 63 | +| dc_undervoltage_recover_p1v | uint16_t | V | 0.1 | 直流欠压恢复值 | 64 | +| heartbeat_enable | uint16_t | S | - | 心跳检测及使能 | 67 | +| clear_fault | uint16_t | - | - | 清除故障 | 70 | +| protection_enable | uint16_t | - | - | 保护使能位设置 | 100 | + +## 4. WebSocket通信定义 + +### 4.1 WebSocket连接信息 + +- **连接URL**:ws://192.168.1.1/ws/ +- **协议名称**:ws + +### 4.2 服务器数据主动通知 + +服务器向已连接的WebSocket客户端发送包含PCS信息和BMS信息的数据 + +**数据格式**: +```json +{ + "code": 0, + "msg": "device_info_update", + "data": { + "pcs_info": { + // PCS信息字段,格式与3.1节定义的pcs_info数据结构完全一致 + "firmware_version": 100, + "hardware_version": 200, + "dc_voltage_p1v": 5600, + "dc_current_p1a": 150, + // ... 其他pcs_info字段 + }, + "bms_info": { + // BMS信息字段,格式与3.2节定义的bms_info数据结构完全一致 + "max_charge_current_p1a": 100, + "max_discharge_current_p1a": 100, + "total_voltage_p1v": 5600, + "total_current_p1a": 150, + // ... 其他bms_info字段 + } + } +} +``` \ No newline at end of file diff --git a/src/cJSON.c b/src/cJSON.c deleted file mode 100644 index bc95cde..0000000 --- a/src/cJSON.c +++ /dev/null @@ -1,2979 +0,0 @@ -/* - 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 -#include -#include -#include -#include -#include - -#ifdef ENABLE_LOCALES -#include -#endif - -#if defined(_MSC_VER) -#pragma warning (pop) -#endif -#ifdef __GNUC__ -#pragma GCC visibility pop -#endif - -#include "cJSON.h" - -/* define our own boolean type */ -#ifdef true -#undef true -#endif -#define true ((cJSON_bool)1) - -#ifdef false -#undef false -#endif -#define false ((cJSON_bool)0) - -typedef struct { - const unsigned char *json; - size_t position; -} error; -static error global_error = { NULL, 0 }; - -CJSON_PUBLIC(const char *) cJSON_GetErrorPtr(void) -{ - return (const char*) (global_error.json + global_error.position); -} - -CJSON_PUBLIC(char *) cJSON_GetStringValue(const cJSON * const item) { - if (!cJSON_IsString(item)) { - return NULL; - } - - return item->valuestring; -} - -/* This is a safeguard to prevent copy-pasters from using incompatible C and header files */ -#if (CJSON_VERSION_MAJOR != 1) || (CJSON_VERSION_MINOR != 7) || (CJSON_VERSION_PATCH != 12) - #error cJSON.h and cJSON.c have different versions. Make sure that both have the same. -#endif - -CJSON_PUBLIC(const char*) cJSON_Version(void) -{ - static char version[15]; - sprintf(version, "%i.%i.%i", CJSON_VERSION_MAJOR, CJSON_VERSION_MINOR, CJSON_VERSION_PATCH); - - return version; -} - -/* Case insensitive string comparison, doesn't consider two NULL pointers equal though */ -static int case_insensitive_strcmp(const unsigned char *string1, const unsigned char *string2) -{ - if ((string1 == NULL) || (string2 == NULL)) - { - return 1; - } - - if (string1 == string2) - { - return 0; - } - - for(; tolower(*string1) == tolower(*string2); (void)string1++, string2++) - { - if (*string1 == '\0') - { - return 0; - } - } - - return tolower(*string1) - tolower(*string2); -} - -typedef struct internal_hooks -{ - void *(CJSON_CDECL *allocate)(size_t size); - void (CJSON_CDECL *deallocate)(void *pointer); - void *(CJSON_CDECL *reallocate)(void *pointer, size_t size); -} internal_hooks; - -#if defined(_MSC_VER) -/* work around MSVC error C2322: '...' address of dllimport '...' is not static */ -static void * CJSON_CDECL internal_malloc(size_t size) -{ - return malloc(size); -} -static void CJSON_CDECL internal_free(void *pointer) -{ - free(pointer); -} -static void * CJSON_CDECL internal_realloc(void *pointer, size_t size) -{ - return realloc(pointer, size); -} -#else -#define internal_malloc malloc -#define internal_free free -#define internal_realloc realloc -#endif - -/* strlen of character literals resolved at compile time */ -#define static_strlen(string_literal) (sizeof(string_literal) - sizeof("")) - -static internal_hooks global_hooks = { internal_malloc, internal_free, internal_realloc }; - -static unsigned char* cJSON_strdup(const unsigned char* string, const internal_hooks * const hooks) -{ - size_t length = 0; - unsigned char *copy = NULL; - - if (string == NULL) - { - return NULL; - } - - length = strlen((const char*)string) + sizeof(""); - copy = (unsigned char*)hooks->allocate(length); - if (copy == NULL) - { - return NULL; - } - memcpy(copy, string, length); - - return copy; -} - -CJSON_PUBLIC(void) cJSON_InitHooks(cJSON_Hooks* hooks) -{ - if (hooks == NULL) - { - /* Reset hooks */ - global_hooks.allocate = malloc; - global_hooks.deallocate = free; - global_hooks.reallocate = realloc; - return; - } - - global_hooks.allocate = malloc; - if (hooks->malloc_fn != NULL) - { - global_hooks.allocate = hooks->malloc_fn; - } - - global_hooks.deallocate = free; - if (hooks->free_fn != NULL) - { - global_hooks.deallocate = hooks->free_fn; - } - - /* use realloc only if both free and malloc are used */ - global_hooks.reallocate = NULL; - if ((global_hooks.allocate == malloc) && (global_hooks.deallocate == free)) - { - global_hooks.reallocate = realloc; - } -} - -/* Internal constructor. */ -static cJSON *cJSON_New_Item(const internal_hooks * const hooks) -{ - cJSON* node = (cJSON*)hooks->allocate(sizeof(cJSON)); - if (node) - { - memset(node, '\0', sizeof(cJSON)); - } - - return node; -} - -/* Delete a cJSON structure. */ -CJSON_PUBLIC(void) cJSON_Delete(cJSON *item) -{ - cJSON *next = NULL; - while (item != NULL) - { - next = item->next; - if (!(item->type & cJSON_IsReference) && (item->child != NULL)) - { - cJSON_Delete(item->child); - } - if (!(item->type & cJSON_IsReference) && (item->valuestring != NULL)) - { - global_hooks.deallocate(item->valuestring); - } - if (!(item->type & cJSON_StringIsConst) && (item->string != NULL)) - { - global_hooks.deallocate(item->string); - } - global_hooks.deallocate(item); - item = next; - } -} - -/* get the decimal point character of the current locale */ -static unsigned char get_decimal_point(void) -{ -#ifdef ENABLE_LOCALES - struct lconv *lconv = localeconv(); - return (unsigned char) lconv->decimal_point[0]; -#else - return '.'; -#endif -} - -typedef struct -{ - const unsigned char *content; - size_t length; - size_t offset; - size_t depth; /* How deeply nested (in arrays/objects) is the input at the current offset. */ - internal_hooks hooks; -} parse_buffer; - -/* check if the given size is left to read in a given parse buffer (starting with 1) */ -#define can_read(buffer, size) ((buffer != NULL) && (((buffer)->offset + size) <= (buffer)->length)) -/* check if the buffer can be accessed at the given index (starting with 0) */ -#define can_access_at_index(buffer, index) ((buffer != NULL) && (((buffer)->offset + index) < (buffer)->length)) -#define cannot_access_at_index(buffer, index) (!can_access_at_index(buffer, index)) -/* get a pointer to the buffer at the position */ -#define buffer_at_offset(buffer) ((buffer)->content + (buffer)->offset) - -/* Parse the input text to generate a number, and populate the result into item. */ -static cJSON_bool parse_number(cJSON * const item, parse_buffer * const input_buffer) -{ - double number = 0; - unsigned char *after_end = NULL; - unsigned char number_c_string[64]; - unsigned char decimal_point = get_decimal_point(); - size_t i = 0; - - if ((input_buffer == NULL) || (input_buffer->content == NULL)) - { - return false; - } - - /* copy the number into a temporary buffer and replace '.' with the decimal point - * of the current locale (for strtod) - * This also takes care of '\0' not necessarily being available for marking the end of the input */ - for (i = 0; (i < (sizeof(number_c_string) - 1)) && can_access_at_index(input_buffer, i); i++) - { - switch (buffer_at_offset(input_buffer)[i]) - { - case '0': - case '1': - case '2': - case '3': - case '4': - case '5': - case '6': - case '7': - case '8': - case '9': - case '+': - case '-': - case 'e': - case 'E': - number_c_string[i] = buffer_at_offset(input_buffer)[i]; - break; - - case '.': - number_c_string[i] = decimal_point; - break; - - default: - goto loop_end; - } - } -loop_end: - number_c_string[i] = '\0'; - - number = strtod((const char*)number_c_string, (char**)&after_end); - if (number_c_string == after_end) - { - return false; /* parse_error */ - } - - item->valuedouble = number; - - /* use saturation in case of overflow */ - if (number >= INT_MAX) - { - item->valueint = INT_MAX; - } - else if (number <= (double)INT_MIN) - { - item->valueint = INT_MIN; - } - else - { - item->valueint = (int)number; - } - - item->type = cJSON_Number; - - input_buffer->offset += (size_t)(after_end - number_c_string); - return true; -} - -/* don't ask me, but the original cJSON_SetNumberValue returns an integer or double */ -CJSON_PUBLIC(double) cJSON_SetNumberHelper(cJSON *object, double number) -{ - if (number >= INT_MAX) - { - object->valueint = INT_MAX; - } - else if (number <= (double)INT_MIN) - { - object->valueint = INT_MIN; - } - else - { - object->valueint = (int)number; - } - - return object->valuedouble = number; -} - -typedef struct -{ - unsigned char *buffer; - size_t length; - size_t offset; - size_t depth; /* current nesting depth (for formatted printing) */ - cJSON_bool noalloc; - cJSON_bool format; /* is this print a formatted print */ - internal_hooks hooks; -} printbuffer; - -/* realloc printbuffer if necessary to have at least "needed" bytes more */ -static unsigned char* ensure(printbuffer * const p, size_t needed) -{ - unsigned char *newbuffer = NULL; - size_t newsize = 0; - - if ((p == NULL) || (p->buffer == NULL)) - { - return NULL; - } - - if ((p->length > 0) && (p->offset >= p->length)) - { - /* make sure that offset is valid */ - return NULL; - } - - if (needed > INT_MAX) - { - /* sizes bigger than INT_MAX are currently not supported */ - return NULL; - } - - needed += p->offset + 1; - if (needed <= p->length) - { - return p->buffer + p->offset; - } - - if (p->noalloc) { - return NULL; - } - - /* calculate new buffer size */ - if (needed > (INT_MAX / 2)) - { - /* overflow of int, use INT_MAX if possible */ - if (needed <= INT_MAX) - { - newsize = INT_MAX; - } - else - { - return NULL; - } - } - else - { - newsize = needed * 2; - } - - if (p->hooks.reallocate != NULL) - { - /* reallocate with realloc if available */ - newbuffer = (unsigned char*)p->hooks.reallocate(p->buffer, newsize); - if (newbuffer == NULL) - { - p->hooks.deallocate(p->buffer); - p->length = 0; - p->buffer = NULL; - - return NULL; - } - } - else - { - /* otherwise reallocate manually */ - newbuffer = (unsigned char*)p->hooks.allocate(newsize); - if (!newbuffer) - { - p->hooks.deallocate(p->buffer); - p->length = 0; - p->buffer = NULL; - - return NULL; - } - if (newbuffer) - { - memcpy(newbuffer, p->buffer, p->offset + 1); - } - p->hooks.deallocate(p->buffer); - } - p->length = newsize; - p->buffer = newbuffer; - - return newbuffer + p->offset; -} - -/* calculate the new length of the string in a printbuffer and update the offset */ -static void update_offset(printbuffer * const buffer) -{ - const unsigned char *buffer_pointer = NULL; - if ((buffer == NULL) || (buffer->buffer == NULL)) - { - return; - } - buffer_pointer = buffer->buffer + buffer->offset; - - buffer->offset += strlen((const char*)buffer_pointer); -} - -/* securely comparison of floating-point variables */ -static cJSON_bool compare_double(double a, double b) -{ - return (fabs(a - b) <= CJSON_DOUBLE_PRECISION); -} - -/* Render the number nicely from the given item into a string. */ -static cJSON_bool print_number(const cJSON * const item, printbuffer * const output_buffer) -{ - unsigned char *output_pointer = NULL; - double d = item->valuedouble; - int length = 0; - size_t i = 0; - unsigned char number_buffer[26] = {0}; /* temporary buffer to print the number into */ - unsigned char decimal_point = get_decimal_point(); - double test = 0.0; - - if (output_buffer == NULL) - { - return false; - } - - /* This checks for NaN and Infinity */ - if ((d * 0) != 0) - { - length = sprintf((char*)number_buffer, "null"); - } - else - { - /* Try 15 decimal places of precision to avoid nonsignificant nonzero digits */ - length = sprintf((char*)number_buffer, "%1.15g", d); - - /* Check whether the original double can be recovered */ - if ((sscanf((char*)number_buffer, "%lg", &test) != 1) || !compare_double((double)test, d)) - { - /* If not, print with 17 decimal places of precision */ - length = sprintf((char*)number_buffer, "%1.17g", d); - } - } - - /* sprintf failed or buffer overrun occurred */ - if ((length < 0) || (length > (int)(sizeof(number_buffer) - 1))) - { - return false; - } - - /* reserve appropriate space in the output */ - output_pointer = ensure(output_buffer, (size_t)length + sizeof("")); - if (output_pointer == NULL) - { - return false; - } - - /* copy the printed number to the output and replace locale - * dependent decimal point with '.' */ - for (i = 0; i < ((size_t)length); i++) - { - if (number_buffer[i] == decimal_point) - { - output_pointer[i] = '.'; - continue; - } - - output_pointer[i] = number_buffer[i]; - } - output_pointer[i] = '\0'; - - output_buffer->offset += (size_t)length; - - return true; -} - -/* parse 4 digit hexadecimal number */ -static unsigned parse_hex4(const unsigned char * const input) -{ - unsigned int h = 0; - size_t i = 0; - - for (i = 0; i < 4; i++) - { - /* parse digit */ - if ((input[i] >= '0') && (input[i] <= '9')) - { - h += (unsigned int) input[i] - '0'; - } - else if ((input[i] >= 'A') && (input[i] <= 'F')) - { - h += (unsigned int) 10 + input[i] - 'A'; - } - else if ((input[i] >= 'a') && (input[i] <= 'f')) - { - h += (unsigned int) 10 + input[i] - 'a'; - } - else /* invalid */ - { - return 0; - } - - if (i < 3) - { - /* shift left to make place for the next nibble */ - h = h << 4; - } - } - - return h; -} - -/* converts a UTF-16 literal to UTF-8 - * A literal can be one or two sequences of the form \uXXXX */ -static unsigned char utf16_literal_to_utf8(const unsigned char * const input_pointer, const unsigned char * const input_end, unsigned char **output_pointer) -{ - long unsigned int codepoint = 0; - unsigned int first_code = 0; - const unsigned char *first_sequence = input_pointer; - unsigned char utf8_length = 0; - unsigned char utf8_position = 0; - unsigned char sequence_length = 0; - unsigned char first_byte_mark = 0; - - if ((input_end - first_sequence) < 6) - { - /* input ends unexpectedly */ - goto fail; - } - - /* get the first utf16 sequence */ - first_code = parse_hex4(first_sequence + 2); - - /* check that the code is valid */ - if (((first_code >= 0xDC00) && (first_code <= 0xDFFF))) - { - goto fail; - } - - /* UTF16 surrogate pair */ - if ((first_code >= 0xD800) && (first_code <= 0xDBFF)) - { - const unsigned char *second_sequence = first_sequence + 6; - unsigned int second_code = 0; - sequence_length = 12; /* \uXXXX\uXXXX */ - - if ((input_end - second_sequence) < 6) - { - /* input ends unexpectedly */ - goto fail; - } - - if ((second_sequence[0] != '\\') || (second_sequence[1] != 'u')) - { - /* missing second half of the surrogate pair */ - goto fail; - } - - /* get the second utf16 sequence */ - second_code = parse_hex4(second_sequence + 2); - /* check that the code is valid */ - if ((second_code < 0xDC00) || (second_code > 0xDFFF)) - { - /* invalid second half of the surrogate pair */ - goto fail; - } - - - /* calculate the unicode codepoint from the surrogate pair */ - codepoint = 0x10000 + (((first_code & 0x3FF) << 10) | (second_code & 0x3FF)); - } - else - { - sequence_length = 6; /* \uXXXX */ - codepoint = first_code; - } - - /* encode as UTF-8 - * takes at maximum 4 bytes to encode: - * 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx */ - if (codepoint < 0x80) - { - /* normal ascii, encoding 0xxxxxxx */ - utf8_length = 1; - } - else if (codepoint < 0x800) - { - /* two bytes, encoding 110xxxxx 10xxxxxx */ - utf8_length = 2; - first_byte_mark = 0xC0; /* 11000000 */ - } - else if (codepoint < 0x10000) - { - /* three bytes, encoding 1110xxxx 10xxxxxx 10xxxxxx */ - utf8_length = 3; - first_byte_mark = 0xE0; /* 11100000 */ - } - else if (codepoint <= 0x10FFFF) - { - /* four bytes, encoding 1110xxxx 10xxxxxx 10xxxxxx 10xxxxxx */ - utf8_length = 4; - first_byte_mark = 0xF0; /* 11110000 */ - } - else - { - /* invalid unicode codepoint */ - goto fail; - } - - /* encode as utf8 */ - for (utf8_position = (unsigned char)(utf8_length - 1); utf8_position > 0; utf8_position--) - { - /* 10xxxxxx */ - (*output_pointer)[utf8_position] = (unsigned char)((codepoint | 0x80) & 0xBF); - codepoint >>= 6; - } - /* encode first byte */ - if (utf8_length > 1) - { - (*output_pointer)[0] = (unsigned char)((codepoint | first_byte_mark) & 0xFF); - } - else - { - (*output_pointer)[0] = (unsigned char)(codepoint & 0x7F); - } - - *output_pointer += utf8_length; - - return sequence_length; - -fail: - return 0; -} - -/* Parse the input text into an unescaped cinput, and populate item. */ -static cJSON_bool parse_string(cJSON * const item, parse_buffer * const input_buffer) -{ - const unsigned char *input_pointer = buffer_at_offset(input_buffer) + 1; - const unsigned char *input_end = buffer_at_offset(input_buffer) + 1; - unsigned char *output_pointer = NULL; - unsigned char *output = NULL; - - /* not a string */ - if (buffer_at_offset(input_buffer)[0] != '\"') - { - goto fail; - } - - { - /* calculate approximate size of the output (overestimate) */ - size_t allocation_length = 0; - size_t skipped_bytes = 0; - while (((size_t)(input_end - input_buffer->content) < input_buffer->length) && (*input_end != '\"')) - { - /* is escape sequence */ - if (input_end[0] == '\\') - { - if ((size_t)(input_end + 1 - input_buffer->content) >= input_buffer->length) - { - /* prevent buffer overflow when last input character is a backslash */ - goto fail; - } - skipped_bytes++; - input_end++; - } - input_end++; - } - if (((size_t)(input_end - input_buffer->content) >= input_buffer->length) || (*input_end != '\"')) - { - goto fail; /* string ended unexpectedly */ - } - - /* This is at most how much we need for the output */ - allocation_length = (size_t) (input_end - buffer_at_offset(input_buffer)) - skipped_bytes; - output = (unsigned char*)input_buffer->hooks.allocate(allocation_length + sizeof("")); - if (output == NULL) - { - goto fail; /* allocation failure */ - } - } - - output_pointer = output; - /* loop through the string literal */ - while (input_pointer < input_end) - { - if (*input_pointer != '\\') - { - *output_pointer++ = *input_pointer++; - } - /* escape sequence */ - else - { - unsigned char sequence_length = 2; - if ((input_end - input_pointer) < 1) - { - goto fail; - } - - switch (input_pointer[1]) - { - case 'b': - *output_pointer++ = '\b'; - break; - case 'f': - *output_pointer++ = '\f'; - break; - case 'n': - *output_pointer++ = '\n'; - break; - case 'r': - *output_pointer++ = '\r'; - break; - case 't': - *output_pointer++ = '\t'; - break; - case '\"': - case '\\': - case '/': - *output_pointer++ = input_pointer[1]; - break; - - /* UTF-16 literal */ - case 'u': - sequence_length = utf16_literal_to_utf8(input_pointer, input_end, &output_pointer); - if (sequence_length == 0) - { - /* failed to convert UTF16-literal to UTF-8 */ - goto fail; - } - break; - - default: - goto fail; - } - input_pointer += sequence_length; - } - } - - /* zero terminate the output */ - *output_pointer = '\0'; - - item->type = cJSON_String; - item->valuestring = (char*)output; - - input_buffer->offset = (size_t) (input_end - input_buffer->content); - input_buffer->offset++; - - return true; - -fail: - if (output != NULL) - { - input_buffer->hooks.deallocate(output); - } - - if (input_pointer != NULL) - { - input_buffer->offset = (size_t)(input_pointer - input_buffer->content); - } - - return false; -} - -/* Render the cstring provided to an escaped version that can be printed. */ -static cJSON_bool print_string_ptr(const unsigned char * const input, printbuffer * const output_buffer) -{ - const unsigned char *input_pointer = NULL; - unsigned char *output = NULL; - unsigned char *output_pointer = NULL; - size_t output_length = 0; - /* numbers of additional characters needed for escaping */ - size_t escape_characters = 0; - - if (output_buffer == NULL) - { - return false; - } - - /* empty string */ - if (input == NULL) - { - output = ensure(output_buffer, sizeof("\"\"")); - if (output == NULL) - { - return false; - } - strcpy((char*)output, "\"\""); - - return true; - } - - /* set "flag" to 1 if something needs to be escaped */ - for (input_pointer = input; *input_pointer; input_pointer++) - { - switch (*input_pointer) - { - case '\"': - case '\\': - case '\b': - case '\f': - case '\n': - case '\r': - case '\t': - /* one character escape sequence */ - escape_characters++; - break; - default: - if (*input_pointer < 32) - { - /* UTF-16 escape sequence uXXXX */ - escape_characters += 5; - } - break; - } - } - output_length = (size_t)(input_pointer - input) + escape_characters; - - output = ensure(output_buffer, output_length + sizeof("\"\"")); - if (output == NULL) - { - return false; - } - - /* no characters have to be escaped */ - if (escape_characters == 0) - { - output[0] = '\"'; - memcpy(output + 1, input, output_length); - output[output_length + 1] = '\"'; - output[output_length + 2] = '\0'; - - return true; - } - - output[0] = '\"'; - output_pointer = output + 1; - /* copy the string */ - for (input_pointer = input; *input_pointer != '\0'; (void)input_pointer++, output_pointer++) - { - if ((*input_pointer > 31) && (*input_pointer != '\"') && (*input_pointer != '\\')) - { - /* normal character, copy */ - *output_pointer = *input_pointer; - } - else - { - /* character needs to be escaped */ - *output_pointer++ = '\\'; - switch (*input_pointer) - { - case '\\': - *output_pointer = '\\'; - break; - case '\"': - *output_pointer = '\"'; - break; - case '\b': - *output_pointer = 'b'; - break; - case '\f': - *output_pointer = 'f'; - break; - case '\n': - *output_pointer = 'n'; - break; - case '\r': - *output_pointer = 'r'; - break; - case '\t': - *output_pointer = 't'; - break; - default: - /* escape and print as unicode codepoint */ - sprintf((char*)output_pointer, "u%04x", *input_pointer); - output_pointer += 4; - break; - } - } - } - output[output_length + 1] = '\"'; - output[output_length + 2] = '\0'; - - return true; -} - -/* Invoke print_string_ptr (which is useful) on an item. */ -static cJSON_bool print_string(const cJSON * const item, printbuffer * const p) -{ - return print_string_ptr((unsigned char*)item->valuestring, p); -} - -/* Predeclare these prototypes. */ -static cJSON_bool parse_value(cJSON * const item, parse_buffer * const input_buffer); -static cJSON_bool print_value(const cJSON * const item, printbuffer * const output_buffer); -static cJSON_bool parse_array(cJSON * const item, parse_buffer * const input_buffer); -static cJSON_bool print_array(const cJSON * const item, printbuffer * const output_buffer); -static cJSON_bool parse_object(cJSON * const item, parse_buffer * const input_buffer); -static cJSON_bool print_object(const cJSON * const item, printbuffer * const output_buffer); - -/* Utility to jump whitespace and cr/lf */ -static parse_buffer *buffer_skip_whitespace(parse_buffer * const buffer) -{ - if ((buffer == NULL) || (buffer->content == NULL)) - { - return NULL; - } - - while (can_access_at_index(buffer, 0) && (buffer_at_offset(buffer)[0] <= 32)) - { - buffer->offset++; - } - - if (buffer->offset == buffer->length) - { - buffer->offset--; - } - - return buffer; -} - -/* skip the UTF-8 BOM (byte order mark) if it is at the beginning of a buffer */ -static parse_buffer *skip_utf8_bom(parse_buffer * const buffer) -{ - if ((buffer == NULL) || (buffer->content == NULL) || (buffer->offset != 0)) - { - return NULL; - } - - if (can_access_at_index(buffer, 4) && (strncmp((const char*)buffer_at_offset(buffer), "\xEF\xBB\xBF", 3) == 0)) - { - buffer->offset += 3; - } - - return buffer; -} - -/* Parse an object - create a new root, and populate. */ -CJSON_PUBLIC(cJSON *) cJSON_ParseWithOpts(const char *value, const char **return_parse_end, cJSON_bool require_null_terminated) -{ - parse_buffer buffer = { 0, 0, 0, 0, { 0, 0, 0 } }; - cJSON *item = NULL; - - /* reset error position */ - global_error.json = NULL; - global_error.position = 0; - - if (value == NULL) - { - goto fail; - } - - buffer.content = (const unsigned char*)value; - buffer.length = strlen((const char*)value) + sizeof(""); - buffer.offset = 0; - buffer.hooks = global_hooks; - - item = cJSON_New_Item(&global_hooks); - if (item == NULL) /* memory fail */ - { - goto fail; - } - - if (!parse_value(item, buffer_skip_whitespace(skip_utf8_bom(&buffer)))) - { - /* parse failure. ep is set. */ - goto fail; - } - - /* if we require null-terminated JSON without appended garbage, skip and then check for a null terminator */ - if (require_null_terminated) - { - buffer_skip_whitespace(&buffer); - if ((buffer.offset >= buffer.length) || buffer_at_offset(&buffer)[0] != '\0') - { - goto fail; - } - } - if (return_parse_end) - { - *return_parse_end = (const char*)buffer_at_offset(&buffer); - } - - return item; - -fail: - if (item != NULL) - { - cJSON_Delete(item); - } - - if (value != NULL) - { - error local_error; - local_error.json = (const unsigned char*)value; - local_error.position = 0; - - if (buffer.offset < buffer.length) - { - local_error.position = buffer.offset; - } - else if (buffer.length > 0) - { - local_error.position = buffer.length - 1; - } - - if (return_parse_end != NULL) - { - *return_parse_end = (const char*)local_error.json + local_error.position; - } - - global_error = local_error; - } - - return NULL; -} - -/* Default options for cJSON_Parse */ -CJSON_PUBLIC(cJSON *) cJSON_Parse(const char *value) -{ - return cJSON_ParseWithOpts(value, 0, 0); -} - -#define cjson_min(a, b) ((a < b) ? a : b) - -static unsigned char *print(const cJSON * const item, cJSON_bool format, const internal_hooks * const hooks) -{ - static const size_t default_buffer_size = 256; - printbuffer buffer[1]; - unsigned char *printed = NULL; - - memset(buffer, 0, sizeof(buffer)); - - /* create buffer */ - buffer->buffer = (unsigned char*) hooks->allocate(default_buffer_size); - buffer->length = default_buffer_size; - buffer->format = format; - buffer->hooks = *hooks; - if (buffer->buffer == NULL) - { - goto fail; - } - - /* print the value */ - if (!print_value(item, buffer)) - { - goto fail; - } - update_offset(buffer); - - /* check if reallocate is available */ - if (hooks->reallocate != NULL) - { - printed = (unsigned char*) hooks->reallocate(buffer->buffer, buffer->offset + 1); - if (printed == NULL) { - goto fail; - } - buffer->buffer = NULL; - } - else /* otherwise copy the JSON over to a new buffer */ - { - printed = (unsigned char*) hooks->allocate(buffer->offset + 1); - if (printed == NULL) - { - goto fail; - } - memcpy(printed, buffer->buffer, cjson_min(buffer->length, buffer->offset + 1)); - printed[buffer->offset] = '\0'; /* just to be sure */ - - /* free the buffer */ - hooks->deallocate(buffer->buffer); - } - - return printed; - -fail: - if (buffer->buffer != NULL) - { - hooks->deallocate(buffer->buffer); - } - - if (printed != NULL) - { - hooks->deallocate(printed); - } - - return NULL; -} - -/* Render a cJSON item/entity/structure to text. */ -CJSON_PUBLIC(char *) cJSON_Print(const cJSON *item) -{ - return (char*)print(item, true, &global_hooks); -} - -CJSON_PUBLIC(char *) cJSON_PrintUnformatted(const cJSON *item) -{ - return (char*)print(item, false, &global_hooks); -} - -CJSON_PUBLIC(char *) cJSON_PrintBuffered(const cJSON *item, int prebuffer, cJSON_bool fmt) -{ - printbuffer p = { 0, 0, 0, 0, 0, 0, { 0, 0, 0 } }; - - if (prebuffer < 0) - { - return NULL; - } - - p.buffer = (unsigned char*)global_hooks.allocate((size_t)prebuffer); - if (!p.buffer) - { - return NULL; - } - - p.length = (size_t)prebuffer; - p.offset = 0; - p.noalloc = false; - p.format = fmt; - p.hooks = global_hooks; - - if (!print_value(item, &p)) - { - global_hooks.deallocate(p.buffer); - return NULL; - } - - return (char*)p.buffer; -} - -CJSON_PUBLIC(cJSON_bool) cJSON_PrintPreallocated(cJSON *item, char *buffer, const int length, const cJSON_bool format) -{ - printbuffer p = { 0, 0, 0, 0, 0, 0, { 0, 0, 0 } }; - - if ((length < 0) || (buffer == NULL)) - { - return false; - } - - p.buffer = (unsigned char*)buffer; - p.length = (size_t)length; - p.offset = 0; - p.noalloc = true; - p.format = format; - p.hooks = global_hooks; - - return print_value(item, &p); -} - -/* Parser core - when encountering text, process appropriately. */ -static cJSON_bool parse_value(cJSON * const item, parse_buffer * const input_buffer) -{ - if ((input_buffer == NULL) || (input_buffer->content == NULL)) - { - return false; /* no input */ - } - - /* parse the different types of values */ - /* null */ - if (can_read(input_buffer, 4) && (strncmp((const char*)buffer_at_offset(input_buffer), "null", 4) == 0)) - { - item->type = cJSON_NULL; - input_buffer->offset += 4; - return true; - } - /* false */ - if (can_read(input_buffer, 5) && (strncmp((const char*)buffer_at_offset(input_buffer), "false", 5) == 0)) - { - item->type = cJSON_False; - input_buffer->offset += 5; - return true; - } - /* true */ - if (can_read(input_buffer, 4) && (strncmp((const char*)buffer_at_offset(input_buffer), "true", 4) == 0)) - { - item->type = cJSON_True; - item->valueint = 1; - input_buffer->offset += 4; - return true; - } - /* string */ - if (can_access_at_index(input_buffer, 0) && (buffer_at_offset(input_buffer)[0] == '\"')) - { - return parse_string(item, input_buffer); - } - /* number */ - if (can_access_at_index(input_buffer, 0) && ((buffer_at_offset(input_buffer)[0] == '-') || ((buffer_at_offset(input_buffer)[0] >= '0') && (buffer_at_offset(input_buffer)[0] <= '9')))) - { - return parse_number(item, input_buffer); - } - /* array */ - if (can_access_at_index(input_buffer, 0) && (buffer_at_offset(input_buffer)[0] == '[')) - { - return parse_array(item, input_buffer); - } - /* object */ - if (can_access_at_index(input_buffer, 0) && (buffer_at_offset(input_buffer)[0] == '{')) - { - return parse_object(item, input_buffer); - } - - return false; -} - -/* Render a value to text. */ -static cJSON_bool print_value(const cJSON * const item, printbuffer * const output_buffer) -{ - unsigned char *output = NULL; - - if ((item == NULL) || (output_buffer == NULL)) - { - return false; - } - - switch ((item->type) & 0xFF) - { - case cJSON_NULL: - output = ensure(output_buffer, 5); - if (output == NULL) - { - return false; - } - strcpy((char*)output, "null"); - return true; - - case cJSON_False: - output = ensure(output_buffer, 6); - if (output == NULL) - { - return false; - } - strcpy((char*)output, "false"); - return true; - - case cJSON_True: - output = ensure(output_buffer, 5); - if (output == NULL) - { - return false; - } - strcpy((char*)output, "true"); - return true; - - case cJSON_Number: - return print_number(item, output_buffer); - - case cJSON_Raw: - { - size_t raw_length = 0; - if (item->valuestring == NULL) - { - return false; - } - - raw_length = strlen(item->valuestring) + sizeof(""); - output = ensure(output_buffer, raw_length); - if (output == NULL) - { - return false; - } - memcpy(output, item->valuestring, raw_length); - return true; - } - - case cJSON_String: - return print_string(item, output_buffer); - - case cJSON_Array: - return print_array(item, output_buffer); - - case cJSON_Object: - return print_object(item, output_buffer); - - default: - return false; - } -} - -/* Build an array from input text. */ -static cJSON_bool parse_array(cJSON * const item, parse_buffer * const input_buffer) -{ - cJSON *head = NULL; /* head of the linked list */ - cJSON *current_item = NULL; - - if (input_buffer->depth >= CJSON_NESTING_LIMIT) - { - return false; /* to deeply nested */ - } - input_buffer->depth++; - - if (buffer_at_offset(input_buffer)[0] != '[') - { - /* not an array */ - goto fail; - } - - input_buffer->offset++; - buffer_skip_whitespace(input_buffer); - if (can_access_at_index(input_buffer, 0) && (buffer_at_offset(input_buffer)[0] == ']')) - { - /* empty array */ - goto success; - } - - /* check if we skipped to the end of the buffer */ - if (cannot_access_at_index(input_buffer, 0)) - { - input_buffer->offset--; - goto fail; - } - - /* step back to character in front of the first element */ - input_buffer->offset--; - /* loop through the comma separated array elements */ - do - { - /* allocate next item */ - cJSON *new_item = cJSON_New_Item(&(input_buffer->hooks)); - if (new_item == NULL) - { - goto fail; /* allocation failure */ - } - - /* attach next item to list */ - if (head == NULL) - { - /* start the linked list */ - current_item = head = new_item; - } - else - { - /* add to the end and advance */ - current_item->next = new_item; - new_item->prev = current_item; - current_item = new_item; - } - - /* parse next value */ - input_buffer->offset++; - buffer_skip_whitespace(input_buffer); - if (!parse_value(current_item, input_buffer)) - { - goto fail; /* failed to parse value */ - } - buffer_skip_whitespace(input_buffer); - } - while (can_access_at_index(input_buffer, 0) && (buffer_at_offset(input_buffer)[0] == ',')); - - if (cannot_access_at_index(input_buffer, 0) || buffer_at_offset(input_buffer)[0] != ']') - { - goto fail; /* expected end of array */ - } - -success: - input_buffer->depth--; - - item->type = cJSON_Array; - item->child = head; - - input_buffer->offset++; - - return true; - -fail: - if (head != NULL) - { - cJSON_Delete(head); - } - - return false; -} - -/* Render an array to text */ -static cJSON_bool print_array(const cJSON * const item, printbuffer * const output_buffer) -{ - unsigned char *output_pointer = NULL; - size_t length = 0; - cJSON *current_element = item->child; - - if (output_buffer == NULL) - { - return false; - } - - /* Compose the output array. */ - /* opening square bracket */ - output_pointer = ensure(output_buffer, 1); - if (output_pointer == NULL) - { - return false; - } - - *output_pointer = '['; - output_buffer->offset++; - output_buffer->depth++; - - while (current_element != NULL) - { - if (!print_value(current_element, output_buffer)) - { - return false; - } - update_offset(output_buffer); - if (current_element->next) - { - length = (size_t) (output_buffer->format ? 2 : 1); - output_pointer = ensure(output_buffer, length + 1); - if (output_pointer == NULL) - { - return false; - } - *output_pointer++ = ','; - if(output_buffer->format) - { - *output_pointer++ = ' '; - } - *output_pointer = '\0'; - output_buffer->offset += length; - } - current_element = current_element->next; - } - - output_pointer = ensure(output_buffer, 2); - if (output_pointer == NULL) - { - return false; - } - *output_pointer++ = ']'; - *output_pointer = '\0'; - output_buffer->depth--; - - return true; -} - -/* Build an object from the text. */ -static cJSON_bool parse_object(cJSON * const item, parse_buffer * const input_buffer) -{ - cJSON *head = NULL; /* linked list head */ - cJSON *current_item = NULL; - - if (input_buffer->depth >= CJSON_NESTING_LIMIT) - { - return false; /* to deeply nested */ - } - input_buffer->depth++; - - if (cannot_access_at_index(input_buffer, 0) || (buffer_at_offset(input_buffer)[0] != '{')) - { - goto fail; /* not an object */ - } - - input_buffer->offset++; - buffer_skip_whitespace(input_buffer); - if (can_access_at_index(input_buffer, 0) && (buffer_at_offset(input_buffer)[0] == '}')) - { - goto success; /* empty object */ - } - - /* check if we skipped to the end of the buffer */ - if (cannot_access_at_index(input_buffer, 0)) - { - input_buffer->offset--; - goto fail; - } - - /* step back to character in front of the first element */ - input_buffer->offset--; - /* loop through the comma separated array elements */ - do - { - /* allocate next item */ - cJSON *new_item = cJSON_New_Item(&(input_buffer->hooks)); - if (new_item == NULL) - { - goto fail; /* allocation failure */ - } - - /* attach next item to list */ - if (head == NULL) - { - /* start the linked list */ - current_item = head = new_item; - } - else - { - /* add to the end and advance */ - current_item->next = new_item; - new_item->prev = current_item; - current_item = new_item; - } - - /* parse the name of the child */ - input_buffer->offset++; - buffer_skip_whitespace(input_buffer); - if (!parse_string(current_item, input_buffer)) - { - goto fail; /* failed to parse name */ - } - buffer_skip_whitespace(input_buffer); - - /* swap valuestring and string, because we parsed the name */ - current_item->string = current_item->valuestring; - current_item->valuestring = NULL; - - if (cannot_access_at_index(input_buffer, 0) || (buffer_at_offset(input_buffer)[0] != ':')) - { - goto fail; /* invalid object */ - } - - /* parse the value */ - input_buffer->offset++; - buffer_skip_whitespace(input_buffer); - if (!parse_value(current_item, input_buffer)) - { - goto fail; /* failed to parse value */ - } - buffer_skip_whitespace(input_buffer); - } - while (can_access_at_index(input_buffer, 0) && (buffer_at_offset(input_buffer)[0] == ',')); - - if (cannot_access_at_index(input_buffer, 0) || (buffer_at_offset(input_buffer)[0] != '}')) - { - goto fail; /* expected end of object */ - } - -success: - input_buffer->depth--; - - item->type = cJSON_Object; - item->child = head; - - input_buffer->offset++; - return true; - -fail: - if (head != NULL) - { - cJSON_Delete(head); - } - - return false; -} - -/* Render an object to text. */ -static cJSON_bool print_object(const cJSON * const item, printbuffer * const output_buffer) -{ - unsigned char *output_pointer = NULL; - size_t length = 0; - cJSON *current_item = item->child; - - if (output_buffer == NULL) - { - return false; - } - - /* Compose the output: */ - length = (size_t) (output_buffer->format ? 2 : 1); /* fmt: {\n */ - output_pointer = ensure(output_buffer, length + 1); - if (output_pointer == NULL) - { - return false; - } - - *output_pointer++ = '{'; - output_buffer->depth++; - if (output_buffer->format) - { - *output_pointer++ = '\n'; - } - output_buffer->offset += length; - - while (current_item) - { - if (output_buffer->format) - { - size_t i; - output_pointer = ensure(output_buffer, output_buffer->depth); - if (output_pointer == NULL) - { - return false; - } - for (i = 0; i < output_buffer->depth; i++) - { - *output_pointer++ = '\t'; - } - output_buffer->offset += output_buffer->depth; - } - - /* print key */ - if (!print_string_ptr((unsigned char*)current_item->string, output_buffer)) - { - return false; - } - update_offset(output_buffer); - - length = (size_t) (output_buffer->format ? 2 : 1); - output_pointer = ensure(output_buffer, length); - if (output_pointer == NULL) - { - return false; - } - *output_pointer++ = ':'; - if (output_buffer->format) - { - *output_pointer++ = '\t'; - } - output_buffer->offset += length; - - /* print value */ - if (!print_value(current_item, output_buffer)) - { - return false; - } - update_offset(output_buffer); - - /* print comma if not last */ - length = ((size_t)(output_buffer->format ? 1 : 0) + (size_t)(current_item->next ? 1 : 0)); - output_pointer = ensure(output_buffer, length + 1); - if (output_pointer == NULL) - { - return false; - } - if (current_item->next) - { - *output_pointer++ = ','; - } - - if (output_buffer->format) - { - *output_pointer++ = '\n'; - } - *output_pointer = '\0'; - output_buffer->offset += length; - - current_item = current_item->next; - } - - output_pointer = ensure(output_buffer, output_buffer->format ? (output_buffer->depth + 1) : 2); - if (output_pointer == NULL) - { - return false; - } - if (output_buffer->format) - { - size_t i; - for (i = 0; i < (output_buffer->depth - 1); i++) - { - *output_pointer++ = '\t'; - } - } - *output_pointer++ = '}'; - *output_pointer = '\0'; - output_buffer->depth--; - - return true; -} - -/* Get Array size/item / object item. */ -CJSON_PUBLIC(int) cJSON_GetArraySize(const cJSON *array) -{ - cJSON *child = NULL; - size_t size = 0; - - if (array == NULL) - { - return 0; - } - - child = array->child; - - while(child != NULL) - { - size++; - child = child->next; - } - - /* FIXME: Can overflow here. Cannot be fixed without breaking the API */ - - return (int)size; -} - -static cJSON* get_array_item(const cJSON *array, size_t index) -{ - cJSON *current_child = NULL; - - if (array == NULL) - { - return NULL; - } - - current_child = array->child; - while ((current_child != NULL) && (index > 0)) - { - index--; - current_child = current_child->next; - } - - return current_child; -} - -CJSON_PUBLIC(cJSON *) cJSON_GetArrayItem(const cJSON *array, int index) -{ - if (index < 0) - { - return NULL; - } - - return get_array_item(array, (size_t)index); -} - -static cJSON *get_object_item(const cJSON * const object, const char * const name, const cJSON_bool case_sensitive) -{ - cJSON *current_element = NULL; - - if ((object == NULL) || (name == NULL)) - { - return NULL; - } - - current_element = object->child; - if (case_sensitive) - { - while ((current_element != NULL) && (current_element->string != NULL) && (strcmp(name, current_element->string) != 0)) - { - current_element = current_element->next; - } - } - else - { - while ((current_element != NULL) && (case_insensitive_strcmp((const unsigned char*)name, (const unsigned char*)(current_element->string)) != 0)) - { - current_element = current_element->next; - } - } - - if ((current_element == NULL) || (current_element->string == NULL)) { - return NULL; - } - - return current_element; -} - -CJSON_PUBLIC(cJSON *) cJSON_GetObjectItem(const cJSON * const object, const char * const string) -{ - return get_object_item(object, string, false); -} - -CJSON_PUBLIC(cJSON *) cJSON_GetObjectItemCaseSensitive(const cJSON * const object, const char * const string) -{ - return get_object_item(object, string, true); -} - -CJSON_PUBLIC(cJSON_bool) cJSON_HasObjectItem(const cJSON *object, const char *string) -{ - return cJSON_GetObjectItem(object, string) ? 1 : 0; -} - -/* Utility for array list handling. */ -static void suffix_object(cJSON *prev, cJSON *item) -{ - prev->next = item; - item->prev = prev; -} - -/* Utility for handling references. */ -static cJSON *create_reference(const cJSON *item, const internal_hooks * const hooks) -{ - cJSON *reference = NULL; - if (item == NULL) - { - return NULL; - } - - reference = cJSON_New_Item(hooks); - if (reference == NULL) - { - return NULL; - } - - memcpy(reference, item, sizeof(cJSON)); - reference->string = NULL; - reference->type |= cJSON_IsReference; - reference->next = reference->prev = NULL; - return reference; -} - -static cJSON_bool add_item_to_array(cJSON *array, cJSON *item) -{ - cJSON *child = NULL; - - if ((item == NULL) || (array == NULL)) - { - return false; - } - - child = array->child; - - if (child == NULL) - { - /* list is empty, start new one */ - array->child = item; - } - else - { - /* append to the end */ - while (child->next) - { - child = child->next; - } - suffix_object(child, item); - } - - return true; -} - -/* Add item to array/object. */ -CJSON_PUBLIC(void) cJSON_AddItemToArray(cJSON *array, cJSON *item) -{ - add_item_to_array(array, item); -} - -#if defined(__clang__) || (defined(__GNUC__) && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 5)))) - #pragma GCC diagnostic push -#endif -#ifdef __GNUC__ -#pragma GCC diagnostic ignored "-Wcast-qual" -#endif -/* helper function to cast away const */ -static void* cast_away_const(const void* string) -{ - return (void*)string; -} -#if defined(__clang__) || (defined(__GNUC__) && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 5)))) - #pragma GCC diagnostic pop -#endif - - -static cJSON_bool add_item_to_object(cJSON * const object, const char * const string, cJSON * const item, const internal_hooks * const hooks, const cJSON_bool constant_key) -{ - char *new_key = NULL; - int new_type = cJSON_Invalid; - - if ((object == NULL) || (string == NULL) || (item == NULL)) - { - return false; - } - - if (constant_key) - { - new_key = (char*)cast_away_const(string); - new_type = item->type | cJSON_StringIsConst; - } - else - { - new_key = (char*)cJSON_strdup((const unsigned char*)string, hooks); - if (new_key == NULL) - { - return false; - } - - new_type = item->type & ~cJSON_StringIsConst; - } - - if (!(item->type & cJSON_StringIsConst) && (item->string != NULL)) - { - hooks->deallocate(item->string); - } - - item->string = new_key; - item->type = new_type; - - return add_item_to_array(object, item); -} - -CJSON_PUBLIC(void) cJSON_AddItemToObject(cJSON *object, const char *string, cJSON *item) -{ - add_item_to_object(object, string, item, &global_hooks, false); -} - -/* Add an item to an object with constant string as key */ -CJSON_PUBLIC(void) cJSON_AddItemToObjectCS(cJSON *object, const char *string, cJSON *item) -{ - add_item_to_object(object, string, item, &global_hooks, true); -} - -CJSON_PUBLIC(void) cJSON_AddItemReferenceToArray(cJSON *array, cJSON *item) -{ - if (array == NULL) - { - return; - } - - add_item_to_array(array, create_reference(item, &global_hooks)); -} - -CJSON_PUBLIC(void) cJSON_AddItemReferenceToObject(cJSON *object, const char *string, cJSON *item) -{ - if ((object == NULL) || (string == NULL)) - { - return; - } - - add_item_to_object(object, string, create_reference(item, &global_hooks), &global_hooks, false); -} - -CJSON_PUBLIC(cJSON*) cJSON_AddNullToObject(cJSON * const object, const char * const name) -{ - cJSON *null = cJSON_CreateNull(); - if (add_item_to_object(object, name, null, &global_hooks, false)) - { - return null; - } - - cJSON_Delete(null); - return NULL; -} - -CJSON_PUBLIC(cJSON*) cJSON_AddTrueToObject(cJSON * const object, const char * const name) -{ - cJSON *true_item = cJSON_CreateTrue(); - if (add_item_to_object(object, name, true_item, &global_hooks, false)) - { - return true_item; - } - - cJSON_Delete(true_item); - return NULL; -} - -CJSON_PUBLIC(cJSON*) cJSON_AddFalseToObject(cJSON * const object, const char * const name) -{ - cJSON *false_item = cJSON_CreateFalse(); - if (add_item_to_object(object, name, false_item, &global_hooks, false)) - { - return false_item; - } - - cJSON_Delete(false_item); - return NULL; -} - -CJSON_PUBLIC(cJSON*) cJSON_AddBoolToObject(cJSON * const object, const char * const name, const cJSON_bool boolean) -{ - cJSON *bool_item = cJSON_CreateBool(boolean); - if (add_item_to_object(object, name, bool_item, &global_hooks, false)) - { - return bool_item; - } - - cJSON_Delete(bool_item); - return NULL; -} - -CJSON_PUBLIC(cJSON*) cJSON_AddNumberToObject(cJSON * const object, const char * const name, const double number) -{ - cJSON *number_item = cJSON_CreateNumber(number); - if (add_item_to_object(object, name, number_item, &global_hooks, false)) - { - return number_item; - } - - cJSON_Delete(number_item); - return NULL; -} - -CJSON_PUBLIC(cJSON*) cJSON_AddStringToObject(cJSON * const object, const char * const name, const char * const string) -{ - cJSON *string_item = cJSON_CreateString(string); - if (add_item_to_object(object, name, string_item, &global_hooks, false)) - { - return string_item; - } - - cJSON_Delete(string_item); - return NULL; -} - -CJSON_PUBLIC(cJSON*) cJSON_AddRawToObject(cJSON * const object, const char * const name, const char * const raw) -{ - cJSON *raw_item = cJSON_CreateRaw(raw); - if (add_item_to_object(object, name, raw_item, &global_hooks, false)) - { - return raw_item; - } - - cJSON_Delete(raw_item); - return NULL; -} - -CJSON_PUBLIC(cJSON*) cJSON_AddObjectToObject(cJSON * const object, const char * const name) -{ - cJSON *object_item = cJSON_CreateObject(); - if (add_item_to_object(object, name, object_item, &global_hooks, false)) - { - return object_item; - } - - cJSON_Delete(object_item); - return NULL; -} - -CJSON_PUBLIC(cJSON*) cJSON_AddArrayToObject(cJSON * const object, const char * const name) -{ - cJSON *array = cJSON_CreateArray(); - if (add_item_to_object(object, name, array, &global_hooks, false)) - { - return array; - } - - cJSON_Delete(array); - return NULL; -} - -CJSON_PUBLIC(cJSON *) cJSON_DetachItemViaPointer(cJSON *parent, cJSON * const item) -{ - if ((parent == NULL) || (item == NULL)) - { - return NULL; - } - - if (item->prev != NULL) - { - /* not the first element */ - item->prev->next = item->next; - } - if (item->next != NULL) - { - /* not the last element */ - item->next->prev = item->prev; - } - - if (item == parent->child) - { - /* first element */ - parent->child = item->next; - } - /* make sure the detached item doesn't point anywhere anymore */ - item->prev = NULL; - item->next = NULL; - - return item; -} - -CJSON_PUBLIC(cJSON *) cJSON_DetachItemFromArray(cJSON *array, int which) -{ - if (which < 0) - { - return NULL; - } - - return cJSON_DetachItemViaPointer(array, get_array_item(array, (size_t)which)); -} - -CJSON_PUBLIC(void) cJSON_DeleteItemFromArray(cJSON *array, int which) -{ - cJSON_Delete(cJSON_DetachItemFromArray(array, which)); -} - -CJSON_PUBLIC(cJSON *) cJSON_DetachItemFromObject(cJSON *object, const char *string) -{ - cJSON *to_detach = cJSON_GetObjectItem(object, string); - - return cJSON_DetachItemViaPointer(object, to_detach); -} - -CJSON_PUBLIC(cJSON *) cJSON_DetachItemFromObjectCaseSensitive(cJSON *object, const char *string) -{ - cJSON *to_detach = cJSON_GetObjectItemCaseSensitive(object, string); - - return cJSON_DetachItemViaPointer(object, to_detach); -} - -CJSON_PUBLIC(void) cJSON_DeleteItemFromObject(cJSON *object, const char *string) -{ - cJSON_Delete(cJSON_DetachItemFromObject(object, string)); -} - -CJSON_PUBLIC(void) cJSON_DeleteItemFromObjectCaseSensitive(cJSON *object, const char *string) -{ - cJSON_Delete(cJSON_DetachItemFromObjectCaseSensitive(object, string)); -} - -/* Replace array/object items with new ones. */ -CJSON_PUBLIC(void) cJSON_InsertItemInArray(cJSON *array, int which, cJSON *newitem) -{ - cJSON *after_inserted = NULL; - - if (which < 0) - { - return; - } - - after_inserted = get_array_item(array, (size_t)which); - if (after_inserted == NULL) - { - add_item_to_array(array, newitem); - return; - } - - newitem->next = after_inserted; - newitem->prev = after_inserted->prev; - after_inserted->prev = newitem; - if (after_inserted == array->child) - { - array->child = newitem; - } - else - { - newitem->prev->next = newitem; - } -} - -CJSON_PUBLIC(cJSON_bool) cJSON_ReplaceItemViaPointer(cJSON * const parent, cJSON * const item, cJSON * replacement) -{ - if ((parent == NULL) || (replacement == NULL) || (item == NULL)) - { - return false; - } - - if (replacement == item) - { - return true; - } - - replacement->next = item->next; - replacement->prev = item->prev; - - if (replacement->next != NULL) - { - replacement->next->prev = replacement; - } - if (replacement->prev != NULL) - { - replacement->prev->next = replacement; - } - if (parent->child == item) - { - parent->child = replacement; - } - - item->next = NULL; - item->prev = NULL; - cJSON_Delete(item); - - return true; -} - -CJSON_PUBLIC(void) cJSON_ReplaceItemInArray(cJSON *array, int which, cJSON *newitem) -{ - if (which < 0) - { - return; - } - - cJSON_ReplaceItemViaPointer(array, get_array_item(array, (size_t)which), newitem); -} - -static cJSON_bool replace_item_in_object(cJSON *object, const char *string, cJSON *replacement, cJSON_bool case_sensitive) -{ - if ((replacement == NULL) || (string == NULL)) - { - return false; - } - - /* replace the name in the replacement */ - if (!(replacement->type & cJSON_StringIsConst) && (replacement->string != NULL)) - { - cJSON_free(replacement->string); - } - replacement->string = (char*)cJSON_strdup((const unsigned char*)string, &global_hooks); - replacement->type &= ~cJSON_StringIsConst; - - cJSON_ReplaceItemViaPointer(object, get_object_item(object, string, case_sensitive), replacement); - - return true; -} - -CJSON_PUBLIC(void) cJSON_ReplaceItemInObject(cJSON *object, const char *string, cJSON *newitem) -{ - replace_item_in_object(object, string, newitem, false); -} - -CJSON_PUBLIC(void) cJSON_ReplaceItemInObjectCaseSensitive(cJSON *object, const char *string, cJSON *newitem) -{ - replace_item_in_object(object, string, newitem, true); -} - -/* Create basic types: */ -CJSON_PUBLIC(cJSON *) cJSON_CreateNull(void) -{ - cJSON *item = cJSON_New_Item(&global_hooks); - if(item) - { - item->type = cJSON_NULL; - } - - return item; -} - -CJSON_PUBLIC(cJSON *) cJSON_CreateTrue(void) -{ - cJSON *item = cJSON_New_Item(&global_hooks); - if(item) - { - item->type = cJSON_True; - } - - return item; -} - -CJSON_PUBLIC(cJSON *) cJSON_CreateFalse(void) -{ - cJSON *item = cJSON_New_Item(&global_hooks); - if(item) - { - item->type = cJSON_False; - } - - return item; -} - -CJSON_PUBLIC(cJSON *) cJSON_CreateBool(cJSON_bool boolean) -{ - cJSON *item = cJSON_New_Item(&global_hooks); - if(item) - { - item->type = boolean ? cJSON_True : cJSON_False; - } - - return item; -} - -CJSON_PUBLIC(cJSON *) cJSON_CreateNumber(double num) -{ - cJSON *item = cJSON_New_Item(&global_hooks); - if(item) - { - item->type = cJSON_Number; - item->valuedouble = num; - - /* use saturation in case of overflow */ - if (num >= INT_MAX) - { - item->valueint = INT_MAX; - } - else if (num <= (double)INT_MIN) - { - item->valueint = INT_MIN; - } - else - { - item->valueint = (int)num; - } - } - - return item; -} - -CJSON_PUBLIC(cJSON *) cJSON_CreateString(const char *string) -{ - cJSON *item = cJSON_New_Item(&global_hooks); - if(item) - { - item->type = cJSON_String; - item->valuestring = (char*)cJSON_strdup((const unsigned char*)string, &global_hooks); - if(!item->valuestring) - { - cJSON_Delete(item); - return NULL; - } - } - - return item; -} - -CJSON_PUBLIC(cJSON *) cJSON_CreateStringReference(const char *string) -{ - cJSON *item = cJSON_New_Item(&global_hooks); - if (item != NULL) - { - item->type = cJSON_String | cJSON_IsReference; - item->valuestring = (char*)cast_away_const(string); - } - - return item; -} - -CJSON_PUBLIC(cJSON *) cJSON_CreateObjectReference(const cJSON *child) -{ - cJSON *item = cJSON_New_Item(&global_hooks); - if (item != NULL) { - item->type = cJSON_Object | cJSON_IsReference; - item->child = (cJSON*)cast_away_const(child); - } - - return item; -} - -CJSON_PUBLIC(cJSON *) cJSON_CreateArrayReference(const cJSON *child) { - cJSON *item = cJSON_New_Item(&global_hooks); - if (item != NULL) { - item->type = cJSON_Array | cJSON_IsReference; - item->child = (cJSON*)cast_away_const(child); - } - - return item; -} - -CJSON_PUBLIC(cJSON *) cJSON_CreateRaw(const char *raw) -{ - cJSON *item = cJSON_New_Item(&global_hooks); - if(item) - { - item->type = cJSON_Raw; - item->valuestring = (char*)cJSON_strdup((const unsigned char*)raw, &global_hooks); - if(!item->valuestring) - { - cJSON_Delete(item); - return NULL; - } - } - - return item; -} - -CJSON_PUBLIC(cJSON *) cJSON_CreateArray(void) -{ - cJSON *item = cJSON_New_Item(&global_hooks); - if(item) - { - item->type=cJSON_Array; - } - - return item; -} - -CJSON_PUBLIC(cJSON *) cJSON_CreateObject(void) -{ - cJSON *item = cJSON_New_Item(&global_hooks); - if (item) - { - item->type = cJSON_Object; - } - - return item; -} - -/* Create Arrays: */ -CJSON_PUBLIC(cJSON *) cJSON_CreateIntArray(const int *numbers, int count) -{ - size_t i = 0; - cJSON *n = NULL; - cJSON *p = NULL; - cJSON *a = NULL; - - if ((count < 0) || (numbers == NULL)) - { - return NULL; - } - - a = cJSON_CreateArray(); - for(i = 0; a && (i < (size_t)count); i++) - { - n = cJSON_CreateNumber(numbers[i]); - if (!n) - { - cJSON_Delete(a); - return NULL; - } - if(!i) - { - a->child = n; - } - else - { - suffix_object(p, n); - } - p = n; - } - - return a; -} - -CJSON_PUBLIC(cJSON *) cJSON_CreateFloatArray(const float *numbers, int count) -{ - size_t i = 0; - cJSON *n = NULL; - cJSON *p = NULL; - cJSON *a = NULL; - - if ((count < 0) || (numbers == NULL)) - { - return NULL; - } - - a = cJSON_CreateArray(); - - for(i = 0; a && (i < (size_t)count); i++) - { - n = cJSON_CreateNumber((double)numbers[i]); - if(!n) - { - cJSON_Delete(a); - return NULL; - } - if(!i) - { - a->child = n; - } - else - { - suffix_object(p, n); - } - p = n; - } - - return a; -} - -CJSON_PUBLIC(cJSON *) cJSON_CreateDoubleArray(const double *numbers, int count) -{ - size_t i = 0; - cJSON *n = NULL; - cJSON *p = NULL; - cJSON *a = NULL; - - if ((count < 0) || (numbers == NULL)) - { - return NULL; - } - - a = cJSON_CreateArray(); - - for(i = 0;a && (i < (size_t)count); i++) - { - n = cJSON_CreateNumber(numbers[i]); - if(!n) - { - cJSON_Delete(a); - return NULL; - } - if(!i) - { - a->child = n; - } - else - { - suffix_object(p, n); - } - p = n; - } - - return a; -} - -CJSON_PUBLIC(cJSON *) cJSON_CreateStringArray(const char *const *strings, int count) -{ - size_t i = 0; - cJSON *n = NULL; - cJSON *p = NULL; - cJSON *a = NULL; - - if ((count < 0) || (strings == NULL)) - { - return NULL; - } - - a = cJSON_CreateArray(); - - for (i = 0; a && (i < (size_t)count); i++) - { - n = cJSON_CreateString(strings[i]); - if(!n) - { - cJSON_Delete(a); - return NULL; - } - if(!i) - { - a->child = n; - } - else - { - suffix_object(p,n); - } - p = n; - } - - return a; -} - -/* Duplication */ -CJSON_PUBLIC(cJSON *) cJSON_Duplicate(const cJSON *item, cJSON_bool recurse) -{ - cJSON *newitem = NULL; - cJSON *child = NULL; - cJSON *next = NULL; - cJSON *newchild = NULL; - - /* Bail on bad ptr */ - if (!item) - { - goto fail; - } - /* Create new item */ - newitem = cJSON_New_Item(&global_hooks); - if (!newitem) - { - goto fail; - } - /* Copy over all vars */ - newitem->type = item->type & (~cJSON_IsReference); - newitem->valueint = item->valueint; - newitem->valuedouble = item->valuedouble; - if (item->valuestring) - { - newitem->valuestring = (char*)cJSON_strdup((unsigned char*)item->valuestring, &global_hooks); - if (!newitem->valuestring) - { - goto fail; - } - } - if (item->string) - { - newitem->string = (item->type&cJSON_StringIsConst) ? item->string : (char*)cJSON_strdup((unsigned char*)item->string, &global_hooks); - if (!newitem->string) - { - goto fail; - } - } - /* If non-recursive, then we're done! */ - if (!recurse) - { - return newitem; - } - /* Walk the ->next chain for the child. */ - child = item->child; - while (child != NULL) - { - newchild = cJSON_Duplicate(child, true); /* Duplicate (with recurse) each item in the ->next chain */ - if (!newchild) - { - goto fail; - } - if (next != NULL) - { - /* If newitem->child already set, then crosswire ->prev and ->next and move on */ - next->next = newchild; - newchild->prev = next; - next = newchild; - } - else - { - /* Set newitem->child and move to it */ - newitem->child = newchild; - next = newchild; - } - child = child->next; - } - - return newitem; - -fail: - if (newitem != NULL) - { - cJSON_Delete(newitem); - } - - return NULL; -} - -static void skip_oneline_comment(char **input) -{ - *input += static_strlen("//"); - - for (; (*input)[0] != '\0'; ++(*input)) - { - if ((*input)[0] == '\n') { - *input += static_strlen("\n"); - return; - } - } -} - -static void skip_multiline_comment(char **input) -{ - *input += static_strlen("/*"); - - for (; (*input)[0] != '\0'; ++(*input)) - { - if (((*input)[0] == '*') && ((*input)[1] == '/')) - { - *input += static_strlen("*/"); - return; - } - } -} - -static void minify_string(char **input, char **output) { - (*output)[0] = (*input)[0]; - *input += static_strlen("\""); - *output += static_strlen("\""); - - - for (; (*input)[0] != '\0'; (void)++(*input), ++(*output)) { - (*output)[0] = (*input)[0]; - - if ((*input)[0] == '\"') { - (*output)[0] = '\"'; - *input += static_strlen("\""); - *output += static_strlen("\""); - return; - } else if (((*input)[0] == '\\') && ((*input)[1] == '\"')) { - (*output)[1] = (*input)[1]; - *input += static_strlen("\""); - *output += static_strlen("\""); - } - } -} - -CJSON_PUBLIC(void) cJSON_Minify(char *json) -{ - char *into = json; - - if (json == NULL) - { - return; - } - - while (json[0] != '\0') - { - switch (json[0]) - { - case ' ': - case '\t': - case '\r': - case '\n': - json++; - break; - - case '/': - if (json[1] == '/') - { - skip_oneline_comment(&json); - } - else if (json[1] == '*') - { - skip_multiline_comment(&json); - } else { - json++; - } - break; - - case '\"': - minify_string(&json, (char**)&into); - break; - - default: - into[0] = json[0]; - json++; - into++; - } - } - - /* and null-terminate. */ - *into = '\0'; -} - -CJSON_PUBLIC(cJSON_bool) cJSON_IsInvalid(const cJSON * const item) -{ - if (item == NULL) - { - return false; - } - - return (item->type & 0xFF) == cJSON_Invalid; -} - -CJSON_PUBLIC(cJSON_bool) cJSON_IsFalse(const cJSON * const item) -{ - if (item == NULL) - { - return false; - } - - return (item->type & 0xFF) == cJSON_False; -} - -CJSON_PUBLIC(cJSON_bool) cJSON_IsTrue(const cJSON * const item) -{ - if (item == NULL) - { - return false; - } - - return (item->type & 0xff) == cJSON_True; -} - - -CJSON_PUBLIC(cJSON_bool) cJSON_IsBool(const cJSON * const item) -{ - if (item == NULL) - { - return false; - } - - return (item->type & (cJSON_True | cJSON_False)) != 0; -} -CJSON_PUBLIC(cJSON_bool) cJSON_IsNull(const cJSON * const item) -{ - if (item == NULL) - { - return false; - } - - return (item->type & 0xFF) == cJSON_NULL; -} - -CJSON_PUBLIC(cJSON_bool) cJSON_IsNumber(const cJSON * const item) -{ - if (item == NULL) - { - return false; - } - - return (item->type & 0xFF) == cJSON_Number; -} - -CJSON_PUBLIC(cJSON_bool) cJSON_IsString(const cJSON * const item) -{ - if (item == NULL) - { - return false; - } - - return (item->type & 0xFF) == cJSON_String; -} - -CJSON_PUBLIC(cJSON_bool) cJSON_IsArray(const cJSON * const item) -{ - if (item == NULL) - { - return false; - } - - return (item->type & 0xFF) == cJSON_Array; -} - -CJSON_PUBLIC(cJSON_bool) cJSON_IsObject(const cJSON * const item) -{ - if (item == NULL) - { - return false; - } - - return (item->type & 0xFF) == cJSON_Object; -} - -CJSON_PUBLIC(cJSON_bool) cJSON_IsRaw(const cJSON * const item) -{ - if (item == NULL) - { - return false; - } - - return (item->type & 0xFF) == cJSON_Raw; -} - -CJSON_PUBLIC(cJSON_bool) cJSON_Compare(const cJSON * const a, const cJSON * const b, const cJSON_bool case_sensitive) -{ - if ((a == NULL) || (b == NULL) || ((a->type & 0xFF) != (b->type & 0xFF)) || cJSON_IsInvalid(a)) - { - return false; - } - - /* check if type is valid */ - switch (a->type & 0xFF) - { - case cJSON_False: - case cJSON_True: - case cJSON_NULL: - case cJSON_Number: - case cJSON_String: - case cJSON_Raw: - case cJSON_Array: - case cJSON_Object: - break; - - default: - return false; - } - - /* identical objects are equal */ - if (a == b) - { - return true; - } - - switch (a->type & 0xFF) - { - /* in these cases and equal type is enough */ - case cJSON_False: - case cJSON_True: - case cJSON_NULL: - return true; - - case cJSON_Number: - if (compare_double(a->valuedouble, b->valuedouble)) - { - return true; - } - return false; - - case cJSON_String: - case cJSON_Raw: - if ((a->valuestring == NULL) || (b->valuestring == NULL)) - { - return false; - } - if (strcmp(a->valuestring, b->valuestring) == 0) - { - return true; - } - - return false; - - case cJSON_Array: - { - cJSON *a_element = a->child; - cJSON *b_element = b->child; - - for (; (a_element != NULL) && (b_element != NULL);) - { - if (!cJSON_Compare(a_element, b_element, case_sensitive)) - { - return false; - } - - a_element = a_element->next; - b_element = b_element->next; - } - - /* one of the arrays is longer than the other */ - if (a_element != b_element) { - return false; - } - - return true; - } - - case cJSON_Object: - { - cJSON *a_element = NULL; - cJSON *b_element = NULL; - cJSON_ArrayForEach(a_element, a) - { - /* TODO This has O(n^2) runtime, which is horrible! */ - b_element = get_object_item(b, a_element->string, case_sensitive); - if (b_element == NULL) - { - return false; - } - - if (!cJSON_Compare(a_element, b_element, case_sensitive)) - { - return false; - } - } - - /* doing this twice, once on a and b to prevent true comparison if a subset of b - * TODO: Do this the proper way, this is just a fix for now */ - cJSON_ArrayForEach(b_element, b) - { - a_element = get_object_item(a, b_element->string, case_sensitive); - if (a_element == NULL) - { - return false; - } - - if (!cJSON_Compare(b_element, a_element, case_sensitive)) - { - return false; - } - } - - return true; - } - - default: - return false; - } -} - -CJSON_PUBLIC(void *) cJSON_malloc(size_t size) -{ - return global_hooks.allocate(size); -} - -CJSON_PUBLIC(void) cJSON_free(void *object) -{ - global_hooks.deallocate(object); -} diff --git a/src/cJSON.h b/src/cJSON.h deleted file mode 100644 index e96b8cf..0000000 --- a/src/cJSON.h +++ /dev/null @@ -1,293 +0,0 @@ -/* - 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 - -/* cJSON Types: */ -#define cJSON_Invalid (0) -#define cJSON_False (1 << 0) -#define cJSON_True (1 << 1) -#define cJSON_NULL (1 << 2) -#define cJSON_Number (1 << 3) -#define cJSON_String (1 << 4) -#define cJSON_Array (1 << 5) -#define cJSON_Object (1 << 6) -#define cJSON_Raw (1 << 7) /* raw json */ - -#define cJSON_IsReference 256 -#define cJSON_StringIsConst 512 - -/* The cJSON structure: */ -typedef struct cJSON -{ - /* next/prev allow you to walk array/object chains. Alternatively, use GetArraySize/GetArrayItem/GetObjectItem */ - struct cJSON *next; - struct cJSON *prev; - /* An array or object item will have a child pointer pointing to a chain of the items in the array/object. */ - struct cJSON *child; - - /* The type of the item, as above. */ - int type; - - /* The item's string, if type==cJSON_String and type == cJSON_Raw */ - char *valuestring; - /* writing to valueint is DEPRECATED, use cJSON_SetNumberValue instead */ - int valueint; - /* The item's number, if type==cJSON_Number */ - double valuedouble; - - /* The item's name string, if this item is the child of, or is in the list of subitems of an object. */ - char *string; -} cJSON; - -typedef struct cJSON_Hooks -{ - /* malloc/free are CDECL on Windows regardless of the default calling convention of the compiler, so ensure the hooks allow passing those functions directly. */ - void *(CJSON_CDECL *malloc_fn)(size_t sz); - void (CJSON_CDECL *free_fn)(void *ptr); -} cJSON_Hooks; - -typedef int cJSON_bool; - -/* Limits how deeply nested arrays/objects can be before cJSON rejects to parse them. - * This is to prevent stack overflows. */ -#ifndef CJSON_NESTING_LIMIT -#define CJSON_NESTING_LIMIT 1000 -#endif - -/* Precision of double variables comparison */ -#ifndef CJSON_DOUBLE_PRECISION -#define CJSON_DOUBLE_PRECISION .0000000000000001 -#endif - -/* returns the version of cJSON as a string */ -CJSON_PUBLIC(const char*) cJSON_Version(void); - -/* Supply malloc, realloc and free functions to cJSON */ -CJSON_PUBLIC(void) cJSON_InitHooks(cJSON_Hooks* hooks); - -/* Memory Management: the caller is always responsible to free the results from all variants of cJSON_Parse (with cJSON_Delete) and cJSON_Print (with stdlib free, cJSON_Hooks.free_fn, or cJSON_free as appropriate). The exception is cJSON_PrintPreallocated, where the caller has full responsibility of the buffer. */ -/* Supply a block of JSON, and this returns a cJSON object you can interrogate. */ -CJSON_PUBLIC(cJSON *) cJSON_Parse(const char *value); -/* ParseWithOpts allows you to require (and check) that the JSON is null terminated, and to retrieve the pointer to the final byte parsed. */ -/* If you supply a ptr in return_parse_end and parsing fails, then return_parse_end will contain a pointer to the error so will match cJSON_GetErrorPtr(). */ -CJSON_PUBLIC(cJSON *) cJSON_ParseWithOpts(const char *value, const char **return_parse_end, cJSON_bool require_null_terminated); - -/* Render a cJSON entity to text for transfer/storage. */ -CJSON_PUBLIC(char *) cJSON_Print(const cJSON *item); -/* Render a cJSON entity to text for transfer/storage without any formatting. */ -CJSON_PUBLIC(char *) cJSON_PrintUnformatted(const cJSON *item); -/* Render a cJSON entity to text using a buffered strategy. prebuffer is a guess at the final size. guessing well reduces reallocation. fmt=0 gives unformatted, =1 gives formatted */ -CJSON_PUBLIC(char *) cJSON_PrintBuffered(const cJSON *item, int prebuffer, cJSON_bool fmt); -/* Render a cJSON entity to text using a buffer already allocated in memory with given length. Returns 1 on success and 0 on failure. */ -/* NOTE: cJSON is not always 100% accurate in estimating how much memory it will use, so to be safe allocate 5 bytes more than you actually need */ -CJSON_PUBLIC(cJSON_bool) cJSON_PrintPreallocated(cJSON *item, char *buffer, const int length, const cJSON_bool format); -/* Delete a cJSON entity and all subentities. */ -CJSON_PUBLIC(void) cJSON_Delete(cJSON *item); - -/* Returns the number of items in an array (or object). */ -CJSON_PUBLIC(int) cJSON_GetArraySize(const cJSON *array); -/* Retrieve item number "index" from array "array". Returns NULL if unsuccessful. */ -CJSON_PUBLIC(cJSON *) cJSON_GetArrayItem(const cJSON *array, int index); -/* Get item "string" from object. Case insensitive. */ -CJSON_PUBLIC(cJSON *) cJSON_GetObjectItem(const cJSON * const object, const char * const string); -CJSON_PUBLIC(cJSON *) cJSON_GetObjectItemCaseSensitive(const cJSON * const object, const char * const string); -CJSON_PUBLIC(cJSON_bool) cJSON_HasObjectItem(const cJSON *object, const char *string); -/* For analysing failed parses. This returns a pointer to the parse error. You'll probably need to look a few chars back to make sense of it. Defined when cJSON_Parse() returns 0. 0 when cJSON_Parse() succeeds. */ -CJSON_PUBLIC(const char *) cJSON_GetErrorPtr(void); - -/* Check if the item is a string and return its valuestring */ -CJSON_PUBLIC(char *) cJSON_GetStringValue(const cJSON * const item); - -/* These functions check the type of an item */ -CJSON_PUBLIC(cJSON_bool) cJSON_IsInvalid(const cJSON * const item); -CJSON_PUBLIC(cJSON_bool) cJSON_IsFalse(const cJSON * const item); -CJSON_PUBLIC(cJSON_bool) cJSON_IsTrue(const cJSON * const item); -CJSON_PUBLIC(cJSON_bool) cJSON_IsBool(const cJSON * const item); -CJSON_PUBLIC(cJSON_bool) cJSON_IsNull(const cJSON * const item); -CJSON_PUBLIC(cJSON_bool) cJSON_IsNumber(const cJSON * const item); -CJSON_PUBLIC(cJSON_bool) cJSON_IsString(const cJSON * const item); -CJSON_PUBLIC(cJSON_bool) cJSON_IsArray(const cJSON * const item); -CJSON_PUBLIC(cJSON_bool) cJSON_IsObject(const cJSON * const item); -CJSON_PUBLIC(cJSON_bool) cJSON_IsRaw(const cJSON * const item); - -/* These calls create a cJSON item of the appropriate type. */ -CJSON_PUBLIC(cJSON *) cJSON_CreateNull(void); -CJSON_PUBLIC(cJSON *) cJSON_CreateTrue(void); -CJSON_PUBLIC(cJSON *) cJSON_CreateFalse(void); -CJSON_PUBLIC(cJSON *) cJSON_CreateBool(cJSON_bool boolean); -CJSON_PUBLIC(cJSON *) cJSON_CreateNumber(double num); -CJSON_PUBLIC(cJSON *) cJSON_CreateString(const char *string); -/* raw json */ -CJSON_PUBLIC(cJSON *) cJSON_CreateRaw(const char *raw); -CJSON_PUBLIC(cJSON *) cJSON_CreateArray(void); -CJSON_PUBLIC(cJSON *) cJSON_CreateObject(void); - -/* Create a string where valuestring references a string so - * it will not be freed by cJSON_Delete */ -CJSON_PUBLIC(cJSON *) cJSON_CreateStringReference(const char *string); -/* Create an object/array that only references it's elements so - * they will not be freed by cJSON_Delete */ -CJSON_PUBLIC(cJSON *) cJSON_CreateObjectReference(const cJSON *child); -CJSON_PUBLIC(cJSON *) cJSON_CreateArrayReference(const cJSON *child); - -/* These utilities create an Array of count items. - * The parameter count cannot be greater than the number of elements in the number array, otherwise array access will be out of bounds.*/ -CJSON_PUBLIC(cJSON *) cJSON_CreateIntArray(const int *numbers, int count); -CJSON_PUBLIC(cJSON *) cJSON_CreateFloatArray(const float *numbers, int count); -CJSON_PUBLIC(cJSON *) cJSON_CreateDoubleArray(const double *numbers, int count); -CJSON_PUBLIC(cJSON *) cJSON_CreateStringArray(const char *const *strings, int count); - -/* Append item to the specified array/object. */ -CJSON_PUBLIC(void) cJSON_AddItemToArray(cJSON *array, cJSON *item); -CJSON_PUBLIC(void) cJSON_AddItemToObject(cJSON *object, const char *string, cJSON *item); -/* Use this when string is definitely const (i.e. a literal, or as good as), and will definitely survive the cJSON object. - * WARNING: When this function was used, make sure to always check that (item->type & cJSON_StringIsConst) is zero before - * writing to `item->string` */ -CJSON_PUBLIC(void) cJSON_AddItemToObjectCS(cJSON *object, const char *string, cJSON *item); -/* Append reference to item to the specified array/object. Use this when you want to add an existing cJSON to a new cJSON, but don't want to corrupt your existing cJSON. */ -CJSON_PUBLIC(void) cJSON_AddItemReferenceToArray(cJSON *array, cJSON *item); -CJSON_PUBLIC(void) cJSON_AddItemReferenceToObject(cJSON *object, const char *string, cJSON *item); - -/* Remove/Detach items from Arrays/Objects. */ -CJSON_PUBLIC(cJSON *) cJSON_DetachItemViaPointer(cJSON *parent, cJSON * const item); -CJSON_PUBLIC(cJSON *) cJSON_DetachItemFromArray(cJSON *array, int which); -CJSON_PUBLIC(void) cJSON_DeleteItemFromArray(cJSON *array, int which); -CJSON_PUBLIC(cJSON *) cJSON_DetachItemFromObject(cJSON *object, const char *string); -CJSON_PUBLIC(cJSON *) cJSON_DetachItemFromObjectCaseSensitive(cJSON *object, const char *string); -CJSON_PUBLIC(void) cJSON_DeleteItemFromObject(cJSON *object, const char *string); -CJSON_PUBLIC(void) cJSON_DeleteItemFromObjectCaseSensitive(cJSON *object, const char *string); - -/* Update array items. */ -CJSON_PUBLIC(void) cJSON_InsertItemInArray(cJSON *array, int which, cJSON *newitem); /* Shifts pre-existing items to the right. */ -CJSON_PUBLIC(cJSON_bool) cJSON_ReplaceItemViaPointer(cJSON * const parent, cJSON * const item, cJSON * replacement); -CJSON_PUBLIC(void) cJSON_ReplaceItemInArray(cJSON *array, int which, cJSON *newitem); -CJSON_PUBLIC(void) cJSON_ReplaceItemInObject(cJSON *object,const char *string,cJSON *newitem); -CJSON_PUBLIC(void) cJSON_ReplaceItemInObjectCaseSensitive(cJSON *object,const char *string,cJSON *newitem); - -/* Duplicate a cJSON item */ -CJSON_PUBLIC(cJSON *) cJSON_Duplicate(const cJSON *item, cJSON_bool recurse); -/* Duplicate will create a new, identical cJSON item to the one you pass, in new memory that will - * need to be released. With recurse!=0, it will duplicate any children connected to the item. - * The item->next and ->prev pointers are always zero on return from Duplicate. */ -/* Recursively compare two cJSON items for equality. If either a or b is NULL or invalid, they will be considered unequal. - * case_sensitive determines if object keys are treated case sensitive (1) or case insensitive (0) */ -CJSON_PUBLIC(cJSON_bool) cJSON_Compare(const cJSON * const a, const cJSON * const b, const cJSON_bool case_sensitive); - -/* Minify a strings, remove blank characters(such as ' ', '\t', '\r', '\n') from strings. - * The input pointer json cannot point to a read-only address area, such as a string constant, - * but should point to a readable and writable adress area. */ -CJSON_PUBLIC(void) cJSON_Minify(char *json); - -/* Helper functions for creating and adding items to an object at the same time. - * They return the added item or NULL on failure. */ -CJSON_PUBLIC(cJSON*) cJSON_AddNullToObject(cJSON * const object, const char * const name); -CJSON_PUBLIC(cJSON*) cJSON_AddTrueToObject(cJSON * const object, const char * const name); -CJSON_PUBLIC(cJSON*) cJSON_AddFalseToObject(cJSON * const object, const char * const name); -CJSON_PUBLIC(cJSON*) cJSON_AddBoolToObject(cJSON * const object, const char * const name, const cJSON_bool boolean); -CJSON_PUBLIC(cJSON*) cJSON_AddNumberToObject(cJSON * const object, const char * const name, const double number); -CJSON_PUBLIC(cJSON*) cJSON_AddStringToObject(cJSON * const object, const char * const name, const char * const string); -CJSON_PUBLIC(cJSON*) cJSON_AddRawToObject(cJSON * const object, const char * const name, const char * const raw); -CJSON_PUBLIC(cJSON*) cJSON_AddObjectToObject(cJSON * const object, const char * const name); -CJSON_PUBLIC(cJSON*) cJSON_AddArrayToObject(cJSON * const object, const char * const name); - -/* When assigning an integer value, it needs to be propagated to valuedouble too. */ -#define cJSON_SetIntValue(object, number) ((object) ? (object)->valueint = (object)->valuedouble = (number) : (number)) -/* helper for the cJSON_SetNumberValue macro */ -CJSON_PUBLIC(double) cJSON_SetNumberHelper(cJSON *object, double number); -#define cJSON_SetNumberValue(object, number) ((object != NULL) ? cJSON_SetNumberHelper(object, (double)number) : (number)) - -/* Macro for iterating over an array or object */ -#define cJSON_ArrayForEach(element, array) for(element = (array != NULL) ? (array)->child : NULL; element != NULL; element = element->next) - -/* malloc/free objects using the malloc/free functions that have been set with cJSON_InitHooks */ -CJSON_PUBLIC(void *) cJSON_malloc(size_t size); -CJSON_PUBLIC(void) cJSON_free(void *object); - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/src/http-server.c b/src/http-server.c deleted file mode 100644 index d8ff023..0000000 --- a/src/http-server.c +++ /dev/null @@ -1,159 +0,0 @@ -/* - * lws-minimal-http-server-form-get - * - * Written in 2010-2019 by Andy Green - * - * This file is made available under the Creative Commons CC0 1.0 - * Universal Public Domain Dedication. - * - * This demonstrates a minimal http server that performs a form GET with a couple - * of parameters. It dumps the parameters to the console log and redirects - * to another page. - */ - -#include -#include -#include - -static int interrupted; - -static const char * param_names[] = { - "text1", - "send" -}; - -static int callback_http(struct lws *wsi, enum lws_callback_reasons reason, void *user, - void *in, size_t len) -{ - uint8_t buf[LWS_PRE + LWS_RECOMMENDED_MIN_HEADER_SPACE], - *start = &buf[LWS_PRE], *p = start, - *end = &buf[sizeof(buf) - 1]; - int n; - - switch (reason) { - case LWS_CALLBACK_HTTP: - - if (!lws_hdr_total_length(wsi, WSI_TOKEN_GET_URI)) - /* not a GET */ - break; - lwsl_err("%s: %s\n", __func__, (const char *)in); - if (strcmp((const char *)in, "/api")) - /* not our form URL */ - break; - - /* we just dump the decoded things to the log */ - - for (n = 0; n < (int)LWS_ARRAY_SIZE(param_names); n++) { - int rv = lws_get_urlarg_by_name_safe(wsi, param_names[n], - (char *)buf, sizeof(buf)); - if (rv < 0) - lwsl_user("%s: undefined\n", param_names[n]); - else - lwsl_user("%s: (len %d) '%s'\n", param_names[n], - (int)rv, buf); - } - - /* - * 修改为返回JSON格式数据,而不是重定向到静态页面 - */ - - // 设置HTTP响应头 - const char *json_response = "{\"status\": \"success\", \"message\": \"API request processed\", \"params_received\": true}"; - int json_len = strlen(json_response); - - if (lws_add_http_common_headers(wsi, HTTP_STATUS_OK, "application/json", - json_len, &p, end) < 0) - return -1; - printf( "reponse http header:[%s]\n", start); - // 发送HTTP头 - if (lws_finalize_write_http_header(wsi, start, &p, end) < 0) - return -1; - - // 准备JSON响应内容 - // 发送JSON响应体 - if (lws_write(wsi, (unsigned char *)json_response, strlen(json_response), LWS_WRITE_HTTP_FINAL) < 0){ - printf( " response json data: %s fail!\n", json_response); - return -1; - }else{ - printf( " response json data: %s success!\n", json_response); - } - - break; - - default: - break; - } - - return lws_callback_http_dummy(wsi, reason, user, in, len); -} - -static struct lws_protocols protocols[] = { - { "http", callback_http, 0, 0, 0, NULL, 0 }, - LWS_PROTOCOL_LIST_TERM -}; - -/* default mount serves the URL space from ./mount-origin */ - -static const struct lws_http_mount mount = { - /* .mount_next */ NULL, /* linked-list "next" */ - /* .mountpoint */ "/", /* mountpoint URL */ - /* .origin */ "./mount-origin", /* serve from dir */ - /* .def */ "index.html", /* default filename */ - /* .protocol */ NULL, - /* .cgienv */ NULL, - /* .extra_mimetypes */ NULL, - /* .interpret */ NULL, - /* .cgi_timeout */ 0, - /* .cache_max_age */ 0, - /* .auth_mask */ 0, - /* .cache_reusable */ 0, - /* .cache_revalidate */ 0, - /* .cache_intermediaries */ 0, - /* .origin_protocol */ LWSMPRO_FILE, /* files in a dir */ - /* .mountpoint_len */ 1, /* char count */ - /* .basic_auth_login_file */ NULL, -}; - -void sigint_handler(int sig) -{ - interrupted = 1; -} - -int http_get_test( int argc, const char **argv) -{ - struct lws_context_creation_info info; - struct lws_context *context; - const char *p; - int n = 0, logs = LLL_USER | LLL_ERR | LLL_WARN | LLL_NOTICE - /* for LLL_ verbosity above NOTICE to be built into lws, - * lws must have been configured and built with - * -DCMAKE_BUILD_TYPE=DEBUG instead of =RELEASE */ - /* | LLL_INFO */ /* | LLL_PARSER */ /* | LLL_HEADER */ - /* | LLL_EXT */ /* | LLL_CLIENT */ /* | LLL_LATENCY */ - /* | LLL_DEBUG */; - - //signal(SIGINT, sigint_handler); - - lws_set_log_level(logs, NULL); - lwsl_user("LWS minimal http server GET | visit http://localhost:3000\n"); - - memset(&info, 0, sizeof info); /* otherwise uninitialized garbage */ - info.port = 3000; - info.protocols = protocols; - info.mounts = NULL; //&mount; - info.options = - LWS_SERVER_OPTION_HTTP_HEADERS_SECURITY_BEST_PRACTICES_ENFORCE; - - context = lws_create_context(&info); - if (!context) { - lwsl_err("lws init failed\n"); - return 1; - } - - while (n >= 0 && !interrupted) - n = lws_service(context, 0); - - lws_context_destroy(context); - - return 0; -} diff --git a/src/main.c b/src/main.c index 2f38d61..e64c067 100644 --- a/src/main.c +++ b/src/main.c @@ -1,11 +1,17 @@ #include #include -#include "pcs_ctrl.h" +#include "user.h" int bms_start(void); int pcs_start(void); -int http_get_test( int argc, const char **argv); -int main(void) { +int webserver_start(void); + +board_info_t g_board_info; + +int main(void) +{ + user_log_init(); + // 启动PCS控制系统 if ( pcs_start()==0) { printf("PCS controller started successfully\n"); @@ -21,8 +27,8 @@ int main(void) { fprintf(stderr, "main: Failed to start PCS controller\n"); return -1; } - // 主线程保持运行(可根据需要添加信号处理或退出逻辑) - http_get_test(1, NULL ); + webserver_start(); + while (1) { sleep(1); } diff --git a/src/user.h b/src/user.h new file mode 100644 index 0000000..472ccc1 --- /dev/null +++ b/src/user.h @@ -0,0 +1,19 @@ +#ifndef USER_H +#define USER_H + +#include +#include +#include +#include +#include + +#include "user_bms.h" +#include "user_pcs.h" +#include "user_web.h" + +typedef struct{ + bms_info_t bms_data; + pcs_info_t pcs_data; +}board_info_t; + +#endif // USER_H diff --git a/src/user_bms.c b/src/user_bms.c index 5507ba6..613aa6b 100644 --- a/src/user_bms.c +++ b/src/user_bms.c @@ -12,10 +12,11 @@ #include static int can_socket = -1; -static bms_data_t bms_data = {0}; static struct sockaddr_can addr; static struct ifreq ifr; +static bms_info_t g_bms; + // 字节序转换 (小端转主机字节序) static uint16_t le16_to_host(const uint8_t *data) { return (uint16_t)(data[0] | (data[1] << 8)); @@ -28,7 +29,7 @@ static int16_t le16s_to_host(const uint8_t *data) { bool user_bms_init(const char *can_interface) { // 初始化BMS数据 - memset(&bms_data, 0, sizeof(bms_data_t)); + memset(&g_bms, 0, sizeof(g_bms)); // 创建CAN socket if ((can_socket = socket(PF_CAN, SOCK_RAW, CAN_RAW)) < 0) { @@ -87,72 +88,72 @@ bool user_bms_send_heartbeat(uint16_t heartbeat_value) { void user_bms_parse_frame1(const uint8_t *data) { // 解析最大允许充电电流 (0.1A) - bms_data.max_charge_current_p1a = le16_to_host(data); + g_bms.data.max_charge_current_p1a = le16_to_host(data); // 解析最大允许放电电流 (0.1A) - bms_data.max_discharge_current_p1a = le16_to_host(data + 2); + g_bms.data.max_discharge_current_p1a = le16_to_host(data + 2); // 解析总电压 (0.1V) - bms_data.total_voltage_p1v = le16_to_host(data + 4); + g_bms.data.total_voltage_p1v = le16_to_host(data + 4); // 解析总电流 (0.1A) - bms_data.total_current_p1a = le16s_to_host(data + 6); + g_bms.data.total_current_p1a = le16s_to_host(data + 6); } void user_bms_parse_frame2(const uint8_t *data) { // 解析总SOC (0.1%) - bms_data.total_soc_p1 = le16_to_host(data); + g_bms.data.total_soc_p1 = le16_to_host(data); // 解析总SOH (0.1%) - bms_data.total_soh_p1 = le16_to_host(data + 2); + g_bms.data.total_soh_p1 = le16_to_host(data + 2); // 解析最大允许充电电压 (0.1V) - bms_data.max_charge_voltage_p1v = le16_to_host(data + 4); + g_bms.data.max_charge_voltage_p1v = le16_to_host(data + 4); // 第7-8字节为预留,不处理 - bms_data.reserve_2 = le16_to_host(data + 6); + g_bms.data.reserve_2 = le16_to_host(data + 6); } void user_bms_parse_frame3(const uint8_t *data) { // 解析电池状态 - bms_data.battery_status = le16_to_host(data); + g_bms.data.battery_status = le16_to_host(data); // 解析轻度告警 - bms_data.light_alarm = le16_to_host(data + 2); + g_bms.data.light_alarm = le16_to_host(data + 2); // 解析中度告警 - bms_data.medium_alarm = le16_to_host(data + 4); + g_bms.data.medium_alarm = le16_to_host(data + 4); // 解析严重告警 - bms_data.serious_alarm = le16_to_host(data + 6); + g_bms.data.serious_alarm = le16_to_host(data + 6); } void user_bms_parse_frame4(const uint8_t *data) { // 解析单体最低电池电压 (0.001V) - bms_data.min_cell_voltage_p3v = le16_to_host(data); + g_bms.data.min_cell_voltage_p3v = le16_to_host(data); // 解析单体最低电池电压编号 - bms_data.min_cell_num = le16_to_host(data + 2); + g_bms.data.min_cell_num = le16_to_host(data + 2); // 解析单体最高电池电压 (0.001V) - bms_data.max_cell_voltage_p3v = le16_to_host(data + 4); + g_bms.data.max_cell_voltage_p3v = le16_to_host(data + 4); // 解析单体最高电池电压编号 - bms_data.max_cell_num = le16_to_host(data + 6); + g_bms.data.max_cell_num = le16_to_host(data + 6); } void user_bms_parse_frame5(const uint8_t *data) { // 解析单体最低电池温度 (0.1℃) - bms_data.min_cell_temp_p1c = le16s_to_host(data); + g_bms.data.min_cell_temp_p1c = le16s_to_host(data); // 解析单体最低电池温度编号 - bms_data.min_temp_num = le16_to_host(data + 2); + g_bms.data.min_temp_num = le16_to_host(data + 2); // 解析单体最高电池温度 (0.1℃) - bms_data.max_cell_temp_p1c = le16s_to_host(data + 4); + g_bms.data.max_cell_temp_p1c = le16s_to_host(data + 4); // 解析单体最高电池温度编号 - bms_data.max_temp_num = le16_to_host(data + 6); + g_bms.data.max_temp_num = le16_to_host(data + 6); } void user_bms_receive_data(void) { @@ -169,8 +170,8 @@ void user_bms_receive_data(void) { if (nbytes != sizeof(struct can_frame)) return; // 更新最后接收时间 - bms_data.last_update_time = time(NULL); - bms_data.is_connected = true; + g_bms.data.last_update_time = time(NULL); + g_bms.data.is_connected = true; // 根据CAN ID解析不同的数据帧 switch (frame.can_id) { @@ -210,14 +211,21 @@ void user_bms_receive_data(void) { } } -const bms_data_t *user_bms_get_data(void) { - // 检查BMS连接状态 (5秒超时) - time_t now = time(NULL); - if (now - bms_data.last_update_time > 5) { - bms_data.is_connected = false; +const bms_data_t *user_bms_get_data( bms_data_t *data ) +{ +// 检查BMS连接状态 (5秒超时) +// time_t now = time(NULL); +// if (now - bms_data.last_update_time > 5) { +// bms_data.is_connected = false; +// } + if( data ){ + //todo locked + memcpy( data, &g_bms.data, sizeof( bms_data_t) ); + //todo unlocked + }else{ + data = &g_bms.data; } - - return &bms_data; + return data; } void user_bms_deinit(void) { @@ -251,19 +259,23 @@ static void* bms_task_thread(void* arg) // 接收BMS数据 user_bms_receive_data(); - // 获取BMS数据 - const bms_data_t *bms = user_bms_get_data(); - - // 打印BMS状态 - if (bms->is_connected) { - printf("\rBMS Connected - SOC: %.1f%% Voltage: %.1fV Current: %.1fA ", - bms->total_soc_p1/10.0f, bms->total_voltage_p1v/10.0, bms->total_current_p1a/10.0); - fflush(stdout); - } else { - printf("\rBMS Disconnected... "); - fflush(stdout); + #if 0 + { + // 获取BMS数据 + const bms_data_t data; + user_bms_get_data( &data ); + + // 打印BMS状态 + if (bms->is_connected) { + printf("\rBMS Connected - SOC: %.1f%% Voltage: %.1fV Current: %.1fA ", + bms->total_soc_p1/10.0f, bms->total_voltage_p1v/10.0, bms->total_current_p1a/10.0); + fflush(stdout); + } else { + printf("\rBMS Disconnected... "); + fflush(stdout); + } } - + #endif // 500ms延时 usleep(500000); } @@ -274,7 +286,7 @@ static void* bms_task_thread(void* arg) } /** - * @brief 启动PCS控制线程 + * @brief 启动BMS控制线程 * @return true-启动成功 false-启动失败 */ int bms_start(void) { diff --git a/src/user_bms.h b/src/user_bms.h index 4a7d7c7..7a2e16e 100644 --- a/src/user_bms.h +++ b/src/user_bms.h @@ -55,6 +55,12 @@ typedef struct { uint32_t last_update_time; // 最后更新时间戳 } bms_data_t; +typedef struct{ + bms_data_t data; + int connected; + int lock; //for w/r data; +} bms_info_t; + // 初始化BMS通信模块 bool user_bms_init(const char *can_interface); @@ -65,7 +71,7 @@ bool user_bms_send_heartbeat(uint16_t heartbeat_value); void user_bms_receive_data(void); // 获取BMS数据 -const bms_data_t *user_bms_get_data(void); +const bms_data_t *user_bms_get_data( bms_data_t *data ); // 关闭BMS通信模块 void user_bms_deinit(void); diff --git a/src/user_mb.c b/src/user_mb.c index 97554d2..fe6fc60 100644 --- a/src/user_mb.c +++ b/src/user_mb.c @@ -88,11 +88,6 @@ void user_mb_destroy(user_mb_handler_t *handler) { /* 停止模块 */ user_mb_stop(handler); - /* 释放寄存器范围 */ - if (handler->reg_ranges != NULL) { - free(handler->reg_ranges); - } - /* 销毁写入队列 */ if (handler->write_queue != NULL) { cQDelete(handler->write_queue); diff --git a/src/user_pcs.c b/src/user_pcs.c index 549ab4e..2c4f2e8 100644 --- a/src/user_pcs.c +++ b/src/user_pcs.c @@ -4,7 +4,7 @@ #include // 添加usleep函数所需的头文件 #include "user_pcs.h" -user_pcs_device_info_t g_pcs_info; +pcs_info_t g_pcs; /* PCS模块句柄结构体 */ struct user_pcs_handler { @@ -19,11 +19,11 @@ struct user_pcs_handler { }; /* 协议解析函数 - 根据pcs-modbus.txt协议实现 */ -int user_pcs_read_all(user_pcs_handler_t *pcs, user_pcs_device_info_t *device_info) +int user_pcs_read_all(user_pcs_handler_t *pcs, pcs_data_t *pcs_data) { user_mb_handler_t *mb_handler; - if( pcs && pcs->mb_handler && device_info ){ + if( pcs && pcs->mb_handler && pcs_data ){ mb_handler = pcs->mb_handler; }else{ return -1; @@ -34,348 +34,348 @@ int user_pcs_read_all(user_pcs_handler_t *pcs, user_pcs_device_info_t *device_in // 读取软件版本 (从站地址1,保持寄存器,地址0) if (user_mb_get_reg_value(mb_handler, 1, USER_MB_REG_HOLDING_REGISTER, 0, &value)) { - device_info->firmware_version = value; + pcs_data->firmware_version = value; } // 读取硬件版本 (从站地址1,保持寄存器,地址1) if (user_mb_get_reg_value(mb_handler, 1, USER_MB_REG_HOLDING_REGISTER, 1, &value)) { - device_info->hardware_version = value; + pcs_data->hardware_version = value; } // 读取直流电压 (从站地址1,保持寄存器,地址2,0.1V精度) if (user_mb_get_reg_value(mb_handler, 1, USER_MB_REG_HOLDING_REGISTER, 2, &value)) { - device_info->dc_voltage_p1v = value; + pcs_data->dc_voltage_p1v = value; } // 读取直流正电压 (从站地址1,保持寄存器,地址3,0.1V精度) if (user_mb_get_reg_value(mb_handler, 1, USER_MB_REG_HOLDING_REGISTER, 3, &value)) { - device_info->dc_pos_voltage_p1v = value; + pcs_data->dc_pos_voltage_p1v = value; } // 读取直流负电压 (从站地址1,保持寄存器,地址4,0.1V精度) if (user_mb_get_reg_value(mb_handler, 1, USER_MB_REG_HOLDING_REGISTER, 4, &value)) { - device_info->dc_neg_voltage_p1v = value; + pcs_data->dc_neg_voltage_p1v = value; } // 读取直流电流 (从站地址1,保持寄存器,地址5,0.1A精度,S16类型) if (user_mb_get_reg_value(mb_handler, 1, USER_MB_REG_HOLDING_REGISTER, 5, &value)) { - device_info->dc_current_p1a = (int16_t)value; + pcs_data->dc_current_p1a = (int16_t)value; } // 读取直流功率 (从站地址1,保持寄存器,地址6,0.1kW精度,S16类型) if (user_mb_get_reg_value(mb_handler, 1, USER_MB_REG_HOLDING_REGISTER, 6, &value)) { - device_info->dc_power_p1kw = (int16_t)value; + pcs_data->dc_power_p1kw = (int16_t)value; } // 读取AB线电压 (从站地址1,保持寄存器,地址7,0.1V精度) if (user_mb_get_reg_value(mb_handler, 1, USER_MB_REG_HOLDING_REGISTER, 7, &value)) { - device_info->line_voltage_ab_p1v = value; + pcs_data->line_voltage_ab_p1v = value; } // 读取BC线电压 (从站地址1,保持寄存器,地址8,0.1V精度) if (user_mb_get_reg_value(mb_handler, 1, USER_MB_REG_HOLDING_REGISTER, 8, &value)) { - device_info->line_voltage_bc_p1v = value; + pcs_data->line_voltage_bc_p1v = value; } // 读取CA线电压 (从站地址1,保持寄存器,地址9,0.1V精度) if (user_mb_get_reg_value(mb_handler, 1, USER_MB_REG_HOLDING_REGISTER, 9, &value)) { - device_info->line_voltage_ca_p1v = value; + pcs_data->line_voltage_ca_p1v = value; } // 读取A相电流 (从站地址1,保持寄存器,地址10,0.1A精度,S16类型) if (user_mb_get_reg_value(mb_handler, 1, USER_MB_REG_HOLDING_REGISTER, 10, &value)) { - device_info->phase_current_a_p1a = (int16_t)value; + pcs_data->phase_current_a_p1a = (int16_t)value; } // 读取B相电流 (从站地址1,保持寄存器,地址11,0.1A精度,S16类型) if (user_mb_get_reg_value(mb_handler, 1, USER_MB_REG_HOLDING_REGISTER, 11, &value)) { - device_info->phase_current_b_p1a = (int16_t)value; + pcs_data->phase_current_b_p1a = (int16_t)value; } // 读取C相电流 (从站地址1,保持寄存器,地址12,0.1A精度,S16类型) if (user_mb_get_reg_value(mb_handler, 1, USER_MB_REG_HOLDING_REGISTER, 12, &value)) { - device_info->phase_current_c_p1a = (int16_t)value; + pcs_data->phase_current_c_p1a = (int16_t)value; } // 读取视在功率 (从站地址1,保持寄存器,地址13,0.1kVA精度,S16类型) if (user_mb_get_reg_value(mb_handler, 1, USER_MB_REG_HOLDING_REGISTER, 13, &value)) { - device_info->apparent_power_p1kva = (int16_t)value; + pcs_data->apparent_power_p1kva = (int16_t)value; } // 读取有功功率 (从站地址1,保持寄存器,地址14,0.1kW精度,S16类型) if (user_mb_get_reg_value(mb_handler, 1, USER_MB_REG_HOLDING_REGISTER, 14, &value)) { - device_info->active_power_p1kw = (int16_t)value; + pcs_data->active_power_p1kw = (int16_t)value; } // 读取无功功率 (从站地址1,保持寄存器,地址15,0.1kVar精度,S16类型) if (user_mb_get_reg_value(mb_handler, 1, USER_MB_REG_HOLDING_REGISTER, 15, &value)) { - device_info->reactive_power_p1kvar = (int16_t)value; + pcs_data->reactive_power_p1kvar = (int16_t)value; } // 读取功率因数 (从站地址1,保持寄存器,地址16,0.001精度,S16类型) if (user_mb_get_reg_value(mb_handler, 1, USER_MB_REG_HOLDING_REGISTER, 16, &value)) { - device_info->power_factor_p3 = (int16_t)value; + pcs_data->power_factor_p3 = (int16_t)value; } // 读取电网频率 (从站地址1,保持寄存器,地址17,0.01Hz精度) if (user_mb_get_reg_value(mb_handler, 1, USER_MB_REG_HOLDING_REGISTER, 17, &value)) { - device_info->grid_frequency_p1hz = value; + pcs_data->grid_frequency_p1hz = value; } // 读取模块温度 (从站地址1,保持寄存器,地址18,0.1℃精度,S16类型) if (user_mb_get_reg_value(mb_handler, 1, USER_MB_REG_HOLDING_REGISTER, 18, &value)) { - device_info->module_temperature_p1c = (int16_t)value; + pcs_data->module_temperature_p1c = (int16_t)value; } // 读取环境温度 (从站地址1,保持寄存器,地址20,0.1℃精度,S16类型) if (user_mb_get_reg_value(mb_handler, 1, USER_MB_REG_HOLDING_REGISTER, 20, &value)) { - device_info->ambient_temperature_p1c = (int16_t)value; + pcs_data->ambient_temperature_p1c = (int16_t)value; } // 读取漏电流 (从站地址1,保持寄存器,地址23,0.01A精度) if (user_mb_get_reg_value(mb_handler, 1, USER_MB_REG_HOLDING_REGISTER, 23, &value)) { - device_info->leakage_current_p1a = value; + pcs_data->leakage_current_p1a = value; } // 读取工作状态 (从站地址1,保持寄存器,地址27) if (user_mb_get_reg_value(mb_handler, 1, USER_MB_REG_HOLDING_REGISTER, 27, &value)) { - device_info->running_state = value; + pcs_data->running_state = value; } // 读取运行模式显示 (从站地址1,保持寄存器,地址28) if (user_mb_get_reg_value(mb_handler, 1, USER_MB_REG_HOLDING_REGISTER, 28, &value)) { - device_info->operation_mode = value; + pcs_data->operation_mode = value; } // 读取故障1 (从站地址1,保持寄存器,地址29) if (user_mb_get_reg_value(mb_handler, 1, USER_MB_REG_HOLDING_REGISTER, 29, &value)) { - device_info->error_code = value; + pcs_data->error_code = value; } // 读取故障2 (从站地址1,保持寄存器,地址30) if (user_mb_get_reg_value(mb_handler, 1, USER_MB_REG_HOLDING_REGISTER, 30, &value)) { - device_info->error_code2 = value; + pcs_data->error_code2 = value; } // 读取电网A相电压 (从站地址1,保持寄存器,地址32,0.1V精度) if (user_mb_get_reg_value(mb_handler, 1, USER_MB_REG_HOLDING_REGISTER, 32, &value)) { - device_info->grid_voltage_a_p1v = value; + pcs_data->grid_voltage_a_p1v = value; } // 读取电网B相电压 (从站地址1,保持寄存器,地址33,0.1V精度) if (user_mb_get_reg_value(mb_handler, 1, USER_MB_REG_HOLDING_REGISTER, 33, &value)) { - device_info->grid_voltage_b_p1v = value; + pcs_data->grid_voltage_b_p1v = value; } // 读取电网C相电压 (从站地址1,保持寄存器,地址34,0.1V精度) if (user_mb_get_reg_value(mb_handler, 1, USER_MB_REG_HOLDING_REGISTER, 34, &value)) { - device_info->grid_voltage_c_p1v = value; + pcs_data->grid_voltage_c_p1v = value; } /* 读取控制参数 - 遥控、遥调信息(读/写) */ // 读取开关机设置 (从站地址1,保持寄存器,地址35) if (user_mb_get_reg_value(mb_handler, 1, USER_MB_REG_HOLDING_REGISTER, 35, &value)) { - device_info->on_off_setting = value; + pcs_data->on_off_setting = value; } // 读取工作模式设置 (从站地址1,保持寄存器,地址36) if (user_mb_get_reg_value(mb_handler, 1, USER_MB_REG_HOLDING_REGISTER, 36, &value)) { - device_info->work_mode_setting = value; + pcs_data->work_mode_setting = value; } // 读取无功调节方式 (从站地址1,保持寄存器,地址37) if (user_mb_get_reg_value(mb_handler, 1, USER_MB_REG_HOLDING_REGISTER, 37, &value)) { - device_info->reactive_power_mode = value; + pcs_data->reactive_power_mode = value; } // 读取功率因数设置 (从站地址1,保持寄存器,地址38,0.001精度,S16类型) if (user_mb_get_reg_value(mb_handler, 1, USER_MB_REG_HOLDING_REGISTER, 38, &value)) { - device_info->power_factor_setting_p3 = (int16_t)value; + pcs_data->power_factor_setting_p3 = (int16_t)value; } // 读取无功电流设置 (从站地址1,保持寄存器,地址39,0.1A精度,S16类型) if (user_mb_get_reg_value(mb_handler, 1, USER_MB_REG_HOLDING_REGISTER, 39, &value)) { - device_info->reactive_current_setting_p1a = (int16_t)value; + pcs_data->reactive_current_setting_p1a = (int16_t)value; } // 读取恒流电流值 (从站地址1,保持寄存器,地址46,0.1A精度,S16类型) if (user_mb_get_reg_value(mb_handler, 1, USER_MB_REG_HOLDING_REGISTER, 46, &value)) { - device_info->target_current_p1a = (int16_t)value; + pcs_data->target_current_p1a = (int16_t)value; } // 读取恒压电压值 (从站地址1,保持寄存器,地址48,0.1V精度) if (user_mb_get_reg_value(mb_handler, 1, USER_MB_REG_HOLDING_REGISTER, 48, &value)) { - device_info->target_voltage_p1v = value; + pcs_data->target_voltage_p1v = value; } // 读取恒压限流值 (从站地址1,保持寄存器,地址49,0.1A精度) if (user_mb_get_reg_value(mb_handler, 1, USER_MB_REG_HOLDING_REGISTER, 49, &value)) { - device_info->voltage_limit_current_p1a = value; + pcs_data->voltage_limit_current_p1a = value; } // 读取恒功率目标值 (从站地址1,保持寄存器,地址51,0.1kW精度,S16类型) if (user_mb_get_reg_value(mb_handler, 1, USER_MB_REG_HOLDING_REGISTER, 51, &value)) { - device_info->target_power_p1kw = (int16_t)value; + pcs_data->target_power_p1kw = (int16_t)value; } // 读取离网逆变电压设置 (从站地址1,保持寄存器,地址53) if (user_mb_get_reg_value(mb_handler, 1, USER_MB_REG_HOLDING_REGISTER, 53, &value)) { - device_info->offline_voltage = value; + pcs_data->offline_voltage = value; } // 读取离网逆变频率设置 (从站地址1,保持寄存器,地址54) if (user_mb_get_reg_value(mb_handler, 1, USER_MB_REG_HOLDING_REGISTER, 54, &value)) { - device_info->offline_frequency = value; + pcs_data->offline_frequency = value; } // 读取电网额定电压 (从站地址1,保持寄存器,地址55) if (user_mb_get_reg_value(mb_handler, 1, USER_MB_REG_HOLDING_REGISTER, 55, &value)) { - device_info->grid_voltage = value; + pcs_data->grid_voltage = value; } // 读取电网额定频率 (从站地址1,保持寄存器,地址56) if (user_mb_get_reg_value(mb_handler, 1, USER_MB_REG_HOLDING_REGISTER, 56, &value)) { - device_info->grid_frequency = value; + pcs_data->grid_frequency = value; } // 读取电网过压保护值 (从站地址1,保持寄存器,地址57,0.1V精度) if (user_mb_get_reg_value(mb_handler, 1, USER_MB_REG_HOLDING_REGISTER, 57, &value)) { - device_info->grid_overvoltage_threshold_p1v = value; + pcs_data->grid_overvoltage_threshold_p1v = value; } // 读取电网欠压保护值 (从站地址1,保持寄存器,地址58,0.1V精度) if (user_mb_get_reg_value(mb_handler, 1, USER_MB_REG_HOLDING_REGISTER, 58, &value)) { - device_info->grid_undervoltage_threshold_p1v = value; + pcs_data->grid_undervoltage_threshold_p1v = value; } // 读取电网过频保护值 (从站地址1,保持寄存器,地址59,0.01Hz精度) if (user_mb_get_reg_value(mb_handler, 1, USER_MB_REG_HOLDING_REGISTER, 59, &value)) { - device_info->grid_overfrequency_threshold_p1hz = value; + pcs_data->grid_overfrequency_threshold_p1hz = value; } // 读取电网欠频保护值 (从站地址1,保持寄存器,地址60,0.01Hz精度) if (user_mb_get_reg_value(mb_handler, 1, USER_MB_REG_HOLDING_REGISTER, 60, &value)) { - device_info->grid_underfrequency_threshold_p1hz = value; + pcs_data->grid_underfrequency_threshold_p1hz = value; } // 读取直流过压保护值 (从站地址1,保持寄存器,地址61,0.1V精度) if (user_mb_get_reg_value(mb_handler, 1, USER_MB_REG_HOLDING_REGISTER, 61, &value)) { - device_info->dc_overvoltage_threshold_p1v = value; + pcs_data->dc_overvoltage_threshold_p1v = value; } // 读取直流过压恢复值 (从站地址1,保持寄存器,地址62,0.1V精度) if (user_mb_get_reg_value(mb_handler, 1, USER_MB_REG_HOLDING_REGISTER, 62, &value)) { - device_info->dc_overvoltage_recover_p1v = value; + pcs_data->dc_overvoltage_recover_p1v = value; } // 读取直流欠压保护值 (从站地址1,保持寄存器,地址63,0.1V精度) if (user_mb_get_reg_value(mb_handler, 1, USER_MB_REG_HOLDING_REGISTER, 63, &value)) { - device_info->dc_undervoltage_threshold_p1v = value; + pcs_data->dc_undervoltage_threshold_p1v = value; } // 读取直流欠压恢复值 (从站地址1,保持寄存器,地址64,0.1V精度) if (user_mb_get_reg_value(mb_handler, 1, USER_MB_REG_HOLDING_REGISTER, 64, &value)) { - device_info->dc_undervoltage_recover_p1v = value; + pcs_data->dc_undervoltage_recover_p1v = value; } // 读取心跳检测及使能 (从站地址1,保持寄存器,地址67) if (user_mb_get_reg_value(mb_handler, 1, USER_MB_REG_HOLDING_REGISTER, 67, &value)) { - device_info->heartbeat_enable = value; + pcs_data->heartbeat_enable = value; } // 读取清除故障命令 (从站地址1,保持寄存器,地址70) if (user_mb_get_reg_value(mb_handler, 1, USER_MB_REG_HOLDING_REGISTER, 70, &value)) { - device_info->clear_fault = value; + pcs_data->clear_fault = value; } // 新增: 读取寄存器100-138 if (user_mb_get_reg_value(mb_handler, 1, USER_MB_REG_HOLDING_REGISTER, 100, &value)) { - device_info->protection_enable = value; + pcs_data->protection_enable = value; } if (user_mb_get_reg_value(mb_handler, 1, USER_MB_REG_HOLDING_REGISTER, 101, &value)) { - device_info->grid_overvoltage1_prot_time = value; + pcs_data->grid_overvoltage1_prot_time = value; } if (user_mb_get_reg_value(mb_handler, 1, USER_MB_REG_HOLDING_REGISTER, 102, &value)) { - device_info->grid_overvoltage2_value = value; + pcs_data->grid_overvoltage2_value = value; } if (user_mb_get_reg_value(mb_handler, 1, USER_MB_REG_HOLDING_REGISTER, 103, &value)) { - device_info->grid_overvoltage2_prot_time = value; + pcs_data->grid_overvoltage2_prot_time = value; } if (user_mb_get_reg_value(mb_handler, 1, USER_MB_REG_HOLDING_REGISTER, 104, &value)) { - device_info->grid_overvoltage3_value = value; + pcs_data->grid_overvoltage3_value = value; } if (user_mb_get_reg_value(mb_handler, 1, USER_MB_REG_HOLDING_REGISTER, 105, &value)) { - device_info->grid_overvoltage3_prot_time = value; + pcs_data->grid_overvoltage3_prot_time = value; } if (user_mb_get_reg_value(mb_handler, 1, USER_MB_REG_HOLDING_REGISTER, 108, &value)) { - device_info->grid_undervoltage1_prot_time = value; + pcs_data->grid_undervoltage1_prot_time = value; } if (user_mb_get_reg_value(mb_handler, 1, USER_MB_REG_HOLDING_REGISTER, 109, &value)) { - device_info->grid_undervoltage2_value = value; + pcs_data->grid_undervoltage2_value = value; } if (user_mb_get_reg_value(mb_handler, 1, USER_MB_REG_HOLDING_REGISTER, 110, &value)) { - device_info->grid_undervoltage2_prot_time = value; + pcs_data->grid_undervoltage2_prot_time = value; } if (user_mb_get_reg_value(mb_handler, 1, USER_MB_REG_HOLDING_REGISTER, 111, &value)) { - device_info->grid_undervoltage3_value = value; + pcs_data->grid_undervoltage3_value = value; } if (user_mb_get_reg_value(mb_handler, 1, USER_MB_REG_HOLDING_REGISTER, 112, &value)) { - device_info->grid_undervoltage3_prot_time = value; + pcs_data->grid_undervoltage3_prot_time = value; } if (user_mb_get_reg_value(mb_handler, 1, USER_MB_REG_HOLDING_REGISTER, 115, &value)) { - device_info->grid_overfrequency1_prot_time = value; + pcs_data->grid_overfrequency1_prot_time = value; } if (user_mb_get_reg_value(mb_handler, 1, USER_MB_REG_HOLDING_REGISTER, 116, &value)) { - device_info->grid_overfrequency2_value = value; + pcs_data->grid_overfrequency2_value = value; } if (user_mb_get_reg_value(mb_handler, 1, USER_MB_REG_HOLDING_REGISTER, 117, &value)) { - device_info->grid_overfrequency2_prot_time = value; + pcs_data->grid_overfrequency2_prot_time = value; } if (user_mb_get_reg_value(mb_handler, 1, USER_MB_REG_HOLDING_REGISTER, 118, &value)) { - device_info->grid_overfrequency3_value = value; + pcs_data->grid_overfrequency3_value = value; } if (user_mb_get_reg_value(mb_handler, 1, USER_MB_REG_HOLDING_REGISTER, 119, &value)) { - device_info->grid_overfrequency3_prot_time = value; + pcs_data->grid_overfrequency3_prot_time = value; } if (user_mb_get_reg_value(mb_handler, 1, USER_MB_REG_HOLDING_REGISTER, 122, &value)) { - device_info->grid_underfrequency1_prot_time = value; + pcs_data->grid_underfrequency1_prot_time = value; } if (user_mb_get_reg_value(mb_handler, 1, USER_MB_REG_HOLDING_REGISTER, 123, &value)) { - device_info->grid_underfrequency2_value = value; + pcs_data->grid_underfrequency2_value = value; } if (user_mb_get_reg_value(mb_handler, 1, USER_MB_REG_HOLDING_REGISTER, 124, &value)) { - device_info->grid_underfrequency2_prot_time = value; + pcs_data->grid_underfrequency2_prot_time = value; } if (user_mb_get_reg_value(mb_handler, 1, USER_MB_REG_HOLDING_REGISTER, 125, &value)) { - device_info->grid_underfrequency3_value = value; + pcs_data->grid_underfrequency3_value = value; } if (user_mb_get_reg_value(mb_handler, 1, USER_MB_REG_HOLDING_REGISTER, 126, &value)) { - device_info->grid_underfrequency3_prot_time = value; + pcs_data->grid_underfrequency3_prot_time = value; } if (user_mb_get_reg_value(mb_handler, 1, USER_MB_REG_HOLDING_REGISTER, 129, &value)) { - device_info->undervoltage_reactive_slope = value; + pcs_data->undervoltage_reactive_slope = value; } if (user_mb_get_reg_value(mb_handler, 1, USER_MB_REG_HOLDING_REGISTER, 130, &value)) { - device_info->reactive_undervoltage_entry = value; + pcs_data->reactive_undervoltage_entry = value; } if (user_mb_get_reg_value(mb_handler, 1, USER_MB_REG_HOLDING_REGISTER, 131, &value)) { - device_info->reactive_undervoltage_exit = value; + pcs_data->reactive_undervoltage_exit = value; } if (user_mb_get_reg_value(mb_handler, 1, USER_MB_REG_HOLDING_REGISTER, 134, &value)) { - device_info->overvoltage_reactive_slope = value; + pcs_data->overvoltage_reactive_slope = value; } if (user_mb_get_reg_value(mb_handler, 1, USER_MB_REG_HOLDING_REGISTER, 135, &value)) { - device_info->reactive_overvoltage_entry = value; + pcs_data->reactive_overvoltage_entry = value; } if (user_mb_get_reg_value(mb_handler, 1, USER_MB_REG_HOLDING_REGISTER, 136, &value)) { - device_info->reactive_overvoltage_exit = value; + pcs_data->reactive_overvoltage_exit = value; } // 新增: 读取寄存器139-298 (调试变量48-207) for (int i = 0; i < 160; i++) { if (user_mb_get_reg_value(mb_handler, 1, USER_MB_REG_HOLDING_REGISTER, 139 + i, &value)) { - device_info->debug_vars[i] = value; + pcs_data->debug_vars[i] = value; } } @@ -383,11 +383,11 @@ int user_pcs_read_all(user_pcs_handler_t *pcs, user_pcs_device_info_t *device_in } /* 协议格式化函数 - 将PCS设备信息转换为Modbus寄存器值并写入 */ -int user_pcs_write_all(user_pcs_handler_t *pcs, const user_pcs_device_info_t *device_info) +int user_pcs_write_all(user_pcs_handler_t *pcs, const pcs_data_t *pcs_data) { user_mb_handler_t *mb_handler; - if( pcs && pcs->mb_handler && device_info ){ + if( pcs && pcs->mb_handler && pcs_data ){ mb_handler = pcs->mb_handler; }else{ return -1; @@ -396,117 +396,117 @@ int user_pcs_write_all(user_pcs_handler_t *pcs, const user_pcs_device_info_t *de /* 将PCS设备信息转换为Modbus寄存器值并写入 - 只写入遥控、遥调信息 */ // 写入开关机设置 (从站地址1,保持寄存器,地址35) - if (!user_mb_write_reg(mb_handler, 1, USER_MB_REG_HOLDING_REGISTER, 35, device_info->on_off_setting)) { + if (!user_mb_write_reg(mb_handler, 1, USER_MB_REG_HOLDING_REGISTER, 35, pcs_data->on_off_setting)) { return -1; } // 写入工作模式设置 (从站地址1,保持寄存器,地址36) - if (!user_mb_write_reg(mb_handler, 1, USER_MB_REG_HOLDING_REGISTER, 36, device_info->work_mode_setting)) { + if (!user_mb_write_reg(mb_handler, 1, USER_MB_REG_HOLDING_REGISTER, 36, pcs_data->work_mode_setting)) { return -1; } // 写入无功调节方式 (从站地址1,保持寄存器,地址37) - if (!user_mb_write_reg(mb_handler, 1, USER_MB_REG_HOLDING_REGISTER, 37, device_info->reactive_power_mode)) { + if (!user_mb_write_reg(mb_handler, 1, USER_MB_REG_HOLDING_REGISTER, 37, pcs_data->reactive_power_mode)) { return -1; } // 写入功率因数设置 (从站地址1,保持寄存器,地址38) - if (!user_mb_write_reg(mb_handler, 1, USER_MB_REG_HOLDING_REGISTER, 38, (uint16_t)device_info->power_factor_setting_p3)) { + if (!user_mb_write_reg(mb_handler, 1, USER_MB_REG_HOLDING_REGISTER, 38, (uint16_t)pcs_data->power_factor_setting_p3)) { return -1; } // 写入无功电流设置 (从站地址1,保持寄存器,地址39) - if (!user_mb_write_reg(mb_handler, 1, USER_MB_REG_HOLDING_REGISTER, 39, (uint16_t)device_info->reactive_current_setting_p1a)) { + if (!user_mb_write_reg(mb_handler, 1, USER_MB_REG_HOLDING_REGISTER, 39, (uint16_t)pcs_data->reactive_current_setting_p1a)) { return -1; } // 写入恒流电流值 (从站地址1,保持寄存器,地址46) - if (!user_mb_write_reg(mb_handler, 1, USER_MB_REG_HOLDING_REGISTER, 46, (uint16_t)device_info->target_current_p1a)) { + if (!user_mb_write_reg(mb_handler, 1, USER_MB_REG_HOLDING_REGISTER, 46, (uint16_t)pcs_data->target_current_p1a)) { return -1; } // 写入恒压电压值 (从站地址1,保持寄存器,地址48) - if (!user_mb_write_reg(mb_handler, 1, USER_MB_REG_HOLDING_REGISTER, 48, device_info->target_voltage_p1v)) { + if (!user_mb_write_reg(mb_handler, 1, USER_MB_REG_HOLDING_REGISTER, 48, pcs_data->target_voltage_p1v)) { return -1; } // 写入恒压限流值 (从站地址1,保持寄存器,地址49) - if (!user_mb_write_reg(mb_handler, 1, USER_MB_REG_HOLDING_REGISTER, 49, device_info->voltage_limit_current_p1a)) { + if (!user_mb_write_reg(mb_handler, 1, USER_MB_REG_HOLDING_REGISTER, 49, pcs_data->voltage_limit_current_p1a)) { return -1; } // 写入恒功率目标值 (从站地址1,保持寄存器,地址51) - if (!user_mb_write_reg(mb_handler, 1, USER_MB_REG_HOLDING_REGISTER, 51, (uint16_t)device_info->target_power_p1kw)) { + if (!user_mb_write_reg(mb_handler, 1, USER_MB_REG_HOLDING_REGISTER, 51, (uint16_t)pcs_data->target_power_p1kw)) { return -1; } // 写入离网逆变电压设置 (从站地址1,保持寄存器,地址53) - if (!user_mb_write_reg(mb_handler, 1, USER_MB_REG_HOLDING_REGISTER, 53, device_info->offline_voltage)) { + if (!user_mb_write_reg(mb_handler, 1, USER_MB_REG_HOLDING_REGISTER, 53, pcs_data->offline_voltage)) { return -1; } // 写入离网逆变频率设置 (从站地址1,保持寄存器,地址54) - if (!user_mb_write_reg(mb_handler, 1, USER_MB_REG_HOLDING_REGISTER, 54, device_info->offline_frequency)) { + if (!user_mb_write_reg(mb_handler, 1, USER_MB_REG_HOLDING_REGISTER, 54, pcs_data->offline_frequency)) { return -1; } // 写入电网额定电压 (从站地址1,保持寄存器,地址55) - if (!user_mb_write_reg(mb_handler, 1, USER_MB_REG_HOLDING_REGISTER, 55, device_info->grid_voltage)) { + if (!user_mb_write_reg(mb_handler, 1, USER_MB_REG_HOLDING_REGISTER, 55, pcs_data->grid_voltage)) { return -1; } // 写入电网额定频率 (从站地址1,保持寄存器,地址56) - if (!user_mb_write_reg(mb_handler, 1, USER_MB_REG_HOLDING_REGISTER, 56, device_info->grid_frequency)) { + if (!user_mb_write_reg(mb_handler, 1, USER_MB_REG_HOLDING_REGISTER, 56, pcs_data->grid_frequency)) { return -1; } // 写入电网过压保护值 (从站地址1,保持寄存器,地址57) - if (!user_mb_write_reg(mb_handler, 1, USER_MB_REG_HOLDING_REGISTER, 57, device_info->grid_overvoltage_threshold_p1v)) { + if (!user_mb_write_reg(mb_handler, 1, USER_MB_REG_HOLDING_REGISTER, 57, pcs_data->grid_overvoltage_threshold_p1v)) { return -1; } // 写入电网欠压保护值 (从站地址1,保持寄存器,地址58) - if (!user_mb_write_reg(mb_handler, 1, USER_MB_REG_HOLDING_REGISTER, 58, device_info->grid_undervoltage_threshold_p1v)) { + if (!user_mb_write_reg(mb_handler, 1, USER_MB_REG_HOLDING_REGISTER, 58, pcs_data->grid_undervoltage_threshold_p1v)) { return -1; } // 写入电网过频保护值 (从站地址1,保持寄存器,地址59) - if (!user_mb_write_reg(mb_handler, 1, USER_MB_REG_HOLDING_REGISTER, 59, device_info->grid_overfrequency_threshold_p1hz)) { + if (!user_mb_write_reg(mb_handler, 1, USER_MB_REG_HOLDING_REGISTER, 59, pcs_data->grid_overfrequency_threshold_p1hz)) { return -1; } // 写入电网欠频保护值 (从站地址1,保持寄存器,地址60) - if (!user_mb_write_reg(mb_handler, 1, USER_MB_REG_HOLDING_REGISTER, 60, device_info->grid_underfrequency_threshold_p1hz)) { + if (!user_mb_write_reg(mb_handler, 1, USER_MB_REG_HOLDING_REGISTER, 60, pcs_data->grid_underfrequency_threshold_p1hz)) { return -1; } // 写入直流过压保护值 (从站地址1,保持寄存器,地址61) - if (!user_mb_write_reg(mb_handler, 1, USER_MB_REG_HOLDING_REGISTER, 61, device_info->dc_overvoltage_threshold_p1v)) { + if (!user_mb_write_reg(mb_handler, 1, USER_MB_REG_HOLDING_REGISTER, 61, pcs_data->dc_overvoltage_threshold_p1v)) { return -1; } // 写入直流过压恢复值 (从站地址1,保持寄存器,地址62) - if (!user_mb_write_reg(mb_handler, 1, USER_MB_REG_HOLDING_REGISTER, 62, device_info->dc_overvoltage_recover_p1v)) { + if (!user_mb_write_reg(mb_handler, 1, USER_MB_REG_HOLDING_REGISTER, 62, pcs_data->dc_overvoltage_recover_p1v)) { return -1; } // 写入直流欠压保护值 (从站地址1,保持寄存器,地址63) - if (!user_mb_write_reg(mb_handler, 1, USER_MB_REG_HOLDING_REGISTER, 63, device_info->dc_undervoltage_threshold_p1v)) { + if (!user_mb_write_reg(mb_handler, 1, USER_MB_REG_HOLDING_REGISTER, 63, pcs_data->dc_undervoltage_threshold_p1v)) { return -1; } // 写入直流欠压恢复值 (从站地址1,保持寄存器,地址64) - if (!user_mb_write_reg(mb_handler, 1, USER_MB_REG_HOLDING_REGISTER, 64, device_info->dc_undervoltage_recover_p1v)) { + if (!user_mb_write_reg(mb_handler, 1, USER_MB_REG_HOLDING_REGISTER, 64, pcs_data->dc_undervoltage_recover_p1v)) { return -1; } // 写入心跳检测及使能 (从站地址1,保持寄存器,地址67) - if (!user_mb_write_reg(mb_handler, 1, USER_MB_REG_HOLDING_REGISTER, 67, device_info->heartbeat_enable)) { + if (!user_mb_write_reg(mb_handler, 1, USER_MB_REG_HOLDING_REGISTER, 67, pcs_data->heartbeat_enable)) { return -1; } // 写入清除故障命令 (从站地址1,保持寄存器,地址70) - if (!user_mb_write_reg(mb_handler, 1, USER_MB_REG_HOLDING_REGISTER, 70, device_info->clear_fault)) { + if (!user_mb_write_reg(mb_handler, 1, USER_MB_REG_HOLDING_REGISTER, 70, pcs_data->clear_fault)) { return -1; } @@ -821,14 +821,14 @@ bool user_pcs_stop(user_pcs_handler_t *handler) { } - +pcs_info_t g_pcs; /** * @brief PCS控制任务线程函数 */ static void* pcs_task_thread(void* arg) { int n = 0; // 修复原代码中n未初始化问题 - user_log_init(); + pcs_data_t pcs_data; printf("pcs_controller demo start!\n"); user_log_info("-----------pcs_controller demo start!\n"); @@ -836,13 +836,13 @@ static void* pcs_task_thread(void* arg) { // 创建并启动PCS模块 user_pcs_handler_t *pcs_handler = user_pcs_create("Main-PCS-Controller", MB_RTU_BUS_1, 1); if (pcs_handler != NULL) { + g_pcs.handler = pcs_handler; // 启动PCS模块 if (user_pcs_start(pcs_handler)) { printf("PCS module started successfully\n"); // 示例:读取和使用设备信息 - user_pcs_device_info_t device_info; - memset(&device_info, 0, sizeof(device_info)); + memset(&pcs_data, 0, sizeof(pcs_data_t)); // 示例:写入单个参数 int16_t new_target_voltage = 2205; @@ -858,11 +858,14 @@ static void* pcs_task_thread(void* arg) { while (1) { // 读取设备信息 - if (user_pcs_read_all(pcs_handler, &device_info) == 0) { + if (user_pcs_read_all(pcs_handler, &pcs_data) == 0) { printf("----------------Device ID: %d, protection_enable[100]:%d,reactive_overvoltage_exit[136]:%d\n", - device_info.firmware_version, - device_info.protection_enable, - device_info.reactive_overvoltage_exit); + pcs_data.firmware_version, + pcs_data.protection_enable, + pcs_data.reactive_overvoltage_exit); + //locked + memcpy( &g_pcs.data, &pcs_data, sizeof( pcs_data_t ) ); + //unlocked } // 每2秒读取一次 diff --git a/src/user_pcs.h b/src/user_pcs.h index 5de2169..ad75219 100644 --- a/src/user_pcs.h +++ b/src/user_pcs.h @@ -38,11 +38,7 @@ typedef enum { } user_pcs_param_type_t; /* PCS设备信息结构体 - 根据pcs-modbus.txt协议更新 */ -typedef struct { - /* 基本信息 */ - uint16_t device_id; - char device_name[32]; - +typedef struct{ //1. 遥测信息(只读) uint16_t firmware_version; // 软件版本 (地址0) uint16_t hardware_version; // 硬件版本 (地址1) @@ -162,7 +158,7 @@ typedef struct { uint16_t reactive_overvoltage_exit; // 无功过电压退出点 (地址136) uint16_t reserved_137_138[2]; // 保留 (地址137-138) uint16_t debug_vars[160]; // 调试变量48-207显示 (地址139-298) -} user_pcs_device_info_t; +} pcs_data_t; /* 单个参数写入函数类型定义 */ typedef bool (*user_pcs_single_param_writer_t)(user_mb_handler_t *mb_handler, @@ -171,6 +167,11 @@ typedef bool (*user_pcs_single_param_writer_t)(user_mb_handler_t *mb_handler, /* PCS模块句柄结构体 */ typedef struct user_pcs_handler user_pcs_handler_t; +typedef struct{ + pcs_data_t data; + int connected; + user_pcs_handler_t *handler; +} pcs_info_t; /* 创建PCS模块实例 */ user_pcs_handler_t *user_pcs_create(const char *name, int bus, int address); @@ -185,9 +186,9 @@ bool user_pcs_start(user_pcs_handler_t *handler); bool user_pcs_stop(user_pcs_handler_t *handler); /* 读取PCS设备信息 */ -int user_pcs_read_all(user_pcs_handler_t *pcs, user_pcs_device_info_t *device_info); +int user_pcs_read_all(user_pcs_handler_t *pcs, pcs_data_t *pcs_data); /* 写入PCS设备信息 */ -int user_pcs_write_all(user_pcs_handler_t *pcs, const user_pcs_device_info_t *device_info); +int user_pcs_write_all(user_pcs_handler_t *pcs, const pcs_data_t *pcs_data); /* 写入单个PCS参数 */ int user_pcs_write_single_param(user_pcs_handler_t *pcs, user_pcs_param_type_t param_type, const void *value); #ifdef __cplusplus diff --git a/src/user_web.h b/src/user_web.h new file mode 100644 index 0000000..e69de29 diff --git a/src/user_web_data.c b/src/user_web_data.c new file mode 100644 index 0000000..2d54138 --- /dev/null +++ b/src/user_web_data.c @@ -0,0 +1,305 @@ +#include "user.h" + +int process_websocket_message(const char *message, size_t len, char **p_resp ); +int process_http_post_message( char * url, char *message, size_t len, char **p_resp ); +int process_http_get_message( char *url, char **p_resp ); + +/* 处理收到的WebSocket数据 */ +int process_websocket_message(const char *message, size_t len, char **p_resp ) +{ + char *response = NULL; + + // 创建响应JSON对象 + cJSON *response_json = cJSON_CreateObject(); + if (!response_json) { + + response = strdup("{\"status\": \"error\", \"message\": \"Failed to create response\"}"); + } + + // 尝试解析接收到的消息 + cJSON *root = cJSON_ParseWithLength(message, len); + printf( "parse json, ret:%p\n", (void*)root ); + if (root) { + // 成功解析JSON + cJSON_AddStringToObject(response_json, "status", "success"); + cJSON_AddStringToObject(response_json, "message", "Received and parsed JSON message"); + + // 将接收到的数据添加到响应中 + cJSON_AddItemReferenceToObject(response_json, "received_data", root); + } else { + // 不是有效的JSON,作为纯文本处理 + cJSON_AddStringToObject(response_json, "status", "info"); + cJSON_AddStringToObject(response_json, "message", "Received plain text message"); + cJSON_AddStringToObject(response_json, "text", message); + + // 如果不是JSON,需要释放root吗?不需要,因为解析失败时cJSON_Parse返回NULL + } + + // 将JSON对象转换为字符串 + response = cJSON_PrintUnformatted(response_json); + + // 如果转换失败,提供默认响应 + if (!response) { + response = strdup("{\"status\": \"error\", \"message\": \"Failed to generate response\"}"); + } + + // 释放JSON对象 + cJSON_Delete(response_json); + + // 如果是JSON,这里不需要释放root,因为它已经通过cJSON_AddItemReferenceToObject添加到response_json中了 + // 当response_json被释放时,root也会被释放 + + if( p_resp ) + *p_resp = response; + return 0; +} + +/* 全局变量声明 */ +extern board_info_t g_board_info; + +extern pcs_info_t g_pcs; + +extern bms_info_t g_bms; + +/* 处理HTTP POST请求 */ +int process_http_post_message( char * url, char *message, size_t len, char **p_resp ) +{ + char *response = NULL; + cJSON *root = NULL; + cJSON *response_json = NULL; + cJSON *data_json = NULL; + + if (!message) { + return -1; + } + + // 创建响应JSON对象 + response_json = cJSON_CreateObject(); + if (!response_json) { + *p_resp = strdup("{\"code\": 1, \"msg\": \"Failed to create response\"}"); + return -1; + } + + // 解析JSON字符串 + root = cJSON_Parse(message); + if (!root) { + printf("JSON解析错误: %s\n", cJSON_GetErrorPtr()); + cJSON_AddNumberToObject(response_json, "code", 1); + cJSON_AddStringToObject(response_json, "msg", "Invalid JSON format"); + response = cJSON_PrintUnformatted(response_json); + cJSON_Delete(response_json); + if (p_resp) { + *p_resp = response; + } + return -1; + } + + // 获取msg字段,确定请求类型 + cJSON *msg_item = cJSON_GetObjectItem(root, "msg"); + if (!msg_item || !cJSON_IsString(msg_item)) { + cJSON_AddNumberToObject(response_json, "code", 1); + cJSON_AddStringToObject(response_json, "msg", "Missing or invalid 'msg' field"); + response = cJSON_PrintUnformatted(response_json); + cJSON_Delete(root); + cJSON_Delete(response_json); + if (p_resp) { + *p_resp = response; + } + return -1; + } + + const char *msg = msg_item->valuestring; + + // 处理获取PCS信息的请求 + if (strcmp(msg, "get_pcs_info") == 0) { + cJSON_AddNumberToObject(response_json, "code", 0); + cJSON_AddStringToObject(response_json, "msg", "get_pcs_info"); + + // 创建data字段 + data_json = cJSON_CreateObject(); + cJSON_AddItemToObject(response_json, "data", data_json); + + // 添加PCS信息字段 + cJSON_AddNumberToObject(data_json, "firmware_version", g_board_info.pcs_data.data.firmware_version); + cJSON_AddNumberToObject(data_json, "hardware_version", g_board_info.pcs_data.data.hardware_version); + cJSON_AddNumberToObject(data_json, "dc_voltage_p1v", g_board_info.pcs_data.data.dc_voltage_p1v); + cJSON_AddNumberToObject(data_json, "dc_pos_voltage_p1v", g_board_info.pcs_data.data.dc_pos_voltage_p1v); + cJSON_AddNumberToObject(data_json, "dc_neg_voltage_p1v", g_board_info.pcs_data.data.dc_neg_voltage_p1v); + cJSON_AddNumberToObject(data_json, "dc_current_p1a", g_board_info.pcs_data.data.dc_current_p1a); + cJSON_AddNumberToObject(data_json, "dc_power_p1kw", g_board_info.pcs_data.data.dc_power_p1kw); + cJSON_AddNumberToObject(data_json, "line_voltage_ab_p1v", g_board_info.pcs_data.data.line_voltage_ab_p1v); + cJSON_AddNumberToObject(data_json, "line_voltage_bc_p1v", g_board_info.pcs_data.data.line_voltage_bc_p1v); + cJSON_AddNumberToObject(data_json, "line_voltage_ca_p1v", g_board_info.pcs_data.data.line_voltage_ca_p1v); + cJSON_AddNumberToObject(data_json, "phase_current_a_p1a", g_board_info.pcs_data.data.phase_current_a_p1a); + cJSON_AddNumberToObject(data_json, "phase_current_b_p1a", g_board_info.pcs_data.data.phase_current_b_p1a); + cJSON_AddNumberToObject(data_json, "phase_current_c_p1a", g_board_info.pcs_data.data.phase_current_c_p1a); + cJSON_AddNumberToObject(data_json, "apparent_power_p1kva", g_board_info.pcs_data.data.apparent_power_p1kva); + cJSON_AddNumberToObject(data_json, "active_power_p1kw", g_board_info.pcs_data.data.active_power_p1kw); + cJSON_AddNumberToObject(data_json, "reactive_power_p1kvar", g_board_info.pcs_data.data.reactive_power_p1kvar); + cJSON_AddNumberToObject(data_json, "power_factor_p3", g_board_info.pcs_data.data.power_factor_p3); + cJSON_AddNumberToObject(data_json, "grid_frequency_p1hz", g_board_info.pcs_data.data.grid_frequency_p1hz); + cJSON_AddNumberToObject(data_json, "module_temperature_p1c", g_board_info.pcs_data.data.module_temperature_p1c); + cJSON_AddNumberToObject(data_json, "ambient_temperature_p1c", g_board_info.pcs_data.data.ambient_temperature_p1c); + cJSON_AddNumberToObject(data_json, "leakage_current_p1a", g_board_info.pcs_data.data.leakage_current_p1a); + cJSON_AddNumberToObject(data_json, "running_state", g_board_info.pcs_data.data.running_state); + cJSON_AddNumberToObject(data_json, "operation_mode", g_board_info.pcs_data.data.operation_mode); + cJSON_AddNumberToObject(data_json, "error_code", g_board_info.pcs_data.data.error_code); + cJSON_AddNumberToObject(data_json, "error_code2", g_board_info.pcs_data.data.error_code2); + cJSON_AddNumberToObject(data_json, "grid_voltage_a_p1v", g_board_info.pcs_data.data.grid_voltage_a_p1v); + cJSON_AddNumberToObject(data_json, "grid_voltage_b_p1v", g_board_info.pcs_data.data.grid_voltage_b_p1v); + cJSON_AddNumberToObject(data_json, "grid_voltage_c_p1v", g_board_info.pcs_data.data.grid_voltage_c_p1v); + cJSON_AddNumberToObject(data_json, "on_off_setting", g_board_info.pcs_data.data.on_off_setting); + cJSON_AddNumberToObject(data_json, "work_mode_setting", g_board_info.pcs_data.data.work_mode_setting); + cJSON_AddNumberToObject(data_json, "reactive_power_mode", g_board_info.pcs_data.data.reactive_power_mode); + cJSON_AddNumberToObject(data_json, "power_factor_setting_p3", g_board_info.pcs_data.data.power_factor_setting_p3); + cJSON_AddNumberToObject(data_json, "reactive_current_setting_p1a", g_board_info.pcs_data.data.reactive_current_setting_p1a); + cJSON_AddNumberToObject(data_json, "target_current_p1a", g_board_info.pcs_data.data.target_current_p1a); + cJSON_AddNumberToObject(data_json, "target_voltage_p1v", g_board_info.pcs_data.data.target_voltage_p1v); + cJSON_AddNumberToObject(data_json, "voltage_limit_current_p1a", g_board_info.pcs_data.data.voltage_limit_current_p1a); + cJSON_AddNumberToObject(data_json, "target_power_p1kw", g_board_info.pcs_data.data.target_power_p1kw); + cJSON_AddNumberToObject(data_json, "offline_voltage", g_board_info.pcs_data.data.offline_voltage); + cJSON_AddNumberToObject(data_json, "offline_frequency", g_board_info.pcs_data.data.offline_frequency); + cJSON_AddNumberToObject(data_json, "grid_voltage", g_board_info.pcs_data.data.grid_voltage); + cJSON_AddNumberToObject(data_json, "grid_frequency", g_board_info.pcs_data.data.grid_frequency); + cJSON_AddNumberToObject(data_json, "grid_overvoltage_threshold_p1v", g_board_info.pcs_data.data.grid_overvoltage_threshold_p1v); + cJSON_AddNumberToObject(data_json, "grid_undervoltage_threshold_p1v", g_board_info.pcs_data.data.grid_undervoltage_threshold_p1v); + cJSON_AddNumberToObject(data_json, "grid_overfrequency_threshold_p1hz", g_board_info.pcs_data.data.grid_overfrequency_threshold_p1hz); + cJSON_AddNumberToObject(data_json, "grid_underfrequency_threshold_p1hz", g_board_info.pcs_data.data.grid_underfrequency_threshold_p1hz); + cJSON_AddNumberToObject(data_json, "dc_overvoltage_threshold_p1v", g_board_info.pcs_data.data.dc_overvoltage_threshold_p1v); + cJSON_AddNumberToObject(data_json, "dc_overvoltage_recover_p1v", g_board_info.pcs_data.data.dc_overvoltage_recover_p1v); + cJSON_AddNumberToObject(data_json, "dc_undervoltage_threshold_p1v", g_board_info.pcs_data.data.dc_undervoltage_threshold_p1v); + cJSON_AddNumberToObject(data_json, "dc_undervoltage_recover_p1v", g_board_info.pcs_data.data.dc_undervoltage_recover_p1v); + cJSON_AddNumberToObject(data_json, "heartbeat_enable", g_board_info.pcs_data.data.heartbeat_enable); + cJSON_AddNumberToObject(data_json, "clear_fault", g_board_info.pcs_data.data.clear_fault); + + // 处理获取BMS信息的请求 + } else if (strcmp(msg, "get_bms_info") == 0) { + cJSON_AddNumberToObject(response_json, "code", 0); + cJSON_AddStringToObject(response_json, "msg", "get_bms_info"); + + // 创建data字段 + data_json = cJSON_CreateObject(); + cJSON_AddItemToObject(response_json, "data", data_json); + + // 添加BMS信息字段 + cJSON_AddNumberToObject(data_json, "max_charge_current_p1a", g_board_info.bms_data.data.max_charge_current_p1a); + cJSON_AddNumberToObject(data_json, "max_discharge_current_p1a", g_board_info.bms_data.data.max_discharge_current_p1a); + cJSON_AddNumberToObject(data_json, "total_voltage_p1v", g_board_info.bms_data.data.total_voltage_p1v); + cJSON_AddNumberToObject(data_json, "total_current_p1a", g_board_info.bms_data.data.total_current_p1a); + cJSON_AddNumberToObject(data_json, "total_soc_p1", g_board_info.bms_data.data.total_soc_p1); + cJSON_AddNumberToObject(data_json, "total_soh_p1", g_board_info.bms_data.data.total_soh_p1); + cJSON_AddNumberToObject(data_json, "max_charge_voltage_p1v", g_board_info.bms_data.data.max_charge_voltage_p1v); + cJSON_AddNumberToObject(data_json, "battery_status", g_board_info.bms_data.data.battery_status); + cJSON_AddNumberToObject(data_json, "light_alarm", g_board_info.bms_data.data.light_alarm); + cJSON_AddNumberToObject(data_json, "medium_alarm", g_board_info.bms_data.data.medium_alarm); + cJSON_AddNumberToObject(data_json, "serious_alarm", g_board_info.bms_data.data.serious_alarm); + cJSON_AddNumberToObject(data_json, "min_cell_voltage_p3v", g_board_info.bms_data.data.min_cell_voltage_p3v); + cJSON_AddNumberToObject(data_json, "min_cell_num", g_board_info.bms_data.data.min_cell_num); + cJSON_AddNumberToObject(data_json, "max_cell_voltage_p3v", g_board_info.bms_data.data.max_cell_voltage_p3v); + cJSON_AddNumberToObject(data_json, "max_cell_num", g_board_info.bms_data.data.max_cell_num); + cJSON_AddNumberToObject(data_json, "min_cell_temp_p1c", g_board_info.bms_data.data.min_cell_temp_p1c); + cJSON_AddNumberToObject(data_json, "min_temp_num", g_board_info.bms_data.data.min_temp_num); + cJSON_AddNumberToObject(data_json, "max_cell_temp_p1c", g_board_info.bms_data.data.max_cell_temp_p1c); + cJSON_AddNumberToObject(data_json, "max_temp_num", g_board_info.bms_data.data.max_temp_num); + + // 处理设置PCS参数的请求 + } else if (strcmp(msg, "set_pcs_parameter") == 0) { + cJSON *data_item = cJSON_GetObjectItem(root, "data"); + if (!data_item || !cJSON_IsObject(data_item)) { + cJSON_AddNumberToObject(response_json, "code", 1); + cJSON_AddStringToObject(response_json, "msg", "Missing or invalid 'data' field"); + } else { + // 标记是否有参数被设置 + bool parameter_set = false; + + // 处理各个PCS参数 + if (cJSON_HasObjectItem(data_item, "on_off_setting")) { + uint16_t value = (uint16_t)cJSON_GetObjectItem(data_item, "on_off_setting")->valueint; + user_pcs_write_single_param(g_pcs.handler, USER_PCS_PARAM_ON_OFF_SETTING, &value); + parameter_set = true; + } + + if (cJSON_HasObjectItem(data_item, "work_mode_setting")) { + uint16_t value = (uint16_t)cJSON_GetObjectItem(data_item, "work_mode_setting")->valueint; + user_pcs_write_single_param(g_pcs.handler, USER_PCS_PARAM_WORK_MODE, &value); + parameter_set = true; + } + + if (cJSON_HasObjectItem(data_item, "reactive_power_mode")) { + uint16_t value = (uint16_t)cJSON_GetObjectItem(data_item, "reactive_power_mode")->valueint; + user_pcs_write_single_param(g_pcs.handler, USER_PCS_PARAM_REACTIVE_POWER_MODE, &value); + parameter_set = true; + } + + if (cJSON_HasObjectItem(data_item, "power_factor_setting_p3")) { + int16_t value = (int16_t)cJSON_GetObjectItem(data_item, "power_factor_setting_p3")->valueint; + user_pcs_write_single_param(g_pcs.handler, USER_PCS_PARAM_POWER_FACTOR, &value); + parameter_set = true; + } + + if (cJSON_HasObjectItem(data_item, "reactive_current_setting_p1a")) { + int16_t value = (int16_t)cJSON_GetObjectItem(data_item, "reactive_current_setting_p1a")->valueint; + user_pcs_write_single_param(g_pcs.handler, USER_PCS_PARAM_REACTIVE_CURRENT, &value); + parameter_set = true; + } + + if (cJSON_HasObjectItem(data_item, "target_current_p1a")) { + int16_t value = (int16_t)cJSON_GetObjectItem(data_item, "target_current_p1a")->valueint; + user_pcs_write_single_param(g_pcs.handler, USER_PCS_PARAM_TARGET_CURRENT, &value); + parameter_set = true; + } + + if (cJSON_HasObjectItem(data_item, "target_voltage_p1v")) { + uint16_t value = (uint16_t)cJSON_GetObjectItem(data_item, "target_voltage_p1v")->valueint; + user_pcs_write_single_param(g_pcs.handler, USER_PCS_PARAM_TARGET_VOLTAGE, &value); + parameter_set = true; + } + + if (cJSON_HasObjectItem(data_item, "voltage_limit_current_p1a")) { + uint16_t value = (uint16_t)cJSON_GetObjectItem(data_item, "voltage_limit_current_p1a")->valueint; + user_pcs_write_single_param(g_pcs.handler, USER_PCS_PARAM_OVERCURRENT_THRESHOLD, &value); + parameter_set = true; + } + + if (cJSON_HasObjectItem(data_item, "target_power_p1kw")) { + int16_t value = (int16_t)cJSON_GetObjectItem(data_item, "target_power_p1kw")->valueint; + user_pcs_write_single_param(g_pcs.handler, USER_PCS_PARAM_TARGET_POWER, &value); + parameter_set = true; + } + + if (cJSON_HasObjectItem(data_item, "clear_fault")) { + uint16_t value = (uint16_t)cJSON_GetObjectItem(data_item, "clear_fault")->valueint; + user_pcs_write_single_param(g_pcs.handler, USER_PCS_PARAM_CLEAR_FAULT, &value); + parameter_set = true; + } + + // 设置响应 + cJSON_AddNumberToObject(response_json, "code", 0); + cJSON_AddStringToObject(response_json, "msg", "set_pcs_parameter"); + } + + // 未知的请求类型 + } else { + cJSON_AddNumberToObject(response_json, "code", 1); + cJSON_AddStringToObject(response_json, "msg", "Unknown message type"); + } + + // 将JSON对象转换为字符串 + response = cJSON_PrintUnformatted(response_json); + + // 如果转换失败,提供默认响应 + if (!response) { + response = strdup("{\"code\": 1, \"msg\": \"Failed to generate response\"}"); + } + + // 释放JSON对象 + cJSON_Delete(root); + cJSON_Delete(response_json); + + // 设置响应指针 + if (p_resp) { + *p_resp = response; + } + + return 0; +} diff --git a/src/user_web_server.c b/src/user_web_server.c new file mode 100644 index 0000000..c728cc5 --- /dev/null +++ b/src/user_web_server.c @@ -0,0 +1,837 @@ +/* + * lws-minimal-http-websocket-combined + * + * 整合 GET、POST 和 WebSocket 功能的最小示例 + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include "user.h" + +#define LWS_PLUGIN_STATIC + +// 添加全局连接管理相关定义 +#define MAX_CLIENTS 128 +#define BROADCAST_INTERVAL 2 // 广播间隔(秒) +static struct lws_context *g_context; +// 全局标志,用于控制广播线程 +static int broadcast_running = 1; + +/* 全局客户端连接列表结构 */ +struct client_connection { + struct lws *wsi; + int active; +}; + +/* 全局客户端连接列表和互斥锁 */ +static struct client_connection clients[MAX_CLIENTS]; +static pthread_mutex_t clients_mutex = PTHREAD_MUTEX_INITIALIZER; + +/* WebSocket 消息结构 */ +struct msg { + void *payload; /* is malloc'd */ + size_t len; + char binary; + char first; + char final; +}; + +/* WebSocket 会话数据 */ +struct per_session_data__minimal_server_echo { + struct lws_ring *ring; + uint32_t msglen; + uint32_t tail; + uint8_t completed:1; + uint8_t flow_controlled:1; + uint8_t write_consume_pending:1; +}; + +/* WebSocket 虚拟主机数据 */ +struct vhd_minimal_server_echo { + struct lws_context *context; + struct lws_vhost *vhost; + + int *interrupted; + int *options; +}; + +/* HTTP POST 会话数据 */ +/* 每个会话的私有数据 */ +struct pss { + struct lws_spa *spa; + char *url; + char *post_body; + size_t post_body_len; +}; + +#define RING_DEPTH 4096 +#define MAX_BUF_SIZE 4096 + +static int interrupted, options; +/* 初始化全局客户端连接列表 */ +static void init_clients_list() { + pthread_mutex_lock(&clients_mutex); + for (int i = 0; i < MAX_CLIENTS; i++) { + clients[i].wsi = NULL; + clients[i].active = 0; + } + pthread_mutex_unlock(&clients_mutex); +} + +/* 将客户端连接添加到全局列表 */ +static int add_client_to_list(struct lws *wsi) { + pthread_mutex_lock(&clients_mutex); + for (int i = 0; i < MAX_CLIENTS; i++) { + if (!clients[i].active) { + clients[i].wsi = wsi; + clients[i].active = 1; + pthread_mutex_unlock(&clients_mutex); + return 0; + } + } + pthread_mutex_unlock(&clients_mutex); + return -1; /* 客户端列表已满 */ +} + +/* 从全局列表中移除客户端连接 */ +static void remove_client_from_list(struct lws *wsi) { + pthread_mutex_lock(&clients_mutex); + for (int i = 0; i < MAX_CLIENTS; i++) { + if (clients[i].active && clients[i].wsi == wsi) { + clients[i].wsi = NULL; + clients[i].active = 0; + break; + } + } + pthread_mutex_unlock(&clients_mutex); +} + +/* 向所有活跃的客户端发送消息 */ +static int send_message_to_all_clients(const char *message, size_t len) { + pthread_mutex_lock(&clients_mutex); + + for (int i = 0; i < MAX_CLIENTS; i++) { + if (clients[i].active && clients[i].wsi) { + struct per_session_data__minimal_server_echo *pss = + lws_wsi_user(clients[i].wsi); + + if (pss && pss->ring) { + struct msg amsg; + int n = lws_ring_get_count_free_elements(pss->ring); + + if (n) { + amsg.first = 1; + amsg.final = 1; + amsg.binary = 0; + amsg.len = len; + + /* 分配消息内存 */ + amsg.payload = malloc(LWS_PRE + len + 1); + if (amsg.payload) { + memset((char *)amsg.payload + LWS_PRE, 0, len + 1); + memcpy((char *)amsg.payload + LWS_PRE, message, len); + + if (lws_ring_insert(pss->ring, &amsg, 1)) { + int x= lws_callback_on_writable(clients[i].wsi); + printf( "broadcast ---------------XXX-------------lws_cb_on_writeable( wsi[%d]:%p), ret:%d\n", x,(void*)clients[i].wsi, x); + lws_cancel_service_pt(clients[i].wsi); + } else { + lwsl_user("Failed to insert message into ring buffer\n"); + free(amsg.payload); + } + } + } + } + } + } + if( g_context ){ + printf( "Cancle service \n" ); + //lws_cancel_service(g_context); + } + + pthread_mutex_unlock(&clients_mutex); + return 0; +} + +#if 1 + +int ws_received_data_handle(struct lws *wsi, const char *data, size_t len, char **p_resp ); +int http_received_data_handle(struct lws *wsi, const char *data, size_t len, char **p_resp); + +#else +/* 测试用广播线程函数 */ +static void *test_thread_func(void *arg) { + time_t rawtime; + struct tm *timeinfo; + char time_string[64]; + arg=arg; + while (broadcast_running) { + // 获取当前时间 + time(&rawtime); + timeinfo = localtime(&rawtime); + + // 格式化时间字符串 + strftime(time_string, sizeof(time_string), "%Y-%m-%d %H:%M:%S", timeinfo); + + // 创建JSON消息 + cJSON *root = cJSON_CreateObject(); + if (root) { + cJSON_AddStringToObject(root, "type", "time_broadcast"); + cJSON_AddStringToObject(root, "timestamp", time_string); + cJSON_AddStringToObject(root, "message", "Server time update"); + + // 转换为字符串 + char *json_string = cJSON_PrintUnformatted(root); + if (json_string) { + // 发送消息给所有客户端 + send_message_to_all_clients(json_string, strlen(json_string)); + lwsl_user("Broadcasting time: %s\n", json_string); + + // 释放JSON字符串 + free(json_string); + } + + // 释放JSON对象 + cJSON_Delete(root); + } + + // 等待指定的时间间隔 + for (int i = 0; i < BROADCAST_INTERVAL && broadcast_running; i++) { + sleep(1); // 每秒检查一次是否需要退出 + } + } + + lwsl_user("Broadcast thread exiting\n"); + pthread_exit(NULL); +} +#endif + +/* 销毁 WebSocket 消息 */ +static void __minimal_destroy_message(void *_msg) { + struct msg *msg = _msg; + + free(msg->payload); + msg->payload = NULL; + msg->len = 0; +} + +/* 使用cJSON解析JSON数据的函数 */ +static int parse_json_with_cjson(const char *json_str, char **text1, char **send); + + +/* 处理WebSocket JSON消息的函数 */ +int process_websocket_message(const char *message, size_t len, char **p_resp ); +int process_http_post_message( char * url, char *message, size_t len, char **p_resp ); +int process_http_get_message( char *url, char **p_resp ); + +/* WebSocket 回调函数 */ +static int callback_minimal_server_echo(struct lws *wsi, enum lws_callback_reasons reason, + void *user, void *in, size_t len) +{ + struct per_session_data__minimal_server_echo *pss = + (struct per_session_data__minimal_server_echo *)user; + struct vhd_minimal_server_echo *vhd = (struct vhd_minimal_server_echo *) + lws_protocol_vh_priv_get(lws_get_vhost(wsi), + lws_get_protocol(wsi)); + const struct msg *pmsg; + struct msg amsg; + int m, n, flags; + + // 添加详细的回调日志,记录reason值和对应的含义 + switch (reason) { + case LWS_CALLBACK_PROTOCOL_INIT: + lwsl_user("WebSocket: 协议初始化\n"); + break; + case LWS_CALLBACK_ESTABLISHED: + lwsl_user("WebSocket: 连接已建立\n"); + break; + case LWS_CALLBACK_RECEIVE: + lwsl_user("WebSocket: 收到消息\n"); + break; + case LWS_CALLBACK_CLOSED: + lwsl_user("WebSocket: 连接已关闭\n"); + break; + default: + lwsl_user("WebSocket: 回调 reason=%d\n", reason); + break; + } + + switch (reason) { + case LWS_CALLBACK_PROTOCOL_INIT: + vhd = lws_protocol_vh_priv_zalloc(lws_get_vhost(wsi), + lws_get_protocol(wsi), + sizeof(struct vhd_minimal_server_echo)); + if (!vhd) + return -1; + + vhd->context = lws_get_context(wsi); + vhd->vhost = lws_get_vhost(wsi); + + /* 获取通过 pvo 传递的指针 */ + vhd->interrupted = (int *)lws_pvo_search( + (const struct lws_protocol_vhost_options *)in, + "interrupted")->value; + vhd->options = (int *)lws_pvo_search( + (const struct lws_protocol_vhost_options *)in, + "options")->value; + break; + + case LWS_CALLBACK_ESTABLISHED: + lwsl_warn("WebSocket connection established\n"); + pss->ring = lws_ring_create(sizeof(struct msg), RING_DEPTH, + __minimal_destroy_message); + if (!pss->ring) + return 1; + pss->tail = 0; + + // 将新连接添加到全局客户端列表 + if (add_client_to_list(wsi) != 0) { + lwsl_err("Failed to add client to list\n"); + } + break; + + // 修改LWS_CALLBACK_SERVER_WRITEABLE回调处理逻辑 + case LWS_CALLBACK_SERVER_WRITEABLE: + printf( "cb ---- LWS_CALLBACK_SERVER_WRITEABLE --------------\n" ); + if (pss->write_consume_pending) { + /* 执行延迟的 fifo 消费 */ + lws_ring_consume_single_tail(pss->ring, &pss->tail, 1); + pss->write_consume_pending = 0; + } + + pmsg = lws_ring_get_element(pss->ring, &pss->tail); + if (!pmsg) { + break; + } + + flags = lws_write_ws_flags( + pmsg->binary ? LWS_WRITE_BINARY : LWS_WRITE_TEXT, + pmsg->first, pmsg->final); + + /* 注意我们在 payload 中已经预留了 LWS_PRE 的空间 */ + m = lws_write(wsi, ((unsigned char *)pmsg->payload) + + LWS_PRE, pmsg->len, (enum lws_write_protocol)flags); + if (m < (int)pmsg->len) { + lwsl_err("ERROR %d writing to ws socket\n", m); + return -1; + } + + /* 立即消费已发送的消息,而不是等待下一次回调 */ + lws_ring_consume_single_tail(pss->ring, &pss->tail, 1); + pss->write_consume_pending = 0; // 确保标志被重置 + + /* 如果有更多消息,立即请求下一次可写回调 */ + pmsg = lws_ring_get_element(pss->ring, &pss->tail); + if (pmsg) { + + int x = lws_callback_on_writable(wsi); + printf( "LWS_CALLBACK_SERVER_WRITEABLE -- cb on writeable(wsi:%p) ----ret %d\n", (void*)wsi, x); + } + + if (pss->flow_controlled && + (int)lws_ring_get_count_free_elements(pss->ring) > RING_DEPTH - 5) { + lws_rx_flow_control(wsi, 1); + pss->flow_controlled = 0; + } + + if ((*vhd->options & 1) && pmsg && pmsg->final) + pss->completed = 1; + + break; + + case LWS_CALLBACK_RECEIVE: + lwsl_user("WebSocket message received: %s\n", (const char *)in); + + // 使用cJSON处理接收到的消息 + char *processed_response; + if( process_websocket_message((const char *)in, len, &processed_response ) == 0 ){ + printf("处理后的WebSocket响应: %s\n", processed_response); + } + + amsg.first = (char)lws_is_first_fragment(wsi); + amsg.final = (char)lws_is_final_fragment(wsi); + amsg.binary = (char)lws_frame_is_binary(wsi); + n = (int)lws_ring_get_count_free_elements(pss->ring); + if (!n) { + lwsl_user("dropping!\n"); + if (processed_response) free(processed_response); + break; + } + + if (amsg.final) + pss->msglen = 0; + else + pss->msglen += (uint32_t)len; + + // 如果有处理后的响应,使用它作为回显;否则使用原始消息 + const char *echo_content = processed_response ? processed_response : (const char *)in; + size_t echo_len = processed_response ? strlen(processed_response) : len; + + amsg.len = echo_len; + /* 注意我们多分配了 LWS_PRE 的空间 */ + amsg.payload = malloc(LWS_PRE + echo_len + 1); + if (!amsg.payload) { + lwsl_user("OOM: dropping\n"); + if (processed_response) free(processed_response); + break; + } + + memset((char *)amsg.payload + LWS_PRE, 0, echo_len + 1); + memcpy((char *)amsg.payload + LWS_PRE, echo_content, echo_len); + + if (!lws_ring_insert(pss->ring, &amsg, 1)) { + __minimal_destroy_message(&amsg); + lwsl_user("dropping!\n"); + } else { + lws_callback_on_writable(wsi); + } + + // 释放处理后的响应 + if (processed_response) { + free(processed_response); + } + + break; + + case LWS_CALLBACK_CLOSED: + lwsl_user("WebSocket连接已关闭,释放资源\n"); + + // 从全局客户端列表中移除连接 + remove_client_from_list(wsi); + + if (pss->ring) { + lws_ring_destroy(pss->ring); + pss->ring = NULL; + } + break; + + default: + break; + } + + return 0; +} + +static int callback_http(struct lws *wsi, enum lws_callback_reasons reason, void *user, void *in, size_t len) +{ + struct pss *pss = (struct pss *)user; + uint8_t buf[LWS_PRE + MAX_BUF_SIZE], *start = &buf[LWS_PRE], + *p = start, *end = &buf[sizeof(buf) - 1]; + int json_len; + const char *json_response = NULL; + + switch (reason) { + case LWS_CALLBACK_HTTP: + /* 处理 GET 请求 */ + printf( "------LWS_CALLBACK_HTTP------in[%s]-\n", (char*)in ); + if (lws_hdr_total_length(wsi, WSI_TOKEN_GET_URI)) { + /* 处理 GET 请求,返回 JSON 而不是重定向 */ + if( strstr( in, "api" ) ){ + if( pss->url ){ + free( pss->url ); + } + pss->url = strdup((const char *)in); + + /* 使用cJSON构建JSON响应 */ + cJSON *root = cJSON_CreateObject(); + if (root) { + cJSON_AddStringToObject(root, "method", "GET"); + cJSON_AddStringToObject(root, "status", "success"); + cJSON_AddStringToObject(root, "message", "This is a GET response"); + + json_response = cJSON_PrintUnformatted(root); + json_len = json_response ? strlen(json_response) : 0; + } + + /* 设置 HTTP 头 */ + if (lws_add_http_common_headers(wsi, HTTP_STATUS_OK, "application/json", + json_len, &p, end) < 0) { + if (root) cJSON_Delete(root); + if (json_response) free((void*)json_response); + return -1; + } + if (lws_finalize_write_http_header(wsi, start, &p, end) < 0) { + if (root) cJSON_Delete(root); + if (json_response) free((void*)json_response); + return -1; + } + + /* 写入 JSON 响应体 */ + if (lws_write(wsi, (unsigned char *)json_response, json_len, LWS_WRITE_HTTP_FINAL) < 0) { + if (root) cJSON_Delete(root); + if (json_response) free((void*)json_response); + return -1; + } + + // 释放资源 + if (root) cJSON_Delete(root); + if (json_response) free((void*)json_response); + + return -1; // 修复:成功处理请求后返回-1而不是0 + } + }else if (lws_hdr_total_length(wsi, WSI_TOKEN_POST_URI)) { + /* 增加 POST 请求专用路径 */ + if( strstr( in, "api" ) ){ + if( pss->url ){ + free( pss->url ); + } + pss->url = strdup((const char *)in); + return 0; + } + if (!strcmp((const char *)in, "/api/post")) { + // POST 请求将通过后续的回调处理 + return 0; + } + } else { + printf("------------not GET method\n" ); + } + // 对于其他路径,让 lws_callback_http_dummy 处理 + break; + + case LWS_CALLBACK_HTTP_BODY: + /* 处理 POST 请求体 */ + if (!pss->post_body) { + pss->post_body = malloc(len + 1); + if (!pss->post_body) { + return -1; + } + memcpy(pss->post_body, in, len); + pss->post_body[len] = '\0'; + pss->post_body_len = len; + } else { + char *new_body = realloc(pss->post_body, pss->post_body_len + len + 1); + if (!new_body) { + free(pss->post_body); + pss->post_body = NULL; + return -1; + } + pss->post_body = new_body; + memcpy(pss->post_body + pss->post_body_len, in, len); + pss->post_body[pss->post_body_len + len] = '\0'; + pss->post_body_len += len; + } + break; + + case LWS_CALLBACK_CLOSED_CLIENT_HTTP: + if (pss->spa && lws_spa_destroy(pss->spa)) + return -1; + if (pss->post_body) { + free(pss->post_body); + pss->post_body = NULL; + } + break; + + case LWS_CALLBACK_HTTP_BODY_COMPLETION: + /* 构建 JSON 响应 */ + if (pss->post_body) { + char *resp = NULL; + char *text1 = NULL; + char *send = NULL; + + printf("接收到的JSON请求体: %s\n", pss->post_body); + + // 使用cJSON解析JSON格式的请求体 + if( process_http_post_message(pss->url, pss->post_body, pss->post_body_len, &resp) == 0){ + // 调试输出,查看解析后的参数 + printf("解析JSON参数: text1='%s', send='%s'\n", text1 ? text1 : "", send ? send : ""); + + /* 使用cJSON动态构建JSON响应 */ + cJSON *root = cJSON_CreateObject(); + if (root) { + cJSON_AddStringToObject(root, "method", "POST"); + cJSON_AddStringToObject(root, "status", "success"); + cJSON_AddStringToObject(root, "message", "This is a JSON POST response"); + + // 创建data对象 + cJSON *data = cJSON_CreateObject(); + if (data) { + cJSON_AddStringToObject(data, "text1", text1 ? text1 : ""); + cJSON_AddStringToObject(data, "send", send ? send : ""); + cJSON_AddItemToObject(root, "data", data); + } + + char *json_body = cJSON_PrintUnformatted(root); + json_len = json_body ? strlen(json_body) : 0; + + /* 重置缓冲区指针用于HTTP头 */ + p = start; + + /* 设置 HTTP 头 */ + if (lws_add_http_common_headers(wsi, HTTP_STATUS_OK, "application/json", + json_len, &p, end) < 0) { + printf("设置HTTP头失败\n"); + free(text1); + free(send); + cJSON_Delete(root); + if (json_body) free(json_body); + return -1; + } + if (lws_finalize_write_http_header(wsi, start, &p, end) < 0) { + printf("写入HTTP头失败\n"); + free(text1); + free(send); + cJSON_Delete(root); + if (json_body) free(json_body); + return -1; + } + + /* 写入 JSON 响应体 */ + if (lws_write(wsi, (unsigned char *)json_body, json_len, LWS_WRITE_HTTP_FINAL) < 0) { + printf("写入响应体失败\n"); + free(text1); + free(send); + cJSON_Delete(root); + if (json_body) free(json_body); + return -1; + } + printf("成功返回JSON响应: %s\n", json_body); + + // 释放资源 + free(json_body); + cJSON_Delete(root); + } + + // 释放解析出的参数 + free(text1); + free(send); + } else { + /* JSON解析失败 */ + printf("JSON解析失败\n"); + // 使用cJSON构建错误响应 + cJSON *root = cJSON_CreateObject(); + if (root) { + cJSON_AddStringToObject(root, "method", "POST"); + cJSON_AddStringToObject(root, "status", "error"); + cJSON_AddStringToObject(root, "message", "Invalid JSON format"); + + json_response = cJSON_PrintUnformatted(root); + json_len = json_response ? strlen(json_response) : 0; + } + + if (lws_add_http_common_headers(wsi, HTTP_STATUS_BAD_REQUEST, "application/json", + json_len, &p, end) < 0) { + if (root) cJSON_Delete(root); + if (json_response) free((void*)json_response); + return -1; + } + if (lws_finalize_write_http_header(wsi, start, &p, end) < 0) { + if (root) cJSON_Delete(root); + if (json_response) free((void*)json_response); + return -1; + } + if (lws_write(wsi, (unsigned char *)json_response, json_len, LWS_WRITE_HTTP_FINAL) < 0) { + if (root) cJSON_Delete(root); + if (json_response) free((void*)json_response); + return -1; + } + + // 释放资源 + if (root) cJSON_Delete(root); + if (json_response) free((void*)json_response); + } + } else { + /* 如果没有请求体,返回默认的JSON响应 */ + + // 使用cJSON构建错误响应 + cJSON *root = cJSON_CreateObject(); + if (root) { + cJSON_AddStringToObject(root, "method", "POST"); + cJSON_AddStringToObject(root, "status", "error"); + cJSON_AddStringToObject(root, "message", "No request body received"); + + json_response = cJSON_PrintUnformatted(root); + json_len = json_response ? strlen(json_response) : 0; + } + + if (lws_add_http_common_headers(wsi, HTTP_STATUS_BAD_REQUEST, "application/json", + json_len, &p, end) < 0) { + if (root) cJSON_Delete(root); + if (json_response) free((void*)json_response); + return -1; + } + if (lws_finalize_write_http_header(wsi, start, &p, end) < 0) { + if (root) cJSON_Delete(root); + if (json_response) free((void*)json_response); + return -1; + } + if (lws_write(wsi, (unsigned char *)json_response, json_len, LWS_WRITE_HTTP_FINAL) < 0) { + if (root) cJSON_Delete(root); + if (json_response) free((void*)json_response); + return -1; + } + + // 释放资源 + if (root) cJSON_Delete(root); + if (json_response) free((void*)json_response); + } + break; + + case LWS_CALLBACK_HTTP_DROP_PROTOCOL: + /* 当 wsi 用户空间将要被销毁时调用 */ + if (pss->spa) { + lws_spa_destroy(pss->spa); + pss->spa = NULL; + } + if (pss->post_body) { + free(pss->post_body); + pss->post_body = NULL; + } + break; + + default: + break; + } + + return lws_callback_http_dummy(wsi, reason, user, in, len); +} + +/* 注册协议 */ +static struct lws_protocols protocols[] = { + { "http", callback_http, sizeof(struct pss), 0, 0, NULL, 0 }, + { "ws", callback_minimal_server_echo, + sizeof(struct per_session_data__minimal_server_echo), 0, 0, NULL, 0 }, + LWS_PROTOCOL_LIST_TERM +}; + +/* 传递指针给协议 */ +static const struct lws_protocol_vhost_options pvo_options = { + NULL, + NULL, + "options", /* pvo 名称 */ + (void *)&options /* pvo 值 */ +}; + +static const struct lws_protocol_vhost_options pvo_interrupted = { + &pvo_options, + NULL, + "interrupted", /* pvo 名称 */ + (void *)&interrupted /* pvo 值 */ +}; + +static const struct lws_protocol_vhost_options pvo = { + NULL, /* "next" pvo 链表 */ + &pvo_interrupted, /* "child" pvo 链表 */ + "ws", /* 此虚拟主机上我们所属的协议名称 */ + "" /* 忽略 */ +}; + +/* WebSocket 扩展 */ +static const struct lws_extension extensions[] = { + { + "permessage-deflate", + lws_extension_callback_pm_deflate, + "permessage-deflate" + "; client_no_context_takeover" + "; client_max_window_bits" + }, + { NULL, NULL, NULL /* 终止符 */ } +}; + +/* 默认挂载服务 URL 空间 */ +static const struct lws_http_mount mount = { + /* .mount_next */ NULL, /* 链表 "next" */ + /* .mountpoint */ "/", /* 挂载点 URL */ + /* .origin */ "./mount-origin", /* 从目录提供服务 */ + /* .def */ "index.html", /* 默认文件名 */ + /* .protocol */ NULL, + /* .cgienv */ NULL, + /* .extra_mimetypes */ NULL, + /* .interpret */ NULL, + /* .cgi_timeout */ 0, + /* .cache_max_age */ 0, + /* .auth_mask */ 0, + /* .cache_reusable */ 0, + /* .cache_revalidate */ 0, + /* .cache_intermediaries */ 0, + /* .origin_protocol */ LWSMPRO_FILE, /* 目录中的文件 */ + /* .mountpoint_len */ 1, /* 字符计数 */ + /* .basic_auth_login_file */ NULL, +}; + + +static void* webserver_task_thread(void* arg) +{ + struct lws_context_creation_info info; + struct lws_context *context; + const char *p; + int n = 0, logs = LLL_USER | LLL_ERR | LLL_WARN | LLL_NOTICE + /* 要在内置 lws 中包含高于 NOTICE 的 LLL_ 详细度, + * lws 必须配置并构建为 + * -DCMAKE_BUILD_TYPE=DEBUG 而不是 =RELEASE */ + /* | LLL_INFO */ /* | LLL_PARSER */ /* | LLL_HEADER */ + /* | LLL_EXT */ /* | LLL_CLIENT */ /* | LLL_LATENCY */ + /* | LLL_DEBUG */; + pthread_t broadcast_thread; + int thread_create_result; + + lws_set_log_level(logs, NULL); + lwsl_user("LWS minimal HTTP & WebSocket combined server | visit http://localhost:7681\n"); + + // 初始化全局客户端连接列表 + for (int i = 0; i < MAX_CLIENTS; i++) { + clients[i].wsi = NULL; + clients[i].active = 0; + } + + memset(&info, 0, sizeof info); /* 否则是未初始化的垃圾值 */ + info.port = 7681; + info.protocols = protocols; + info.mounts = &mount; + info.pvo = &pvo; + info.extensions = extensions; + info.options = LWS_SERVER_OPTION_VALIDATE_UTF8 | + LWS_SERVER_OPTION_HTTP_HEADERS_SECURITY_BEST_PRACTICES_ENFORCE; + info.mounts = NULL; //&mount; + + context = lws_create_context(&info); + if (!context) { + lwsl_err("lws init failed\n"); + return NULL; + } + g_context = context; + +#if 0 + // 创建广播线程 + init_clients_list(); + broadcast_running = 1; + thread_create_result = pthread_create(&broadcast_thread, NULL, test_thread_func, NULL); + if (thread_create_result != 0) { + lwsl_err("Failed to create broadcast thread\n"); + lws_context_destroy(context); + return NULL; + } +#endif + + while (n >= 0 && !interrupted){ + lws_service(context, 0); + } + + // 停止广播线程 + broadcast_running = 0; + pthread_join(broadcast_thread, NULL); + + lws_context_destroy(context); + + return 0; +} + +int webserver_start(void) +{ + pthread_t thread_id; + int ret = pthread_create(&thread_id, NULL, webserver_task_thread, NULL); + if (ret != 0) { + perror("webserver_start: pthread_create failed"); + return -1; + } + // 分离线程,避免资源泄漏 + pthread_detach(thread_id); + printf("webserver_start... \n" ); + return 0; +} + diff --git a/test.html b/test.html new file mode 100644 index 0000000..b696ef1 --- /dev/null +++ b/test.html @@ -0,0 +1,488 @@ + + + + + + HTTP & WebSocket 综合测试页面 + + + +

HTTP & WebSocket 综合测试页面

+ + +
+

GET 请求测试

+

点击按钮发送 GET 请求到服务器,并查看返回的 JSON 数据。

+ + + +
+ 等待响应... +
+
+ + +
+

POST 请求测试

+

填写表单并提交,服务器将返回包含表单数据的 JSON 响应。

+ +
+ + +
+ +
+ + +
+ + + + +
+ 等待响应... +
+
+ + +
+

WebSocket 测试

+

连接到 WebSocket 服务器,并发送/接收消息。

+ +
+ + +
+ +
+ + + 未连接 +
+ + +
+ + + + -- 2.34.1