Kaynağa Gözat

update LED 485

zhao006 6 ay önce
ebeveyn
işleme
051b155967
49 değiştirilmiş dosya ile 7751 ekleme ve 603 silme
  1. 4 4
      app/HW/include/hd_eth.h
  2. 8 8
      app/HW/include/led.h
  3. 6 0
      app/HW/include/netconf.h
  4. 1 1
      app/HW/include/timer.h
  5. 5 5
      app/HW/include/usart.h
  6. 5 0
      app/HW/include/wwdgt.h
  7. 7 5
      app/HW/source/hd_eth.c
  8. 3 3
      app/HW/source/led.c
  9. 68 4
      app/HW/source/netconf.c
  10. 1 0
      app/HW/source/timer.c
  11. 11 21
      app/HW/source/usart.c
  12. 19 0
      app/HW/source/wwdgt.c
  13. BIN
      app/MDK/Objects/dtu_simple.axf
  14. 6336 0
      app/MDK/Objects/dtu_simple.hex
  15. BIN
      app/MDK/Objects/simple.bin
  16. 142 179
      app/MDK/dtu_simple.uvoptx
  17. 13 2
      app/MDK/dtu_simple.uvprojx
  18. 2 1
      app/System/include/data_task.h
  19. 1 35
      app/System/include/gateway_message.h
  20. 1 1
      app/System/include/gd32_flash.h
  21. 1 1
      app/System/include/log.h
  22. 1 1
      app/System/include/sys_http.h
  23. 1 1
      app/System/include/sys_mqtt.h
  24. 46 1
      app/System/include/tcp_server.h
  25. 8 0
      app/System/include/updata.h
  26. 280 132
      app/System/source/data_task.c
  27. 2 2
      app/System/source/gateway_message.c
  28. 1 1
      app/System/source/httpclient.c
  29. 9 9
      app/System/source/log.c
  30. 42 17
      app/System/source/sys_http.c
  31. 40 29
      app/System/source/sys_mqtt.c
  32. 346 13
      app/System/source/tcp_server.c
  33. 17 8
      app/System/source/udp.c
  34. 2 2
      app/System/source/udp.h
  35. 140 0
      app/System/source/updata.c
  36. 1 0
      app/USR/include/main.h
  37. 1 1
      app/USR/include/mqtt_config.h
  38. 1 1
      app/USR/include/tcp_client.h
  39. 6 1
      app/USR/source/gd32f30x_it.c
  40. 93 31
      app/USR/source/main.c
  41. 37 17
      app/USR/source/tcp_client.c
  42. 20 0
      app/dlt/inc/dlt645.h
  43. 3 18
      app/dlt/port/dlt645_port.c
  44. 5 5
      app/dlt/src/dlt645_data.c
  45. 5 38
      app/modbus/mmodbus.c
  46. 4 1
      app/modbus/mmodbus.h
  47. 1 1
      app/mqttclient/mqttclient/mqttclient.c
  48. 1 1
      bootloader/MDK/dtu_simple_bootloader.uvoptx
  49. 4 2
      bootloader/MDK/dtu_simple_bootloader.uvprojx

+ 4 - 4
app/HW/include/hd_eth.h

@@ -57,13 +57,13 @@ OF SUCH DAMAGE.
 /* static IP address: IP_ADDR0.IP_ADDR1.IP_ADDR2.IP_ADDR3 */
 #define IP_ADDR0   192
 #define IP_ADDR1   168
-#define IP_ADDR2   2
-#define IP_ADDR3   222
+#define IP_ADDR2   0
+#define IP_ADDR3   100
 
 /* remote station IP address: IP_S_ADDR0.IP_S_ADDR1.IP_S_ADDR2.IP_S_ADDR3 */
 #define IP_S_ADDR0   192
 #define IP_S_ADDR1   168
-#define IP_S_ADDR2   2
+#define IP_S_ADDR2   0
 #define IP_S_ADDR3   22
 
 /* net mask */
@@ -75,7 +75,7 @@ OF SUCH DAMAGE.
 /* gateway address */
 #define GW_ADDR0   192
 #define GW_ADDR1   168
-#define GW_ADDR2   2
+#define GW_ADDR2   0
 #define GW_ADDR3   1  
 
 /* MII and RMII mode selection */

+ 8 - 8
app/HW/include/led.h

@@ -6,8 +6,8 @@
 typedef enum 
 {
     LED_DEV = 0,
-		LED_485STATE,
-		LED_NETSTATE
+		LED_485RX,
+		LED_485TX
 } led_typedef_enum;
 
 
@@ -18,13 +18,13 @@ typedef enum
 #define LED_DEV_GPIO_PORT                GPIOB
 #define LED_DEV_GPIO_CLK                 RCU_GPIOB
 
-#define LED_485STATE_PIN                 GPIO_PIN_2
-#define LED_485STATE_GPIO_PORT           GPIOD
-#define LED_485STATE_GPIO_CLK            RCU_GPIOD
+#define LED_485TX_PIN                		 GPIO_PIN_2
+#define LED_485TX_GPIO_PORT          	 	 GPIOD
+#define LED_485TX_GPIO_CLK          		 RCU_GPIOD
 
-#define LED_NETSTATE_PIN                 GPIO_PIN_3
-#define LED_NETSTATE_GPIO_PORT           GPIOB
-#define LED_NETSTATE_GPIO_CLK            RCU_GPIOB
+#define LED_485RX_PIN                 	 GPIO_PIN_3
+#define LED_485RX_GPIO_PORT           	 GPIOB
+#define LED_485RX_GPIO_CLK            	 RCU_GPIOB
 /* configure led GPIO */
 void gd_eval_led_init(led_typedef_enum lednum);
 /* turn on selected led */

+ 6 - 0
app/HW/include/netconf.h

@@ -18,4 +18,10 @@ void lwip_stack_init(void);
 /* dhcp_task */
 void dhcp_task(void * pvParameters);
 extern volatile int dhcp_done;
+
+void DHCP_open(void);
+void DHCP_close(void);
+
+void set_ipaddr(char* buf);
+
 #endif /* NETCONF_H */

+ 1 - 1
app/HW/include/timer.h

@@ -11,4 +11,4 @@ extern void timer5_init(void);//
 extern void timer5_start(void);//启动定时器4命令函数
 extern void timer5_stop(void);//关闭定时器4命令函数 
 
-#endif
+#endif

+ 5 - 5
app/HW/include/usart.h

@@ -3,11 +3,11 @@
 
 #include "gd32f30x.h"
 
-typedef struct usart_data_buf_s
-{
-	uint8_t data[256];
-	uint16_t data_cnt;
-} usart_data_buf_t;
+//typedef struct usart_data_buf_s
+//{
+//	uint8_t data[256];
+//	uint16_t data_cnt;
+//} usart_data_buf_t;
 
 #define DE485_PIN                        GPIO_PIN_8
 #define DE485_GPIO_PORT                  GPIOA

+ 5 - 0
app/HW/include/wwdgt.h

@@ -0,0 +1,5 @@
+#ifndef WWDGT_H
+#define WWDGT_H
+#include "gd32f30x_fwdgt.h"
+void watchdog_init(void);
+#endif

+ 7 - 5
app/HW/source/hd_eth.c

@@ -8,6 +8,8 @@
 #include "tcpip.h"
 #include "lwip/netif.h"
 #include "led.h"
+#include "delay.h"
+
 
 
 volatile uint32_t  EthStatus = 0;
@@ -46,7 +48,7 @@ void enet_system_setup(void)
 static void enet_mac_dma_config(void)
 {
     ErrStatus reval_state = ERROR;
-    
+		
     /* enable ethernet clock  */
     rcu_periph_clock_enable(RCU_ENET);
     rcu_periph_clock_enable(RCU_ENETTX);
@@ -56,19 +58,19 @@ static void enet_mac_dma_config(void)
     enet_deinit();
 
     reval_state = enet_software_reset();
+	
     if(ERROR == reval_state){
-        while(1){
+        while(1){								
         }
     }
+		
 /* configure the parameters which are usually less cared for enet initialization */  
 //  enet_initpara_config(HALFDUPLEX_OPTION, ENET_CARRIERSENSE_ENABLE|ENET_RECEIVEOWN_ENABLE|ENET_RETRYTRANSMISSION_DISABLE|ENET_BACKOFFLIMIT_10|ENET_DEFERRALCHECK_DISABLE);
   enet_initpara_config(DMA_OPTION, ENET_FLUSH_RXFRAME_ENABLE|ENET_SECONDFRAME_OPT_ENABLE|ENET_NORMAL_DESCRIPTOR);
 #ifdef CHECKSUM_BY_HARDWARE
 		if( enet_init(ENET_AUTO_NEGOTIATION, ENET_AUTOCHECKSUM_DROP_FAILFRAMES, ENET_BROADCAST_FRAMES_PASS))
 		{
-			EthStatus = ETH_INIT_FLAG;
-			gd_eval_led_init(LED_NETSTATE);
-			gd_eval_led_on(LED_NETSTATE);
+			EthStatus = ETH_INIT_FLAG;		
 		}
     else
 		{

+ 3 - 3
app/HW/source/led.c

@@ -1,7 +1,7 @@
 #include "led.h"
-static uint32_t GPIO_PORT[LEDn] = {LED_DEV_GPIO_PORT,LED_485STATE_GPIO_PORT,LED_NETSTATE_GPIO_PORT};
-static uint32_t GPIO_PIN[LEDn] = {LED_DEV_PIN,LED_485STATE_PIN,LED_NETSTATE_PIN};
-static rcu_periph_enum GPIO_CLK[LEDn] = {LED_DEV_GPIO_CLK,LED_485STATE_GPIO_CLK,LED_NETSTATE_GPIO_CLK};
+static uint32_t GPIO_PORT[LEDn] = {LED_DEV_GPIO_PORT,LED_485RX_GPIO_PORT,LED_485TX_GPIO_PORT};
+static uint32_t GPIO_PIN[LEDn] = {LED_DEV_PIN,LED_485RX_PIN,LED_485TX_PIN};
+static rcu_periph_enum GPIO_CLK[LEDn] = {LED_DEV_GPIO_CLK,LED_485RX_GPIO_CLK,LED_485TX_GPIO_CLK};
 
 /*!
     \brief      configure led GPIO

+ 68 - 4
app/HW/source/netconf.c

@@ -46,6 +46,9 @@ OF SUCH DAMAGE.
 #include <stdio.h>
 #include "lwip/inet.h"
 #include "hd_eth.h"
+#include "gateway_message.h"
+#include "string.h"
+#include "led.h"
 
 #define MAX_DHCP_TRIES       4
 
@@ -110,11 +113,13 @@ void lwip_stack_init(void)
 		}
 		if (EthStatus == (ETH_INIT_FLAG | ETH_LINK_FLAG))
 		{ 
+			
     /* Set Ethernet link flag */
     g_mynetif.flags |= NETIF_FLAG_LINK_UP;
 
     /* When the netif is fully configured this function must be called.*/
     netif_set_up(&g_mynetif);
+		
 #ifdef USE_DHCP
     dhcp_state = DHCP_START;
 #else
@@ -130,6 +135,7 @@ void lwip_stack_init(void)
   {
     /*  When the netif link is down this function must be called.*/
     netif_set_down(&g_mynetif);
+	
 #ifdef USE_DHCP
     dhcp_state = DHCP_TIMEOUT;
 #endif /* USE_DHCP */
@@ -143,7 +149,7 @@ void lwip_stack_init(void)
 	sys_timeout(2000, ETH_CheckLinkStatus_timer, NULL);	
 }
 
-#ifdef USE_DHCP
+
 /*!
     \brief      dhcp_task
     \param[in]  none
@@ -151,6 +157,7 @@ void lwip_stack_init(void)
     \retval     none
 */
 volatile int dhcp_done;
+#ifdef USE_DHCP
 void dhcp_task(void * pvParameters)
 {
     struct ip_addr ipaddr;
@@ -179,6 +186,7 @@ void dhcp_task(void * pvParameters)
 							char p[100];
 							sprintf(p,"\r\nDHCP -- eval board ip address: %d.%d.%d.%d \r\n", ip4_addr1_16(&ip_address), \
                         ip4_addr2_16(&ip_address), ip4_addr3_16(&ip_address), ip4_addr4_16(&ip_address));
+							printf("%s",p);
             }else{
                 /* DHCP timeout */
                 if(g_mynetif.dhcp->tries > MAX_DHCP_TRIES){
@@ -200,7 +208,9 @@ void dhcp_task(void * pvParameters)
         }
     
         /* wait 250 ms */
-        vTaskDelay(1000);
+				vTaskDelay(250);
+        //vTaskDelay(1000);
+				
     }   
 }
 
@@ -295,8 +305,62 @@ void ETH_link_callback(struct netif *netif)
 	}
 	else 
 	{
-		printf("network is down");		
+		printf("network is down");
 		enet_disable();
 		netif_set_down(&g_mynetif);
 	}
-}
+}
+
+void DHCP_open()
+{
+	#ifdef USE_DHCP
+	 dhcp_state = DHCP_START;
+	#endif
+}
+void DHCP_close()
+{
+	#ifdef USE_DHCP
+	dhcp_stop(&g_mynetif);
+	#endif
+}
+
+void set_ipaddr(char* buf)
+{
+		struct ip_addr ipaddr;
+    struct ip_addr netmask;
+    struct ip_addr gw;
+	
+		int ipaddr0,ipaddr1,ipaddr2,ipaddr3;
+		int maskaddr0,maskaddr1,maskaddr2,maskaddr3;
+		int gwaddr0,gwaddr1,gwaddr2,gwaddr3;
+	
+		ipaddr0 = parseIntField(buf,"\"ipv4\":\"" );
+		ipaddr1 = parseIntField(strstr(buf,"\"ipv4\":\"") + 1,"." );
+		ipaddr2 = parseIntField(strstr(strstr(buf,"\"ipv4\":\"") + 1,"." ) + 1,".");
+		ipaddr3 = parseIntField(strstr(strstr(strstr(buf,"\"ipv4\":\"") + 1,"." ) + 1,".") + 1 ,".");
+
+		maskaddr0 = parseIntField(buf,"\"subnetMask\":\"" );
+		maskaddr1 = parseIntField(strstr(buf,"\"subnetMask\":\"") + 1,"." );
+		maskaddr2 = parseIntField(strstr(strstr(buf,"\"subnetMask\":\"") + 1,"." ) + 1,".");
+		maskaddr3 = parseIntField(strstr(strstr(strstr(buf,"\"subnetMask\":\"") + 1,"." ) + 1,".") + 1 ,".");
+		
+		gwaddr0 = parseIntField(buf,"\"defaultGateway\":\"" );
+		gwaddr1 = parseIntField(strstr(buf,"\"defaultGateway\":\"") + 1,"." );
+		gwaddr2 = parseIntField(strstr(strstr(buf,"\"defaultGateway\":\"") + 1,"." ) + 1,".");
+		gwaddr3 = parseIntField(strstr(strstr(strstr(buf,"\"defaultGateway\":\"") + 1,"." ) + 1,".") + 1 ,".");	
+	
+		IP4_ADDR(&ipaddr, ipaddr0 ,ipaddr1 , ipaddr2 , ipaddr3 );
+    IP4_ADDR(&netmask, maskaddr0, maskaddr1, maskaddr2, maskaddr3);
+    IP4_ADDR(&gw, gwaddr0, gwaddr1, gwaddr2,gwaddr3);
+		// 设置网络接口的IP地址
+    netif_set_addr(&g_mynetif, &ipaddr , &netmask, &gw);
+		// 停止DHCP客户端
+		dhcp_stop(&g_mynetif);
+		
+		// 重启网络接口以使更改生效
+    netif_set_up(&g_mynetif);
+    netif_set_down(&g_mynetif);
+    netif_set_up(&g_mynetif);
+
+}
+

+ 1 - 0
app/HW/source/timer.c

@@ -35,6 +35,7 @@ void TIMER5_IRQHandler(void)
 {
     if (timer_interrupt_flag_get(TIMER5, TIMER_INT_UP) != RESET)
     {
+				
         timer_interrupt_flag_clear(TIMER5, TIMER_INT_UP); // 清除中断标志
         delay_counter++; // 延时计数器加1
     }

+ 11 - 21
app/HW/source/usart.c

@@ -1,7 +1,8 @@
 #include "usart.h"
 #include "mmodbus.h"
 #include "dlt645.h"
-
+#include "gateway_message.h"
+#include "led.h"
 
 void nvic_config(void);
 void gd_485_DE_pin_init(void)
@@ -61,7 +62,7 @@ void gd_com_485_send(uint8_t *message,uint16_t size){
  */
 void config_485_port(uint32_t com,uint32_t baudrate, uint8_t databits, uint8_t stopbits, uint8_t parity)
 {
-	 uint32_t com_id = 0U;
+//	 uint32_t com_id = 0U;
 	 uint8_t wordLength;
 		if(parity!=0)
 		{
@@ -101,26 +102,15 @@ void nvic_config(void)
 }
 void USART0_IRQHandler(void)
 {
-		mmodbus_callback();
-}
 
-//void USART0_IRQHandler(void)
-//{
-//  if (RESET != usart_interrupt_flag_get(USART0, USART_INT_FLAG_RBNE))
-//  {
-//   usart_interrupt_flag_clear(USART0, USART_INT_FLAG_RBNE);
-//  }
+			GATEWAY_PARAMS *get;
+			get= get_gateway_config_params();
+			if(get->device_params->protocol == 3)
+			mmodbus_callback();
+			else if(get->device_params->protocol == 1 || get->device_params->protocol == 2)
+			dlt_callback();
+			
+}
 
-//  if (RESET != usart_interrupt_flag_get(USART0, USART_INT_FLAG_IDLE))
-//  {
-//		usart_data_receive(USART0);
-//		usart_interrupt_flag_clear(USART0, USART_INT_FLAG_IDLE);
-//  }
-//  else
-//  {
-//		usart_data_receive(USART0);
-//    usart_interrupt_flag_clear(USART0, USART_INT_FLAG_RBNE);
-//  }
-//}
 
 

+ 19 - 0
app/HW/source/wwdgt.c

@@ -0,0 +1,19 @@
+#include "wwdgt.h"
+
+void watchdog_init(void)
+{
+		rcu_osci_on(RCU_IRC40K);                            /* 使能IRC40K时钟 */
+    while(SUCCESS != rcu_osci_stab_wait(RCU_IRC40K));   /* wait till IRC40K is ready */
+    fwdgt_write_enable();
+    fwdgt_config(2500, FWDGT_PSC_DIV16);                /* 40K / 16 = 2.5 KHz t = 1/2.5 *2500 = 1s; 1S超时 */
+    fwdgt_write_disable();
+//    fwdgt_enable();
+}
+
+// 独立看门狗喂狗
+void feed_fwdg()
+{
+    fwdgt_write_enable();
+    fwdgt_counter_reload();
+    fwdgt_write_disable();    
+}

BIN
app/MDK/Objects/dtu_simple.axf


Dosya farkı çok büyük olduğundan ihmal edildi
+ 6336 - 0
app/MDK/Objects/dtu_simple.hex


BIN
app/MDK/Objects/simple.bin


Dosya farkı çok büyük olduğundan ihmal edildi
+ 142 - 179
app/MDK/dtu_simple.uvoptx


Dosya farkı çok büyük olduğundan ihmal edildi
+ 13 - 2
app/MDK/dtu_simple.uvprojx


+ 2 - 1
app/System/include/data_task.h

@@ -8,13 +8,14 @@
 
 #include "include.h"
 
+uint32_t my_pow(int x,int y);
 
 //Ö÷ÒªµÄÊý¾Ý´¦ÀíÏß³Ì
 #define DATA_TASK_PRIO    3 
 #define DATA_STK_SIZE  2*1024
 
 #define GetCurrentTime()  xTaskGetTickCount()
-
+extern int ID;
 extern void data_task(void *pdata);
 void  data_task_creat(void);
 

+ 1 - 35
app/System/include/gateway_message.h

@@ -71,7 +71,6 @@ typedef struct _GATEWAY_PARAMS
 	uint8_t data_valid_flag;  // 数据有效标志  0xF1:有效  其它:无效
 	uint8_t host[20];		  // MQTT服务器地址
 	uint16_t port;			  // MQTT服务器端口号
-//	uint16_t port[2];
 	uint8_t messageTopic[50]; // MQTT消息主题
 	uint8_t commandTopic[50]; // MQTT指令主题
 	uint8_t username[20];			//MQTT用户名
@@ -100,6 +99,7 @@ typedef struct _GATEWAY_PARAMS
 } GATEWAY_PARAMS;
 
 void addGatewayParams(char *gatewayString);
+void addDevice(char *string);
 
 int parseIntField(const char *data, const char *field);
 void parseStringField(const char *data, const char *field, char *value);
@@ -107,39 +107,5 @@ void parseStringField(const char *data, const char *field, char *value);
 GATEWAY_PARAMS *get_gateway_config_params(void);
 int extract_substring(const char *input_string, const char *start_token, const char *end_token, char *result);
 
-//////////////////////////////////////////////////////////////////////////////////////////////////////////
 
-void analysis_read_data(DEVICE_PARAMS *device, char* buf);
-
-typedef struct _MODBUS_READ_DATA
-{
-	uint8_t deviceId[20];
-	// modbus读出的数据名
-	uint8_t power;	
-	uint8_t temp;
-	uint8_t mode;
-	uint8_t fan;
-	uint8_t roomTemp;
-	uint8_t fault;
-	
-	struct _MODBUS_READ_DATA *nextParams;
-} MODBUS_READ_DATA;
-
-typedef struct _DLT_READ_DATA
-{
-	uint8_t deviceId[20];
-	// dlt读出的数据名
-	uint8_t deviceID645[6];
-	uint8_t keyword[20];   // 所读属性的名称
-	uint32_t Identification; // 645数据标识
-	uint8_t data[9];
-	
-	struct _DLT_READ_DATA *nextParams;
-} DLT_READ_DATA;
-
-typedef struct _READ_DATA
-{
-	MODBUS_READ_DATA   *read_modbus_data;
-	DLT_READ_DATA  		 *read_dlt645_data;
-}READ_DATA;
 #endif

+ 1 - 1
app/System/include/gd32_flash.h

@@ -5,7 +5,7 @@
 #define FMC_PAGE_SIZE           ((uint16_t)0x1000U)
 #define FMC_WRITE_START_ADDR    ((uint32_t)0x08038800U)
 #define FMC_WRITE_END_ADDR      ((uint32_t)0x0803FFFFU)
-void gd32_flash_test();
+void gd32_flash_test(void);
 
 void GD32_EraseFlash(uint16_t start, uint16_t num);
 int save_config_params(char *params);

+ 1 - 1
app/System/include/log.h

@@ -23,6 +23,6 @@ typedef enum LOG_LEVEL_U
 }logLevel_t;
 
 void LogPrint(logLevel_t logLevel,const char *file, const char *func, const int line, char * fmt, ...);
-void log_init();
+void log_init(void);
 #define LOG_PRINT(logLevel, fmt, ...) LogPrint(logLevel,__FILE__,__FUNCTION__, __LINE__, fmt, ##__VA_ARGS__)
 #endif /* INC_LOG_H_ */

+ 1 - 1
app/System/include/sys_http.h

@@ -4,8 +4,8 @@
 
 extern uint8_t  load_http_config;
 void http_getDemo(void);
-
 void http_postDemo(void);
+int get_http_config(void);
 #endif 
 
 

+ 1 - 1
app/System/include/sys_mqtt.h

@@ -12,6 +12,6 @@ struct Pub_Queue
 	char *pub_topic;
 	char *message;
 };
-void mqtt_task_creat();
+void mqtt_task_creat(void);
 void mqtt_publish_data(char *payload,mqtt_qos_t qos,uint16_t pub_length,char *topic);
 #endif

+ 46 - 1
app/System/include/tcp_server.h

@@ -1,4 +1,49 @@
 #ifndef TCP_SERVER_H
 #define TCP_SERVER_H
-void tcp_server_init();
+
+#include "stdint.h"
+
+#define WRITE_CONFIG	1
+#define WRITE_CONFIG_ADD	2
+#define READ_CONFIG	3
+#define FIND_DEVICE	4
+#define IP_CONFIG	5
+#define TOGGLE_MODE	6
+#define UPDATE	7
+#define REBOOT	8
+
+
+
+extern uint8_t tcp_config;
+extern uint8_t ProtocolsModeFlag;
+extern uint8_t TransparentModeFlag;
+
+void tcp_server_init(void);
+
+// 储存上位机下发的ip_config数据
+typedef struct _ip_config
+{
+		uint8_t host[20];	
+		uint8_t subnetMask[20];
+    uint8_t defaultGateway[20];	
+		uint16_t udpLogPort;  
+} ip_config;
+ip_config *get_ip_config(void);
+
+
+// 储存上位机发送的config数据,并返回上位机操作结果
+void save_config(int client_socket,char* dataBuf);
+
+// 储存上位机发送的config_add数据,并返回上位机操作结果
+void add_config(int client_socket, char* dataBuf);
+
+// 发送设备当前的config数据
+void send_config(int client_socket);
+// 解析设备当前的硬件信息(结构体内的数据)
+void get_device_params(char* device_params);
+
+// 切换工作模式
+void work_mode(char* buf);
+
+
 #endif

+ 8 - 0
app/System/include/updata.h

@@ -0,0 +1,8 @@
+#ifndef UPDATA_H
+#define UPDATA_H
+#include "stdint.h"
+void updata_task_creat(int client_socket);
+void updata_task(void *pvParameters);
+
+uint16_t Checkcrc16(const uint8_t *nData, uint16_t wLength);
+#endif

+ 280 - 132
app/System/source/data_task.c

@@ -3,87 +3,83 @@
 #include "sys_mqtt.h"
 #include "sys_http.h"
 #include "mmodbus.h"
-#include "dlt645.h"
-#include "dlt645_1997_private.h"
 #include "dlt645_port.h"
 #include "gd32_flash.h"
 #include "protocol.h"
-#include "sys_http.h"
-#include "jsmn.h"
 #include "timer.h"
+#include "led.h"
+#include "tcp_server.h"
+#include "log.h"
 
-uint8_t time_count = 0, jsonCunt = 0, count = 0;
-uint8_t protocol_485;
-int time1,time2;
-int ID = 0;
+void protocolsModeFunc(GATEWAY_PARAMS* current_device, char* buf, char* string);
+void transparentModeFunc(DEVICE_PARAMS* current_device);
 
+int ID = 1;
+uint8_t count = 0;
+uint8_t startFlag = 0;// 读取数据初始标志位
+int time1,time2;
 void data_task(void *pdata)
-{
-		 
-		dlt645_init(1);
-		mmodbus_init(1);
-		while(!load_http_config)
-		{
-			vTaskDelay(100);
-		}
-
-		portENTER_CRITICAL();
-		char *device_config_json=pvPortMalloc( 10 *1024 );
-		read_data_from_flash(device_config_json);
-		addGatewayParams(device_config_json);	
-		vPortFree(device_config_json);
-		device_config_json = NULL;
-		portEXIT_CRITICAL();
-		
+{			
+		dlt645_init(1);	// 若读不到数据,则延时 参数 秒
+		mmodbus_init(10);// 若读不到数据,则延时 参数 秒
 		GATEWAY_PARAMS *get;
-		get= get_gateway_config_params();
+		// 如果flash有config数据,则解析,进行下一步;若flash无config数据,则等待上位机发送数据
+		do{
+				char *device_config_json=pvPortMalloc( 10 *1024 );
+				memset(device_config_json,0,strlen(device_config_json));
+				portENTER_CRITICAL();
+				read_data_from_flash(device_config_json);		
+				addGatewayParams(device_config_json);
+				vPortFree(device_config_json);
+				portEXIT_CRITICAL();
+				get= get_gateway_config_params();
+				delay_ms(100);
+		}while(get->device_params == NULL);
+		LogPrint(LOG_INFO,__FILE__,__FUNCTION__,__LINE__,"device params not empty");
 		DEVICE_PARAMS *current_device=get->device_params;
 		
-		char *buf = pvPortMalloc(1024);	// 接收读取的数据
-		char *string = pvPortMalloc(1024);	// 接收读取的数据
+		char *buf = pvPortMalloc(1024);			// 接收读取的全部数据
+		char *string = pvPortMalloc(1024);	// 接收读取的不同数据
+		if(buf == NULL || string == NULL)
+		{
+			LogPrint(LOG_ERROR,__FILE__,__FUNCTION__,__LINE__,"buf or string malloc fail");
+		}
 		memset(buf,0,strlen(buf));
 		memset(string,0,strlen(string));
-		
 		while (current_device!=NULL)
-		{		
-			time1 = GetCurrentTime();
-			if(mqtt_connectFlag)
+		{				
+			if(ProtocolsModeFlag)
+			{		
+				protocolsModeFunc(get, buf, string);	
+			}
+			else if(TransparentModeFlag)
 			{
-				if(jsonCunt && time2  <= time1 - ( 10 * 1000))// 60s进行一次全数据发送
-				{
-						read_device_data(current_device, buf, string);
-						send_mqtt(buf);
-						memset(buf,0,strlen(buf));					
-						time2 = GetCurrentTime();
-					current_device=get->device_params;
-				}
-				else
-				{
-					read_device_data(current_device, buf, string);
-					if(count > 0)// count检测是否含有数据
-					{
-						send_mqtt(string);
-						memset(string,0,strlen(string));
-						current_device=get->device_params;
-						count = 0;
-						if(!time_count)
-						{
-							jsonCunt = 1;
-							time_count = 1;
-							time2 = GetCurrentTime();
-						}
-					}
-				}	
-				memset(buf,0,strlen(buf));				
-			}		
-			
-			vTaskDelay(100);
+				transparentModeFunc(current_device);
+			}
+			current_device=get->device_params;	
+			vTaskDelay(1000);
 		}	
 		vPortFree(buf);
-		buf = NULL;
-		
-}	
+		vPortFree(string);
+		LogPrint(LOG_ERROR,__FILE__,__FUNCTION__,__LINE__,"data_task return");
+}
 
+/*
+*********************************************************************************************************
+*	函 数 名: int compareArrays(uint8_t arr1[], uint8_t arr2[], int size)
+*	功能说明: 比较两个数组是否相同
+*	形    参: arr1[] 数组1,arr2[] 数组2,size 比较数组的大小
+*	返 回 值: 1: 相同 0:不相同
+*********************************************************************************************************
+*/
+int compareArrays(uint8_t arr1[], uint8_t arr2[], int size) {
+    for (int i = 0; i < size; ++i) {
+        if (arr1[i] != arr2[i]) {
+            return 1; // 两个数组不相同,返回0
+        }
+    }   
+    return 0; // 两个数组相同,返回1
+}
 /*
 *********************************************************************************************************
 *	函 数 名: int READ_MODBUS_DATA(DEVICE_PARAMS *device)
@@ -97,29 +93,27 @@ int read_device_data(DEVICE_PARAMS *device, char* buf, char* string)
 		DEVICE_PARAMS *current_device=device;	
 		GATEWAY_READ_MODBUS_COMMAND *currentModbusParams = current_device->params->gateway_read_modbus_command;
 		GATEWAY_READ_DLT645_COMMAND *currentDLT645Params = current_device->params->gateway_read_dlt645_command;	
-	
 		while(current_device->params != NULL)
-		{				
+		{	
+				gd_eval_led_toggle(LED_485TX);
 				if (current_device->protocol == MODBUS_READ)
 				{
-						protocol_485=1;
-						uint8_t state;
+						uint8_t cmd;	//开关水阀命令
+						uint8_t state;	// 水阀状态
 						uint16_t data[currentModbusParams->registerByteNum /2]; // modbus寄存器长度
-						uint8_t data1[currentModbusParams->registerByteNum /2];
+						
 						mmodbus_set16bitOrder(current_device->MDBbigLittleFormat);
 						// 读水阀状态
 						if(currentModbusParams->functionCode == 0x01)
 						{
 							bool success = mmodbus_readCoil(currentModbusParams->slaveAddress,
 																		 currentModbusParams->registerByteNum /2,
-																		 data1);
+																		 &state);
 							if(success)
 							{
-								uint8_t value;
-								value = data1[0];
-								if(value == 0)
+								if(state == 0)
 								{
-								sprintf(buf + strlen(buf), "{\"deviceId\":\"%s\",\"%s\":close},", 
+									sprintf(buf + strlen(buf), "{\"deviceId\":\"%s\",\"%s\":close},", 
 																									current_device->deviceID, currentModbusParams->keyword);
 								}else{
 									sprintf(buf + strlen(buf), "{\"deviceId\":\"%s\",\"%s\":open},", 
@@ -141,12 +135,11 @@ int read_device_data(DEVICE_PARAMS *device, char* buf, char* string)
 						// 读单个寄存器
 						if (currentModbusParams->functionCode == 0x03)
 						{
-//								bool success = mmodbus_readHoldingRegisters16i(0x17,0x00,0x02,data);
+//  							bool success = mmodbus_readHoldingRegisters16i(0x17,0x00,0x02,data);
 								bool success = mmodbus_readHoldingRegisters16i(currentModbusParams->slaveAddress,
 																															 currentModbusParams->registerAddress,
 																															 currentModbusParams->registerByteNum /2,
 																															 data);
-
 								if (success)
 								{
 										uint32_t value;
@@ -175,9 +168,8 @@ int read_device_data(DEVICE_PARAMS *device, char* buf, char* string)
 
 										}
 										else
-										{
-//												float convertedValue = (float)value / pow(10, currentModbusParams->decimalPoint);
-//												currentModbusParams->value=convertedValue;
+										{ 	
+												currentModbusParams->value = value / my_pow(10,currentModbusParams->decimalPoint);
 										}
 																	
 								}					
@@ -199,7 +191,7 @@ int read_device_data(DEVICE_PARAMS *device, char* buf, char* string)
 						{
 							bool success = mmodbus_writeCoil(currentModbusParams->slaveAddress,
 																							 currentModbusParams->registerByteNum /2,
-																							 state);
+																							 cmd);
 							if(success)
 							{
 								
@@ -244,14 +236,11 @@ int read_device_data(DEVICE_PARAMS *device, char* buf, char* string)
 											sprintf(buf + strlen(buf) - 1, ""); 
 											return 1;
 									}
-							}
-							
+							}							
 						}
-
 				}
 				else if (current_device->protocol == DLT645_2007 || current_device->protocol == DLT645_97)
 				{
-						protocol_485=2;
 						uint8_t read_buf[10];
 						uint32_t dltValue;
 						
@@ -271,32 +260,59 @@ int read_device_data(DEVICE_PARAMS *device, char* buf, char* string)
 						}
 						if (rs != -1)
 						{
-								if (rs <= 4)
-								{
-										memcpy(currentDLT645Params->data, read_buf, 4);
-										currentDLT645Params->rxLen = 4;
-								}
-								else if (rs == 5)
+							if(compareArrays(read_buf,currentDLT645Params->data,10))// 不相同1,相同0
 								{
-										memcpy(currentDLT645Params->data, read_buf, 5);
-										currentDLT645Params->rxLen = 5;
+										if (rs <= 4)
+										{
+												memcpy(currentDLT645Params->data, read_buf, 4);
+												currentDLT645Params->rxLen = 4;
+										}
+										else if (rs == 5)
+										{
+												memcpy(currentDLT645Params->data, read_buf, 5);
+												currentDLT645Params->rxLen = 5;
+										}
+										else if (rs > 5)
+										{
+												memcpy(currentDLT645Params->data, read_buf, 9);
+												currentDLT645Params->rxLen = 9;
+										}
+										dltValue = currentDLT645Params->data[0] << 24 | currentDLT645Params->data[1] << 16|
+																				currentDLT645Params->data[2] << 8  | currentDLT645Params->data[3];
+										
+										sprintf(string + strlen(string), "{\"identifier\":\"%s\",\"deviceID645\":\"%02x%02x%02x%02x%02x%02x\",\"identifier645\":%d,\"value\":%X}",
+																										currentDLT645Params->keyword, currentDLT645Params->deviceID645[0],
+																										currentDLT645Params->deviceID645[1],currentDLT645Params->deviceID645[2],
+																										currentDLT645Params->deviceID645[3],currentDLT645Params->deviceID645[4],
+																										currentDLT645Params->deviceID645[5],currentDLT645Params->Identification,dltValue);
+										count++;
 								}
-							else if (rs > 5)
+								else
 								{
-										memcpy(currentDLT645Params->data, read_buf, 9);
-										currentDLT645Params->rxLen = 9;
+										if (rs <= 4)
+										{
+												memcpy(currentDLT645Params->data, read_buf, 4);
+												currentDLT645Params->rxLen = 4;
+										}
+										else if (rs == 5)
+										{
+												memcpy(currentDLT645Params->data, read_buf, 5);
+												currentDLT645Params->rxLen = 5;
+										}
+										else if (rs > 5)
+										{
+												memcpy(currentDLT645Params->data, read_buf, 9);
+												currentDLT645Params->rxLen = 9;
+										}
+										dltValue = currentDLT645Params->data[0] << 24 | currentDLT645Params->data[1] << 16|
+																				currentDLT645Params->data[2] << 8  | currentDLT645Params->data[3];
+										
+										sprintf(buf + strlen(buf), "{\"identifier\":\"%s\",\"deviceID645\":\"%02x%02x%02x%02x%02x%02x\",\"identifier645\":%d,\"value\":%X}",
+																								currentDLT645Params->keyword, currentDLT645Params->deviceID645[0],
+																								currentDLT645Params->deviceID645[1],currentDLT645Params->deviceID645[2],
+																								currentDLT645Params->deviceID645[3],currentDLT645Params->deviceID645[4],
+																								currentDLT645Params->deviceID645[5],currentDLT645Params->Identification,dltValue);
 								}
-															
-								dltValue = currentDLT645Params->data[0] << 24 | currentDLT645Params->data[1] << 16|
-																		currentDLT645Params->data[2] << 8  | currentDLT645Params->data[3];
-								
-								sprintf(buf + strlen(buf), "{\"identifier\":\"%s\",\"deviceID645\":\"%02x%02x%02x%02x%02x%02x\",\"identifier645\":%d,\"value\":%X}",
-																				currentDLT645Params->keyword, currentDLT645Params->deviceID645[0],
-																				currentDLT645Params->deviceID645[1],currentDLT645Params->deviceID645[2],
-																				currentDLT645Params->deviceID645[3],currentDLT645Params->deviceID645[4],
-																				currentDLT645Params->deviceID645[5],currentDLT645Params->Identification,dltValue);
-								count++;
-			
 						}
 		
 								currentDLT645Params = currentDLT645Params->nextParams;		
@@ -310,9 +326,8 @@ int read_device_data(DEVICE_PARAMS *device, char* buf, char* string)
 												return 1;
 										}
 								}										
-				}			
-				
-		}		
+				}
+			}	
 		return 1;
 	
 }
@@ -326,16 +341,13 @@ int read_device_data(DEVICE_PARAMS *device, char* buf, char* string)
 *********************************************************************************************************
 */
 void send_mqtt(char*buf){
+		LogPrint(LOG_INFO,__FILE__,__FUNCTION__,__LINE__,"send to mqtt");
 		GATEWAY_PARAMS *get;
 		get= get_gateway_config_params();
-//		char *pubJsonString = pvPortMalloc(strlen(buf)); 
-		char pubJsonString[500];
-	  sprintf(pubJsonString,"ID: %d {\"DEVICEID\":\"%s\",\"data\":[%s]}",ID++, get->deviceId, buf);	// 组成要发送的json语句							
-	 	mqtt_qos_t qos = QOS0;
-		uint16_t pub_length = strlen(pubJsonString);
-		mqtt_publish_data(pubJsonString, qos, pub_length, (char*)&get->messageTopic);	
-//		vPortFree(pubJsonString);
-//		pubJsonString = NULL;
+		char *pubJsonString = pvPortMalloc(700);
+	  sprintf(pubJsonString,"ID: %d {\"DEVICEID\":\"%s\",\"data\":[%s]}",ID, get->deviceId, buf);	// 组成要发送的json语句	
+		mqtt_publish_data(pubJsonString, QOS0, strlen(pubJsonString), (char*)&get->messageTopic);	
+		vPortFree(pubJsonString);
 }
 
 /*
@@ -367,11 +379,11 @@ void write_modbus_data(char* JSON_STRING)
 				GATEWAY_WRITE_MODBUS_COMMAND *currentModbusParams = current_device->params->gateway_write_modbus_command;
 				if(!strcmp(device_ID,jsonMsg.deviceId)) //匹配ID
 				{
-					delay_ms(200);
+					portENTER_CRITICAL();
+					delay_ms(50);
 					if(jsonMsg.function == 5)
 					// 开关阀门
-					{
-						
+					{			
 						mmodbus_writeCoil(jsonMsg.slaveAddress,jsonMsg.registerAddress,jsonMsg.cmd);
 					}
 					if(jsonMsg.function == 6)
@@ -380,37 +392,173 @@ void write_modbus_data(char* JSON_STRING)
 						if(jsonMsg.power)
 						{
 								mmodbus_writeHoldingRegister16i(currentModbusParams->slaveAddress, 
-																								currentModbusParams->registerAddress, 
-																								jsonMsg.power);
+																								currentModbusParams->registerAddress, jsonMsg.power);
 						}
-						delay_ms(100);
+						delay_ms(10);
 						if(jsonMsg.temp)
 						{
 								currentModbusParams = currentModbusParams->nextParams;							
 								mmodbus_writeHoldingRegister16i(currentModbusParams->slaveAddress, 
-																								currentModbusParams->registerAddress, 
-																								jsonMsg.temp);	
+																								currentModbusParams->registerAddress, jsonMsg.temp);	
 						}
-						delay_ms(100);
+						delay_ms(10);
 						if(jsonMsg.mode)
 						{
 								currentModbusParams = currentModbusParams->nextParams;
 								mmodbus_writeHoldingRegister16i(currentModbusParams->slaveAddress, 
-																								currentModbusParams->registerAddress, 
-																								jsonMsg.mode);
+																								currentModbusParams->registerAddress, jsonMsg.mode);
 						}
-						delay_ms(100);
+						delay_ms(10);
 					  if(jsonMsg.fan)
 						{
 								currentModbusParams = currentModbusParams->nextParams;
 								mmodbus_writeHoldingRegister16i(currentModbusParams->slaveAddress, 
-																								currentModbusParams->registerAddress, 
-																								jsonMsg.fan);	
+																								currentModbusParams->registerAddress, jsonMsg.fan);	
 						}
-						delay_ms(100);
 					}	
+					delay_ms(10);
+					portEXIT_CRITICAL();
 				}
 				current_device = current_device->nextDevice;
 		}
 }
+// 重定义pow函数
+uint32_t my_pow(int base, int exponent) {
+    uint32_t result = 1;
+    for(int i = 0; i < exponent; i++) {
+        result *= base;
+    }
+    return result;
+}
+
+void protocolsModeFunc(GATEWAY_PARAMS* get, char* buf, char* string)
+{
+		if(mqtt_connectFlag)
+		{
+				time1 = GetCurrentTime();
+
+				if(startFlag && time2  <= time1 - ( 10 * 1000))// 60s进行一次全数据发送
+				{
+						LogPrint(LOG_INFO,__FILE__,__FUNCTION__,__LINE__,"protocolsMode:All data");
+						read_device_data(get->device_params, buf, string);
+						send_mqtt(buf);				
+						time2 = GetCurrentTime();
+				}
+				else
+				{
+						read_device_data(get->device_params, buf, string);
+						if(count > 0)// count检测string是否含有数据
+						{
+							LogPrint(LOG_INFO,__FILE__,__FUNCTION__,__LINE__,"protocolsMode:Different data");
+							count = 0;
+							send_mqtt(string);	
+							time2 = GetCurrentTime();		
+						}					
+				}
+				startFlag = 1;	
+				memset(buf,0,strlen(buf));				
+				memset(string,0,strlen(string));	
+				
+		}				
+}
+
+
+
+int transparent_data(DEVICE_PARAMS *device)
+{
+		DEVICE_PARAMS *current_device=device;	
+		GATEWAY_READ_MODBUS_COMMAND *currentModbusParams = current_device->params->gateway_read_modbus_command;
+		GATEWAY_READ_DLT645_COMMAND *currentDLT645Params = current_device->params->gateway_read_dlt645_command;	
+		while(current_device->params != NULL)
+		{	
+				gd_eval_led_toggle(LED_485TX);			
+				if (current_device->protocol == MODBUS_READ)
+				{
+						uint16_t data[currentModbusParams->registerByteNum /2]; // modbus寄存器长度		
+						mmodbus_set16bitOrder(current_device->MDBbigLittleFormat);
+						// 读单个寄存器
+						if (currentModbusParams->functionCode == 0x03)
+						{
+//								bool success = mmodbus_readHoldingRegisters16i(0x17,0x00,0x02,data);
+  							bool success = mmodbus_readHoldingRegisters16i(currentModbusParams->slaveAddress,
+																															 currentModbusParams->registerAddress,
+																															 currentModbusParams->registerByteNum /2,
+																															 data);
+								if (success)
+								{
+										uint32_t value;		
+										if((value - currentModbusParams->value) != 0)
+										{
+											for (uint8_t i = 0; i < mmodbus.rxBuf[2]; i += 2)
+											{
+												uint8_t H = mmodbus.rxBuf[i + 3];
+												mmodbus.rxBuf[i + 3] = mmodbus.rxBuf[i + 3 + 1];
+												mmodbus.rxBuf[i + 3 + 1] = H;
+											}
+											gd_com_485_send(mmodbus.rxBuf,mmodbus.rxIndex);
+											count++;
+											vTaskDelay(100);
+										}									
+								}					
+								currentModbusParams = currentModbusParams->nextParams;
+								if (currentModbusParams == NULL)	
+								{
+										current_device = current_device->nextDevice;
+										currentModbusParams = current_device->params->gateway_read_modbus_command;
+										if(current_device == NULL)
+										{
+												return 1;
+										}
+								}												
+						}
+				}
+				else if (current_device->protocol == DLT645_2007 || current_device->protocol == DLT645_97)
+				{
+						uint8_t read_buf[10];
+										
+						memset(read_buf, 0, 10);
+						memset(currentDLT645Params->data, 0, 10);
+
+						dlt645_set_addr(&dlt645, currentDLT645Params->deviceID645);
+						int8_t rs;
+						if (current_device->protocol == DLT645_2007)
+						{
+								rs = dlt645_read_data(&dlt645, currentDLT645Params->Identification, read_buf, DLT645_2007);
+						}
+						else if (current_device->protocol == DLT645_1997)
+						{
+								rs = dlt645_read_data(&dlt645, currentDLT645Params->Identification, read_buf, DLT645_1997);
+						}
+						if (rs != -1)
+						{
+								if(compareArrays(read_buf,currentDLT645Params->data,10))// 不相同1,相同0
+								{
+									portENTER_CRITICAL();
+									gd_com_485_send(mmodbus.rxBuf,mmodbus.rxIndex);
+									portEXIT_CRITICAL();
+									vTaskDelay(100);
+								}
+						}
+							currentDLT645Params = currentDLT645Params->nextParams;		
+							if (currentDLT645Params == NULL)	
+							{
+									current_device = current_device->nextDevice;
+									currentDLT645Params = current_device->params->gateway_read_dlt645_command;
+									if(current_device == NULL)
+									{
+											return 1;
+									}
+							}										
+				}	
+		gd_eval_led_off(LED_485TX);					
+		}		
+		return 1;
+	
+}
+void transparentModeFunc(DEVICE_PARAMS* current_device)
+{
+			LogPrint(LOG_INFO,__FILE__,__FUNCTION__,__LINE__,"transparentMode:All data");
+			printf("transparentMode:All data\n");
+			transparent_data(current_device);		
+}
 

+ 2 - 2
app/System/source/gateway_message.c

@@ -15,7 +15,6 @@ GATEWAY_PARAMS *get_gateway_config_params()
 
 void parseStringField(const char *data, const char *field, char *value);
 int parseIntField(const char *data, const char *field);
-void addDevice(char *string);
 int extract_substring(const char *input_string, const char *start_token, const char *end_token, char *result);
 void addSensorListParams(char *paramString, DEVICE_PARAMS *device);
 void addCommandListParams(char *paramString, DEVICE_PARAMS *device);
@@ -183,6 +182,7 @@ void addSensorListParams(char *paramString, DEVICE_PARAMS *device)
     case MODBUS:
 		{
         GATEWAY_READ_MODBUS_COMMAND *read_modbus_command = pvPortMalloc(sizeof(GATEWAY_READ_MODBUS_COMMAND));
+				memset(read_modbus_command, 0, sizeof(GATEWAY_READ_MODBUS_COMMAND));
 				parseStringField(paramString,"\"identifier\":\"",(char *)&read_modbus_command->keyword);
         read_modbus_command->decimalPoint = parseIntField(paramString, "\"precise\":");
         read_modbus_command->functionCode = parseIntField(paramString, "\"rFunctionCode\":");
@@ -218,8 +218,8 @@ void addCommandListParams(char *paramString, DEVICE_PARAMS *device)
 {
 	
  	GATEWAY_WRITE_MODBUS_COMMAND *write_modbus_command=pvPortMalloc(sizeof(GATEWAY_WRITE_MODBUS_COMMAND));
+	memset(write_modbus_command, 0, sizeof(GATEWAY_WRITE_MODBUS_COMMAND));
 	parseStringField(paramString,"\"identifier\":\"",(char *)&write_modbus_command->keyword);
-
 	write_modbus_command->functionCode=parseIntField(paramString, "\"wFunctionCode\":");
 	write_modbus_command->slaveAddress=parseIntField(paramString, "\"slaveAddress\":");
 	write_modbus_command->registerAddress = parseIntField(paramString, "\"registerAddress\":");

+ 1 - 1
app/System/source/httpclient.c

@@ -167,7 +167,7 @@ int http_clientPacketRequest_GET(int sock, char *host, char *url)
 	strcat((char *)httpSendBuffer, "\r\n");
 	strcat((char *)httpSendBuffer, "Connection: close\r\n");	
 	strcat((char *)httpSendBuffer, "Accept: application/json\r\n");
-	strcat((char *)httpSendBuffer, "User-Agent: stm32f207\r\n");		
+	strcat((char *)httpSendBuffer, "User-Agent: gd32f307\r\n");		
 	strcat((char *)httpSendBuffer, "Cache-Control: no-cache\r\n");	
 	//Ìí¼ÓÒ»¸ö¿Õ°×ÐÐ
 	strcat((char *)httpSendBuffer, "\r\n"); 

+ 9 - 9
app/System/source/log.c

@@ -21,9 +21,10 @@ void LogPrint(logLevel_t logLevel,const char *file, const char *func, const int
 		char buf[LOG_LEN_MAX];
 		vsnprintf(buf, sizeof(buf), fmt, args);
 		va_end(args);
-		char *p=pvPortMalloc(1024);
-			switch (logLevel)
-			{
+//		char *p=pvPortMalloc(1024);
+		char p[1024];
+		switch (logLevel)
+		{
 		#ifdef _LOG_INFO
 				case LOG_INFO:
 					sprintf(p,"[%s][%s][%s:%4d] %s\r\n", "INFO",file,func, line, buf);
@@ -44,13 +45,12 @@ void LogPrint(logLevel_t logLevel,const char *file, const char *func, const int
 					break;
 				default:
 					break;
-			}
-			udp_send_printf(p);
-			vPortFree(p);
-			p = NULL;
-			udp_log_close();
-			xSemaphoreGive(logMutex);
 		}
+		udp_send_printf(p);
+//		vPortFree(p);
+		udp_log_close();
+		xSemaphoreGive(logMutex);
+	}
 }
 
 void log_init()

+ 42 - 17
app/System/source/sys_http.c

@@ -3,10 +3,9 @@
 #include "stdio.h"
 #include "main.h"
 #include "sys_http.h"
-#include "FreeRTOS.h"
-#include "task.h"
 #include "log.h"
 #include "gd32_flash.h"
+#include "netconf.h"
 
 //http配置标志位
 uint8_t load_http_config=0;
@@ -14,24 +13,50 @@ uint8_t load_http_config=0;
 //目前为此处去控制http一次性读入数据大小,应为该处为读入函数
 void http_getDemo(void)
 {
-
 	int datalen;
 	int ret;
-	char *http_data=pvPortMalloc(18 * 1024); // 接收数据上限为19K
-	char *http=pvPortMalloc(50);
-	sprintf(http,"/iot/transmit/getTransmitConfig/%s",gatewayId);
-	ret = http_clientGet("gpu.ringzle.com", http, 8082, 0, http_data, &datalen);
-	if(ret==200) //获取成功
-	{		
-//		save_config_params(http_data);
-		load_http_config=1;
+	while(dhcp_done != 1)
+	{
+		vTaskDelay(100);
+	}
+	char *device_config=pvPortMalloc(10);
+	memset(device_config, 0,10);
+	read_data_from_flash(device_config);	
+	if((strstr(device_config,"tcp_config")) == NULL)
+	{
+//		LogPrint(LOG_INFO,__FILE__,__FUNCTION__,__LINE__,"HTTP Get config");
+		char *http_data=pvPortMalloc(10 * 1024); // 接收数据上限为25K
+		char *http=pvPortMalloc(50);
+		sprintf(http,"/iot/transmit/getTransmitConfig/%s",gatewayId);
+		ret = http_clientGet("gpu.ringzle.com", http, 8082, 0, http_data, &datalen);
+		if(ret==200) //获取成功
+		{	
+//			LogPrint(LOG_INFO,__FILE__,__FUNCTION__,__LINE__,"HTTP Get config success");
+//			sprintf(http_data,"tcp_config");
+			save_config_params(http_data);
+			load_http_config=1;
+		}
+		vPortFree(http_data);
+		vPortFree(http);
 	}
-	HTTP_PRINTF("%s", (char *)http_data);
-	HTTP_PRINTF("\r\n ret=%d datalen=%d\r\n", ret, datalen);
-	vPortFree(http_data);
-	vPortFree(http);
-	http_data = NULL;
-	http = NULL;
+	vPortFree(device_config);
+}
+
+char *postData = "{\"bandwidth\":250,\"codeRate\":4700}";
+
+uint8_t postResult[512];
+
+//POST请求 http://gpu.ringzle.com/iot/test/httpTest  端口号8082
+void http_postDemo(void)
+{
+	int datalen, ret;
+	
+	memset(postResult, 0, sizeof(postResult));
+	
+//	ret = http_clientPost("gpu.ringzle.com", "/iot/test/httpTest", 8082, 0, http_data, 5837, postResult, &datalen);
+	ret = http_clientPost("gpu.ringzle.com", "/iot/test/httpTest", 8082, 0, (uint8_t *)postData, strlen(postData), postResult, &datalen);
+	HTTP_PRINTF("%s", (char *)postResult);
+	HTTP_PRINTF("\r\n ret=%d datalen=%d\r\n", ret, datalen);	
 }
 
 /*

+ 40 - 29
app/System/source/sys_mqtt.c

@@ -10,13 +10,13 @@
 #include "mqtt_config.h"
 #include "mqtt_log.h"
 #include "sys_mqtt.h"
+#include "sys_http.h"
 #include "gateway_message.h"
 #include "data_task.h"
 #include "netconf.h"
-
+#include "tcp_server.h"
 int mqtt_connectFlag;
 static void mqtt_publish_task(void *arg);
-
 /*
  *接收并处理mqtt订阅消息
  */
@@ -24,8 +24,8 @@ static void topic1_handler(void *client, message_data_t *msg)
 {
 	(void)client;
 	MQTT_LOG_I("topic: %s\nmessage:%s", msg->topic_name, (char *)msg->message->payload);
+	LogPrint(LOG_INFO,__FILE__,__FUNCTION__,__LINE__,"Write Modbus Data");
 	// json 解析数据
-	
 	write_modbus_data((char*)msg->message->payload);
 }
 /*
@@ -51,30 +51,41 @@ void mqtt_task_creat()
 	client = mqtt_lease();
 	printf("\nwelcome to mqttclient test...\n");
 	xQueue1 = xQueueCreate(10, sizeof(struct Pub_Queue *)); // 创建一个mqtt上传的队列
-	xTaskCreate(mqtt_publish_task, "mqtt_publish_task", 1024, client, 4, NULL);
+	xTaskCreate(mqtt_publish_task, "mqtt_publish_task", 512, client, 4, NULL);
 }
 
 static void mqtt_publish_task(void *arg)
 {
-	while(dhcp_done!=1)
+		// 确保dhcp配置完成
+	while(dhcp_done != 1)
 	{
 		vTaskDelay(100);
 	}
-	int rc;
-	mqtt_client_t *client = (mqtt_client_t *)arg;
 
+	GATEWAY_PARAMS *get;
+	get= get_gateway_config_params();	
+	int rc;
+	int msgId = 0;
+	char port[6];  
+	mqtt_client_t *client;
+	
+__MQTT_START:
+	rc = -1;
+	client = (mqtt_client_t *)arg;
 	while (rc < 0)
 	{
-	  rc = mqtt_init(client, "client_id_002", NULL, NULL, "36.134.23.11", "1883", 120);
-		LogPrint(LOG_INFO,__FILE__,__FUNCTION__,__LINE__,"NET TEST");
-		vTaskDelay(1000);	
+		vTaskDelay(1000);
+		sprintf(port, "%hu", get->port);
+	  rc = mqtt_init(client, "client_id_001", (char*)&get->username,(char*)&get->passwd,(char*)&get->host,port, 120);				
 	}
+	LogPrint(LOG_INFO,__FILE__,__FUNCTION__,__LINE__,"MQTT Connect success");
 	mqtt_connectFlag = 1;
-//	vPortFree(port);
-	mqtt_subscribe(client, "sub_topic_task", QOS0, topic1_handler);
+	if(mqtt_subscribe(client, (char*)&get->commandTopic, QOS0, topic1_handler) != 0)
+	{
+		LogPrint(LOG_WARN,__FILE__,__FUNCTION__,__LINE__,"MQTT Subscribe fail");
+	}
 	mqtt_message_t msg;
 	memset(&msg, 0, sizeof(msg));
-
 	mqtt_list_subscribe_topic(client);
 	struct Pub_Queue *pxMessage;
 	while (1)
@@ -87,22 +98,19 @@ static void mqtt_publish_task(void *arg)
 				msg.payloadlen = pxMessage->pubLength;
 				msg.qos = pxMessage->qos;
 				msg.payload = (void *)pxMessage->message;
-				mqtt_publish(client, pxMessage->pub_topic, &msg);
-		
-				
-				memset(pxMessage->message,0, pxMessage->pubLength);
-				memset(pxMessage->pub_topic, 0,strlen(pxMessage->pub_topic));
-				memset(pxMessage, 0, sizeof(struct Pub_Queue));
-				vPortFree(pxMessage->message);
+				if(mqtt_publish(client, pxMessage->pub_topic, &msg) != 0)// 0:成功
+				{
+					LogPrint(LOG_ERROR,__FILE__,__FUNCTION__,__LINE__,"MQTT Publish Failed");
+					mqtt_disconnect(client);// 关闭mqtt连接
+					goto __MQTT_START;
+				}
+				LogPrint(LOG_INFO,__FILE__,__FUNCTION__,__LINE__,"MQTT Publish Message No:%d",ID++);
 				vPortFree(pxMessage->pub_topic);
+				vPortFree(pxMessage->message);
 				vPortFree(pxMessage);
-				pxMessage->message = NULL;
-				pxMessage->pub_topic = NULL;
-				pxMessage = NULL;
-				
 			}
 		}
-		vTaskDelay(100);
+		vTaskDelay(1000);
 	}
 }
 /*
@@ -113,9 +121,9 @@ static void mqtt_publish_task(void *arg)
  *  函数作用:向队列中写入mqtt上传的消息
  *  TODO:队列满无法写入的情况处理
  */
+
 void mqtt_publish_data(char *payload, mqtt_qos_t qos, uint16_t pub_length, char *topic)
 {
-
 	struct Pub_Queue *pxMessage = pvPortMalloc(sizeof(struct Pub_Queue));
 	pxMessage->message = pvPortMalloc(pub_length + 1);
 	memset(pxMessage->message, 0, (pub_length + 1));
@@ -123,10 +131,13 @@ void mqtt_publish_data(char *payload, mqtt_qos_t qos, uint16_t pub_length, char
 
 	pxMessage->pub_topic = pvPortMalloc(strlen(topic) + 1);
 	memset(pxMessage->pub_topic, 0, (strlen(topic) + 1));
-//	strcpy(pxMessage->pub_topic, topic);
-	pxMessage->pub_topic = "/device/DTtest0003";
+	strcpy(pxMessage->pub_topic, topic);
+	
 	pxMessage->pubLength = pub_length;
 	pxMessage->qos = qos;
-	xQueueSend(xQueue1, (void *)&pxMessage, (TickType_t)0);
 	
+	if(pxMessage->message == NULL)
+		LogPrint(LOG_ERROR,__FILE__,__FUNCTION__,__LINE__,"queue message malloc fail");
+	
+	xQueueSend(xQueue1, (void *)&pxMessage, (TickType_t)0);
 }

+ 346 - 13
app/System/source/tcp_server.c

@@ -10,14 +10,222 @@
 #include "lwip/api.h"
 #include "sockets.h"
 #include "log.h"
+#include "netconf.h"
+#include "gateway_message.h"
+#include "gd32_flash.h"
+#include "stdlib.h"
+#include "protocol.h"
+#include "delay.h"
+#include "sys_mqtt.h"
+#include "updata.h"
+
+uint8_t closeFlag = 0;				// DHCP关闭标志位
+uint8_t tcp_config = 0;		  	// 存储config标志位
+uint8_t ProtocolsModeFlag = 1;// 开启内置协议模式
+uint8_t TransparentModeFlag = 0;	// 表示用串口透传 将数据原封不动的发给客户端
+
+ip_config load_ip_config = {0};
+ip_config *get_ip_config()
+{
+    return &load_ip_config;
+}
+
+// 解析设备当前的硬件信息(结构体内的数据)
+void get_device_params(char* device_params)
+{
+	GATEWAY_PARAMS *get;
+	get= get_gateway_config_params();
+	DEVICE_PARAMS *current_device=get->device_params;
+	sprintf(device_params, "{\"read_config\":\"success\",\"baudrate\":%d,\"checkBit\":%d,\"commandTopic\":%s,\"dataBit\":%d,\
+\"deviceId\": \"%s\",\"host\":\"%s\",\"inboundTime\":%d,\"messageTopic\":\"%s\",\"port\":%d,\"stopBit\":%d,\"deviceList\":[",get->baudrate,
+			get->checkBit,get->commandTopic,get->dataBits,get->deviceId,get->host,get->inboundTime,get->messageTopic,get->port,get->stopBit);
+	while(current_device != NULL)
+	{	
+		sprintf(device_params + strlen(device_params),"{\"protocol\":%d,\"bigLittleFormat\":%d,\"deviceId\":\"%s\",\"sensorData\":[",
+												current_device->protocol,current_device->MDBbigLittleFormat,current_device->deviceID);
+			GATEWAY_READ_DLT645_COMMAND *read_dlt645_command = current_device->params->gateway_read_dlt645_command;
+			GATEWAY_READ_MODBUS_COMMAND *read_modbus_command = current_device->params->gateway_read_modbus_command;
+			GATEWAY_WRITE_MODBUS_COMMAND *write_modbus_command = current_device->params->gateway_write_modbus_command;
+			
+			// dlt645 read
+			while(read_dlt645_command != NULL)
+			{	
+				sprintf(device_params + strlen(device_params),"{\"identifier645\":%d,\"identifier\":\"%s\",\"deviceID645\":\"%s\"},",
+											read_dlt645_command->Identification,read_dlt645_command->keyword,read_dlt645_command->deviceID645);
+				read_dlt645_command = read_dlt645_command->nextParams;
+			}
+		
+			// modbus read
+			while(read_modbus_command != NULL)
+			{
+				sprintf(device_params + strlen(device_params),"{\"rFunctionCode\":%d,\"registerAddress\":%d,\"slaveAddress\":%d,\"registerByteNum\":%d\"identifier\":\"%s\",\"precise\":%d},",
+																											read_modbus_command->functionCode, read_modbus_command->registerAddress,read_modbus_command->slaveAddress,
+																											read_modbus_command->registerByteNum,read_modbus_command->keyword,read_modbus_command->decimalPoint);
+				read_modbus_command = read_modbus_command->nextParams;
+			}
+			
+			// modbus write
+			sprintf(device_params + strlen(device_params)-1,"], \"commandData\":[");//sensorData:[ 
+			while(write_modbus_command != NULL)
+			{
+				sprintf(device_params + strlen(device_params),"{\"registerAddress\":%d,\"slaveAddress\":%d,\"wFunctionCode\":%d,\"registerByteNum\":%d},",
+								write_modbus_command->registerAddress,write_modbus_command->slaveAddress,write_modbus_command->functionCode,write_modbus_command->registerByteNum);
+				write_modbus_command = write_modbus_command->nextParams;
+			}		
+			sprintf(device_params + strlen(device_params)-1,"]}");// commandData:[
+			current_device = current_device->nextDevice;	
+	}
+	sprintf(device_params + strlen(device_params),"]}");
+}
+// 储存上位机发送的config数据,并返回上位机操作结果
+void save_config(int client_socket,char* dataBuf)
+{
+		save_config_params(dataBuf);// 储存到flash 不用判断失败
+		char* retMsg = pvPortMalloc(32);
+		memset(retMsg, 0, strlen(retMsg));
+		retMsg = "{\"write_config\":\"success\"}";
+		send(client_socket, retMsg, strlen(retMsg), 0);	
+		vPortFree(retMsg);
+		tcp_config	= 1;
+}
+// 储存上位机发送的config_add数据,并返回上位机操作结果
+void add_config(int client_socket, char* dataBuf)
+{	
+	GATEWAY_PARAMS *get;
+	get= get_gateway_config_params();
+	DEVICE_PARAMS *device=get->device_params;
+	char* retMsg = pvPortMalloc(32);
+	memset(retMsg, 0, strlen(retMsg));
+	while(device != NULL)// 一直轮询到当前为NULL
+	{
+		device = device->nextDevice;
+	}
+	addDevice(dataBuf);
+	// 再检查更新后的deviceId是否为NULL
+	if(device == NULL)// error
+	{	
+		retMsg = "{\"write_config\":\"error\"}";
+		send(client_socket, retMsg, strlen(retMsg), 0);	
+	}
+	else// success
+	{
+		retMsg = "{\"write_config\":\"success\"}";
+		send(client_socket, retMsg, strlen(retMsg), 0);	
+	}
+		vPortFree(retMsg);
+}
+// 设备嗅探
+void find_device(int client_socket)
+{
+	char deviceId[50];// 发送设备名
+	GATEWAY_PARAMS *get;
+	get= get_gateway_config_params();
+	if(get->device_params == NULL)
+	{	
+		sprintf(deviceId, "{\"find_device\":\"%s\"}", gatewayId);		
+		send(client_socket, deviceId, strlen(deviceId), 0);
+	}
+	else
+	{
+		sprintf(deviceId, "{\"find_device\":\"%s\"}", get->deviceId);		
+		send(client_socket, deviceId, strlen(deviceId), 0);
+	}
+	memset(deviceId, 0, 50);
+}
+
+// 发送设备当前的config数据
+void send_config(int client_socket)
+{
+	GATEWAY_PARAMS *get;
+	get= get_gateway_config_params();
+	char* device_params = pvPortMalloc(3 * 1024);
+	memset(device_params,0,3 * 1024);
+	if(get->device_params == NULL)
+	{
+		sprintf(device_params, "{\"read_config\":\"error\"}");
+		send(client_socket, device_params, strlen(device_params), 0);
+	}
+	else
+	{
+		get_device_params(device_params);
+		send(client_socket, device_params, strlen(device_params), 0);
+	}
+	vPortFree(device_params);
+}
+
+// 解析上位机发送的ip_config数据
+void analysis_ip_config(int client_socket, int sockfd,struct sockaddr_in tcpServerSock, char* buf)
+{
+		// 打开DHCP
+		if (strstr(buf, "\"dhcpMode\":\"open\"") != NULL)
+		{
+			DHCP_open();			
+			char* retMsg = pvPortMalloc(32);
+			retMsg = "{\"ip_config\":\"success\"}";
+			send(client_socket,retMsg,strlen(retMsg),0);
+			vPortFree(retMsg);
+		}
+		// 关闭DHCP
+		else if (strstr(buf, "\"dhcpMode\":\"close\"") != NULL)
+		{		
+			uint8_t prot[6];
+			// 设置静态IP地址,并关闭DHCP
+			set_ipaddr(buf);
+			// 解析buf内的数据,保存到load_ip_config结构体
+			parseStringField(buf, "\"ipv4\":\"", (char *)&load_ip_config.host);// eg:192.168.1.100
+			parseStringField(buf, "\"subnetMask\":\"", (char *)&load_ip_config.subnetMask);// eg:255.255.255.0
+			parseStringField(buf, "\"defaultGateway\":\"", (char *)&load_ip_config.defaultGateway);// eg:192.168.1.1
+			parseStringField(buf, "\"udpLogPort\":\"", (char *)&prot);
+			load_ip_config.udpLogPort = atoi((char *)&prot);
+			// 关闭服务端和客户端
+			lwip_close(sockfd);	
+			lwip_close(client_socket);
+			// DHCP关闭标志位置 1 
+			closeFlag = 1;
+		}
+}
+
+// 切换工作模式
+void work_mode(char* buf)
+{
+	/* 用标志位开关data_task任务中,发送数据的方式 */
+		// 内置协议模式
+		if(strstr(buf,"protocolsMode") != NULL)
+		{
+			ProtocolsModeFlag = 1;// 开启内置协议模式
+			TransparentModeFlag = 0; // 关闭透明传输模式
+			LogPrint(LOG_INFO,__FILE__,__FUNCTION__,__LINE__,"ProtocolsMode");	
+		}
+		// 透明传输模式
+		if(strstr(buf,"TransparentMode") != NULL)
+		{
+			ProtocolsModeFlag = 0;// 关闭内置协议模式
+			TransparentModeFlag = 1; // 开启透明传输模式
+			LogPrint(LOG_INFO,__FILE__,__FUNCTION__,__LINE__,"TransparentModeFlag");	
+		}
+}
+
+#define RECV_BUF_SIZE			3 * 1024
 
 void tcp_server_task(void *pvParameters)
 {
     int ret,sockfd;
+		int recv_size;
     struct sockaddr_in tcpServerSock;
     struct sockaddr_in client_sock;
+		// 命令集
+		char* recv_cmd[] = {"\"cmd\":\"write_config\"","\"cmd\":\"write_config_add\"",
+												"\"cmd\":\"read_config\"","\"cmd\":\"find_device\"",
+												"\"cmd\":\"ip_config\"","\"cmd\":\"toggle_work_mode\"",
+												"\"cmd\":\"software_update\"","\"cmd\":\"reboot\"",
+												"\"cmd\":\"error_cmd\""};// cmd:error_cmd 仅为了判断错误的命令
+		while(dhcp_done!=1)
+		{
+			vTaskDelay(100);
+		}
+
     tcpServerSock.sin_family = AF_INET;
-		inet_aton("192.168.2.228",&(tcpServerSock.sin_addr));
+		inet_aton("192.168.0.100",&(tcpServerSock.sin_addr));
 //    tcpServerSock.sin_addr.s_addr = htonl(IPADDR_ANY);
     tcpServerSock.sin_port = htons(8080);
 tcp_server_begin:
@@ -40,19 +248,144 @@ tcp_server_begin:
         sockfd = -1;
         goto tcp_server_begin;
     }
-		
-    while (1)
+		socklen_t len = sizeof(client_sock);
+    int client_socket = accept(sockfd, (struct sockaddr*)&client_sock,&len);
+		if (client_socket<0)
     {
-				vTaskDelay(1000);
-        socklen_t len = sizeof(client_sock);
-        int client_socket = accept(sockfd, (struct sockaddr*)&client_sock,&len);
-				LogPrint(LOG_INFO,__FILE__,__FUNCTION__,__LINE__,"上位机成功连接%s");
-        if (client_socket<0)
-        {
-            printf("error");
-        }
+      printf("error");
     }
-    
+		LogPrint(LOG_INFO,__FILE__,__FUNCTION__,__LINE__,"PC connect success");	
+    while (1)
+    {		
+				vTaskDelay(100);
+
+				char* dataBuf = pvPortMalloc(RECV_BUF_SIZE);// 存储config数据			最大20K,暂定3K
+				if(dataBuf == NULL) 
+					LogPrint(LOG_ERROR,__FILE__,__FUNCTION__,__LINE__,"recv buf malloc fail");	
+				memset(dataBuf,0,strlen(dataBuf));
+				// 	获取上位机发送的数据
+				recv_size=recv(client_socket,dataBuf,RECV_BUF_SIZE,0);
+				// 插入tcp_config标志位,后续不通过http获取默认配置数据
+				sprintf(dataBuf + strlen(dataBuf),"tcp_config");
+
+					// 接收到消息
+					// 解析上位机发送的CMD命令	
+					if(recv_size>0)
+					{
+						int j = 0;
+						for(int i = 0; i < sizeof(recv_cmd)/sizeof(recv_cmd[0]); i++)
+						{
+							if(strstr(dataBuf,recv_cmd[i]) != NULL)
+							{
+								i = sizeof(recv_cmd)/sizeof(recv_cmd[0]);
+							}
+							j++;
+						}
+						
+						if (ProtocolsModeFlag) {
+								switch (j) {
+									case WRITE_CONFIG:
+											save_config(client_socket, dataBuf);
+											vPortFree(dataBuf);
+											LogPrint(LOG_INFO, __FILE__, __FUNCTION__, __LINE__, "write config");
+											break;
+									case WRITE_CONFIG_ADD:
+											add_config(client_socket, dataBuf);
+											vPortFree(dataBuf);
+											LogPrint(LOG_INFO, __FILE__, __FUNCTION__, __LINE__, "write config add");
+											break;
+									case READ_CONFIG:
+											send_config(client_socket);
+											vPortFree(dataBuf);
+											LogPrint(LOG_INFO, __FILE__, __FUNCTION__, __LINE__, "read config");
+											break;
+									case FIND_DEVICE:
+											find_device(client_socket);
+											vPortFree(dataBuf);
+											LogPrint(LOG_INFO, __FILE__, __FUNCTION__, __LINE__, "find device");
+											break;
+									case IP_CONFIG:
+											LogPrint(LOG_INFO, __FILE__, __FUNCTION__, __LINE__, "ipconfig");
+											analysis_ip_config(client_socket, sockfd, tcpServerSock, dataBuf);
+											if (closeFlag == 1) {
+													// 更新新的地址
+													inet_aton((char*)&load_ip_config.host, &(tcpServerSock.sin_addr));
+													closeFlag = 0;
+													vPortFree(dataBuf);
+													goto tcp_server_begin;
+											}
+											vPortFree(dataBuf);
+											break;
+									case TOGGLE_MODE:
+											work_mode(dataBuf);
+											vPortFree(dataBuf);
+											LogPrint(LOG_INFO, __FILE__, __FUNCTION__, __LINE__, "toggle work mode");
+											break;
+									case UPDATE:
+											LogPrint(LOG_INFO, __FILE__, __FUNCTION__, __LINE__, "update");
+											vPortFree(dataBuf);
+											updata_task_creat(client_socket);
+											break;
+									case REBOOT:
+											send(client_socket,"{\"reboot\":\"success\"}", 20, 0);
+											LogPrint(LOG_INFO, __FILE__, __FUNCTION__, __LINE__, "reboot");
+											__set_PRIMASK(1);
+											NVIC_SystemReset();
+											break;
+									default:
+											send(client_socket,"{\"cmd:error\"}", 15, 0);
+											LogPrint(LOG_INFO, __FILE__, __FUNCTION__, __LINE__, "Command error");
+								}
+							} else {
+								switch (j) {
+									case FIND_DEVICE:
+											find_device(client_socket);
+											vPortFree(dataBuf);
+											LogPrint(LOG_INFO, __FILE__, __FUNCTION__, __LINE__, "find device");
+											break;
+									case IP_CONFIG:
+											LogPrint(LOG_INFO, __FILE__, __FUNCTION__, __LINE__, "ip config");
+											analysis_ip_config(client_socket, sockfd, tcpServerSock, dataBuf);
+											if (closeFlag == 1) {
+													// 更新新的地址
+													inet_aton((char*)&load_ip_config.host, &(tcpServerSock.sin_addr));
+													closeFlag = 0;
+													vPortFree(dataBuf);
+													goto tcp_server_begin;
+											}
+											vPortFree(dataBuf);
+											break;
+									case TOGGLE_MODE:
+											work_mode(dataBuf);
+											vPortFree(dataBuf);
+											LogPrint(LOG_INFO, __FILE__, __FUNCTION__, __LINE__, "toggle work mode");
+											break;
+									case UPDATE:
+											LogPrint(LOG_INFO, __FILE__, __FUNCTION__, __LINE__, "update");
+											vPortFree(dataBuf);
+											updata_task_creat(client_socket);
+											break;
+									case REBOOT:
+											send(client_socket,"{\"reboot\":\"success\"}", 20, 0);
+											LogPrint(LOG_INFO, __FILE__, __FUNCTION__, __LINE__, "reboot");
+											__set_PRIMASK(1);
+											NVIC_SystemReset();	
+											break;
+									default:
+											send(client_socket,"{\"cmd:error\"}", 15, 0);
+											LogPrint(LOG_INFO, __FILE__, __FUNCTION__, __LINE__, "Command error");
+							}
+						}
+					}
+					// 没接收到消息
+					else if(recv_size==0)
+					{
+						lwip_close(client_socket);
+						LOG_PRINT(LOG_ERROR,"PC disconnect,wait reconnect");
+						client_socket= accept(sockfd, (struct sockaddr*)&client_sock,&len);
+					}
+					vPortFree(dataBuf);
+			}
 }
 /*!
     \brief      initialize the tcp_client application
@@ -62,5 +395,5 @@ tcp_server_begin:
 */
 void tcp_server_init(void)
 {
-    xTaskCreate(tcp_server_task, "TCP_CLIENT", DEFAULT_THREAD_STACKSIZE, NULL, 1, NULL);
+    xTaskCreate(tcp_server_task, "TCP_SERVER", DEFAULT_THREAD_STACKSIZE, NULL, 1, NULL);
 }

+ 17 - 8
app/System/source/udp.c

@@ -46,6 +46,7 @@ OF SUCH DAMAGE.
 #include "lwip/memp.h"
 #include "main.h"
 #include "lwip/api.h"
+#include "tcp_server.h"
 
 
 #define UDP_TASK_PRIO       ( tskIDLE_PRIORITY + 5)
@@ -160,7 +161,7 @@ static void udp_task(void *arg)
 volatile int8_t sockfd=-1;
 #define UDP_LOCAL_PORT 12345
 #define UDP_REMOTE_PORT 54321
-#define SERCER_IP_ADDRESS "192.168.2.211"       //接收服务器ip
+#define SERCER_IP_ADDRESS "192.168.0.102"       //接收服务器ip
 struct sockaddr_in remote_addr;
 int udp_log_start()
 {
@@ -183,8 +184,17 @@ int udp_log_start()
     goto exit;
   }
 	//设置远程服务器地址 TODO:服务器地址配置后自动获取
+	ip_config *get;
+	get= get_ip_config();
 	remote_addr.sin_family=AF_INET;
-	remote_addr.sin_port=htons(UDP_REMOTE_PORT);
+	if(get->udpLogPort != 0)
+	{
+		remote_addr.sin_port=htons(get->udpLogPort);
+	}
+	else
+	{
+		remote_addr.sin_port=htons(UDP_REMOTE_PORT);
+	}
 	inet_aton(SERCER_IP_ADDRESS,&(remote_addr.sin_addr));
 	return 1;
 	
@@ -197,14 +207,13 @@ void udp_log_close()
 	lwip_close(sockfd);
 	sockfd=-1;
 }
-
+#include "usart.h"
 int fputc(int ch, FILE *f)
 {
-	if(sockfd>=0)
-	{
-		sendto(sockfd, &ch, 1, 0, (struct sockaddr *)&remote_addr,sizeof(remote_addr));
-    return ch;
-	}
+//		gd_485_DE_tx();
+//		usart_data_transmit(USART0, ch);
+//		while (RESET == usart_flag_get(USART0, USART_FLAG_TC));
+//		gd_485_DE_rx();
 }
 
 int udp_send_printf(char *p)

+ 2 - 2
app/System/source/udp.h

@@ -14,7 +14,7 @@
 
 /* function declarations */
 /* initialize the tcp_client application */
-int udp_log_start();
-void udp_log_close();
+int udp_log_start(void);
+void udp_log_close(void);
 int udp_send_printf(char *p);
 #endif /* UDP_ECHO_H */

+ 140 - 0
app/System/source/updata.c

@@ -0,0 +1,140 @@
+#include "updata.h"
+#include "FREERTOS.h"
+#include "task.h"
+#include "delay.h"
+#include "sockets.h"
+#include "string.h"
+
+static const uint16_t wCRCTable[] =
+    {
+        0X0000, 0XC0C1, 0XC181, 0X0140, 0XC301, 0X03C0, 0X0280, 0XC241,
+        0XC601, 0X06C0, 0X0780, 0XC741, 0X0500, 0XC5C1, 0XC481, 0X0440,
+        0XCC01, 0X0CC0, 0X0D80, 0XCD41, 0X0F00, 0XCFC1, 0XCE81, 0X0E40,
+        0X0A00, 0XCAC1, 0XCB81, 0X0B40, 0XC901, 0X09C0, 0X0880, 0XC841,
+        0XD801, 0X18C0, 0X1980, 0XD941, 0X1B00, 0XDBC1, 0XDA81, 0X1A40,
+        0X1E00, 0XDEC1, 0XDF81, 0X1F40, 0XDD01, 0X1DC0, 0X1C80, 0XDC41,
+        0X1400, 0XD4C1, 0XD581, 0X1540, 0XD701, 0X17C0, 0X1680, 0XD641,
+        0XD201, 0X12C0, 0X1380, 0XD341, 0X1100, 0XD1C1, 0XD081, 0X1040,
+        0XF001, 0X30C0, 0X3180, 0XF141, 0X3300, 0XF3C1, 0XF281, 0X3240,
+        0X3600, 0XF6C1, 0XF781, 0X3740, 0XF501, 0X35C0, 0X3480, 0XF441,
+        0X3C00, 0XFCC1, 0XFD81, 0X3D40, 0XFF01, 0X3FC0, 0X3E80, 0XFE41,
+        0XFA01, 0X3AC0, 0X3B80, 0XFB41, 0X3900, 0XF9C1, 0XF881, 0X3840,
+        0X2800, 0XE8C1, 0XE981, 0X2940, 0XEB01, 0X2BC0, 0X2A80, 0XEA41,
+        0XEE01, 0X2EC0, 0X2F80, 0XEF41, 0X2D00, 0XEDC1, 0XEC81, 0X2C40,
+        0XE401, 0X24C0, 0X2580, 0XE541, 0X2700, 0XE7C1, 0XE681, 0X2640,
+        0X2200, 0XE2C1, 0XE381, 0X2340, 0XE101, 0X21C0, 0X2080, 0XE041,
+        0XA001, 0X60C0, 0X6180, 0XA141, 0X6300, 0XA3C1, 0XA281, 0X6240,
+        0X6600, 0XA6C1, 0XA781, 0X6740, 0XA501, 0X65C0, 0X6480, 0XA441,
+        0X6C00, 0XACC1, 0XAD81, 0X6D40, 0XAF01, 0X6FC0, 0X6E80, 0XAE41,
+        0XAA01, 0X6AC0, 0X6B80, 0XAB41, 0X6900, 0XA9C1, 0XA881, 0X6840,
+        0X7800, 0XB8C1, 0XB981, 0X7940, 0XBB01, 0X7BC0, 0X7A80, 0XBA41,
+        0XBE01, 0X7EC0, 0X7F80, 0XBF41, 0X7D00, 0XBDC1, 0XBC81, 0X7C40,
+        0XB401, 0X74C0, 0X7580, 0XB541, 0X7700, 0XB7C1, 0XB681, 0X7640,
+        0X7200, 0XB2C1, 0XB381, 0X7340, 0XB101, 0X71C0, 0X7080, 0XB041,
+        0X5000, 0X90C1, 0X9181, 0X5140, 0X9301, 0X53C0, 0X5280, 0X9241,
+        0X9601, 0X56C0, 0X5780, 0X9741, 0X5500, 0X95C1, 0X9481, 0X5440,
+        0X9C01, 0X5CC0, 0X5D80, 0X9D41, 0X5F00, 0X9FC1, 0X9E81, 0X5E40,
+        0X5A00, 0X9AC1, 0X9B81, 0X5B40, 0X9901, 0X59C0, 0X5880, 0X9841,
+        0X8801, 0X48C0, 0X4980, 0X8941, 0X4B00, 0X8BC1, 0X8A81, 0X4A40,
+        0X4E00, 0X8EC1, 0X8F81, 0X4F40, 0X8D01, 0X4DC0, 0X4C80, 0X8C41,
+        0X4400, 0X84C1, 0X8581, 0X4540, 0X8701, 0X47C0, 0X4680, 0X8641,
+        0X8201, 0X42C0, 0X4380, 0X8341, 0X4100, 0X81C1, 0X8081, 0X4040};
+// crc校验
+uint16_t Checkcrc16(const uint8_t *nData, uint16_t wLength)
+{
+  uint8_t nTemp;
+  uint16_t wCRCWord = 0xFFFF;
+  while (wLength--)
+  {
+    nTemp = *nData++ ^ wCRCWord;
+    wCRCWord >>= 8;
+    wCRCWord ^= wCRCTable[nTemp];
+  }
+  return wCRCWord;
+}
+int i=0 ;
+//void updata_task(void* pvParameters)
+// 更新OTA数据
+void updata_task_creat(int client_socket)
+{
+	int recv_size;
+	uint16_t crc;	
+	uint8_t buf[1029];// 接收的一包数据(包括头标志、包序列、包序列反码、包数据、校验位)
+	uint8_t databuf[1024];// 保存包数据
+	
+	uint16_t packId = 0x01;
+	uint8_t stx = 0x02,eot = 0x04,ack = 0x06,nak = 0x15,C = 0x43;
+	
+	char* retMsg = pvPortMalloc(32);
+	memset(retMsg, 0, strlen(retMsg));
+	retMsg = "{\"software_update\":\"ready\"}";
+	send(client_socket, retMsg, strlen(retMsg), 0);	
+	vPortFree(retMsg);
+
+	// 发送第一个C
+	send(client_socket, &C, 1, 0);
+__start:
+	memset(buf, 0, sizeof(buf));
+	recv_size = recv(client_socket, buf, sizeof(buf), 0);
+	if(recv_size == 0)
+	{
+		//等待3S
+		delay_ms(3000);
+		//3s再发送C
+		send(client_socket, &C, 1, 0);
+		recv_size = recv(client_socket,buf,sizeof(buf),0);
+	}
+	do{
+			// 检测头标志
+			if(buf[0] != stx)
+			{
+				send(client_socket, &nak, 1, 0);
+				goto __start;
+			}
+			// 检测包序列
+			if(buf[1] != packId)
+			{
+				send(client_socket, &nak, 1, 0);
+				goto __start;
+			}
+			// 检测包号反码
+			if(buf[2] !=(~packId & 0xff))
+			{
+				send(client_socket, &nak, 1, 0);
+				goto __start;
+			}
+			// 提取数据包
+			for(int i = 0; i < 1024; i++)
+			{
+				databuf[i] = buf[3 + i];
+			}
+			crc = Checkcrc16(databuf, 1024);
+			// 检测数据包的校验码
+			if (((crc & 0x00FF) != buf[1028]) || (((crc & 0xFF00) >> 8) != buf[1027]))
+			{	
+				send(client_socket, &nak, 1, 0);
+				goto __start;
+			}
+			// 对数据包进行操作
+			/*                */
+			memset(databuf, 0, sizeof(databuf));
+			// 准备接收下一包数据
+			send(client_socket, &ack, 1, 0);
+			packId += 1;
+			memset(buf, 0, 1029);
+	}while(recv(client_socket,buf,sizeof(buf),0) > 1);
+	
+		// 接收到结束信号,反馈ack
+		if(buf[0] == eot)
+			send(client_socket, &ack, 1, 0);
+		// 所有数据包接受完成
+		
+}
+
+
+//#define UPDATA_TASK_PRIO ( tskIDLE_PRIORITY + 6 )
+//void updata_task_creat(void* client_socket)
+//{
+//	xTaskCreate(updata_task, "UPDATA",256, client_socket, UPDATA_TASK_PRIO, NULL);
+//}
+

+ 1 - 0
app/USR/include/main.h

@@ -18,6 +18,7 @@
 #include "stdint.h"
 #include "hd_eth.h"
 #include "FreeRTOS.h"
+#include "task.h"
 //SemaphoreHandle_t logMutex;
 extern char  gatewayId[11];
 

+ 1 - 1
app/USR/include/mqtt_config.h

@@ -37,7 +37,7 @@
 #define     MQTT_VERSION                        4           // 4 is mqtt 3.1.1
 #define     MQTT_RECONNECT_DEFAULT_DURATION     1000
 #define     MQTT_THREAD_STACK_SIZE              2048
-#define     MQTT_THREAD_PRIO                    5
+#define     MQTT_THREAD_PRIO                    3		//5
 #define     MQTT_THREAD_TICK                    50
 
 

+ 1 - 1
app/USR/include/tcp_client.h

@@ -11,7 +11,7 @@
 
 #ifndef TCP_CLIENT_H
 #define TCP_CLIENT_H
-
+#include "stdint.h"
 /* function declarations */
 /* initialize the tcp_client application */
 void tcp_client_init(void);

+ 6 - 1
app/USR/source/gd32f30x_it.c

@@ -45,6 +45,8 @@ OF SUCH DAMAGE.
 #include "queue.h"
 #include "lwip/sys.h"
 
+#include "led.h"
+#include "log.h"
 extern xSemaphoreHandle g_rx_semaphore;
 
 /*!
@@ -65,9 +67,12 @@ void NMI_Handler(void)
 */
 void HardFault_Handler(void)
 {
+		gd_eval_led_off(LED_DEV);	
+		LogPrint(LOG_ERROR,__FILE__,__FUNCTION__,__LINE__,"HardFault");
     /* if Hard Fault exception occurs, go to infinite loop */
     while (1)
-    {
+    {	
+			gd_eval_led_off(LED_DEV);	
     }
 }
 

+ 93 - 31
app/USR/source/main.c

@@ -54,6 +54,7 @@ OF SUCH DAMAGE.
 #include "log.h"
 #include "gd32_flash.h"
 #include "timer.h"
+#include "wwdgt.h"
 
 #include "sys_http.h"
 #include "data_task.h"
@@ -61,24 +62,23 @@ OF SUCH DAMAGE.
 
 /*
 *freertos优先级管理
-*管理启动流程任务 init_task        	优先级 1
-*freertos时间任务 prvTimerTask     	优先级 2
-*上位机交互任务  	tcp_server        优先级 1
-*可能会开启的任务 dhcp_task        	优先级 4
+*管理启动流程任务	init_task        	优先级 1
+*freertos时间任务	prvTimerTask     	优先级 2
+*上位机交互任务		tcp_server        优先级 1
+*可能会开启的任务	dhcp_task        	优先级 4
 *mqtt通信任务			mqtt_publish_task 优先级 4
-*以太网输入任务   ethernetif_input 	优先级 5
-*数据处理任务     data_task         优先级 3
+*以太网输入任务		ethernetif_input 	优先级 5
+*数据处理任务			data_task					优先级 3
+*OTA升级任务				updata_task				优先级 5 
 */
 #define INIT_TASK_PRIO   ( tskIDLE_PRIORITY + 1 )
 #define DHCP_TASK_PRIO   ( tskIDLE_PRIORITY + 4 )
 #define LED_TASK_PRIO    ( tskIDLE_PRIORITY + 2 )
-
-
-
  
 void led_task(void * pvParameters); 
 void init_task(void * pvParameters);
-char  gatewayId[11];
+void readID(char *strId);
+char gatewayId[11];
 
 /*!
     \brief      main function
@@ -88,23 +88,44 @@ char  gatewayId[11];
 */
 int main(void)
 {
-		sprintf(gatewayId,"DTtest0001");//DT8pd3ac6h  DTbma5ac6h  DTtest0001
-	   /* configure 4 bits pre-emption priority */
+		readID(gatewayId);
+		/* remap PB3  PB4 */
+		rcu_periph_clock_enable(RCU_AF);// 使能映射功能的时钟	
+		gpio_pin_remap_config(GPIO_SWJ_SWDPENABLE_REMAP, ENABLE);// 重映射PB3、PB4
+		gpio_bit_set(GPIOC,GPIO_PIN_9);
+	
+		/* LED init */
+		gd_eval_led_init(LED_DEV);			// 状态灯
+		gd_eval_led_init(LED_485RX);		// 485 RX 通信灯
+		gd_eval_led_init(LED_485TX);		// 485 TX 通信灯
+	
+	  /* configure 4 bits pre-emption priority */
     nvic_priority_group_set(NVIC_PRIGROUP_PRE4_SUB0);
-		gd_485_DE_pin_init();
-		config_485_port(COM_485,115200,8,1,0);
 		
+		/* 485 init */
+		gd_485_DE_pin_init();
+		config_485_port(COM_485,9600,8,1,0);
+		printf("start\n");
+	
+		/* timer init */
 		timer5_init();
+		// 02设备直连电源时需要延迟
+		//delay_ms(50);
+    /*  FWDGT init */
+		watchdog_init();
+		
+		/* LED_DEV open */
+		gd_eval_led_on(LED_DEV);
 
-    /* init task */
+		/* init task */
     xTaskCreate(init_task, "INIT",256, NULL, INIT_TASK_PRIO, NULL);
-    /* start scheduler */
+		
+		/* start scheduler */
     vTaskStartScheduler();
     while(1)
 		{
 			
-    }
-		
+    }	
 }
 
 /*!
@@ -113,10 +134,8 @@ int main(void)
     \param[out] none
     \retval     none
 */
-int fttime1, fttime2;
 void init_task(void * pvParameters)
 {
-//		gd32_flash_test();
     /* configure ethernet (GPIOs, clocks, MAC, DMA) */ 
     enet_system_setup();
     /* initilaize the LwIP stack */
@@ -124,19 +143,21 @@ void init_task(void * pvParameters)
 		log_init();
     /* initilaize the tcp server: telnet 8000 */
 //    hello_gigadevice_init();
-    /* initilaize the tcp client: echo 1026 */
-//    tcp_client_init();
-    /* initilaize the udp: echo 1025 */
-	 tcp_server_init();
+//		/* initilaize the tcp client: echo 1026 */
+//		tcp_client_init();
+	  /* initilaize the udp: echo 1025 */
+		tcp_server_init();
 #ifdef USE_DHCP
     /* start DHCP client */
-    xTaskCreate(dhcp_task, "DHCP", 512, NULL, DHCP_TASK_PRIO, NULL);
+		xTaskCreate(dhcp_task, "DHCP", 512, NULL, DHCP_TASK_PRIO, NULL);
 #endif /* USE_DHCP */
 		
     /* start toogle LED task every 250ms */
 //    xTaskCreate(led_task, "LED", 512, NULL, LED_TASK_PRIO, NULL);
+
 		http_getDemo();
-		xTaskCreate(data_task, "DATA",1024, NULL, DATA_TASK_PRIO, NULL);
+
+		xTaskCreate(data_task, "DATA",512, NULL, DATA_TASK_PRIO, NULL);
 		mqtt_task_creat();
     for( ;; ){
         vTaskDelete(NULL);
@@ -149,14 +170,14 @@ void init_task(void * pvParameters)
     \param[out] none
     \retval     none
 */
-
+// 为了看到闪烁的效果,把485的一些数据丢掉
 void led_task(void * pvParameters)
 {  
     for( ;; ){
-        /* toggle LED3 each 250ms */
-        gd_eval_led_toggle(LED_DEV);
-        vTaskDelay(250);
-    }
+//        /* toggle LED3 each 250ms */
+//        gd_eval_led_toggle(LED_DEV);
+        vTaskDelay(100);
+		} 
 }
 
 
@@ -173,3 +194,44 @@ void vApplicationMallocFailedHook()
 {
 		LogPrint(LOG_ERROR,__FILE__,__FUNCTION__,__LINE__,"malloc error");
 }
+
+
+/*
+ *  函数名:void readID(char *strId)
+ *  输入参数:无
+ *  输出参数:strId
+ *  返回值:无
+ *  函数作用:读取长度12的芯片Id并组合从中取出对应字符防止其重复
+ */
+void readID(char *strId)
+{
+	static const char *hex_table = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMN";
+	uint32_t CpuID1, CpuID2, CpuID3;
+	CpuID1 = *(volatile uint32_t *)(0x1FFFF7E8);
+	CpuID2 = *(volatile uint32_t *)(0x1FFFF7EC);
+	CpuID3 = *(volatile uint32_t *)(0x1FFFF7F0);
+	strId[0] = 'D';
+	strId[1] = 'T';
+	
+	for (uint8_t i = 0, j = 0; i < 8; i += 2)
+	{
+		uint32_t sum1 = (CpuID1 >> ((j % 4) * 8)) & 0xFF; // 按字节取出
+		uint8_t index1 = sum1 / 16;
+		uint8_t remainder1 = sum1 % 16;
+
+		uint32_t sum2 = (CpuID2 >> ((j % 4) * 8)) & 0xFF; // 按字节取出
+		uint8_t index2 = sum2 / 16;
+		uint8_t remainder2 = sum2 % 16;
+
+		uint32_t sum3 = (CpuID3 >> ((j % 4) * 8)) & 0xFF; // 按字节取出
+		uint8_t index3 = sum3 / 16;
+		uint8_t remainder3 = sum3 % 16;
+
+		strId[i + 2] = hex_table[index1 + index2 + index3];
+		strId[i + 1 + 2] = hex_table[remainder1 + remainder2 + remainder3];
+
+		j++;
+	}
+	strId[10] = '\0';
+}
+

+ 37 - 17
app/USR/source/tcp_client.c

@@ -51,6 +51,8 @@ OF SUCH DAMAGE.
 #define MAX_BUF_SIZE                    50
 #define TIME_WAITING_FOR_CONNECT        ( ( portTickType ) 500 )
 
+uint8_t load_tcp_config = 0;
+
 #if ((LWIP_SOCKET == 0) && (LWIP_NETCONN == 1))
 
 struct recev_packet 
@@ -149,19 +151,19 @@ static void tcp_client_task(void *arg)
 
 #endif /* ((LWIP_SOCKET == 0) && (LWIP_NETCONN == 1)) */
 
-
+int lenth1,lenth2;
 
 #if LWIP_SOCKET
 #include "lwip/sockets.h"
-#define SERVER_IP_ADDRESS "192.168.2.210"
+#include "netconf.h"
+#include "gd32_flash.h"
+#define SERVER_IP_ADDRESS "192.168.0.101"
 #define SERVER_PORT 8080
 #define MESSAGE "hello, world"
-
 static void tcp_client_task(void *arg)
 {
     int ret, sockfd = -1;
     struct sockaddr_in svr_addr;
-    char buf[100];
 
     /* Create the socket outside the loop */
     sockfd = socket(AF_INET, SOCK_STREAM, 0);
@@ -187,14 +189,18 @@ static void tcp_client_task(void *arg)
         svr_addr.sin_family = AF_INET;
         svr_addr.sin_port = htons(SERVER_PORT);
         inet_aton(SERVER_IP_ADDRESS, &(svr_addr.sin_addr));
-
-        /* Connect to the server */
+		while(dhcp_done!=1)
+		{
+			vTaskDelay(100);
+		}
+			/* Connect to the server */
 			ret = connect(sockfd, (struct sockaddr *)&svr_addr, sizeof(svr_addr));
       if (ret < 0)
       {
             perror("Connect error");
             vTaskDelay(pdMS_TO_TICKS(1000)); // Delay for 1 second
       }
+			
 			while (1)
 			{
         /* Send "hello, world" to the server */
@@ -210,16 +216,32 @@ static void tcp_client_task(void *arg)
 						}
             continue;
         }
-/*
+
         //Receive response from the server (if needed) 
-        ret = recv(sockfd, buf, sizeof(buf), 0);
-        if (ret <= 0)
-        {
-            perror("Receive error");
-            vTaskDelay(pdMS_TO_TICKS(1000)); // Delay for 1 second
-            continue;
-        }
-*/
+				char buf[10];
+				ret = recv(sockfd, buf, sizeof(buf), 0);
+/*				
+				char buf[1460];// 接收一包TCP数据
+				char* dataBuf = pvPortMalloc(3 * 1024);// 最大20K,暂定3K
+				memset(dataBuf,0,strlen(dataBuf));
+				sprintf(dataBuf,"tcp_config");
+				do{
+						memset(buf, 0, sizeof(buf) + 4);
+						ret = recv(sockfd, buf, sizeof(buf), 0);
+						if (ret <= 0)
+						{
+								perror("Receive error");
+								vTaskDelay(pdMS_TO_TICKS(1000)); // Delay for 1 second
+								continue;
+						}
+						lenth1 = strlen(dataBuf);
+						lenth2 = strlen(buf);
+						memcpy(dataBuf + lenth1,buf,strlen(buf));
+						lenth1 = strlen(dataBuf);
+						}while(buf[1459] != NULL );	
+					save_config_params(dataBuf);
+					vPortFree(dataBuf);				
+*/				
         /* Process the received data if needed */
 
         vTaskDelay(pdMS_TO_TICKS(5000)); // Delay for 5 seconds before the next iteration
@@ -228,8 +250,6 @@ static void tcp_client_task(void *arg)
     /* Close the socket after the loop */
     close(sockfd);
 }
-
-
 #endif /* LWIP_SOCKET */
 
 

+ 20 - 0
app/dlt/inc/dlt645.h

@@ -29,7 +29,27 @@ typedef enum
     DLT645_2007 = 1,
     DLT645_1997
 } dlt645_protocal;
+/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
+#define DLT_RXSIZE 200
 
+// DLT645采集使用的串口名
+#define DLT645_USART COM_485
+#define DLT645_CTRL_GPIO DE485_GPIO_PORT
+#define DLT645_CTRL_PIN DE485_PIN
+
+// DL/T 645硬件拓展结构体
+typedef struct
+{
+	uint8_t dlt645_Tx; // 用于串口接收的状态
+	uint32_t timeout;  //
+	uint8_t rxBuf[DLT_RXSIZE];
+	uint8_t done;
+	uint8_t index;
+} dlt645_port_t;
+
+extern dlt645_port_t dlt645_port;
+
+/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
 //设置从机地址
 extern void dlt645_set_addr(dlt645_t *ctx, uint8_t *addr);
 //设置调试开关

+ 3 - 18
app/dlt/port/dlt645_port.c

@@ -15,24 +15,9 @@
 #include "usart.h"
 #include "string.h"
 
-#define DLT_RXSIZE 200
 
-// DLT645采集使用的串口名
-#define DLT645_USART COM_485
-#define DLT645_CTRL_GPIO DE485_GPIO_PORT
-#define DLT645_CTRL_PIN DE485_PIN
-
-// DL/T 645硬件拓展结构体
-typedef struct
-{
-	uint8_t dlt645_Tx; // 用于串口接收的状态
-	uint32_t timeout;  //
-	uint8_t rxBuf[DLT_RXSIZE];
-	uint8_t done;
-	uint8_t index;
-} dlt645_port_t;
-
-static dlt645_port_t dlt645_port;
+dlt645_port_t dlt645_port;
+//static dlt645_port_t dlt645_port;
 
 // dlt645 环境结构体
 dlt645_t dlt645;
@@ -72,7 +57,7 @@ static int dlt645_hw_read(dlt645_t *ctx, uint8_t *msg, uint16_t len)
 	int startTime = gettick();
 	while (1)
 	{
-		if (gettick() - startTime > dlt645_port.timeout )
+		if (gettick() - startTime > dlt645_port.timeout * 1000 )
 			return 0;
 		if (dlt645_port.done == 1)
 		{

+ 5 - 5
app/dlt/src/dlt645_data.c

@@ -11,7 +11,7 @@
 *************************************************/
 #include "dlt645_private.h"
 #include <string.h>
-#include <math.h>
+#include "data_task.h"
 
 //字节位置枚举类型
 typedef enum
@@ -216,13 +216,13 @@ int data_package_translate_to_int(uint8_t *read_data, uint16_t len)
             {
             //当前处理字节低位
             case BYTE_LOW_ADDRESS:
-                i_value += ((read_data[current_index] - 0x33) & 0x0f) * pow(10, number_weight);
+                i_value += ((read_data[current_index] - 0x33) & 0x0f) * my_pow(10,number_weight);
                 number_weight++;
                 current_byte_part = BYTE_HIGH_ADDRESS;
                 break;
             //当前处理字节高位
             case BYTE_HIGH_ADDRESS:
-                i_value += ((read_data[current_index] - 0x33) >> 4) * pow(10, number_weight);
+                i_value += ((read_data[current_index] - 0x33) >> 4) * my_pow(10,number_weight);
                 number_weight++;
                 current_byte_part = BYTE_RESET;
                 break;
@@ -261,7 +261,7 @@ int dlt645_data_parse_by_format_to_float(uint8_t *read_data, uint16_t read_len,
             break;
         }
     }
-    float fval = ival / pow(10, num_weight);
+    float fval = ival / my_pow(10,num_weight);
     memcpy(store_address, &fval, 4);
     return 0;
 }
@@ -283,7 +283,7 @@ int dlt645_data_parse_by_format_to_float_and_DATE(uint8_t *read_data, uint16_t r
             break;
         }
     }
-    float fval = ival / pow(10, num_weight);
+    float fval = ival / my_pow(10,num_weight);
     memcpy(store_address, &fval, 4);
     return 0;
 }

+ 5 - 38
app/modbus/mmodbus.c

@@ -3,6 +3,7 @@
 #include "usart.h"
 #include "delay.h"
 #include "log.h"
+#include "led.h"
 MModBus_t mmodbus;
 
 // #####################################################################################################
@@ -58,40 +59,6 @@ uint16_t mmodbus_crc16(const uint8_t *nData, uint16_t wLength)
 
 
 #endif
-volatile uint8_t flag;
-// #####################################################################################################
-//void mmodbus_callback(void)
-//{ 
-//	uint16_t data;
-//  if (RESET != usart_flag_get(_MMODBUS_USART, USART_FLAG_RBNE))
-//  {
-//		flag=0;
-//    if (mmodbus.rxIndex < _MMODBUS_RXSIZE - 1)
-//    {
-//      mmodbus.rxBuf[mmodbus.rxIndex] = usart_data_receive(_MMODBUS_USART);
-//      mmodbus.rxIndex++;
-//    }
-//    else
-//      usart_data_receive(_MMODBUS_USART);
-//  }
-
-//	if ((mmodbus.rxIndex > 0) && RESET != usart_flag_get(_MMODBUS_USART, USART_FLAG_IDLE) )
-//	{	
-//		mmodbus.done = 1;
-//		usart_data_receive(_MMODBUS_USART);
-//		usart_interrupt_flag_clear(_MMODBUS_USART, USART_INT_FLAG_IDLE);
-
-//		return;
-//	}
-//		else
-//		{
-//			data = usart_data_receive(_MMODBUS_USART);
-//			usart_interrupt_flag_clear(_MMODBUS_USART, USART_INT_FLAG_RBNE);
-//			
-//		}
-//  mmodbus.rxTime = gettick();
-//}
-
 void mmodbus_callback(void)
 { 
   if (RESET != usart_interrupt_flag_get(_MMODBUS_USART, USART_INT_FLAG_RBNE))
@@ -114,7 +81,7 @@ void mmodbus_callback(void)
 		mmodbus.done = 1;
 		usart_data_receive(_MMODBUS_USART);
 		usart_interrupt_flag_clear(_MMODBUS_USART, USART_INT_FLAG_IDLE);
-
+		gd_eval_led_toggle(LED_485RX);
 		return;
 	}
 		else
@@ -132,13 +99,13 @@ uint16_t mmodbus_receiveRaw(uint32_t timeout)
   uint32_t startTime = gettick();
   while (1)
   {
-    if (gettick() - startTime> timeout)
+    if (gettick() - startTime> timeout * 1000)
       return 0;
     if (mmodbus.done == 1)
     {
       return mmodbus.rxIndex;
     }
-    mmodbus_delay(1);
+    mmodbus_delay(5);
   }
 }
 // ##################################################################################################
@@ -408,7 +375,7 @@ bool mmodbus_readHoldingRegisters8i(uint8_t slaveAddress, uint16_t startnumber,
   txData[6] = (crc & 0x00FF);
   txData[7] = (crc & 0xFF00) >> 8;
   mmodbus_sendRaw(txData, 8, 100);
-  uint16_t recLen = mmodbus_receiveRaw(100);
+  uint16_t recLen = mmodbus_receiveRaw(mmodbus.timeout);
   if (recLen == 0)
     return false;
   if (mmodbus.rxBuf[0] != slaveAddress)

+ 4 - 1
app/modbus/mmodbus.h

@@ -52,7 +52,8 @@
 #include  <stdint.h>
 #include "FreeRTOS.h"
 #include "task.h"
-#define   mmodbus_delay(x) 	delay_ms(x)
+#define   mmodbus_delay(x) 	delay_ms(x) // vTaskDelay(x)
+
 
 
 /*
@@ -123,6 +124,7 @@ typedef struct
   
 }MModBus_t;
 
+extern MModBus_t mmodbus;
 //##################################################################################################
 
 void    mmodbus_callback(void);
@@ -161,4 +163,5 @@ bool    mmodbus_writeHoldingRegisters16i(uint8_t slaveAddress, uint16_t startnum
 uint16_t mmodbus_crc16(const uint8_t *nData, uint16_t wLength);
 
 //##################################################################################################
+bool mmodbus_readHoldingRegisters8i(uint8_t slaveAddress, uint16_t startnumber, uint16_t length, uint8_t *data);
 #endif

+ 1 - 1
app/mqttclient/mqttclient/mqttclient.c

@@ -1120,7 +1120,7 @@ static int mqtt_init(mqtt_client_t* c)
     c->mqtt_packet_id = 1;
     c->mqtt_clean_session = 0;          //no clear session by default
     c->mqtt_will_flag = 0;
-    c->mqtt_cmd_timeout = MQTT_DEFAULT_CMD_TIMEOUT;
+    c->mqtt_cmd_timeout = MQTT_MAX_CMD_TIMEOUT;
     c->mqtt_client_state = CLIENT_STATE_INITIALIZED;
     
     c->mqtt_ping_outstanding = 0;

+ 1 - 1
bootloader/MDK/dtu_simple_bootloader.uvoptx

@@ -10,7 +10,7 @@
     <aExt>*.s*; *.src; *.a*</aExt>
     <oExt>*.obj; *.o</oExt>
     <lExt>*.lib</lExt>
-    <tExt>*.txt; *.h; *.inc</tExt>
+    <tExt>*.txt; *.h; *.inc; *.md</tExt>
     <pExt>*.plm</pExt>
     <CppX>*.cpp</CppX>
     <nMigrate>0</nMigrate>

+ 4 - 2
bootloader/MDK/dtu_simple_bootloader.uvprojx

@@ -10,7 +10,7 @@
       <TargetName>BOOTLOARDER</TargetName>
       <ToolsetNumber>0x4</ToolsetNumber>
       <ToolsetName>ARM-ADS</ToolsetName>
-      <pCCUsed>5060750::V5.06 update 6 (build 750)::ARMCC</pCCUsed>
+      <pCCUsed>5060960::V5.06 update 7 (build 960)::.\ARMCC</pCCUsed>
       <uAC6>0</uAC6>
       <TargetOption>
         <TargetCommonOption>
@@ -185,6 +185,8 @@
             <uocXRam>0</uocXRam>
             <RvdsVP>2</RvdsVP>
             <RvdsMve>0</RvdsMve>
+            <RvdsCdeCp>0</RvdsCdeCp>
+            <nBranchProt>0</nBranchProt>
             <hadIRAM2>0</hadIRAM2>
             <hadIROM2>0</hadIROM2>
             <StupSel>8</StupSel>
@@ -351,7 +353,7 @@
             <NoWarn>0</NoWarn>
             <uSurpInc>0</uSurpInc>
             <useXO>0</useXO>
-            <uClangAs>0</uClangAs>
+            <ClangAsOpt>4</ClangAsOpt>
             <VariousControls>
               <MiscControls></MiscControls>
               <Define></Define>