增加流量计气体修正系数
authorkyz <kongyuzhong@google.com>
Tue, 23 Apr 2024 06:34:14 +0000 (14:34 +0800)
committerkyz <kongyuzhong@google.com>
Tue, 23 Apr 2024 06:34:14 +0000 (14:34 +0800)
1.wifi连接支持设备锁定指令
2.流量计气体修正系数可配置
3.调试工具增加参数读写功能
4.上报平台数据按协议调整

17 files changed:
MDK-ARM/welding_controller_v2.uvprojx
tools_v2/test.py
tools_v2/test.ui
user/at_parser.c
user/cJSON.c [new file with mode: 0644]
user/cJSON.h [new file with mode: 0644]
user/user.h
user/user_adc.c
user/user_app.c
user/user_cdc_rx_2.c
user/user_debug.c
user/user_eth.c
user/user_flowmeter.c
user/user_report.c
user/user_ui.c
user/user_valve_ctrl.c
user/user_wifi.c

index 0334dad8242325c22ea52c2a1cfe562d41518f7b..7c12b8bdb59bdaba838b91275464e2a78d907056 100644 (file)
               <FileType>1</FileType>
               <FilePath>..\user\ht1622.c</FilePath>
             </File>
+            <File>
+              <FileName>cJSON.c</FileName>
+              <FileType>1</FileType>
+              <FilePath>..\user\cJSON.c</FilePath>
+            </File>
           </Files>
         </Group>
         <Group>
index ff11d207c95c777c05a9d8a81d2bcafa59fef356..39aa76cf3d6271ab94ce86a1a565f4d2e58cb37a 100644 (file)
@@ -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] )
index 94e5fd357a7c97f27f71ce9de7e5959d9877f75c..62fcbe0746bb432e11841c50cfdf9ace1ef717fc 100644 (file)
@@ -6,7 +6,7 @@
    <rect>
     <x>0</x>
     <y>0</y>
-    <width>1324</width>
+    <width>1535</width>
     <height>845</height>
    </rect>
   </property>
      </rect>
     </property>
     <property name="currentIndex">
-     <number>2</number>
+     <number>3</number>
     </property>
     <widget class="QWidget" name="tab">
      <attribute name="title">
      <attribute name="title">
       <string>页</string>
      </attribute>
+     <widget class="QPushButton" name="btn_debug_write_2">
+      <property name="geometry">
+       <rect>
+        <x>310</x>
+        <y>70</y>
+        <width>91</width>
+        <height>51</height>
+       </rect>
+      </property>
+      <property name="text">
+       <string>参数读取</string>
+      </property>
+     </widget>
+     <widget class="QLabel" name="label_9">
+      <property name="geometry">
+       <rect>
+        <x>50</x>
+        <y>30</y>
+        <width>41</width>
+        <height>31</height>
+       </rect>
+      </property>
+      <property name="text">
+       <string>UUID:</string>
+      </property>
+     </widget>
+     <widget class="QLineEdit" name="lineEdit_uuid_3">
+      <property name="geometry">
+       <rect>
+        <x>100</x>
+        <y>30</y>
+        <width>201</width>
+        <height>31</height>
+       </rect>
+      </property>
+      <property name="text">
+       <string>00000000-00000000-00000000</string>
+      </property>
+      <property name="readOnly">
+       <bool>true</bool>
+      </property>
+     </widget>
+     <widget class="QTableWidget" name="tableWidget_devinfo_2">
+      <property name="geometry">
+       <rect>
+        <x>50</x>
+        <y>70</y>
+        <width>191</width>
+        <height>121</height>
+       </rect>
+      </property>
+      <row>
+       <property name="text">
+        <string>焊接工艺</string>
+       </property>
+      </row>
+      <row>
+       <property name="text">
+        <string>节气因子</string>
+       </property>
+      </row>
+      <row>
+       <property name="text">
+        <string>前气开度</string>
+       </property>
+      </row>
+      <column>
+       <property name="text">
+        <string/>
+       </property>
+      </column>
+     </widget>
+     <widget class="QPushButton" name="btn_debug_write_3">
+      <property name="geometry">
+       <rect>
+        <x>310</x>
+        <y>130</y>
+        <width>91</width>
+        <height>51</height>
+       </rect>
+      </property>
+      <property name="text">
+       <string>参数写入</string>
+      </property>
+     </widget>
+     <widget class="QTableWidget" name="tableWidget_devinfo_3">
+      <property name="geometry">
+       <rect>
+        <x>50</x>
+        <y>200</y>
+        <width>191</width>
+        <height>91</height>
+       </rect>
+      </property>
+      <row>
+       <property name="text">
+        <string>流量补偿</string>
+       </property>
+      </row>
+      <row>
+       <property name="text">
+        <string>气体修正系数</string>
+       </property>
+      </row>
+      <column>
+       <property name="text">
+        <string/>
+       </property>
+      </column>
+     </widget>
+     <widget class="QTableWidget" name="tableWidget_devinfo_4">
+      <property name="geometry">
+       <rect>
+        <x>50</x>
+        <y>300</y>
+        <width>221</width>
+        <height>151</height>
+       </rect>
+      </property>
+      <row>
+       <property name="text">
+        <string>WIFI SSID</string>
+       </property>
+      </row>
+      <row>
+       <property name="text">
+        <string>密码</string>
+       </property>
+      </row>
+      <row>
+       <property name="text">
+        <string>服务器地址</string>
+       </property>
+      </row>
+      <row>
+       <property name="text">
+        <string>服务器端口</string>
+       </property>
+      </row>
+      <column>
+       <property name="text">
+        <string/>
+       </property>
+      </column>
+     </widget>
+     <widget class="QLabel" name="label_10">
+      <property name="geometry">
+       <rect>
+        <x>620</x>
+        <y>110</y>
+        <width>51</width>
+        <height>31</height>
+       </rect>
+      </property>
+      <property name="text">
+       <string>焊接工艺</string>
+      </property>
+     </widget>
+     <widget class="QLineEdit" name="lineEdit_uuid_4">
+      <property name="geometry">
+       <rect>
+        <x>680</x>
+        <y>110</y>
+        <width>71</width>
+        <height>31</height>
+       </rect>
+      </property>
+      <property name="text">
+       <string/>
+      </property>
+      <property name="readOnly">
+       <bool>true</bool>
+      </property>
+     </widget>
+     <widget class="QPushButton" name="btn_debug_write_4">
+      <property name="geometry">
+       <rect>
+        <x>760</x>
+        <y>110</y>
+        <width>91</width>
+        <height>31</height>
+       </rect>
+      </property>
+      <property name="text">
+       <string>参数写入</string>
+      </property>
+     </widget>
+     <widget class="QGroupBox" name="groupBox_6">
+      <property name="geometry">
+       <rect>
+        <x>570</x>
+        <y>230</y>
+        <width>391</width>
+        <height>221</height>
+       </rect>
+      </property>
+      <property name="title">
+       <string>设备参数</string>
+      </property>
+     </widget>
+     <widget class="QLabel" name="label_11">
+      <property name="geometry">
+       <rect>
+        <x>620</x>
+        <y>150</y>
+        <width>51</width>
+        <height>31</height>
+       </rect>
+      </property>
+      <property name="text">
+       <string>焊接工艺</string>
+      </property>
+     </widget>
+     <widget class="QLineEdit" name="lineEdit_uuid_5">
+      <property name="geometry">
+       <rect>
+        <x>680</x>
+        <y>150</y>
+        <width>71</width>
+        <height>31</height>
+       </rect>
+      </property>
+      <property name="text">
+       <string/>
+      </property>
+      <property name="readOnly">
+       <bool>true</bool>
+      </property>
+     </widget>
+     <widget class="QPushButton" name="btn_debug_write_5">
+      <property name="geometry">
+       <rect>
+        <x>760</x>
+        <y>150</y>
+        <width>91</width>
+        <height>31</height>
+       </rect>
+      </property>
+      <property name="text">
+       <string>参数写入</string>
+      </property>
+     </widget>
+     <widget class="QLabel" name="label_12">
+      <property name="geometry">
+       <rect>
+        <x>620</x>
+        <y>190</y>
+        <width>51</width>
+        <height>31</height>
+       </rect>
+      </property>
+      <property name="text">
+       <string>焊接工艺</string>
+      </property>
+     </widget>
+     <widget class="QLineEdit" name="lineEdit_uuid_6">
+      <property name="geometry">
+       <rect>
+        <x>680</x>
+        <y>190</y>
+        <width>71</width>
+        <height>31</height>
+       </rect>
+      </property>
+      <property name="text">
+       <string/>
+      </property>
+      <property name="readOnly">
+       <bool>true</bool>
+      </property>
+     </widget>
+     <widget class="QPushButton" name="btn_debug_write_6">
+      <property name="geometry">
+       <rect>
+        <x>760</x>
+        <y>190</y>
+        <width>91</width>
+        <height>31</height>
+       </rect>
+      </property>
+      <property name="text">
+       <string>参数写入</string>
+      </property>
+     </widget>
+     <widget class="QTabWidget" name="tabWidget_2">
+      <property name="geometry">
+       <rect>
+        <x>0</x>
+        <y>-20</y>
+        <width>1161</width>
+        <height>831</height>
+       </rect>
+      </property>
+      <property name="currentIndex">
+       <number>3</number>
+      </property>
+      <widget class="QWidget" name="tab_5">
+       <attribute name="title">
+        <string>Tab 1</string>
+       </attribute>
+       <widget class="QFrame" name="frame_curr_2">
+        <property name="geometry">
+         <rect>
+          <x>0</x>
+          <y>130</y>
+          <width>1141</width>
+          <height>201</height>
+         </rect>
+        </property>
+        <property name="frameShape">
+         <enum>QFrame::StyledPanel</enum>
+        </property>
+        <property name="frameShadow">
+         <enum>QFrame::Raised</enum>
+        </property>
+       </widget>
+       <widget class="QFrame" name="frame_flow_2">
+        <property name="geometry">
+         <rect>
+          <x>0</x>
+          <y>340</y>
+          <width>1141</width>
+          <height>461</height>
+         </rect>
+        </property>
+        <property name="frameShape">
+         <enum>QFrame::StyledPanel</enum>
+        </property>
+        <property name="frameShadow">
+         <enum>QFrame::Raised</enum>
+        </property>
+       </widget>
+       <widget class="QTableWidget" name="tableWidget_devinfo_5">
+        <property name="geometry">
+         <rect>
+          <x>10</x>
+          <y>70</y>
+          <width>1141</width>
+          <height>51</height>
+         </rect>
+        </property>
+        <row>
+         <property name="text">
+          <string/>
+         </property>
+        </row>
+        <column>
+         <property name="text">
+          <string>焊接时间</string>
+         </property>
+        </column>
+        <column>
+         <property name="text">
+          <string>焊接电流</string>
+         </property>
+        </column>
+        <column>
+         <property name="text">
+          <string>目标流量</string>
+         </property>
+        </column>
+        <column>
+         <property name="text">
+          <string>实时流量</string>
+         </property>
+        </column>
+        <column>
+         <property name="text">
+          <string>气体压力</string>
+         </property>
+        </column>
+        <column>
+         <property name="text">
+          <string>控制电流</string>
+         </property>
+        </column>
+        <column>
+         <property name="text">
+          <string>焊接工艺</string>
+         </property>
+        </column>
+        <column>
+         <property name="text">
+          <string>节气因子</string>
+         </property>
+        </column>
+        <column>
+         <property name="text">
+          <string>默认开度</string>
+         </property>
+        </column>
+        <column>
+         <property name="text">
+          <string>电流校准</string>
+         </property>
+        </column>
+        <column>
+         <property name="text">
+          <string>流量校准</string>
+         </property>
+        </column>
+        <item row="0" column="0">
+         <property name="text">
+          <string>0</string>
+         </property>
+        </item>
+        <item row="0" column="1">
+         <property name="text">
+          <string>0</string>
+         </property>
+        </item>
+        <item row="0" column="2">
+         <property name="text">
+          <string>0</string>
+         </property>
+        </item>
+        <item row="0" column="3">
+         <property name="text">
+          <string>0</string>
+         </property>
+        </item>
+        <item row="0" column="4">
+         <property name="text">
+          <string>0</string>
+         </property>
+        </item>
+        <item row="0" column="5">
+         <property name="text">
+          <string>0</string>
+         </property>
+        </item>
+        <item row="0" column="6">
+         <property name="text">
+          <string>0</string>
+         </property>
+        </item>
+        <item row="0" column="7">
+         <property name="text">
+          <string>0</string>
+         </property>
+        </item>
+        <item row="0" column="8">
+         <property name="text">
+          <string>0</string>
+         </property>
+        </item>
+        <item row="0" column="9">
+         <property name="text">
+          <string>0</string>
+         </property>
+        </item>
+        <item row="0" column="10">
+         <property name="text">
+          <string>0</string>
+         </property>
+        </item>
+       </widget>
+       <widget class="QPushButton" name="btn_connect_devinfo_2">
+        <property name="geometry">
+         <rect>
+          <x>10</x>
+          <y>0</y>
+          <width>71</width>
+          <height>61</height>
+         </rect>
+        </property>
+        <property name="text">
+         <string>连接</string>
+        </property>
+        <property name="autoDefault">
+         <bool>false</bool>
+        </property>
+       </widget>
+       <widget class="QGroupBox" name="groupBox_7">
+        <property name="geometry">
+         <rect>
+          <x>540</x>
+          <y>0</y>
+          <width>611</width>
+          <height>61</height>
+         </rect>
+        </property>
+        <property name="title">
+         <string>GroupBox</string>
+        </property>
+        <widget class="QPushButton" name="btn_debug_write_7">
+         <property name="geometry">
+          <rect>
+           <x>510</x>
+           <y>10</y>
+           <width>91</width>
+           <height>51</height>
+          </rect>
+         </property>
+         <property name="text">
+          <string>写入</string>
+         </property>
+        </widget>
+        <widget class="QLineEdit" name="lineEdit_debug_value_2">
+         <property name="geometry">
+          <rect>
+           <x>150</x>
+           <y>20</y>
+           <width>41</width>
+           <height>31</height>
+          </rect>
+         </property>
+         <property name="text">
+          <string>80</string>
+         </property>
+        </widget>
+        <widget class="QSlider" name="horizontalSlider_2">
+         <property name="geometry">
+          <rect>
+           <x>230</x>
+           <y>20</y>
+           <width>271</width>
+           <height>31</height>
+          </rect>
+         </property>
+         <property name="orientation">
+          <enum>Qt::Horizontal</enum>
+         </property>
+        </widget>
+        <widget class="QComboBox" name="cb_debug_mode_2">
+         <property name="geometry">
+          <rect>
+           <x>10</x>
+           <y>20</y>
+           <width>121</width>
+           <height>31</height>
+          </rect>
+         </property>
+         <property name="editable">
+          <bool>true</bool>
+         </property>
+         <property name="duplicatesEnabled">
+          <bool>false</bool>
+         </property>
+         <property name="frame">
+          <bool>true</bool>
+         </property>
+         <item>
+          <property name="text">
+           <string>关闭模拟调试</string>
+          </property>
+         </item>
+         <item>
+          <property name="text">
+           <string>模拟焊接电流</string>
+          </property>
+         </item>
+         <item>
+          <property name="text">
+           <string>比例阀控制电流</string>
+          </property>
+         </item>
+        </widget>
+        <widget class="QLabel" name="label_debug_curr_unit_2">
+         <property name="geometry">
+          <rect>
+           <x>200</x>
+           <y>20</y>
+           <width>21</width>
+           <height>31</height>
+          </rect>
+         </property>
+         <property name="text">
+          <string>A</string>
+         </property>
+        </widget>
+       </widget>
+       <widget class="QGroupBox" name="groupBox_8">
+        <property name="geometry">
+         <rect>
+          <x>90</x>
+          <y>0</y>
+          <width>441</width>
+          <height>61</height>
+         </rect>
+        </property>
+        <property name="title">
+         <string>GroupBox</string>
+        </property>
+        <widget class="QLabel" name="label_13">
+         <property name="geometry">
+          <rect>
+           <x>20</x>
+           <y>21</y>
+           <width>41</width>
+           <height>31</height>
+          </rect>
+         </property>
+         <property name="text">
+          <string>版本:</string>
+         </property>
+        </widget>
+        <widget class="QLabel" name="label_fw_ver_3">
+         <property name="geometry">
+          <rect>
+           <x>70</x>
+           <y>20</y>
+           <width>81</width>
+           <height>31</height>
+          </rect>
+         </property>
+         <property name="text">
+          <string>V1.0</string>
+         </property>
+        </widget>
+        <widget class="QLabel" name="label_14">
+         <property name="geometry">
+          <rect>
+           <x>190</x>
+           <y>20</y>
+           <width>41</width>
+           <height>31</height>
+          </rect>
+         </property>
+         <property name="text">
+          <string>UUID:</string>
+         </property>
+        </widget>
+        <widget class="QLineEdit" name="lineEdit_uuid_7">
+         <property name="geometry">
+          <rect>
+           <x>230</x>
+           <y>20</y>
+           <width>201</width>
+           <height>31</height>
+          </rect>
+         </property>
+         <property name="text">
+          <string>00000000-00000000-00000000</string>
+         </property>
+         <property name="readOnly">
+          <bool>true</bool>
+         </property>
+        </widget>
+       </widget>
+      </widget>
+      <widget class="QWidget" name="tab_6">
+       <attribute name="title">
+        <string>Tab 2</string>
+       </attribute>
+       <widget class="QFrame" name="frame_curr_raw_2">
+        <property name="geometry">
+         <rect>
+          <x>0</x>
+          <y>240</y>
+          <width>1151</width>
+          <height>561</height>
+         </rect>
+        </property>
+        <property name="frameShape">
+         <enum>QFrame::StyledPanel</enum>
+        </property>
+        <property name="frameShadow">
+         <enum>QFrame::Raised</enum>
+        </property>
+       </widget>
+       <widget class="QPushButton" name="btn_files_select_2">
+        <property name="geometry">
+         <rect>
+          <x>10</x>
+          <y>60</y>
+          <width>111</width>
+          <height>51</height>
+         </rect>
+        </property>
+        <property name="text">
+         <string>日志选择</string>
+        </property>
+       </widget>
+       <widget class="QListWidget" name="listWidget_log_files_2">
+        <property name="geometry">
+         <rect>
+          <x>130</x>
+          <y>0</y>
+          <width>931</width>
+          <height>231</height>
+         </rect>
+        </property>
+       </widget>
+       <widget class="QPushButton" name="btn_connect_curr_2">
+        <property name="geometry">
+         <rect>
+          <x>10</x>
+          <y>0</y>
+          <width>111</width>
+          <height>51</height>
+         </rect>
+        </property>
+        <property name="text">
+         <string>连接</string>
+        </property>
+       </widget>
+       <widget class="QPushButton" name="btn_files_clear_2">
+        <property name="geometry">
+         <rect>
+          <x>10</x>
+          <y>120</y>
+          <width>111</width>
+          <height>51</height>
+         </rect>
+        </property>
+        <property name="text">
+         <string>日志清除</string>
+        </property>
+       </widget>
+      </widget>
+      <widget class="QWidget" name="tab_7">
+       <attribute name="title">
+        <string>页</string>
+       </attribute>
+       <widget class="QGroupBox" name="groupBox_9">
+        <property name="geometry">
+         <rect>
+          <x>10</x>
+          <y>100</y>
+          <width>591</width>
+          <height>591</height>
+         </rect>
+        </property>
+        <property name="title">
+         <string>GroupBox</string>
+        </property>
+        <widget class="QLineEdit" name="lineEdit_image_addr_2">
+         <property name="geometry">
+          <rect>
+           <x>80</x>
+           <y>70</y>
+           <width>111</width>
+           <height>31</height>
+          </rect>
+         </property>
+        </widget>
+        <widget class="Line" name="line_4">
+         <property name="geometry">
+          <rect>
+           <x>10</x>
+           <y>140</y>
+           <width>571</width>
+           <height>20</height>
+          </rect>
+         </property>
+         <property name="orientation">
+          <enum>Qt::Horizontal</enum>
+         </property>
+        </widget>
+        <widget class="QLineEdit" name="lineEdit_fw_path_2">
+         <property name="geometry">
+          <rect>
+           <x>80</x>
+           <y>30</y>
+           <width>331</width>
+           <height>31</height>
+          </rect>
+         </property>
+        </widget>
+        <widget class="QPushButton" name="btn_select_fw_2">
+         <property name="geometry">
+          <rect>
+           <x>10</x>
+           <y>30</y>
+           <width>61</width>
+           <height>31</height>
+          </rect>
+         </property>
+         <property name="text">
+          <string>固件..</string>
+         </property>
+         <property name="autoDefault">
+          <bool>false</bool>
+         </property>
+        </widget>
+        <widget class="QLabel" name="label_15">
+         <property name="geometry">
+          <rect>
+           <x>210</x>
+           <y>70</y>
+           <width>91</width>
+           <height>31</height>
+          </rect>
+         </property>
+         <property name="text">
+          <string>数据包最大长度</string>
+         </property>
+        </widget>
+        <widget class="QPushButton" name="btn_download_2">
+         <property name="geometry">
+          <rect>
+           <x>420</x>
+           <y>30</y>
+           <width>161</width>
+           <height>101</height>
+          </rect>
+         </property>
+         <property name="text">
+          <string>下载</string>
+         </property>
+        </widget>
+        <widget class="QLineEdit" name="lineEdit_pkt_max_sz_2">
+         <property name="geometry">
+          <rect>
+           <x>310</x>
+           <y>70</y>
+           <width>101</width>
+           <height>31</height>
+          </rect>
+         </property>
+         <property name="text">
+          <string>1024</string>
+         </property>
+         <property name="dragEnabled">
+          <bool>false</bool>
+         </property>
+         <property name="readOnly">
+          <bool>false</bool>
+         </property>
+         <property name="clearButtonEnabled">
+          <bool>false</bool>
+         </property>
+        </widget>
+        <widget class="QTextEdit" name="update_log_2">
+         <property name="geometry">
+          <rect>
+           <x>10</x>
+           <y>160</y>
+           <width>571</width>
+           <height>421</height>
+          </rect>
+         </property>
+         <property name="inputMethodHints">
+          <set>Qt::ImhDigitsOnly</set>
+         </property>
+        </widget>
+        <widget class="QLabel" name="label_16">
+         <property name="geometry">
+          <rect>
+           <x>10</x>
+           <y>70</y>
+           <width>51</width>
+           <height>31</height>
+          </rect>
+         </property>
+         <property name="text">
+          <string>起始地址</string>
+         </property>
+        </widget>
+        <widget class="QProgressBar" name="progressBar_2">
+         <property name="geometry">
+          <rect>
+           <x>10</x>
+           <y>110</y>
+           <width>401</width>
+           <height>20</height>
+          </rect>
+         </property>
+         <property name="autoFillBackground">
+          <bool>false</bool>
+         </property>
+         <property name="value">
+          <number>0</number>
+         </property>
+         <property name="textVisible">
+          <bool>true</bool>
+         </property>
+         <property name="orientation">
+          <enum>Qt::Horizontal</enum>
+         </property>
+        </widget>
+       </widget>
+       <widget class="QPushButton" name="btn_connect_update_2">
+        <property name="geometry">
+         <rect>
+          <x>20</x>
+          <y>30</y>
+          <width>71</width>
+          <height>61</height>
+         </rect>
+        </property>
+        <property name="text">
+         <string>连接</string>
+        </property>
+        <property name="autoDefault">
+         <bool>false</bool>
+        </property>
+       </widget>
+       <widget class="QGroupBox" name="groupBox_10">
+        <property name="geometry">
+         <rect>
+          <x>100</x>
+          <y>30</y>
+          <width>501</width>
+          <height>61</height>
+         </rect>
+        </property>
+        <property name="title">
+         <string>GroupBox</string>
+        </property>
+        <widget class="QLabel" name="label_17">
+         <property name="geometry">
+          <rect>
+           <x>20</x>
+           <y>21</y>
+           <width>41</width>
+           <height>31</height>
+          </rect>
+         </property>
+         <property name="text">
+          <string>版本:</string>
+         </property>
+        </widget>
+        <widget class="QLabel" name="label_fw_ver_4">
+         <property name="geometry">
+          <rect>
+           <x>70</x>
+           <y>20</y>
+           <width>61</width>
+           <height>31</height>
+          </rect>
+         </property>
+         <property name="text">
+          <string>V1.0</string>
+         </property>
+        </widget>
+        <widget class="QLabel" name="label_18">
+         <property name="geometry">
+          <rect>
+           <x>150</x>
+           <y>20</y>
+           <width>41</width>
+           <height>31</height>
+          </rect>
+         </property>
+         <property name="text">
+          <string>UUID:</string>
+         </property>
+        </widget>
+        <widget class="QLineEdit" name="lineEdit_uuid_8">
+         <property name="geometry">
+          <rect>
+           <x>190</x>
+           <y>20</y>
+           <width>301</width>
+           <height>31</height>
+          </rect>
+         </property>
+         <property name="text">
+          <string>00000000-00000000-00000000</string>
+         </property>
+         <property name="readOnly">
+          <bool>true</bool>
+         </property>
+        </widget>
+       </widget>
+      </widget>
+      <widget class="QWidget" name="tab_8">
+       <attribute name="title">
+        <string>页</string>
+       </attribute>
+       <widget class="QGroupBox" name="groupBox_11">
+        <property name="geometry">
+         <rect>
+          <x>20</x>
+          <y>30</y>
+          <width>421</width>
+          <height>171</height>
+         </rect>
+        </property>
+        <property name="title">
+         <string>设备参数</string>
+        </property>
+        <widget class="QLabel" name="label_22">
+         <property name="geometry">
+          <rect>
+           <x>40</x>
+           <y>120</y>
+           <width>51</width>
+           <height>31</height>
+          </rect>
+         </property>
+         <property name="text">
+          <string>前后气</string>
+         </property>
+        </widget>
+        <widget class="QLabel" name="label_20">
+         <property name="geometry">
+          <rect>
+           <x>40</x>
+           <y>40</y>
+           <width>51</width>
+           <height>31</height>
+          </rect>
+         </property>
+         <property name="text">
+          <string>焊接工艺</string>
+         </property>
+        </widget>
+        <widget class="QLabel" name="label_21">
+         <property name="geometry">
+          <rect>
+           <x>40</x>
+           <y>80</y>
+           <width>51</width>
+           <height>31</height>
+          </rect>
+         </property>
+         <property name="text">
+          <string>节气因子</string>
+         </property>
+        </widget>
+        <widget class="QLineEdit" name="lineEdit_cfg_factor">
+         <property name="geometry">
+          <rect>
+           <x>100</x>
+           <y>80</y>
+           <width>141</width>
+           <height>31</height>
+          </rect>
+         </property>
+         <property name="text">
+          <string>0</string>
+         </property>
+         <property name="readOnly">
+          <bool>false</bool>
+         </property>
+        </widget>
+        <widget class="QLineEdit" name="lineEdit_cfg_prev">
+         <property name="geometry">
+          <rect>
+           <x>100</x>
+           <y>120</y>
+           <width>141</width>
+           <height>31</height>
+          </rect>
+         </property>
+         <property name="text">
+          <string>0</string>
+         </property>
+         <property name="readOnly">
+          <bool>false</bool>
+         </property>
+        </widget>
+        <widget class="QPushButton" name="btn_dev_cfg_write">
+         <property name="geometry">
+          <rect>
+           <x>330</x>
+           <y>40</y>
+           <width>81</width>
+           <height>71</height>
+          </rect>
+         </property>
+         <property name="text">
+          <string>写入</string>
+         </property>
+        </widget>
+        <widget class="QPushButton" name="btn_dev_cfg_read">
+         <property name="geometry">
+          <rect>
+           <x>250</x>
+           <y>40</y>
+           <width>81</width>
+           <height>71</height>
+          </rect>
+         </property>
+         <property name="text">
+          <string>读取</string>
+         </property>
+        </widget>
+        <widget class="QComboBox" name="cb_cfg_method">
+         <property name="geometry">
+          <rect>
+           <x>100</x>
+           <y>40</y>
+           <width>141</width>
+           <height>31</height>
+          </rect>
+         </property>
+         <property name="editable">
+          <bool>false</bool>
+         </property>
+         <property name="duplicatesEnabled">
+          <bool>false</bool>
+         </property>
+         <property name="frame">
+          <bool>true</bool>
+         </property>
+         <item>
+          <property name="text">
+           <string>TIG</string>
+          </property>
+         </item>
+         <item>
+          <property name="text">
+           <string>MIG</string>
+          </property>
+         </item>
+         <item>
+          <property name="text">
+           <string>MAG</string>
+          </property>
+         </item>
+        </widget>
+       </widget>
+       <widget class="QGroupBox" name="groupBox_12">
+        <property name="geometry">
+         <rect>
+          <x>20</x>
+          <y>210</y>
+          <width>421</width>
+          <height>131</height>
+         </rect>
+        </property>
+        <property name="title">
+         <string>流量校准</string>
+        </property>
+        <widget class="QLabel" name="label_24">
+         <property name="geometry">
+          <rect>
+           <x>20</x>
+           <y>40</y>
+           <width>71</width>
+           <height>31</height>
+          </rect>
+         </property>
+         <property name="text">
+          <string>流量补偿</string>
+         </property>
+        </widget>
+        <widget class="QLineEdit" name="lineEdit_flow_coeff">
+         <property name="geometry">
+          <rect>
+           <x>210</x>
+           <y>80</y>
+           <width>31</width>
+           <height>31</height>
+          </rect>
+         </property>
+         <property name="text">
+          <string>0</string>
+         </property>
+         <property name="readOnly">
+          <bool>true</bool>
+         </property>
+        </widget>
+        <widget class="QLabel" name="label_25">
+         <property name="geometry">
+          <rect>
+           <x>20</x>
+           <y>80</y>
+           <width>71</width>
+           <height>31</height>
+          </rect>
+         </property>
+         <property name="text">
+          <string>气体修正系数</string>
+         </property>
+        </widget>
+        <widget class="QLineEdit" name="lineEdit_flow_comp">
+         <property name="geometry">
+          <rect>
+           <x>100</x>
+           <y>40</y>
+           <width>141</width>
+           <height>31</height>
+          </rect>
+         </property>
+         <property name="text">
+          <string>0</string>
+         </property>
+         <property name="readOnly">
+          <bool>false</bool>
+         </property>
+        </widget>
+        <widget class="QPushButton" name="btn_flow_cal_write">
+         <property name="geometry">
+          <rect>
+           <x>330</x>
+           <y>40</y>
+           <width>81</width>
+           <height>71</height>
+          </rect>
+         </property>
+         <property name="text">
+          <string>写入</string>
+         </property>
+        </widget>
+        <widget class="QPushButton" name="btn_flow_cal_read">
+         <property name="geometry">
+          <rect>
+           <x>250</x>
+           <y>40</y>
+           <width>81</width>
+           <height>71</height>
+          </rect>
+         </property>
+         <property name="text">
+          <string>读取</string>
+         </property>
+        </widget>
+        <widget class="QComboBox" name="cb_flow_coeff">
+         <property name="geometry">
+          <rect>
+           <x>100</x>
+           <y>80</y>
+           <width>111</width>
+           <height>31</height>
+          </rect>
+         </property>
+         <property name="editable">
+          <bool>false</bool>
+         </property>
+         <property name="duplicatesEnabled">
+          <bool>false</bool>
+         </property>
+         <property name="frame">
+          <bool>true</bool>
+         </property>
+         <item>
+          <property name="text">
+           <string>氩气(1.0)</string>
+          </property>
+         </item>
+         <item>
+          <property name="text">
+           <string>二氧化碳(0.57)</string>
+          </property>
+         </item>
+         <item>
+          <property name="text">
+           <string>混合气(0.91)</string>
+          </property>
+         </item>
+        </widget>
+       </widget>
+       <widget class="QGroupBox" name="groupBox_13">
+        <property name="geometry">
+         <rect>
+          <x>20</x>
+          <y>350</y>
+          <width>421</width>
+          <height>131</height>
+         </rect>
+        </property>
+        <property name="title">
+         <string>WIFI</string>
+        </property>
+        <widget class="QLabel" name="label_26">
+         <property name="geometry">
+          <rect>
+           <x>40</x>
+           <y>40</y>
+           <width>51</width>
+           <height>31</height>
+          </rect>
+         </property>
+         <property name="text">
+          <string>SSID</string>
+         </property>
+        </widget>
+        <widget class="QLineEdit" name="lineEdit_wifi_passwd">
+         <property name="geometry">
+          <rect>
+           <x>100</x>
+           <y>80</y>
+           <width>141</width>
+           <height>31</height>
+          </rect>
+         </property>
+         <property name="text">
+          <string>0</string>
+         </property>
+         <property name="readOnly">
+          <bool>false</bool>
+         </property>
+        </widget>
+        <widget class="QLabel" name="label_27">
+         <property name="geometry">
+          <rect>
+           <x>40</x>
+           <y>80</y>
+           <width>51</width>
+           <height>31</height>
+          </rect>
+         </property>
+         <property name="text">
+          <string>密码</string>
+         </property>
+        </widget>
+        <widget class="QLineEdit" name="lineEdit_wifi_ssid">
+         <property name="geometry">
+          <rect>
+           <x>100</x>
+           <y>40</y>
+           <width>141</width>
+           <height>31</height>
+          </rect>
+         </property>
+         <property name="text">
+          <string>0</string>
+         </property>
+         <property name="readOnly">
+          <bool>false</bool>
+         </property>
+        </widget>
+        <widget class="QPushButton" name="btn_wifi_cfg_read">
+         <property name="geometry">
+          <rect>
+           <x>250</x>
+           <y>40</y>
+           <width>81</width>
+           <height>71</height>
+          </rect>
+         </property>
+         <property name="text">
+          <string>读取</string>
+         </property>
+        </widget>
+        <widget class="QPushButton" name="btn_wifi_cfg_write">
+         <property name="geometry">
+          <rect>
+           <x>330</x>
+           <y>40</y>
+           <width>81</width>
+           <height>71</height>
+          </rect>
+         </property>
+         <property name="text">
+          <string>写入</string>
+         </property>
+        </widget>
+       </widget>
+       <widget class="QGroupBox" name="groupBox_14">
+        <property name="geometry">
+         <rect>
+          <x>20</x>
+          <y>490</y>
+          <width>421</width>
+          <height>131</height>
+         </rect>
+        </property>
+        <property name="title">
+         <string>平台配置</string>
+        </property>
+        <widget class="QLabel" name="label_28">
+         <property name="geometry">
+          <rect>
+           <x>20</x>
+           <y>40</y>
+           <width>71</width>
+           <height>31</height>
+          </rect>
+         </property>
+         <property name="text">
+          <string>服务器地址</string>
+         </property>
+        </widget>
+        <widget class="QLineEdit" name="lineEdit_iot_port">
+         <property name="geometry">
+          <rect>
+           <x>100</x>
+           <y>80</y>
+           <width>141</width>
+           <height>31</height>
+          </rect>
+         </property>
+         <property name="text">
+          <string>0</string>
+         </property>
+         <property name="readOnly">
+          <bool>false</bool>
+         </property>
+        </widget>
+        <widget class="QLabel" name="label_29">
+         <property name="geometry">
+          <rect>
+           <x>20</x>
+           <y>80</y>
+           <width>71</width>
+           <height>31</height>
+          </rect>
+         </property>
+         <property name="text">
+          <string>端口</string>
+         </property>
+        </widget>
+        <widget class="QLineEdit" name="lineEdit_iot_host">
+         <property name="geometry">
+          <rect>
+           <x>100</x>
+           <y>40</y>
+           <width>141</width>
+           <height>31</height>
+          </rect>
+         </property>
+         <property name="text">
+          <string>0</string>
+         </property>
+         <property name="readOnly">
+          <bool>false</bool>
+         </property>
+        </widget>
+        <widget class="QPushButton" name="btn_iot_cfg_write">
+         <property name="geometry">
+          <rect>
+           <x>330</x>
+           <y>40</y>
+           <width>81</width>
+           <height>71</height>
+          </rect>
+         </property>
+         <property name="text">
+          <string>写入</string>
+         </property>
+        </widget>
+        <widget class="QPushButton" name="btn_iot_cfg_read">
+         <property name="geometry">
+          <rect>
+           <x>250</x>
+           <y>40</y>
+           <width>81</width>
+           <height>71</height>
+          </rect>
+         </property>
+         <property name="text">
+          <string>读取</string>
+         </property>
+        </widget>
+       </widget>
+      </widget>
+     </widget>
     </widget>
    </widget>
   </widget>
index 2a2a385879aec07b097b22bb8513d7ea8b864ee1..fe6f3a9e0499c5b543de7e4c853ea67b4e8be87f 100644 (file)
@@ -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 (file)
index 0000000..ce2999d
--- /dev/null
@@ -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 <string.h>
+#include <stdio.h>
+#include <stdint.h>
+#include <math.h>
+#include <stdlib.h>
+#include <float.h>
+#include <limits.h>
+#include <ctype.h>
+#include <locale.h>
+
+#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 (file)
index 0000000..2e3715a
--- /dev/null
@@ -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 <stdint.h>
+#include <stddef.h>
+
+       /* cJSON Types: */
+#define cJSON_Invalid (0)
+#define cJSON_False  (1 << 0)
+#define cJSON_True   (1 << 1)
+#define cJSON_NULL   (1 << 2)
+#define cJSON_Number (1 << 3)
+#define cJSON_String (1 << 4)
+#define cJSON_Array  (1 << 5)
+#define cJSON_Object (1 << 6)
+#define cJSON_Raw    (1 << 7) /* raw json */
+
+#define cJSON_IsReference 256
+#define cJSON_StringIsConst 512
+
+       /* The cJSON structure: */
+       typedef struct cJSON
+       {
+               /* next/prev allow you to walk array/object chains. Alternatively, use GetArraySize/GetArrayItem/GetObjectItem */
+               struct cJSON *next;
+               struct cJSON *prev;
+               /* An array or object item will have a child pointer pointing to a chain of the items in the array/object. */
+               struct cJSON *child;
+
+               /* The type of the item, as above. */
+               int type;
+
+               /* The item's string, if type==cJSON_String  and type == cJSON_Raw */
+               char *valuestring;
+               /* writing to valueint is DEPRECATED, use cJSON_SetNumberValue instead */
+               int valueint;
+               /* The item's number, if type==cJSON_Number */
+               double valuedouble;
+
+               /* The item's name string, if this item is the child of, or is in the list of subitems of an object. */
+               char *string;
+       } cJSON;
+
+       typedef 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
index 4d6ab68e413e254dab61815b64f1e38798cae254..7e0f2d20754fe1e2f1e5ffcd3f09b2bc2c2dcbf5 100644 (file)
@@ -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采集
index 41007bfb4f028fa0e06591a846cd0d75727bf52d..014041a813ccc3a27929910731851a0546ef18df 100644 (file)
@@ -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;
index 005a69ce8a3aa0dbc039a232a7309c878918e336..81d4483133ff365a0b609b8999184c732cd32a33 100644 (file)
@@ -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; i<sizeof(cfg->net.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; i<sizeof(cfg->net.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; i<sizeof(cfg->net.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;
 }
 
index e99b870af5cf508b4689217ec804ee55f467a5f0..3a6424f7be90b2ee39a0f12029bc1eec86051001 100644 (file)
     数据字段 发送  mode 4B( 0x544F4F42 -- 重启进入下载模式, 其他值-重启进入正常模式 )
              回应  1B (0-fail, 1-success)
 -------------------------------------------------------------
-    0005: 读取设备UUID
-    数据字段 发送  无
-             回应  UUID(12B)
--------------------------------------------------------------
+    下载固件 指令  A0
+    主程序收到开始下载指令,在SRAM2 中写入标志, 重启设备, boot中读取到标志进入下载模式
 -------------------------------------------------------------
 设备参数
 -------------------------------------------------------------
@@ -58,7 +56,7 @@
 -------------------------------------------------------------
     0012: 读取焊接电流校准值
     数据字段 发送  无
-             回应  校准值 4B
+             回应  补偿值 4B
 -------------------------------------------------------------
     0013: 写入焊接电流校准值
     数据字段 发送  校准值 4B
 -------------------------------------------------------------
     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
 
     }
index 6bb9011ed90f5041263bbd0c5ff9f169b52ef159..63aeb922510fefe3f82ccb46d75ba5507a76e79b 100644 (file)
@@ -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);
index 98884ab31643eaf9323e8dde528c9f68e60614c3..e37a341b361ba766d835f83c01f08ba1b7422459 100644 (file)
@@ -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;
index 6b6f1cc510f78f3417f9d1b22804c19059ff0199..53bf452f47ceae005782630fb934b51bc296d03f 100644 (file)
@@ -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 ){
index dca31eeeff94db211bae8215475ad805de125911..89dded2fb639629ddee636cbedf6a93dfc52cddf 100644 (file)
@@ -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;
 }
index 8bfcfd9c5e59611d806fec36091806fefd7c252a..c2f78ae0fa49353755aad96a0fd857b35fb1b848 100644 (file)
@@ -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);
         }
index 37856adacefeb66d0f8d6a3b09b00db1981bf15f..eec07c8c03b65ec48d7add7c87e6294ce7cbe466 100644 (file)
@@ -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, 按开度百分比计算电流
index fa1097b1c0f4baa239bfc769fb5fbff84b037aae..ee52d68f3c0345d5d203dfc2907383e09dd3c32d 100644 (file)
@@ -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 );
+}
+