From d1b7e883b94335cead522a07d57fc6e8868226f8 Mon Sep 17 00:00:00 2001 From: kyz Date: Tue, 23 Apr 2024 14:34:14 +0800 Subject: [PATCH] =?utf8?q?=E5=A2=9E=E5=8A=A0=E6=B5=81=E9=87=8F=E8=AE=A1?= =?utf8?q?=E6=B0=94=E4=BD=93=E4=BF=AE=E6=AD=A3=E7=B3=BB=E6=95=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=utf8 Content-Transfer-Encoding: 8bit 1.wifi连接支持设备锁定指令 2.流量计气体修正系数可配置 3.调试工具增加参数读写功能 4.上报平台数据按协议调整 --- MDK-ARM/welding_controller_v2.uvprojx | 5 + tools_v2/test.py | 103 +- tools_v2/test.ui | 1437 +++++++++++++++- user/at_parser.c | 2 +- user/cJSON.c | 2269 +++++++++++++++++++++++++ user/cJSON.h | 247 +++ user/user.h | 13 +- user/user_adc.c | 18 +- user/user_app.c | 22 +- user/user_cdc_rx_2.c | 101 +- user/user_debug.c | 3 +- user/user_eth.c | 4 +- user/user_flowmeter.c | 60 +- user/user_report.c | 5 +- user/user_ui.c | 82 +- user/user_valve_ctrl.c | 2 +- user/user_wifi.c | 458 ++++- 17 files changed, 4706 insertions(+), 125 deletions(-) create mode 100644 user/cJSON.c create mode 100644 user/cJSON.h diff --git a/MDK-ARM/welding_controller_v2.uvprojx b/MDK-ARM/welding_controller_v2.uvprojx index 0334dad..7c12b8b 100644 --- a/MDK-ARM/welding_controller_v2.uvprojx +++ b/MDK-ARM/welding_controller_v2.uvprojx @@ -1245,6 +1245,11 @@ 1 ..\user\ht1622.c + + cJSON.c + 1 + ..\user\cJSON.c + diff --git a/tools_v2/test.py b/tools_v2/test.py index ff11d20..39aa76c 100644 --- a/tools_v2/test.py +++ b/tools_v2/test.py @@ -20,7 +20,7 @@ import json #import serial.serialutil #import modbus_tk -import ui_test as ui_welding +import test_ui as ui_welding import time import crcmod @@ -32,12 +32,14 @@ import yn_download #crc16 = crcmod.mkCrcFun(0x18005, rev=True, initCrc=0xFFFF, xorOut=0x0000) from collections import deque +gas_coefficient = [ (u'氩气(1000)',1000), (u'二氧化碳(570)', 570), (u'混合气(910)',910) ] + class App( QDialog, ui_welding.Ui_Dialog ): trigger_rx_pkt = pyqtSignal( tuple ) def __init__( self ): super().__init__() self.setupUi(self) - self.setWindowTitle( u"焊接控制器调试工具 V0.1") + self.setWindowTitle( u"焊接控制器调试工具 V0.2") self.trigger_rx_pkt.connect( self.on_rx_pkt ) @@ -82,6 +84,72 @@ class App( QDialog, ui_welding.Ui_Dialog ): self.btn_files_clear.released.connect( self.on_btn_files_clear ) self.listWidget_log_files.itemClicked.connect( self.on_show_log ) + self.btn_dev_cfg_read.released.connect( lambda: self.on_btn_cfg_read( 1 ) ) + self.btn_dev_cfg_write.released.connect( lambda: self.on_btn_cfg_write( 1 ) ) + self.btn_flow_cal_read.released.connect( lambda: self.on_btn_cfg_read( 2 ) ) + self.btn_flow_cal_write.released.connect( lambda: self.on_btn_cfg_write( 2 ) ) + self.btn_wifi_cfg_read.released.connect( lambda: self.on_btn_cfg_read( 3 ) ) + self.btn_wifi_cfg_write.released.connect( lambda: self.on_btn_cfg_write( 3 ) ) + self.btn_iot_cfg_read.released.connect( lambda: self.on_btn_cfg_read( 4 ) ) + self.btn_iot_cfg_write.released.connect( lambda: self.on_btn_cfg_write( 4 ) ) + + def on_btn_cfg_read( self, cfg ): + if self.connected != 0 or self.ser_opened: + return + if cfg == 1 or cfg == 2: + #B6 read cfg, 节气因子4B,工艺4B,前气开度4B,流量计补偿值4B,流量计气体修正系数4B + cmd = 0x00B6 + elif cfg == 3: + cmd = 0x00B8 + else: + cmd = 0x00BA + if self.ser_open(): + self.tx_cmd( cmd = cmd ) + self.ser_close() + + def on_btn_cfg_write( self, cfg ): + if self.connected != 0 or self.ser_opened: + return + d = b'' + if cfg == 1: + #B6 read cfg, 节气因子4B,工艺4B,前气开度4B,流量计补偿值4B,流量计气体修正系数4B + cmd = 0x00B7 + d = struct.pack( '>LLLlL', + #int(self.lineEdit_cfg_method.text()), + self.cb_cfg_method.currentIndex(), + int(self.lineEdit_cfg_factor.text()), + int(self.lineEdit_cfg_prev.text()), + 100000, #填无效值 + 100000 #填无效值 + ) + print( "write cfg cmd:%04X"%cmd, d.hex()) + elif cfg == 2: + cmd = 0x00B7 + d = struct.pack( '>LLLlL', + 100000, #填无效值 + 100000, #填无效值 + 100000, #填无效值 + int(self.lineEdit_flow_comp.text()), + #int(self.lineEdit_flow_coeff.text()) + gas_coefficient[ self.cb_flow_coeff.currentIndex()][1] + ) + elif cfg == 3: + cmd = 0x00B9 + d = self.lineEdit_wifi_ssid.text().encode( 'utf8') + print( "w type of lineedit text", type( d) ) + d += b'\x00'*(128-len(d)) + d += self.lineEdit_wifi_passwd.text().encode('utf8') + b'\x00'*((128+16)-len( d ) ) + else: + cmd = 0x00BB + d = self.lineEdit_iot_host.text().encode( 'utf8') + d += b'\x00'*(128-len( d)) + d += struct.pack( '>H', int( self.lineEdit_iot_port.text())) + + + if self.ser_open(): + self.tx_cmd( cmd = cmd, data=d ) + self.ser_close() + def draw_image( self, data ): if len( data ) == 10000: x_data=range( 5000 ) @@ -398,6 +466,37 @@ class App( QDialog, ui_welding.Ui_Dialog ): self.curve_valve_curr.setData( np.array( self.flow_x), np.array( self.valve_curr_y)) self.curve_flow.setData( np.array( self.flow_x), np.array( self.flow_y)) self.curve_flow_target.setData( np.array( self.flow_x), np.array( self.flow_target_y)) + elif cmd == 0x00B6 and len(data)>=20: #参数读取 + print( "B6 resp:", data.hex() ) + #//节气因子4B,工艺4B,前气开度4B,流量计补偿值4B,流量计气体修正系数4B + method, factor, prev, comp, coeff = struct.unpack( '>LLLlL', data ) + #self.lineEdit_cfg_method.setText( "%d"%method ) + self.lineEdit_cfg_factor.setText( "%d"%factor ) + self.lineEdit_cfg_prev.setText( "%d"%prev ) + self.lineEdit_flow_comp.setText( "%d"%comp ) + self.lineEdit_flow_coeff.setText( "%d"%coeff) + self.cb_cfg_method.setCurrentIndex( method ) + for idx in range(len(gas_coefficient)): + if gas_coefficient[idx][1] == coeff: + self.cb_flow_coeff.setCurrentIndex(idx) + break + + elif cmd == 0x00B8 and len(data)>=128+16: #参数读取 + print( "B8 resp:", data.hex() ) + #SSID 128B,passwd 16B + ssid = data[:128].decode( "utf8" ).split('\x00')[0] + passwd = data[128:128+16].decode( "utf8" ).split('\x00')[0] + print( "ssid[%s], passwd[%s]"%(len(ssid), len(passwd) ) ) + self.lineEdit_wifi_ssid.setText( ssid ) + self.lineEdit_wifi_passwd.setText( passwd ) + print( "rd %s %s"%( self.lineEdit_wifi_ssid.text(), self.lineEdit_wifi_passwd.text() )) + elif cmd == 0x00BA and len(data)>=128+2: #参数读取 + print( "BA resp:", data.hex() ) + #host 128B,port 2B + host = data[:128].decode( "utf8" ).split('\x00')[0] + port = struct.unpack( ">H", data[128:128+2]) + self.lineEdit_iot_host.setText( host ) + self.lineEdit_iot_port.setText( "%d"%port ) if cmd == self.wait_resp[0]: self.wait_resp = ( cmd, True, data[0] ) diff --git a/tools_v2/test.ui b/tools_v2/test.ui index 94e5fd3..62fcbe0 100644 --- a/tools_v2/test.ui +++ b/tools_v2/test.ui @@ -6,7 +6,7 @@ 0 0 - 1324 + 1535 845 @@ -189,7 +189,7 @@ - 2 + 3 @@ -857,6 +857,1439 @@ 页 + + + + 310 + 70 + 91 + 51 + + + + 参数读取 + + + + + + 50 + 30 + 41 + 31 + + + + UUID: + + + + + + 100 + 30 + 201 + 31 + + + + 00000000-00000000-00000000 + + + true + + + + + + 50 + 70 + 191 + 121 + + + + + 焊接工艺 + + + + + 节气因子 + + + + + 前气开度 + + + + + + + + + + + + 310 + 130 + 91 + 51 + + + + 参数写入 + + + + + + 50 + 200 + 191 + 91 + + + + + 流量补偿 + + + + + 气体修正系数 + + + + + + + + + + + + 50 + 300 + 221 + 151 + + + + + WIFI SSID + + + + + 密码 + + + + + 服务器地址 + + + + + 服务器端口 + + + + + + + + + + + + 620 + 110 + 51 + 31 + + + + 焊接工艺 + + + + + + 680 + 110 + 71 + 31 + + + + + + + true + + + + + + 760 + 110 + 91 + 31 + + + + 参数写入 + + + + + + 570 + 230 + 391 + 221 + + + + 设备参数 + + + + + + 620 + 150 + 51 + 31 + + + + 焊接工艺 + + + + + + 680 + 150 + 71 + 31 + + + + + + + true + + + + + + 760 + 150 + 91 + 31 + + + + 参数写入 + + + + + + 620 + 190 + 51 + 31 + + + + 焊接工艺 + + + + + + 680 + 190 + 71 + 31 + + + + + + + true + + + + + + 760 + 190 + 91 + 31 + + + + 参数写入 + + + + + + 0 + -20 + 1161 + 831 + + + + 3 + + + + Tab 1 + + + + + 0 + 130 + 1141 + 201 + + + + QFrame::StyledPanel + + + QFrame::Raised + + + + + + 0 + 340 + 1141 + 461 + + + + QFrame::StyledPanel + + + QFrame::Raised + + + + + + 10 + 70 + 1141 + 51 + + + + + + + + + + 焊接时间 + + + + + 焊接电流 + + + + + 目标流量 + + + + + 实时流量 + + + + + 气体压力 + + + + + 控制电流 + + + + + 焊接工艺 + + + + + 节气因子 + + + + + 默认开度 + + + + + 电流校准 + + + + + 流量校准 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + + + 10 + 0 + 71 + 61 + + + + 连接 + + + false + + + + + + 540 + 0 + 611 + 61 + + + + GroupBox + + + + + 510 + 10 + 91 + 51 + + + + 写入 + + + + + + 150 + 20 + 41 + 31 + + + + 80 + + + + + + 230 + 20 + 271 + 31 + + + + Qt::Horizontal + + + + + + 10 + 20 + 121 + 31 + + + + true + + + false + + + true + + + + 关闭模拟调试 + + + + + 模拟焊接电流 + + + + + 比例阀控制电流 + + + + + + + 200 + 20 + 21 + 31 + + + + A + + + + + + + 90 + 0 + 441 + 61 + + + + GroupBox + + + + + 20 + 21 + 41 + 31 + + + + 版本: + + + + + + 70 + 20 + 81 + 31 + + + + V1.0 + + + + + + 190 + 20 + 41 + 31 + + + + UUID: + + + + + + 230 + 20 + 201 + 31 + + + + 00000000-00000000-00000000 + + + true + + + + + + + Tab 2 + + + + + 0 + 240 + 1151 + 561 + + + + QFrame::StyledPanel + + + QFrame::Raised + + + + + + 10 + 60 + 111 + 51 + + + + 日志选择 + + + + + + 130 + 0 + 931 + 231 + + + + + + + 10 + 0 + 111 + 51 + + + + 连接 + + + + + + 10 + 120 + 111 + 51 + + + + 日志清除 + + + + + + 页 + + + + + 10 + 100 + 591 + 591 + + + + GroupBox + + + + + 80 + 70 + 111 + 31 + + + + + + + 10 + 140 + 571 + 20 + + + + Qt::Horizontal + + + + + + 80 + 30 + 331 + 31 + + + + + + + 10 + 30 + 61 + 31 + + + + 固件.. + + + false + + + + + + 210 + 70 + 91 + 31 + + + + 数据包最大长度 + + + + + + 420 + 30 + 161 + 101 + + + + 下载 + + + + + + 310 + 70 + 101 + 31 + + + + 1024 + + + false + + + false + + + false + + + + + + 10 + 160 + 571 + 421 + + + + Qt::ImhDigitsOnly + + + + + + 10 + 70 + 51 + 31 + + + + 起始地址 + + + + + + 10 + 110 + 401 + 20 + + + + false + + + 0 + + + true + + + Qt::Horizontal + + + + + + + 20 + 30 + 71 + 61 + + + + 连接 + + + false + + + + + + 100 + 30 + 501 + 61 + + + + GroupBox + + + + + 20 + 21 + 41 + 31 + + + + 版本: + + + + + + 70 + 20 + 61 + 31 + + + + V1.0 + + + + + + 150 + 20 + 41 + 31 + + + + UUID: + + + + + + 190 + 20 + 301 + 31 + + + + 00000000-00000000-00000000 + + + true + + + + + + + 页 + + + + + 20 + 30 + 421 + 171 + + + + 设备参数 + + + + + 40 + 120 + 51 + 31 + + + + 前后气 + + + + + + 40 + 40 + 51 + 31 + + + + 焊接工艺 + + + + + + 40 + 80 + 51 + 31 + + + + 节气因子 + + + + + + 100 + 80 + 141 + 31 + + + + 0 + + + false + + + + + + 100 + 120 + 141 + 31 + + + + 0 + + + false + + + + + + 330 + 40 + 81 + 71 + + + + 写入 + + + + + + 250 + 40 + 81 + 71 + + + + 读取 + + + + + + 100 + 40 + 141 + 31 + + + + false + + + false + + + true + + + + TIG + + + + + MIG + + + + + MAG + + + + + + + + 20 + 210 + 421 + 131 + + + + 流量校准 + + + + + 20 + 40 + 71 + 31 + + + + 流量补偿 + + + + + + 210 + 80 + 31 + 31 + + + + 0 + + + true + + + + + + 20 + 80 + 71 + 31 + + + + 气体修正系数 + + + + + + 100 + 40 + 141 + 31 + + + + 0 + + + false + + + + + + 330 + 40 + 81 + 71 + + + + 写入 + + + + + + 250 + 40 + 81 + 71 + + + + 读取 + + + + + + 100 + 80 + 111 + 31 + + + + false + + + false + + + true + + + + 氩气(1.0) + + + + + 二氧化碳(0.57) + + + + + 混合气(0.91) + + + + + + + + 20 + 350 + 421 + 131 + + + + WIFI + + + + + 40 + 40 + 51 + 31 + + + + SSID + + + + + + 100 + 80 + 141 + 31 + + + + 0 + + + false + + + + + + 40 + 80 + 51 + 31 + + + + 密码 + + + + + + 100 + 40 + 141 + 31 + + + + 0 + + + false + + + + + + 250 + 40 + 81 + 71 + + + + 读取 + + + + + + 330 + 40 + 81 + 71 + + + + 写入 + + + + + + + 20 + 490 + 421 + 131 + + + + 平台配置 + + + + + 20 + 40 + 71 + 31 + + + + 服务器地址 + + + + + + 100 + 80 + 141 + 31 + + + + 0 + + + false + + + + + + 20 + 80 + 71 + 31 + + + + 端口 + + + + + + 100 + 40 + 141 + 31 + + + + 0 + + + false + + + + + + 330 + 40 + 81 + 71 + + + + 写入 + + + + + + 250 + 40 + 81 + 71 + + + + 读取 + + + + + diff --git a/user/at_parser.c b/user/at_parser.c index 2a2a385..fe6f3a9 100644 --- a/user/at_parser.c +++ b/user/at_parser.c @@ -363,7 +363,7 @@ int at_send_wait_reply(const char *cmd, int cmdlen, bool delimiter, { int ret = 0; int intval_ms = AT_CMD_DATA_INTERVAL_MS; - HAL_Printf( "at_send_wait_replay-- cmd:{%s} data:{%s},len:%d\r\n", cmd, data?data:"Null",datalen ); +//HAL_Printf( "at_send_wait_replay-- cmd:{%s} data:{%s},len:%d\r\n", cmd, data?data:"Null",datalen ); at_task_t *tsk; if (inited == 0) { diff --git a/user/cJSON.c b/user/cJSON.c new file mode 100644 index 0000000..ce2999d --- /dev/null +++ b/user/cJSON.c @@ -0,0 +1,2269 @@ +/* +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. */ + +#ifdef __GNUC__ + #pragma GCC visibility push(default) +#endif + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#ifdef __GNUC__ + #pragma GCC visibility pop +#endif + +#include "cJSON.h" + +/* define our own boolean type */ +#define true ((cJSON_bool)1) +#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); +} + +/* This is a safeguard to prevent copy-pasters from using incompatible C and header files */ +#if (CJSON_VERSION_MAJOR != 1) || (CJSON_VERSION_MINOR != 5) || (CJSON_VERSION_PATCH != 3) + #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 *(*allocate)(uint32_t size); + void(*deallocate)(void *pointer); + void *(*reallocate)(void *pointer, size_t size); +} internal_hooks; + +extern void *HAL_Malloc(uint32_t size); +extern void HAL_Free(void *ptr); +static internal_hooks global_hooks = { HAL_Malloc, HAL_Free, 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(""); + if (!(copy = (unsigned char *)hooks->allocate(length))) { + return NULL; + } + memcpy(copy, string, length); + + return copy; +} + +/* 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) +{ + struct lconv *lconv = localeconv(); + return (unsigned char)lconv->decimal_point[0]; +} + +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)) +#define cannot_read(buffer, size) (!can_read(buffer, size)) +/* 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 <= 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 <= 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); + } 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); +} + +/* 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]; /* temporary buffer to print the number into */ + unsigned char decimal_point = get_decimal_point(); + double test; + + 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) || ((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 occured */ + 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); + 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; +} + +/* 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(&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; + } else { + 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) +{ + printbuffer buffer[1]; + unsigned char *printed = NULL; + + memset(buffer, 0, sizeof(buffer)); + + /* create buffer */ + buffer->buffer = (unsigned char *)hooks->allocate(256); + 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->length); + buffer->buffer = NULL; + if (printed == NULL) { + goto fail; + } + } 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 0 + if (printed != NULL) { + hooks->deallocate(printed); + } +#endif + + 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)) { + return NULL; + } + + return (char *)p.buffer; +} + +CJSON_PUBLIC(cJSON_bool) cJSON_PrintPreallocated(cJSON *item, char *buf, const int len, const cJSON_bool fmt) +{ + printbuffer p = { 0, 0, 0, 0, 0, 0, { 0, 0, 0 } }; + + if (len < 0) { + return false; + } + + p.buffer = (unsigned char *)buf; + p.length = (size_t)len; + p.offset = 0; + p.noalloc = true; + p.format = fmt; + 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) { + if (!output_buffer->noalloc) { + output_buffer->hooks.deallocate(output_buffer->buffer); + } + 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; /* faile 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) + (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 *c = array->child; + size_t i = 0; + while (c) { + i++; + c = c->next; + } + + /* FIXME: Can overflow here. Cannot be fixed without breaking the API */ + + return (int)i; +} + +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) && (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; + } + } + + 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 *ref = cJSON_New_Item(hooks); + if (!ref) { + return NULL; + } + memcpy(ref, item, sizeof(cJSON)); + ref->string = NULL; + ref->type |= cJSON_IsReference; + ref->next = ref->prev = NULL; + return ref; +} + +/* Add item to array/object. */ +CJSON_PUBLIC(void) cJSON_AddItemToArray(cJSON *array, cJSON *item) +{ + cJSON *child = NULL; + + if ((item == NULL) || (array == NULL)) { + return; + } + + 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); + } +} + +CJSON_PUBLIC(void) cJSON_AddItemToObject(cJSON *object, const char *string, cJSON *item) +{ + /* call cJSON_AddItemToObjectCS for code reuse */ + cJSON_AddItemToObjectCS(object, (char *)cJSON_strdup((const unsigned char *)string, &global_hooks), item); + /* remove cJSON_StringIsConst flag */ + item->type &= ~cJSON_StringIsConst; +} + +#if defined (__clang__) || ((__GNUC__) && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 5)))) + #pragma GCC diagnostic push +#endif +#ifdef __GNUC__ + #pragma GCC diagnostic ignored "-Wcast-qual" +#endif + +/* Add an item to an object with constant string as key */ +CJSON_PUBLIC(void) cJSON_AddItemToObjectCS(cJSON *object, const char *string, cJSON *item) +{ + if (!item) { + return; + } + if (!(item->type & cJSON_StringIsConst) && item->string) { + global_hooks.deallocate(item->string); + } + item->string = (char *)string; + item->type |= cJSON_StringIsConst; + cJSON_AddItemToArray(object, item); +} +#if defined (__clang__) || ((__GNUC__) && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 5)))) + #pragma GCC diagnostic pop +#endif + +CJSON_PUBLIC(void) cJSON_AddItemReferenceToArray(cJSON *array, cJSON *item) +{ + cJSON_AddItemToArray(array, create_reference(item, &global_hooks)); +} + +CJSON_PUBLIC(void) cJSON_AddItemReferenceToObject(cJSON *object, const char *string, cJSON *item) +{ + cJSON_AddItemToObject(object, string, create_reference(item, &global_hooks)); +} + +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) { + cJSON_AddItemToArray(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)) { + 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) { + 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 b) +{ + cJSON *item = cJSON_New_Item(&global_hooks); + if (item) { + item->type = b ? 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 <= 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_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) { + 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) { + 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) { + 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 **strings, int count) +{ + size_t i = 0; + cJSON *n = NULL; + cJSON *p = NULL; + cJSON *a = NULL; + + if (count < 0) { + 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; +} + +CJSON_PUBLIC(void) cJSON_Minify(char *json) +{ + unsigned char *into = (unsigned char *)json; + while (*json) { + if (*json == ' ') { + json++; + } else if (*json == '\t') { + /* Whitespace characters. */ + json++; + } else if (*json == '\r') { + json++; + } else if (*json == '\n') { + json++; + } else if ((*json == '/') && (json[1] == '/')) { + /* double-slash comments, to end of line. */ + while (*json && (*json != '\n')) { + json++; + } + } else if ((*json == '/') && (json[1] == '*')) { + /* multiline comments. */ + while (*json && !((*json == '*') && (json[1] == '/'))) { + json++; + } + json += 2; + } else if (*json == '\"') { + /* string literals, which are \" sensitive. */ + *into++ = (unsigned char) * json++; + while (*json && (*json != '\"')) { + if (*json == '\\') { + *into++ = (unsigned char) * json++; + } + *into++ = (unsigned char) * json++; + } + *into++ = (unsigned char) * json++; + } else { + /* All other characters. */ + *into++ = (unsigned char) * json++; + } + } + + /* 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 (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; + } + + return true; + } + + case cJSON_Object: { + cJSON *a_element = NULL; + cJSON_ArrayForEach(a_element, a) { + /* TODO This has O(n^2) runtime, which is horrible! */ + cJSON *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; + } + } + + 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/user/cJSON.h b/user/cJSON.h new file mode 100644 index 0000000..2e3715a --- /dev/null +++ b/user/cJSON.h @@ -0,0 +1,247 @@ +/* +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 + + /* project version */ +#define CJSON_VERSION_MAJOR 1 +#define CJSON_VERSION_MINOR 5 +#define CJSON_VERSION_PATCH 3 + +#include +#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 int cJSON_bool; + +#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 2 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 + */ + + /* 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 __stdcall +#elif defined(CJSON_EXPORT_SYMBOLS) +#define CJSON_PUBLIC(type) __declspec(dllexport) type __stdcall +#elif defined(CJSON_IMPORT_SYMBOLS) +#define CJSON_PUBLIC(type) __declspec(dllimport) type __stdcall +#endif +#else /* !WIN32 */ +#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 + + /* 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 + + /* returns the version of cJSON as a string */ + CJSON_PUBLIC(const char*) cJSON_Version(void); + + /* 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); + /* 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 *c); + + /* Returns the number of items in an array (or object). */ + CJSON_PUBLIC(int) cJSON_GetArraySize(const cJSON *array); + /* Retrieve item number "item" 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); + + /* 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); + + /* These utilities create an Array of count items. */ + 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 **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/Detatch 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); + + + /* 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. If not, then cJSON_GetErrorPtr() does the job. */ + CJSON_PUBLIC(cJSON *) cJSON_ParseWithOpts(const char *value, const char **return_parse_end, cJSON_bool require_null_terminated); + + CJSON_PUBLIC(void) cJSON_Minify(char *json); + + /* Macros for creating things quickly. */ +#define cJSON_AddNullToObject(object,name) cJSON_AddItemToObject(object, name, cJSON_CreateNull()) +#define cJSON_AddTrueToObject(object,name) cJSON_AddItemToObject(object, name, cJSON_CreateTrue()) +#define cJSON_AddFalseToObject(object,name) cJSON_AddItemToObject(object, name, cJSON_CreateFalse()) +#define cJSON_AddBoolToObject(object,name,b) cJSON_AddItemToObject(object, name, cJSON_CreateBool(b)) +#define cJSON_AddNumberToObject(object,name,n) cJSON_AddItemToObject(object, name, cJSON_CreateNumber(n)) +#define cJSON_AddStringToObject(object,name,s) cJSON_AddItemToObject(object, name, cJSON_CreateString(s)) +#define cJSON_AddRawToObject(object,name,s) cJSON_AddItemToObject(object, name, cJSON_CreateRaw(s)) + + /* 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/user/user.h b/user/user.h index 4d6ab68..7e0f2d2 100644 --- a/user/user.h +++ b/user/user.h @@ -89,23 +89,25 @@ typedef struct{ char wifi_ssid[128]; char wifi_passwd[16]; char tcp_server[128]; - char tcp_port[8]; + uint16_t tcp_port; + //char tcp_port[8]; }net_cfg_t; typedef struct{ - float flowrate; //流量校准值,单位0.1L/min + int32_t flow_comp_x1000; //compansation 流量补偿值,读取到流量值加这个补偿/1000,单位1L/min + uint32_t flow_coeff_x1000; //correction coefficient 气体修正系数, 从流量计读取到流量值后乘以这个系数/1000 }cal_t; - -#define DEVICE_CFG_FLAG 0x11 //FLAG: 1--255:normal, 0:invaild +#define DEVICE_CFG_FLAG 0x12 //FLAG: 1--255:normal, 0:invaild typedef struct{ - uint8_t flag; uint8_t save_gas_factor; //0-100 uint8_t valve_open_default; //0-100 uint8_t welding_method; //0-2d pid_param_t pid_param; //根据不同气压选择合适pid控制参数 net_cfg_t net; cal_t cal; + uint8_t remote_locked; //1:locked 远程锁定 + uint8_t flag; }dev_cfg_t; //故障码bit位定义 @@ -155,7 +157,6 @@ typedef struct { uint32_t wifi_connected; //0:disconnect, 1:wifi connected, 2:tcp connected uint32_t eth_connected; //0: eth disconnect, 1:eth connected, 2::tcp connected - uint32_t remote_locked; //0: unlock, 1:locked }dev_info_t; extern TIM_HandleTypeDef htim2; //htim2 用于触发DMA ADC采集 diff --git a/user/user_adc.c b/user/user_adc.c index 41007bf..014041a 100644 --- a/user/user_adc.c +++ b/user/user_adc.c @@ -20,7 +20,9 @@ ALIGN_32BYTES (static uint16_t adc3_raw[(ADC3_RAW_NRS+15)&~15] ); //采集100次 static uint16_t adc1_raw_copy[ADC1_RAW_NRS]; static uint16_t adc3_raw_copy[ADC3_RAW_NRS]; -static float adc2_curr[ADC2_RAW_NRS]; + +__attribute__((at(0x20005000))) static uint16_t adc2_raw_copy[ADC2_RAW_NRS]; +__attribute__((at(0x20000000))) static float adc2_curr[ADC2_RAW_NRS]; extern dev_info_t g_dev; @@ -33,8 +35,9 @@ void HAL_ADC_ConvCpltCallback(ADC_HandleTypeDef* hadc) }else if( hadc == &hadc2 ){ SCB_InvalidateDCache_by_Addr((uint32_t *)&adc2_raw[0], sizeof( adc2_raw) ); - for( int32_t i=0; i< ADC2_RAW_NRS; i++ ) - adc2_curr[i] = (adc2_raw[i] * VREF*2/0xffff - 2.5f)/0.625f*400; + //for( int32_t i=0; i< ADC2_RAW_NRS; i++ ) + // adc2_curr[i] = (adc2_raw[i] * VREF*2/0xffff - 2.5f)/0.625f*400; + memcpy( &adc2_raw_copy[0], &adc2_raw[0], sizeof( adc2_raw_copy) ); osEventFlagsSet( g_dev.ev_group, EVENT_ADC2_UPDATE ); }else if( hadc == &hadc3 ){ SCB_InvalidateDCache_by_Addr((uint32_t *)&adc3_raw[0], sizeof( adc3_raw) ); @@ -258,12 +261,12 @@ void user_adc_task( void* unused ) } } if( uxBits & EVENT_ADC2_UPDATE ){ - volatile static uint32_t t2, t3; - t3 = HAL_GetTick() - t2; - t2 = HAL_GetTick(); - //电流互感器 ADC2 HAL_ADC_Start_DMA( &hadc2, (uint32_t*)&adc2_raw[0], ADC2_RAW_NRS ); + + for( int32_t i=0; i< ADC2_RAW_NRS; i++ ) + adc2_curr[i] = (adc2_raw_copy[i] * VREF*2/0xffff - 2.5f)/0.625f*400; + if( g_dev.debug_report == 2 ){ //发送调试数据到pc, extern uint32_t dbg_report_raw_current; extern uint8_t CDC_Transmit_HS(uint8_t* Buf, uint16_t Len); @@ -305,6 +308,7 @@ void user_adc_task( void* unused ) g_dev.state &= ~CURR_SENSOR_ERR; } } + } if( uxBits & EVENT_ADC3_UPDATE ){ volatile static uint32_t t4, t5; diff --git a/user/user_app.c b/user/user_app.c index 005a69c..81d4483 100644 --- a/user/user_app.c +++ b/user/user_app.c @@ -157,11 +157,17 @@ int32_t dev_cfg_load( dev_cfg_t *cfg ) cfg->pid_param.pid_kp = 0.100f; cfg->pid_param.pid_ki = 0.000f; cfg->pid_param.pid_kd = 0.010; + if(cfg->remote_locked != 1 ) + cfg->remote_locked = 0; //检查校准参数 - if( *(uint32_t*)&cfg->cal.flowrate == 0xffffffff || cfg->cal.flowrate > 20.0f || cfg->cal.flowrate < -20.0f ){ - cfg->cal.flowrate = 0; + if( *(uint32_t*)&cfg->cal.flow_comp_x1000 == 0xffffffff || cfg->cal.flow_comp_x1000 > 20*1000 || cfg->cal.flow_comp_x1000 < -20*1000 ){ + cfg->cal.flow_comp_x1000 = 0; } + if( *(uint32_t*)&cfg->cal.flow_coeff_x1000 == 0xffffffff || cfg->cal.flow_coeff_x1000 > 5000 || cfg->cal.flow_coeff_x1000 < 100 ){ + cfg->cal.flow_coeff_x1000 = 0; + } + //检查网络参数 for( int i=0; inet.wifi_ssid); i++ ){ @@ -179,12 +185,12 @@ int32_t dev_cfg_load( dev_cfg_t *cfg ) cfg->net.tcp_server[i] = 0; } } - for( int i=0; inet.tcp_port); i++ ){ - if( cfg->net.tcp_port[i] <= 0x20 || cfg->net.tcp_port[i]>0x7f ){ - cfg->net.tcp_port[i] = 0; - break; - } - } +// for( int i=0; inet.tcp_port); i++ ){ +// if( cfg->net.tcp_port[i] <= 0x20 || cfg->net.tcp_port[i]>0x7f ){ +// cfg->net.tcp_port[i] = 0; +// break; +// } +// } return 0; } diff --git a/user/user_cdc_rx_2.c b/user/user_cdc_rx_2.c index e99b870..3a6424f 100644 --- a/user/user_cdc_rx_2.c +++ b/user/user_cdc_rx_2.c @@ -41,10 +41,8 @@ 数据字段 发送 mode 4B( 0x544F4F42 -- 重启进入下载模式, 其他值-重启进入正常模式 ) 回应 1B (0-fail, 1-success) ------------------------------------------------------------- - 0005: 读取设备UUID - 数据字段 发送 无 - 回应 UUID(12B) -------------------------------------------------------------- + 下载固件 指令 A0 + 主程序收到开始下载指令,在SRAM2 中写入标志, 重启设备, boot中读取到标志进入下载模式 ------------------------------------------------------------- 设备参数 ------------------------------------------------------------- @@ -58,7 +56,7 @@ ------------------------------------------------------------- 0012: 读取焊接电流校准值 数据字段 发送 无 - 回应 校准值 4B + 回应 补偿值 4B ------------------------------------------------------------- 0013: 写入焊接电流校准值 数据字段 发送 校准值 4B @@ -66,11 +64,11 @@ ------------------------------------------------------------- 0014: 读取流量计校准值 数据字段 发送 无 - 回应 校准值 4B + 回应 补偿值 4B, 气体修正系数 4B ------------------------------------------------------------- 0015: 写入流量计校准值 - 数据字段 发送 校准值 4B - 回应 校准值 4B + 数据字段 发送 补偿值 4B, 气体修正系数 4B + 回应 补偿值 4B, 气体修正系数 4B ------------------------------------------------------------- 设备状态 ------------------------------------------------------------- @@ -81,7 +79,7 @@ 0021: 同步时间 数据字段 发送 当前时间4B(秒) 回应 1B (0-fail, 1-success) - 0022: 实时上报数据控制 + 0022: USB实时上报数据控制 数据字段 发送 模式4B ( 0 不实时上报, 1:实时上报焊接电流原始数据, 2:实时上报设备状态) 回应 1B (0-fail, 1-success) 0023: 上报设备状态 @@ -117,6 +115,7 @@ typedef struct{ //uint32_t dbg_report_raw_current = 0; //采集上报原始AD值,用于获取交流脉冲等原始数据,调试不同电流算法。 extern uint8_t CDC_Transmit_HS(uint8_t* Buf, uint16_t Len); +extern void ui_cfg_remote_update( void ); uint16_t get_u16_big( uint8_t *p ) { @@ -259,8 +258,8 @@ int32_t load_app( void ) int32_t handle_cdc_pkt( cdc_pkt_t *pkt ) { - static uint8_t tx_pkt[100]; - uint8_t resp[64]; + static uint8_t tx_pkt[250]; + static uint8_t resp[200]; uint8_t tx_n = 0; #ifdef BOOTLOADER uint32_t off; @@ -406,8 +405,86 @@ int32_t handle_cdc_pkt( cdc_pkt_t *pkt ) break; case 0xB5: //焊接数据清0 break; - case 0xB6: //设备参数下载: 节气因子,工艺,电流校准值, 流量计校准值 + case 0xB6: //设备参数读取 + //工艺4B,节气因子4B,前气开度4B,流量计补偿值4B,流量计气体修正系数4B + put_u32_big( &resp[0], g_dev.cfg.welding_method ); + put_u32_big( &resp[4], g_dev.cfg.save_gas_factor ); + put_u32_big( &resp[8], g_dev.cfg.valve_open_default ); + put_u32_big( &resp[12], g_dev.cfg.cal.flow_comp_x1000 ); + put_u32_big( &resp[16], g_dev.cfg.cal.flow_coeff_x1000 ); + tx_n = wrap_resp_pkt( tx_pkt, pkt->cmd, resp, 20 ); + break; + case 0xB7: //设备参数写入 + //工艺4B,节气因子4B,前气开度4B,流量计补偿值4B,流量计气体修正系数4B + { + uint32_t method = get_u32_big( &pkt->pdata[0] ); + uint32_t factor = get_u32_big( &pkt->pdata[4] ); + uint32_t valve_open = get_u32_big( &pkt->pdata[8] ); + int32_t comp = get_u32_big( &pkt->pdata[12] ); + uint32_t coeff = get_u32_big( &pkt->pdata[16] ); + + if( factor >=2 && factor <= 30 ) + g_dev.cfg.save_gas_factor = factor; + if( method <3 ) + g_dev.cfg.welding_method = method; + if( valve_open <= 100 ) + g_dev.cfg.valve_open_default = valve_open; + if( comp > -10000 && comp < 10000 ) + g_dev.cfg.cal.flow_comp_x1000 = comp; + if(coeff == 0 ||( coeff >100 && coeff < 3000 ) ) + g_dev.cfg.cal.flow_coeff_x1000 = coeff; + dev_cfg_store( &g_dev.cfg ); + ui_cfg_remote_update(); + + put_u32_big( &resp[0], g_dev.cfg.save_gas_factor ); + put_u32_big( &resp[4], g_dev.cfg.welding_method ); + put_u32_big( &resp[8], g_dev.cfg.valve_open_default ); + put_u32_big( &resp[12], g_dev.cfg.cal.flow_comp_x1000 ); + put_u32_big( &resp[16], g_dev.cfg.cal.flow_coeff_x1000 ); + tx_n = wrap_resp_pkt( tx_pkt, pkt->cmd, resp, 20 ); + break; + } + case 0xB8: //WIFI参数读取 + //SSID 128B,passwd 16B + memset(resp, 0, sizeof( resp ) ); + strcpy( (char*)resp, g_dev.cfg.net.wifi_ssid ); + strcpy( (char*)resp+128, g_dev.cfg.net.wifi_passwd ); + tx_n = wrap_resp_pkt( tx_pkt, pkt->cmd, resp, 128+16 ); break; + case 0xB9: //WIFI参数写入 + if(strlen( (char*)&pkt->pdata[0] )&& strlen( (char*)&pkt->pdata[128] ) ){ + strncpy( (char*)g_dev.cfg.net.wifi_ssid, (char*)&pkt->pdata[0], 127 ); + strncpy( (char*)g_dev.cfg.net.wifi_passwd, (char*)&pkt->pdata[128], 15 ); + dev_cfg_store( &g_dev.cfg ); + ui_cfg_remote_update(); + resp[0] = 1; + }else{ + resp[0] = 0; + } + tx_n = wrap_resp_pkt( tx_pkt, pkt->cmd, resp, 1 ); + break; + case 0xBA: //平台配置读取 + //host 128B, port 2B + memset(resp, 0, sizeof( resp ) ); + strncpy( (char*)resp, g_dev.cfg.net.tcp_server, 127 ); + put_u16_big( &resp[128], g_dev.cfg.net.tcp_port ); + tx_n = wrap_resp_pkt( tx_pkt, pkt->cmd, resp, 128+2 ); + break; + case 0xBB: //平台配置写入 + //host 128B, port 2B + if(strlen( (char*)&pkt->pdata[0] ) && (pkt->pdata[128]|pkt->pdata[129])>0 ){ + + strncpy( (char*)g_dev.cfg.net.tcp_server, (char*)&pkt->pdata[0], 127 ); + g_dev.cfg.net.tcp_port = get_u16_big( &pkt->pdata[128] ); + dev_cfg_store( &g_dev.cfg ); + ui_cfg_remote_update(); + + resp[0] = 1; + }else{ + resp[0] = 0; + } + tx_n = wrap_resp_pkt( tx_pkt, pkt->cmd, resp, 1 ); + break; #endif } diff --git a/user/user_debug.c b/user/user_debug.c index 6bb9011..63aeb92 100644 --- a/user/user_debug.c +++ b/user/user_debug.c @@ -21,7 +21,8 @@ void debug_printf(char* str , ...) va_start(aptr, str); if ( vsnprintf(dbg_buffer,sizeof(dbg_buffer)-1, str, aptr) > 0) { - ///CDC_Transmit_HS( (uint8_t*)dbg_buffer, strlen( dbg_buffer) ); + if( !g_dev.debug_report ) + CDC_Transmit_HS( (uint8_t*)dbg_buffer, strlen( dbg_buffer) ); HAL_UART_Transmit( &huart2, (uint8_t*)dbg_buffer, strlen( dbg_buffer), strlen( dbg_buffer)*10 ); } va_end(aptr); diff --git a/user/user_eth.c b/user/user_eth.c index 98884ab..e37a341 100644 --- a/user/user_eth.c +++ b/user/user_eth.c @@ -243,8 +243,8 @@ void user_eth_task( void* unused ) } g_dev.eth_connected = 1; //2. get host and port - port = atoi(g_dev.cfg.net.tcp_port); - if( !strlen(g_dev.cfg.net.tcp_server) || port ==0 || port > 0xffff ){ + port = g_dev.cfg.net.tcp_port; + if( !strlen(g_dev.cfg.net.tcp_server) || port ==0 ){ //无效服务器信息 osDelay( 1000 ); continue; diff --git a/user/user_flowmeter.c b/user/user_flowmeter.c index 6b6f1cc..53bf452 100644 --- a/user/user_flowmeter.c +++ b/user/user_flowmeter.c @@ -175,6 +175,11 @@ void user_flowmeter_task( void* unused ) uint16_t reg_values[16]; uint32_t last_tick = xTaskGetTickCount(); int32_t err = 0; + + float flow_raw; + float total_raw; + float flow_comp; + #if FLOWMETER_MF4008 mf4008_uart_init(); while(1){ @@ -184,12 +189,18 @@ void user_flowmeter_task( void* unused ) if( mb_master_read_regs( 1, 2, reg_values, 5 ) == 0 ){ //读取到 流量 err = 0; - g_dev.flowmeter.flow_speed_raw = ((reg_values[0]<<16)|(reg_values[1]))/1000.0f; - if( g_dev.flowmeter.flow_speed_raw + g_dev.cfg.cal.flowrate > 0 ) - g_dev.flowmeter.flow_speed = g_dev.flowmeter.flow_speed_raw + g_dev.cfg.cal.flowrate; - else - g_dev.flowmeter.flow_speed = 0; - g_dev.flowmeter.flow_total = ((reg_values[2]<<16)|reg_values[3]) +reg_values[4]/1000.0f; + + flow_raw = ((reg_values[0]<<16)|(reg_values[1]))/1000.0f; + total_raw = ((reg_values[2]<<16)|reg_values[3]) +reg_values[4]/1000.0f; + flow_comp = g_dev.cfg.cal.flow_comp_x1000/1000.0f; + + g_dev.flowmeter.flow_speed_raw = flow_raw; + if(flow_raw+flow_comp > 0 ){ + g_dev.flowmeter.flow_speed = flow_raw + flow_comp ); + else + g_dev.flowmeter.flow_speed = 0; + + g_dev.flowmeter.flow_total = total_raw; g_dev.flowmeter.tem = 0; g_dev.flowmeter.state = 0; if( g_dev.state & FLOWMETER_ERR ){ @@ -206,6 +217,8 @@ void user_flowmeter_task( void* unused ) } } #else + + while(1){ //100毫秒扫描一次 //vTaskDelayUntil(&last_tick, 100 ); @@ -213,19 +226,38 @@ void user_flowmeter_task( void* unused ) if( mb_master_read_regs( 1, 0, reg_values, 5 ) == 0 ){ //读取到 流量 + float flow_coeff; err = 0; - g_dev.flowmeter.flow_speed_raw = reg_values[0]/10.0f; - if( g_dev.flowmeter.flow_speed_raw + g_dev.cfg.cal.flowrate > 0 ) - g_dev.flowmeter.flow_speed = g_dev.flowmeter.flow_speed_raw + g_dev.cfg.cal.flowrate; - else - g_dev.flowmeter.flow_speed = 0; - g_dev.flowmeter.flow_total = ((reg_values[1]<<16)|reg_values[2])/10.0f; + flow_raw = reg_values[0]/10.0f; + total_raw = ((reg_values[1]<<16)|reg_values[2])/10.0f; + + + if( g_dev.cfg.cal.flow_coeff_x1000 > 100 && g_dev.cfg.cal.flow_coeff_x1000 < 3000 ){ + //气体修正系数 + flow_coeff = g_dev.cfg.cal.flow_coeff_x1000/1000.0f; + flow_raw *= flow_coeff; + total_raw *= flow_coeff; + } + + g_dev.flowmeter.flow_speed_raw = flow_raw; + + if( g_dev.cfg.cal.flow_comp_x1000 ){ + //加补偿值 + flow_comp = g_dev.cfg.cal.flow_comp_x1000/1000.0f; + flow_raw += flow_comp; + if( flow_raw < 0 ) + flow_raw = 0; + } + + g_dev.flowmeter.flow_speed = flow_raw; + g_dev.flowmeter.flow_total = total_raw; + g_dev.flowmeter.tem = reg_values[3]/10.0f; - g_dev.flowmeter.state = reg_values[4]; + g_dev.flowmeter.state = reg_values[4]; if( g_dev.state & FLOWMETER_ERR ){ g_dev.state &= ~(FLOWMETER_ERR); } - err = 0; + }else{ //读取失败, 故障计数到10次报错 if( err> 10 ){ diff --git a/user/user_report.c b/user/user_report.c index dca31ee..89dded2 100644 --- a/user/user_report.c +++ b/user/user_report.c @@ -27,8 +27,6 @@ static const char *fmt = "{\n\ \"s\":\"%d\",\n\ \"g\":\"%0.1f\"\n\ },\n\ - \"weldCurrent\":\"%0.1f\",\n\ - \"gasFlow\":\"%0.1f\",\n\ \"weldTech\":\"%s\",\n\ \"solarTermFactor\":\"%d\",\n\ \"gasPressure\":\"%d\",\n\ @@ -70,14 +68,13 @@ char * devinfo_report_str( void ) c = 0.0f; sprintf( (char*)tx_buf, fmt, cid++, g_mac_str, c, s, g, - c,g, weld_method_str[g_dev.cfg.welding_method], g_dev.cfg.save_gas_factor, (int)g_dev.pressure, (int)g_dev.flowmeter.flow_total, 1, APP_VER_MAJOR, APP_VER_MINOR, - g_dev.remote_locked ); + g_dev.cfg.remote_locked==1?0:1 ); return tx_buf; } diff --git a/user/user_ui.c b/user/user_ui.c index 8bfcfd9..c2f78ae 100644 --- a/user/user_ui.c +++ b/user/user_ui.c @@ -92,6 +92,8 @@ void ui_handle_lcd_pkt( void ) uint16_t ctrl_value; int16_t flow_cal_x10; uint8_t *p; + char tcp_port_str[10]; + uint32_t port; static net_cfg_t net_cfg; switch( lcd_resp.cmd ){ @@ -110,16 +112,19 @@ void ui_handle_lcd_pkt( void ) net_cfg.wifi_passwd[i] = *p; p++; } - for( int i=0; i< lcd_tcp_server_size; i++ ){ //read passwd + for( int i=0; i< lcd_tcp_server_size; i++ ){ //host if( *p > 0x20 && *p < 0x80 ) net_cfg.tcp_server[i] = *p; p++; } - for( int i=0; i< lcd_tcp_port_size; i++ ){ //read passwd + tcp_port_str[0] = 0; + for( int i=0; i< lcd_tcp_port_size; i++ ){ //port if( *p > 0x20 && *p < 0x80 ) - net_cfg.tcp_port[i] = *p; + tcp_port_str[i] = *p; + //net_cfg.tcp_port[i] = *p; p++; } + port = atoi( tcp_port_str ); #if 0 if( strlen( net_cfg.wifi_ssid)&& strlen( net_cfg.wifi_passwd ) && strlen( net_cfg.tcp_server ) && strlen( net_cfg.tcp_port ) ){ @@ -131,19 +136,21 @@ void ui_handle_lcd_pkt( void ) } } #else - if( !strlen( net_cfg.tcp_server)|| !strlen( net_cfg.tcp_port ) || atoi( net_cfg.tcp_port ) < 0 || atoi( net_cfg.tcp_port )>0xffff){ + if( !strlen( net_cfg.tcp_server)|| port ==0 || port > 0xffff ){ //无效配置,忽略掉 strcpy( net_cfg.tcp_server, g_dev.cfg.net.tcp_server ); - strcpy( net_cfg.tcp_port, g_dev.cfg.net.tcp_port ); - } + net_cfg.tcp_port = g_dev.cfg.net.tcp_port; + }else{ + net_cfg.tcp_port = port; + } if( strcmp( g_dev.cfg.net.tcp_server, net_cfg.tcp_server ) - || strcmp( g_dev.cfg.net.tcp_port, net_cfg.tcp_port ) ){ + || g_dev.cfg.net.tcp_port != net_cfg.tcp_port ){ //平台改变 - printf( "remote srv cfg [%s:%s -> %s:%s], connected -> 0\n", + printf( "remote srv cfg [%s:%d -> %s:%d], connected -> 0\n", g_dev.cfg.net.tcp_server, g_dev.cfg.net.tcp_port, net_cfg.tcp_server, net_cfg.tcp_port ); strcpy( g_dev.cfg.net.tcp_server, net_cfg.tcp_server ); - strcpy( g_dev.cfg.net.tcp_port, net_cfg.tcp_port ); + g_dev.cfg.net.tcp_port = net_cfg.tcp_port; if( strcmp( g_dev.cfg.net.wifi_ssid, net_cfg.wifi_ssid ) || strcmp( g_dev.cfg.net.wifi_passwd, net_cfg.wifi_passwd ) ){ printf( "+++wifi cfg [%s:%s -> %s:%s]\n", @@ -189,6 +196,11 @@ void ui_handle_lcd_pkt( void ) if( ctrl_value < 3 ){ uint8_t welding_method = ctrl_value; g_dev.cfg.welding_method = welding_method; +#if 0 + if( welding_method == 0 ) g_dev.cfg.cal.flow_coeff_x1000 = 1000; + else if ( welding_method == 1 ) g_dev.cfg.cal.flow_coeff_x1000 = 570; + else if ( welding_method == 2 ) g_dev.cfg.cal.flow_coeff_x1000 = 910; +#endif dev_cfg_store( &g_dev.cfg ); } }else if( ctrl_addr == lcd_valve_bypass_addr ){//比例阀旁路 @@ -204,9 +216,9 @@ void ui_handle_lcd_pkt( void ) if( off < -20.0 || off > 20 ){ //error }else{ - g_dev.cfg.cal.flowrate = off; + g_dev.cfg.cal.flow_comp_x1000 = (int32_t)(off*1000); dev_cfg_store( &g_dev.cfg ); - flow_cal_x10 = (int16_t)(g_dev.cfg.cal.flowrate*10); + flow_cal_x10 = (int16_t)(g_dev.cfg.cal.flow_comp_x1000/100); lcd_write_s16( lcd_flow_cal_value_addr, flow_cal_x10 ); } } @@ -343,6 +355,35 @@ void lcd_power_off( void ) HAL_GPIO_WritePin( LCM_EN_GPIO_Port, LCM_EN_Pin, GPIO_PIN_RESET ); } +static uint32_t remote_update_cfg_flag = 0; +void ui_cfg_remote_update( void ) +{ + remote_update_cfg_flag = 1; +} + +void lcd_update_cfg( void ) +{ + char port_str[8]; + uint16_t reg_values[3]; + reg_values[0] = g_dev.cfg.welding_method+1; + reg_values[1] = g_dev.cfg.save_gas_factor; + reg_values[2] = g_dev.cfg.valve_open_default; + lcd_write( lcd_welding_method_addr, reg_values, 3 ); + + osDelay(10 ); + lcd_write_text( lcd_wifi_ssid_addr, (uint8_t*)&g_dev.cfg.net.wifi_ssid, lcd_wifi_ssid_size ); + osDelay(10 ); + lcd_write_text( lcd_wifi_passwd_addr, (uint8_t*)&g_dev.cfg.net.wifi_passwd, lcd_wifi_passwd_size ); + osDelay(10 ); + sprintf(port_str, "%d", g_dev.cfg.net.tcp_port ); + lcd_write_text( lcd_tcp_port_addr, (uint8_t*)&port_str, lcd_tcp_port_size ); + osDelay(10 ); + lcd_write_text( lcd_tcp_server_addr, (uint8_t*)&g_dev.cfg.net.tcp_server, lcd_tcp_server_size ); + osDelay(10 ); + uint16_t flow_cal_x10 = (int16_t)(g_dev.cfg.cal.flow_comp_x1000/100); + lcd_write_s16( lcd_flow_cal_value_addr, flow_cal_x10 ); +} + void user_ui_task( void* unused ) { int16_t flow_cal_x10; @@ -350,6 +391,7 @@ void user_ui_task( void* unused ) //uint32_t last_tick = xTaskGetTickCount(); EventBits_t uxBits; static uint32_t n = 0; + char port_str[8]; //LCD Power ON @@ -378,11 +420,12 @@ void user_ui_task( void* unused ) osDelay(10 ); lcd_write_text( lcd_wifi_passwd_addr, (uint8_t*)&g_dev.cfg.net.wifi_passwd, lcd_wifi_passwd_size ); osDelay(10 ); - lcd_write_text( lcd_tcp_port_addr, (uint8_t*)&g_dev.cfg.net.tcp_port, lcd_tcp_port_size ); + sprintf(port_str, "%d", g_dev.cfg.net.tcp_port ); + lcd_write_text( lcd_tcp_port_addr, (uint8_t*)&port_str, lcd_tcp_port_size ); osDelay(10 ); lcd_write_text( lcd_tcp_server_addr, (uint8_t*)&g_dev.cfg.net.tcp_server, lcd_tcp_server_size ); osDelay(10 ); - flow_cal_x10 = (int16_t)(g_dev.cfg.cal.flowrate*10); + flow_cal_x10 = (int16_t)(g_dev.cfg.cal.flow_comp_x1000/100); lcd_write_s16( lcd_flow_cal_value_addr, flow_cal_x10 ); osDelay(10 ); @@ -390,6 +433,11 @@ void user_ui_task( void* unused ) uxBits = ui_wait_lcd_rx_event( EVENT_LCD_RX_DATA, 500 ); + if( remote_update_cfg_flag ){ + remote_update_cfg_flag = 0; + lcd_update_cfg(); + osDelay(100); + } if( uxBits & EVENT_LCD_RX_DATA ){ ui_handle_lcd_pkt(); }else{ @@ -404,6 +452,12 @@ void user_ui_task( void* unused ) reg_values[1] = g_dev.flowmeter.flow_speed*10; reg_values[2] = g_dev.pressure; reg_values[3] = g_dev.flowmeter.flow_total; + + if(g_dev.cfg.remote_locked==1 ){ + reg_values[0] = 666; //curr 66.6 + reg_values[1] = 666; //flow 66.6; + } + lcd_write( lcd_welding_current_addr, reg_values, 4 ); reg_values[0] = g_dev.wifi_connected; lcd_write( lcd_net_connected_addr, reg_values, 1 ); @@ -416,7 +470,7 @@ void user_ui_task( void* unused ) //正常点击屏幕修改参数会主动上报 //这里防止有数据包没有收到,主动查询一下(焊接工艺, 节气因子, 比例阀开度) n = 0; - lcd_read( lcd_welding_method_addr, 3 ); + ///lcd_read( lcd_welding_method_addr, 3 ); } osDelay(1); } diff --git a/user/user_valve_ctrl.c b/user/user_valve_ctrl.c index 37856ad..eec07c8 100644 --- a/user/user_valve_ctrl.c +++ b/user/user_valve_ctrl.c @@ -515,7 +515,7 @@ void user_valve_ctrl_task( void* unused ) }else{ valve_bypass( 0 ); //旁路电磁阀关闭 //检查焊接电流,判断是否开始焊接 - if( welding_current < 10.0f ){ //焊接电流大于10A 认为开始焊接,小于10A认为焊接停止。 + if( g_dev.cfg.remote_locked || welding_current < 10.0f ){ //焊接电流大于10A 认为开始焊接,小于10A认为焊接停止。 //未开始焊接 //按比例阀开度设置电流, 最小0.7v 最大1.0v, 按开度百分比计算电流 diff --git a/user/user_wifi.c b/user/user_wifi.c index fa1097b..ee52d68 100644 --- a/user/user_wifi.c +++ b/user/user_wifi.c @@ -1,5 +1,6 @@ #include "user.h" #include "at_parser.h" +#include "cJSON.h" //wifi task //uart5 @@ -12,7 +13,7 @@ extern UART_HandleTypeDef huart5; -#define WIFI_RX_BUF_SIZE 512 +#define WIFI_RX_BUF_SIZE (512*4) #define WIFI_RX_BUF_SIZE_MASK (WIFI_RX_BUF_SIZE-1) static char wifi_rx_buf[WIFI_RX_BUF_SIZE]; static uint32_t rx_buf_rd = 0; @@ -23,7 +24,7 @@ static uint8_t wifi_rx_byte = 0; static char g_wifi_ver[50]; -static int32_t wifi_tcp_tx( uint8_t *data, uint32_t sz ); +static int32_t wifi_tcp_tx( uint8_t link, uint8_t *data, uint32_t sz ); void wifi_uart_rx_start( void ) { @@ -37,7 +38,7 @@ void wifi_uart_rx_cb( void ) rx_byte = wifi_rx_byte; wifi_uart_rx_start(); - if( rx_buf_wr+1==rx_buf_rd ){ + if( rx_buf_wr >= rx_buf_rd + WIFI_RX_BUF_SIZE -1 ){ //full! }else{ wifi_rx_buf[rx_buf_wr&WIFI_RX_BUF_SIZE_MASK] = rx_byte; @@ -58,6 +59,11 @@ int32_t wifi_read_byte( uint8_t *rd_byte ) } } +int32_t wifi_received_bytes( void ) +{ + return rx_buf_wr-rx_buf_rd; +} + char * wifi_tx_cmd( char * cmd, uint32_t timeout_ms ) { HAL_UART_Transmit( &huart_wifi, (uint8_t *)cmd, strlen( cmd ), timeout_ms ); @@ -97,6 +103,19 @@ int32_t wifi_init( void ) } osDelay(2*1000); } + + if( ret == 0 ){ + for( int i=0; i<10; i++ ){ + cmd = "AT+CIPMUX=1"; + memset( resp_buf, 0, sizeof( resp_buf) ); + + if( at_send_wait_reply( cmd, strlen(cmd), true, NULL, 0, resp_buf, sizeof( resp_buf)-1, NULL ) ){ + DBG_PRINTF( "at send wait reply timeout!\n" ); + }else if( strstr( resp_buf, "OK" ) ){ + break; + } + } + } return ret; } @@ -163,7 +182,7 @@ int32_t wifi_connect( const char * ssid, const char * passwd ) return 0; } -int32_t tcp_server_connect( const char * tcp_server, const char * port ) +int32_t tcp_server_connect( uint8_t conn_id, const char * tcp_server, uint16_t port ) { char cmd[200]; atcmd_config_t at_cfg; @@ -174,80 +193,95 @@ int32_t tcp_server_connect( const char * tcp_server, const char * port ) at_cfg.reply_prefix = NULL; at_cfg.reply_success_postfix="OK"; //"CONNECT OK"; at_cfg.reply_fail_postfix = "ERROR"; //"ERROR CLOSED"; - sprintf( cmd, "AT+CIPSTART=\"TCP\",\"%s\",%s", tcp_server, port ); + sprintf( cmd, "AT+CIPSTART=%d,\"TCP\",\"%s\",%d", conn_id, tcp_server, port ); + if( at_send_wait_reply( cmd, strlen(cmd), true, NULL, 0, resp_buf, sizeof( resp_buf )-1, &at_cfg ) ){ + return -1; + } + if( strstr( resp_buf, "OK" ) || strstr( resp_buf, "ALREADY CONNECTED" ) ){ + return 0; + }else{ + return -1; + } +} + +int32_t tcp_server_close( uint8_t conn_id ) +{ + char cmd[100]; + atcmd_config_t at_cfg; + char resp_buf[100]; + + //4. 连接TCP服务器 + //AT+CIPSTART="TCP","192.168.3.116",8080 //protocol, server IP and port + at_cfg.reply_prefix = NULL; + at_cfg.reply_success_postfix="OK"; //"CONNECT OK"; + at_cfg.reply_fail_postfix = "ERROR"; //"ERROR CLOSED"; + sprintf( cmd, "AT+CIPCLOSE=%d", conn_id ); if( at_send_wait_reply( cmd, strlen(cmd), true, NULL, 0, resp_buf, sizeof( resp_buf )-1, &at_cfg ) ){ return -1; } if( !strstr( resp_buf, "OK" ) ){ return -1; } - return 0; } extern char * devinfo_report_str( void ); +extern int32_t get_ota_state( void ); + int32_t wifi_devinfo_report( void ) { char * rpt_data; + if( get_ota_state() ){ + //ota http 下载中, 暂停上报数据 + return 0; + } + rpt_data = devinfo_report_str(); - wifi_tcp_tx( (uint8_t *)rpt_data, strlen((char *)rpt_data) ); + wifi_tcp_tx( 0, (uint8_t *)rpt_data, strlen((char *)rpt_data) ); return 0; } -#if 0 -int32_t esp_read_imsi( void ) -{ +static uint8_t tcp_rx_buf[ 512 ]; +static uint16_t tcp_rx_n; - int ret = 0; - char *cmd ; - char *rsp = g_rsp; - char *buffer = g_rsp; - char imsi[20]; - - cmd = "AT+CIMI\r\n"; - bc25_send_with_retry( cmd, strlen(cmd), true, NULL, 0, buffer, BC25_DEFAULT_RSP_LEN, AT_CMD_TEST_RESULT); - - if ( strstr( rsp, "OK" ) && sscanf( rsp, "\r\n%15[^\r]", imsi) == 1 ){ - imsi[15] = 0; - HAL_Printf( "GET IMSI:%s\n", g_IMSI ); - if( strlen( imsi ) == 15 ){ - strcpy( g_IMSI, imsi ); - HAL_ClearGprsFaultCode(1); //clear E1/E5 - return 0; - } - } - return -1; -} -#endif +static uint8_t ota_rx_buf[2048]; +static uint16_t ota_rx_n; + +void ota_start( char* ver, char* url ); +void ota_handle_http_data( uint8_t *data, uint32_t sz ); -#define TCP_MAX_PAYLOAD_SIZE 512 -static uint8_t payload[TCP_MAX_PAYLOAD_SIZE] = {0}; -static void link_down( void *arg, char *rspinfo, int rsplen ) +static void wifi_rpt_link_down( void ) { if( g_dev.wifi_connected == 2 ) - g_dev.wifi_connected = 1; + g_dev.wifi_connected = 1 ; } + +extern int32_t wifi_received_bytes( void ); + static void tcp_rx_data_handle(void *arg, char *rspinfo, int rsplen) { unsigned char unusesymbol = 0; unsigned char datalen[6] = {0}; + unsigned char link_id=0; // unsigned char ipaddr[16] = {0}; int i = 0; int j = 0; int len = 0; -// int remoteport = 0; -// int linkid = 0; - char *recvdata = NULL; //+IPD,20:http://www.cmsoft.cn /*eat , char*/ at_read((char *)&unusesymbol, 1); + /*link id*/ + at_read( (char*)&link_id, 1 ); + /*eat , char*/ + at_read((char *)&unusesymbol, 1); + /* get data len */ i = 0; do { @@ -270,34 +304,96 @@ static void tcp_rx_data_handle(void *arg, char *rspinfo, int rsplen) for (j = 0; j < i; j++) { len = len * 10 + datalen[j] - '0'; } - HAL_Printf( "R:%d\n",len ); - if (len <= TCP_MAX_PAYLOAD_SIZE) { - recvdata = (char *)payload; - } - memset(recvdata, 0, len); - at_read(recvdata, len); + HAL_Printf( "--R:%d, wifi buf: %d[%d..%d]\n",len, rx_buf_wr-rx_buf_rd, rx_buf_rd, rx_buf_wr ); + if( link_id == '0' ){ + if( tcp_rx_n + len >= sizeof(tcp_rx_buf ) ){ + tcp_rx_n = 0; + } + tcp_rx_n = 0; + at_read( (char*)(tcp_rx_buf+tcp_rx_n), len ); + tcp_rx_n += len; + tcp_rx_buf[tcp_rx_n] = 0; + + cJSON*root = cJSON_Parse( (char*)tcp_rx_buf ); + if( root ){ + cJSON *action = cJSON_GetObjectItem( root, "action" ); + if(action && cJSON_IsString( action ) ){ + //lock/unlock 设备响应数据暂定如下: op代表操作数据 lock代表当前机器锁机状态 0锁机 1正常 + //{cmd:"op", mac:"", lock:"0" + if( strcmp( action->valuestring, "lockDevice" )== 0 ){ + debug_printf( "lockdevice %d->1\n", g_dev.cfg.remote_locked ); + g_dev.cfg.remote_locked = 1; + dev_cfg_store( &g_dev.cfg ); + }else if( strcmp( action->valuestring, "unlockDevice" )== 0 ){ + debug_printf( "unlockdevice %d->0\n", g_dev.cfg.remote_locked ); + g_dev.cfg.remote_locked = 0; + dev_cfg_store( &g_dev.cfg ); + }else if( strcmp( action->valuestring, "update" )== 0 ){ + //ota; + cJSON * data; + cJSON * ver; + cJSON * url; + data = cJSON_GetObjectItem( root, "data" ); + debug_printf( "-----ota----- " ); + if(data){ + ver = cJSON_GetObjectItem( data, "version" ); + url = cJSON_GetObjectItem( data, "downloadUrl" ); + if( ver ) debug_printf( "--version:[%s]", ver->valuestring ); + if( url ) debug_printf( "--url:[%s]", url->valuestring ); + if( ver &&url ){ + ///ota_start( ver->valuestring, url->valuestring ); + } + } + debug_printf( "\n" ); + } + } + tcp_rx_n = 0; + cJSON_Delete( root ); + } + }else if( link_id == '1' ){ + if( len <= sizeof(ota_rx_buf ) ){ + int n =at_read( (char*)(ota_rx_buf), len ); + ota_rx_n = len; + debug_printf( " ota recv data %d bytes, rd:%d, wifi buf:%d[%d..%d]\n", len, n, rx_buf_wr-rx_buf_rd, rx_buf_rd, rx_buf_wr ); + ///ota_handle_http_data( ota_rx_buf, ota_rx_n ); + } + } return; } -int32_t wifi_tcp_tx( uint8_t *data, uint32_t sz ) +int32_t wifi_tcp_tx( uint8_t link, uint8_t *data, uint32_t sz ) { //AT+CIPSEND=4 //> xxx static char cmd[500]; - char resp_buf[100]; + char resp_buf[500]; atcmd_config_t at_cfg; #if 1 at_cfg.reply_prefix = "SEND"; at_cfg.reply_success_postfix="OK"; - at_cfg.reply_fail_postfix = NULL; - sprintf( cmd, "AT+CIPSEND=%d", sz ); + at_cfg.reply_fail_postfix = "ERROR"; + sprintf( cmd, "AT+CIPSEND=%d,%d", link, sz ); + resp_buf[0] = 0; if( at_send_wait_reply( cmd, strlen(cmd), true, (char *)data, sz, resp_buf, sizeof( resp_buf )-1, &at_cfg ) ){ return -1; } + if( strstr( resp_buf, "link is not valid" ) ){ + if( link == 0 ){ + wifi_rpt_link_down(); + }else if(link==1){ + //wifi_ota_link_down(); + } + } + #endif return 0; } +#define TCP_CONN_ID 0 +#define OTA_CONN_ID 1 + +void wifi_ota_init( void ); + void user_wifi_task( void* unused ) { @@ -307,6 +403,9 @@ void user_wifi_task( void* unused ) TickType_t last_ticks; g_dev.wifi_connected = 0; + g_dev.eth_connected = 0; + + wifi_ota_init(); MX_UART5_Init(); wifi_uart_rx_start(); @@ -321,7 +420,7 @@ void user_wifi_task( void* unused ) } at_register_callback("+IPD", NULL, NULL, 0, tcp_rx_data_handle, NULL); - at_register_callback( "link is not valid", NULL, NULL, 0, link_down, NULL ); +// at_register_callback( "link is not valid", NULL, NULL, 0, link_down, NULL ); while( 1 ){ ssid = g_dev.cfg.net.wifi_ssid; @@ -342,7 +441,7 @@ void user_wifi_task( void* unused ) while( g_dev.wifi_connected == 1 ){ //tcp connect - if( tcp_server_connect( g_dev.cfg.net.tcp_server, g_dev.cfg.net.tcp_port ) == 0 ){ + if( tcp_server_connect( TCP_CONN_ID, g_dev.cfg.net.tcp_server, g_dev.cfg.net.tcp_port ) == 0 ){ g_dev.wifi_connected = 2; }else{ osDelay( 1000 ); @@ -354,7 +453,7 @@ void user_wifi_task( void* unused ) while( g_dev.wifi_connected == 2 ){ vTaskDelayUntil(&last_ticks, 1000 ); - + if( g_dev.eth_connected == 2 ){ //如果有线已经连接,wifi不上传数据 continue; @@ -378,8 +477,265 @@ const osThreadAttr_t wifiTask_attributes = { .priority = (osPriority_t) osPriorityNormal, }; +const osThreadAttr_t otaTask_attributes = { + .name = "otaTask", + .stack_size = 2048, + .priority = (osPriority_t) osPriorityNormal, +}; + void wifi_task_start( void ) { // wifiTaskHandle = osThreadNew(user_wifi_task, NULL, &wifiTask_attributes); osThreadNew(user_wifi_task, NULL, &wifiTask_attributes); } + + + + +typedef struct{ + char url[300]; + char tcp_srv[100]; + char path[200]; + uint16_t tcp_port; + void * lock; + osThreadId_t task; + uint8_t state; //0:idle, 1:start + uint32_t start_time; + + char fw_ver[20]; + uint32_t fw_received; + uint32_t fw_size; + uint32_t connected; +}ota_t; + +static ota_t g_ota; + +void wifi_ota_init( void ) +{ + memset( &g_ota, 0, sizeof( g_ota ) ); +} + +int32_t get_ota_state( void ) +{ + return g_ota.state; //0:idle, //1.busy +} + +#if WIFI_OTA + +static uint32_t http_wait_data = 0; + +void ota_task( void * unused ); +int32_t ota_url_parse( char* ota_url ); + +void wifi_ota_link_down( void ) +{ + g_ota.connected = 0; +} + +int32_t ota_url_parse( char* ota_url ) +{ + //http://www.test.com:80/path/file.bin + //http://www.test.com/path/file.bin + char * url; + char *path; + char host[100]; + uint16_t port; + + strcpy( g_ota.url, ota_url ); + + url = strstr( ota_url, "http://" ); + if( !url ) + return -1; + + //get host + url+=7; + + port = 80; + if( sscanf( url, "%[^/:]:%hd", host, &port ) < 1 ){ + return -1; + } + + path = strstr( url, "/"); + if( !path ){ + return -1; + } + + strcpy( g_ota.tcp_srv, host ); + strcpy( g_ota.path, path ); + g_ota.tcp_port = port; + + return 0; +} + +#define get_fmt "\ +GET %s HTTP/1.0\r\n\ +Host:%s:%d\r\n\ +Range:bytes=%d-%d\r\n\ +Connection:keep-alive\r\n\r\n" + +void ota_handle_http_data( uint8_t *data, uint32_t sz ) +{ + char *s; + uint8_t *content_data; + uint32_t content_sz; + uint32_t range_start; + uint32_t range_end; + uint32_t file_sz; + + s=strstr( (char*)data, "Content-Range:" ); + if( s && sscanf( s, "Content-Range: bytes %d-%d/%d", &range_start, &range_end, &file_sz ) == 3 ){ + g_ota.fw_size = file_sz; + debug_printf( "recv range:%d-%d/%d\n", range_start, range_end, file_sz ); + if( range_start == g_ota.fw_received ){ + g_ota.fw_received = range_end+1; + debug_printf( "fw_received -> %d\n", g_ota.fw_received ); + http_wait_data = 0; + } + s = strstr( (char*)data, "\r\n\r\n" ); + if( s ){ + content_data = (uint8_t*)(s+4); + uint32_t head_sz = (uint32_t)content_data-(uint32_t)data; + content_sz = sz - head_sz; + debug_printf( "rx content size: %d\n", content_sz ); + } + } + +} + +int32_t http_dowload( void ) +{ + uint32_t blk_start; + uint32_t blk_sz; + uint32_t tick; + uint32_t download_start_time; + + char cmd[200]; + + download_start_time = xTaskGetTickCount(); + while( (g_ota.fw_size == 0 || g_ota.fw_received < g_ota.fw_size) && xTaskGetTickCount()-download_start_time < 30*60*1000 ){ + + if( !g_ota.connected ){ + if( tcp_server_connect( OTA_CONN_ID, g_ota.tcp_srv, g_ota.tcp_port ) < 0 ){ + + osDelay( 2000 ); + continue; + } + g_ota.connected = 1; + } + + blk_start = g_ota.fw_received; + if( g_ota.fw_size && g_ota.fw_size < blk_start+1000 ) + blk_sz = g_ota.fw_size-blk_start; + else + blk_sz = 1000; + + sprintf( cmd, get_fmt, g_ota.path, g_ota.tcp_srv, g_ota.tcp_port, blk_start, blk_start+blk_sz-1 ); + debug_printf( "http get block, cmd[%s]\n", cmd ); + http_wait_data = blk_sz; + tick = xTaskGetTickCount(); + + wifi_tcp_tx(1, (uint8_t *)cmd, strlen(cmd) ); + while( http_wait_data && xTaskGetTickCount()-tick < 20*1000 ){ + osDelay(10); + } + } + + if( g_ota.fw_received == g_ota.fw_size ){ + return 0; + }else{ + return -1; + } +} + + +void ota_task( void * unused ) +{ + int32_t ret; + debug_printf( "ota_task ...\n" ); + debug_printf( "url [%s], host[%s], port[%d], path[%s]\n", g_ota.url, g_ota.tcp_srv, g_ota.tcp_port, g_ota.path ); + + g_ota.start_time = xTaskGetTickCount(); + g_ota.fw_size = 0; + g_ota.fw_ver[0] = 0; + g_ota.fw_received = 0; + + //十分钟超时 + while( xTaskGetTickCount() - g_ota.start_time < 10*60*1000 ){ + + //1. tcp connect + debug_printf( "tcp connect: %s %d ...\n", g_ota.tcp_srv, g_ota.tcp_port ); + if( tcp_server_connect( OTA_CONN_ID, g_ota.tcp_srv, g_ota.tcp_port ) < 0 ){ + + osDelay( 1000 ); + continue; + } + g_ota.connected = 1; + debug_printf( "tcp connected\n" ); + ret = http_dowload(); + if( ret== 0 ){ + //dowload success + //reboot + break; + + }else if( ret == -1 ){ + //fail + goto err_exit; + + }else if( ret == -2 ){ + //reconnect + tcp_server_close( OTA_CONN_ID ); + osDelay( 5000 ); + continue; + } + if( g_ota.connected == 0 ){ + } + } + +err_exit: + tcp_server_close( OTA_CONN_ID ); + g_ota.state = 0; + vTaskDelete( NULL ); +} + + +void ota_start( char* ver, char* url ) +{ + debug_printf("ota_start, ver:%s, url:%s\n" ); + if( g_ota.state ){ + //busy + debug_printf("device busy\n" ); + return; + } + + //1. parser_url + if( ota_url_parse( url ) < 0 ){ + debug_printf("url parse fail!\n" ); + return; + } + + strcpy( g_ota.fw_ver, ver ); + g_ota.task = osThreadNew(ota_task, NULL, &otaTask_attributes); + if( g_ota.task ){ + debug_printf("create ota task success!\n" ); + g_ota.state = 1; + }else{ + debug_printf("create ota task fail!\n" ); + } + return; +} + +#endif //WIFI_OTA + +extern void *HAL_Malloc(uint32_t size); +extern void HAL_Free(void *ptr); + +void *HAL_Malloc(uint32_t size) +{ + return pvPortMalloc( size ); +} + +void HAL_Free(void *ptr) +{ + vPortFree( ptr ); +} + -- 2.34.1