haitao 10 месяцев назад
Родитель
Сommit
44a74a5456

+ 1 - 1
app/CMSIS/source/startup_gd32f30x_cl.s

@@ -50,7 +50,7 @@ __initial_sp
 ;   <o>  Heap Size (in Bytes) <0x0-0xFFFFFFFF:8>
 ; </h>
 
-Heap_Size       EQU     0x00008000
+Heap_Size       EQU     0x000001000
 
                 AREA    HEAP, NOINIT, READWRITE, ALIGN=3
 __heap_base

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

@@ -43,7 +43,7 @@ OF SUCH DAMAGE.
 #define ETH_INIT_FLAG           0x01 /* Ethernet Init Flag */
 #define ETH_LINK_FLAG           0x10 /* Ethernet Link Flag */
 
-#define USE_DHCP       /* enable DHCP, if disabled static address is used */
+//#define USE_DHCP       /* enable DHCP, if disabled static address is used */
 
 /* MAC address: MAC_ADDR0:MAC_ADDR1:MAC_ADDR2:MAC_ADDR3:MAC_ADDR4:MAC_ADDR5 */
 #define MAC_ADDR0   2
@@ -58,7 +58,7 @@ OF SUCH DAMAGE.
 #define IP_ADDR0   192
 #define IP_ADDR1   168
 #define IP_ADDR2   2
-#define IP_ADDR3   126
+#define IP_ADDR3   222
 
 /* remote station IP address: IP_S_ADDR0.IP_S_ADDR1.IP_S_ADDR2.IP_S_ADDR3 */
 #define IP_S_ADDR0   192
@@ -69,7 +69,7 @@ OF SUCH DAMAGE.
 /* net mask */
 #define NETMASK_ADDR0   255
 #define NETMASK_ADDR1   255
-#define NETMASK_ADDR2   254
+#define NETMASK_ADDR2   255
 #define NETMASK_ADDR3   0
 
 /* gateway address */

BIN
app/MDK/Objects/dtu_simple.axf


Разница между файлами не показана из-за своего большого размера
+ 164 - 123
app/MDK/dtu_simple.uvoptx


+ 15 - 5
app/MDK/dtu_simple.uvprojx

@@ -402,11 +402,6 @@
               <FileType>1</FileType>
               <FilePath>..\USR\source\tcp_client.c</FilePath>
             </File>
-            <File>
-              <FileName>udp_echo.c</FileName>
-              <FileType>1</FileType>
-              <FilePath>..\USR\source\udp_echo.c</FilePath>
-            </File>
           </Files>
         </Group>
         <Group>
@@ -422,6 +417,21 @@
               <FileType>1</FileType>
               <FilePath>..\System\source\httpclient.c</FilePath>
             </File>
+            <File>
+              <FileName>tcp_server.c</FileName>
+              <FileType>1</FileType>
+              <FilePath>..\System\source\tcp_server.c</FilePath>
+            </File>
+            <File>
+              <FileName>log.c</FileName>
+              <FileType>1</FileType>
+              <FilePath>..\System\source\log.c</FilePath>
+            </File>
+            <File>
+              <FileName>udp.c</FileName>
+              <FileType>1</FileType>
+              <FilePath>..\System\source\udp.c</FilePath>
+            </File>
           </Files>
         </Group>
         <Group>

+ 28 - 0
app/System/include/log.h

@@ -0,0 +1,28 @@
+
+#ifndef INC_LOG_H_
+#define INC_LOG_H_
+
+#include <stdarg.h>
+
+
+#define _LOG_DEBUG
+#define _LOG_WARN
+#define _LOG_INFO
+
+
+#define LOG_LEN_MAX 256
+
+typedef enum LOG_LEVEL_U
+{
+	LOG_NONE = 0,
+	LOG_INFO,
+	LOG_DEBUG,
+	LOG_WARN,
+	LOG_ERROR,
+	LOG_MAX,
+}logLevel_t;
+
+void LogPrint(logLevel_t logLevel,const char *file, const char *func, const int line, char * fmt, ...);
+void log_init();
+#define LOG_PRINT(logLevel, fmt, ...) LogPrint(logLevel, __FUNCTION__, __LINE__, fmt, ##__VA_ARGS__)
+#endif /* INC_LOG_H_ */

+ 4 - 0
app/System/include/tcp_server.h

@@ -0,0 +1,4 @@
+#ifndef TCP_SERVER_H
+#define TCP_SERVER_H
+void tcp_server_init();
+#endif

+ 0 - 0
app/System/include/udp.h


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

@@ -15,11 +15,11 @@ uint8_t httpRecvBuffer[512];
 
 
 /**
-  * @brief  浠巗ocket缂撳瓨涓��鍙栦竴琛宧ttp鏁版嵁
-	* @param  sock:    宸茬粡杩炴帴鍒版湇鍔″櫒鐨剆ock缂栧彿
-	* @param  buf:     淇濆瓨鏁版嵁鐨刡uffer
-	* @param  size:    buf的最大可用长度
-	* @retval 璇诲彇鍒扮殑鏁版嵁鐨勯暱搴︼紝鍖呮嫭涓や釜瀛楄妭鐨勬崲琛岀�
+  * @brief  从socket缓存中读取一行http数据
+	* @param  sock:    已经连接到服务器的sock编号
+	* @param  buf:     保存数据的buffer
+	* @param  size:    buf的最大可用长度
+	* @retval 读取到的数据的长度,包括两个字节的换行符
   */
 int http_getLine(int sock, uint8_t *buf, int size)
 {
@@ -35,13 +35,13 @@ int http_getLine(int sock, uint8_t *buf, int size)
 	 }
 	 buf[i] = '\0';
  
-	 return i;  //返回读取的到的数据长度
+	 return i;  //返回读取的到的数据长度
 }
 
 /**
-  * @brief  解析http响应行
-	* @param  pbuf:  鍝嶅簲琛岀殑鏁版嵁
-* @retval 其他值: 返回http请求状态   -1: 解析失败
+  * @brief  解析http响应行
+	* @param  pbuf:  响应行的数据
+* @retval 其他值: 返回http请求状态   -1: 解析失败
   */
 int http_parseRequestLine(uint8_t *pbuf)
 {
@@ -61,11 +61,11 @@ int http_parseRequestLine(uint8_t *pbuf)
 }
 
 /**
-  * @brief  DNS瑙f瀽鍥炶皟鍑芥暟
-  * @note   鍦ㄨВ鏋愬煙鍚嶆垚鍔熷悗锛屼細璋冪敤杩欎釜鍑芥暟锛岀劧鍚庡彲浠ヨ�鍙栧埌瀵瑰簲鐨処P鍦板潃
-  * @param  name:         鍩熷悕
-  * @param  host_ip:      鍩熷悕瀵瑰簲鐨刬p鍦板潃
-  * @param  callback_arg: 浼犻€掔殑鍙傛暟
+  * @brief  DNS解析回调函数
+  * @note   在解析域名成功后,会调用这个函数,然后可以读取到对应的IP地址
+  * @param  name:         域名
+  * @param  host_ip:      域名对应的ip地址
+  * @param  callback_arg: 传递的参数
   * @retval None
   */
 void http_dns_found(const char *name, ip_addr_t *host_ip, void *callback_arg)
@@ -75,12 +75,12 @@ void http_dns_found(const char *name, ip_addr_t *host_ip, void *callback_arg)
 }
 
 /**
-  * @brief  杩炴帴鍒癶ttp鏈嶅姟鍣ㄧ殑鍑芥暟
-	* @note   连接到http服务器
-  * @param  host:     鏈嶅姟鍣ㄧ殑鍩熷悕鎴栬€卛p鍦板潃
-	* @param  port:     鏈嶅姟鍣ㄧ�鍙e彿
-	* @param  hostIsIp: host代表的是 域名,还是ip地址  0: host为域名  1: host为ip地址
-	* @retval -1:连接服务器失败  -2: 域名解析失败  >=0: 连接成功,返回值为 sock编号
+  * @brief  连接到http服务器的函数
+	* @note   连接到http服务器
+  * @param  host:     服务器的域名或者ip地址
+	* @param  port:     服务器端口号
+	* @param  hostIsIp: host代表的是 域名,还是ip地址  0: host为域名  1: host为ip地址
+	* @retval -1:连接服务器失败  -2: 域名解析失败  >=0: 连接成功,返回值为 sock编号
   */
 int http_clientConnectToServer(char *host, int port, int hostIsIp)
 {
@@ -89,14 +89,14 @@ int http_clientConnectToServer(char *host, int port, int hostIsIp)
 	int sock = socket(AF_INET, SOCK_STREAM, 0);
 	if(sock < 0) return -2;	
 
-	//濡傛灉浼犲叆鐨刪ost鍙傛暟鏄�煙鍚嶏紝瑙f瀽鍩熷悕
+	//如果传入的host参数是域名,解析域名
 	if(hostIsIp == 0)
 	{
 		ip_addr_t addr;	
 		
     addr.addr = 0;
 		dns_gethostbyname(host, &addr, http_dns_found, &addr);
-		//绛夊緟dns瑙f瀽瀹屾垚
+		//等待dns解析完成
 		timeout = 0;
 		while((addr.addr == 0) && (timeout < 2000)) 
 		{
@@ -116,14 +116,14 @@ int http_clientConnectToServer(char *host, int port, int hostIsIp)
 	serverAddr.sin_port = htons(port);	
   memset(&serverAddr.sin_zero, 0, sizeof(serverAddr.sin_zero));
 	
-	//连接服务器
+	//连接服务器
 	if(connect(sock, (struct sockaddr*)&serverAddr, sizeof(serverAddr)) != 0)
 	{
 		HTTP_PRINTF("connect server error \r\n");
 		return -1;
 	}
 	
-	//璁剧疆鎺ユ敹鏁版嵁瓒呮椂鏃堕棿
+	//设置接收数据超时时间
 	timeout = 3000;
 	setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, &timeout, sizeof(int));	
 	
@@ -133,8 +133,8 @@ int http_clientConnectToServer(char *host, int port, int hostIsIp)
 }
 
 /**
-  * @brief  鍏抽棴socket绔�彛
-	* @param  sock:    宸茬粡杩炴帴鍒版湇鍔″櫒鐨剆ock缂栧彿
+  * @brief  关闭socket端口
+	* @param  sock:    已经连接到服务器的sock编号
   */
 void http_clientClose(int sock)
 {
@@ -143,24 +143,24 @@ void http_clientClose(int sock)
 
 
 /**
-  * @brief  杩炴帴鍒板彂閫丟ET璇锋眰
-	* @note   组装GET数据包,并将GET请求发送出去
-	* @param  sock:    宸茬粡杩炴帴鍒版湇鍔″櫒鐨剆ock缂栧彿
-  * @param  host:    鏈嶅姟鍣ㄧ殑鍩熷悕鎴栬€卛p鍦板潃
-	* @param  url:     璇锋眰璧勬簮鐨勫湴鍧€
-	* @retval -1: 发送请求失败 1:发送成功
+  * @brief  连接到发送GET请求
+	* @note   组装GET数据包,并将GET请求发送出去
+	* @param  sock:    已经连接到服务器的sock编号
+  * @param  host:    服务器的域名或者ip地址
+	* @param  url:     请求资源的地址
+	* @retval -1: 发送请求失败 1:发送成功
   */
 int http_clientPacketRequest_GET(int sock, char *host, char *url)
 {
 	int len;
 	
 	memset(httpSendBuffer, 0, sizeof(httpSendBuffer));
-	//组建请求行
+	//组建请求行
 	sprintf((char *)httpSendBuffer, "GET ");
 	if(url == NULL) strcat((char *)httpSendBuffer, "/");
 	else            strcat((char *)httpSendBuffer, url); 
 	strcat((char *)httpSendBuffer, " HTTP/1.1\r\n");
-	//缁勫缓璇锋眰澶撮儴 
+	//组建请求头部 
 	strcat((char *)httpSendBuffer, "Host: ");
 	strcat((char *)httpSendBuffer, host);	
 	strcat((char *)httpSendBuffer, "\r\n");
@@ -168,12 +168,12 @@ int http_clientPacketRequest_GET(int sock, char *host, char *url)
 	strcat((char *)httpSendBuffer, "Accept: application/json\r\n");
 	strcat((char *)httpSendBuffer, "User-Agent: stm32f207\r\n");		
 	strcat((char *)httpSendBuffer, "Cache-Control: no-cache\r\n");	
-	//娣诲姞涓€涓�┖鐧借�
+	//添加一个空白行
 	strcat((char *)httpSendBuffer, "\r\n"); 
 	len = strlen((char *)httpSendBuffer);
 	HTTP_PRINTF("%s", (char *)httpSendBuffer);	 //
 	
-	//发送请求报文
+	//发送请求报文
 	len = write(sock, httpSendBuffer, len);  
 	if(len <= 0) 
 	{
@@ -185,35 +185,35 @@ int http_clientPacketRequest_GET(int sock, char *host, char *url)
 
 /**
   * @brief  http_clientReadResponse_GET
-	* @note   绛夊緟鏈嶅姟鍣ㄨ繑鍥濭ET鍝嶅簲
-	* @param  sock:    宸茬粡杩炴帴鍒版湇鍔″櫒鐨剆ock缂栧彿
-	* @retval -1: 发送请求失败 1:发送成功
+	* @note   等待服务器返回GET响应
+	* @param  sock:    已经连接到服务器的sock编号
+	* @retval -1: 发送请求失败 1:发送成功
   */
 int http_clientReadResponse_GET(int sock, uint8_t *pbuf, int *datlen)
 {
 	int len, ret;
 	int length = 0;
 	
-	//读取响应行
+	//读取响应行
 	len = http_getLine(sock, httpRecvBuffer, sizeof(httpRecvBuffer));	
 	if(len <= 0) return -1;
 	HTTP_PRINTF("%s", (char *)httpRecvBuffer);
 	
 	ret = http_parseRequestLine(httpRecvBuffer);
 	
-	//读取响应头
+	//读取响应头
 	do
 	{
 		len = http_getLine(sock, httpRecvBuffer, sizeof(httpRecvBuffer));		
 		HTTP_PRINTF("%s", (char *)httpRecvBuffer);
 		if(len <= 2) 
 		{
-			if(len == 2) break;     //璇诲彇鍒颁簡绌鸿�
+			if(len == 2) break;     //读取到了空行
 			else         return -1;
 		}
 	}while(len > 0);
 	
-	//璇诲彇鍝嶅簲涓讳綋鍐呭�
+	//读取响应主体内容
 	length = 0;
 	do
 	{
@@ -232,13 +232,13 @@ int http_clientReadResponse_GET(int sock, uint8_t *pbuf, int *datlen)
 
 /*
 * @brief  http_clientPacketRequest_POST
-* @note   缁勫缓鍜屽彂閫丳OST璇锋眰澶存暟鎹�寘
-* @param  sock:     宸茬粡杩炴帴鍒版湇鍔″櫒鐨剆ock缂栧彿
-* @param  host:     鏈嶅姟鍣ㄥ煙鍚嶆垨鑰匢P鍦板潃
-* @param  url:      请求的资源位置 
-* @param  pbuf:     需要post的数据缓存
-* @param  datalen   需要post的数据长度
-* @retval           -1: 发送失败 1:发送成功
+* @note   组建和发送POST请求头数据包
+* @param  sock:     已经连接到服务器的sock编号
+* @param  host:     服务器域名或者IP地址
+* @param  url:      请求的资源位置 
+* @param  pbuf:     需要post的数据缓存
+* @param  datalen   需要post的数据长度
+* @retval           -1: 发送失败 1:发送成功
 */
 
 char httpTmpBuffer[64];
@@ -247,13 +247,13 @@ int http_clientPacketRequest_POST(int sock, char *host, char *url, int datalen)
 	int len;
 	
 	memset(httpSendBuffer, 0, sizeof(httpSendBuffer));
-	//组建请求行
+	//组建请求行
 	sprintf((char *)httpSendBuffer, "POST ");
 	if(url == NULL) strcat((char *)httpSendBuffer, "/");
 	else            strcat((char *)httpSendBuffer, url); 
 	strcat((char *)httpSendBuffer, " HTTP/1.1\r\n");
 	
-	//缁勫缓璇锋眰澶撮儴
+	//组建请求头部
 	memset(httpTmpBuffer, 0, sizeof(httpTmpBuffer));
 	sprintf(httpTmpBuffer, "Host: %s\r\n", host);
 	strcat((char *)httpSendBuffer, httpTmpBuffer);
@@ -265,13 +265,13 @@ int http_clientPacketRequest_POST(int sock, char *host, char *url, int datalen)
 	memset(httpTmpBuffer, 0, sizeof(httpTmpBuffer));
 	sprintf(httpTmpBuffer, "Content-Length: %d\r\n", datalen);   
 	strcat((char *)httpSendBuffer, httpTmpBuffer);
-	//娣诲姞涓€涓�┖鐧借�
+	//添加一个空白行
 	strcat((char *)httpSendBuffer, "\r\n"); 
 	
 	len = strlen((char *)httpSendBuffer);
 	HTTP_PRINTF("%s", (char *)httpSendBuffer);	
 
-	//发送请求报文
+	//发送请求报文
 	len = write(sock, httpSendBuffer, len);  
 	if(len <= 0) 
 	{
@@ -284,11 +284,11 @@ int http_clientPacketRequest_POST(int sock, char *host, char *url, int datalen)
 
 /*
 * @brief  http_clientPacketBody_POST
-* @note   鍙戦€乸ost鏁版嵁
-* @param  sock:     宸茬粡杩炴帴鍒版湇鍔″櫒鐨剆ock缂栧彿
-* @param  pbuf:     需要post的数据缓存
-* @param  datalen   需要post的数据长度
-* @retval           -1: 发送失败 1:发送成功
+* @note   发送post数据
+* @param  sock:     已经连接到服务器的sock编号
+* @param  pbuf:     需要post的数据缓存
+* @param  datalen   需要post的数据长度
+* @retval           -1: 发送失败 1:发送成功
 */
 int http_clientPacketBody_POST(int sock, uint8_t *pbuf, int datalen)
 {
@@ -320,35 +320,35 @@ int http_clientPacketBody_POST(int sock, uint8_t *pbuf, int datalen)
 
 /*
 * @brief  http_clientReadResponse_POST
-* @note   读取和解析POST返回的响应
-* @param  sock:     宸茬粡杩炴帴鍒版湇鍔″櫒鐨剆ock缂栧彿
-* @retval 响应的返回值
+* @note   读取和解析POST返回的响应
+* @param  sock:     已经连接到服务器的sock编号
+* @retval 响应的返回值
 */
 int http_clientReadResponse_POST(int sock, uint8_t *pbuf, int *datlen)
 {
 	int len, ret;
 	int length = 0;
 	
-	//读取响应行
+	//读取响应行
 	len = http_getLine(sock, httpRecvBuffer, sizeof(httpRecvBuffer));	
 	if(len <= 0) return -1;
 	HTTP_PRINTF("%s", (char *)httpRecvBuffer);
 	
 	ret = http_parseRequestLine(httpRecvBuffer);
 	
-	//读取响应头
+	//读取响应头
 	do
 	{
 		len = http_getLine(sock, httpRecvBuffer, sizeof(httpRecvBuffer));		
 		HTTP_PRINTF("%s", (char *)httpRecvBuffer);
 		if(len <= 2) 
 		{
-			if(len == 2) break;     //璇诲彇鍒颁簡绌鸿�
+			if(len == 2) break;     //读取到了空行
 			else         return -1;
 		}
 	}while(len > 0);	
 	
-	//璇诲彇鍝嶅簲涓讳綋鍐呭�
+	//读取响应主体内容
 	length = 0;
 	do
 	{
@@ -368,14 +368,14 @@ int http_clientReadResponse_POST(int sock, uint8_t *pbuf, int *datlen)
 
 /*
 * @brief  http_clientGet
-* @note   瀹㈡埛绔�彂閫丟ET璇锋眰
-* @param  host:     鏈嶅姟鍣ㄧ殑鍩熷悕鎴栬€匢P鍦板潃
-* @param  url:      璁块棶鏈嶅姟鍣ㄨ祫婧愮殑浣嶇疆
-* @param  port:     服务器的端口号
-* @param  hostIsIp: 绗�竴涓�弬鏁版槸鍩熷悕杩樻槸ip鍦板潃   0:鍩熷悕  1: ip鍦板潃
-* @param  pbuf:     鎺ユ敹鏈嶅姟鍣ㄥ搷搴旂殑鏁版嵁
-* @param  datalen:  鏈嶅姟鍣ㄥ搷搴旀暟鎹�殑闀垮害
-* @retval 负值: GET请求异常, 正值: http协议的返回码
+* @note   客户端发送GET请求
+* @param  host:     服务器的域名或者IP地址
+* @param  url:      访问服务器资源的位置
+* @param  port:     服务器的端口号
+* @param  hostIsIp: 第一个参数是域名还是ip地址   0:域名  1: ip地址
+* @param  pbuf:     接收服务器响应的数据
+* @param  datalen:  服务器响应数据的长度
+* @retval 负值: GET请求异常, 正值: http协议的返回码
 */
 int http_clientGet(char *host, char *url, uint16_t port, uint8_t hostIsIp, uint8_t *pbuf, int *datalen)
 {
@@ -399,16 +399,16 @@ __httpError:
 
 /*
 * @brief  http_clientGet
-* @note   瀹㈡埛绔�彂閫丟ET璇锋眰
-* @param  host:     鏈嶅姟鍣ㄧ殑鍩熷悕鎴栬€匢P鍦板潃
-* @param  url:      璁块棶鏈嶅姟鍣ㄨ祫婧愮殑浣嶇疆
-* @param  port:     服务器的端口号
-* @param  hostIsIp: 绗�竴涓�弬鏁版槸鍩熷悕杩樻槸ip鍦板潃   0:鍩熷悕  1: ip鍦板潃
-* @param  postbuf:  闇€瑕佸彂寰€鏈嶅姟鍣ㄧ殑鏁版嵁
-* @param  postlen:  鍙戦€佹暟鎹�殑闀垮害
-* @param  rtnbuf:     鎺ユ敹鏈嶅姟鍣ㄥ搷搴旂殑鏁版嵁
-* @param  rtnlen:  鏈嶅姟鍣ㄥ搷搴旀暟鎹�殑闀垮害
-* @retval 负值: GET请求异常, 正值: http协议的返回码
+* @note   客户端发送GET请求
+* @param  host:     服务器的域名或者IP地址
+* @param  url:      访问服务器资源的位置
+* @param  port:     服务器的端口号
+* @param  hostIsIp: 第一个参数是域名还是ip地址   0:域名  1: ip地址
+* @param  postbuf:  需要发往服务器的数据
+* @param  postlen:  发送数据的长度
+* @param  rtnbuf:     接收服务器响应的数据
+* @param  rtnlen:  服务器响应数据的长度
+* @retval 负值: GET请求异常, 正值: http协议的返回码
 */
 int http_clientPost(char *host, char *url, uint16_t port, uint8_t hostIsIp, uint8_t *postbuf, int postlen, uint8_t *rtnbuf, int *rtnlen)
 {

+ 58 - 0
app/System/source/log.c

@@ -0,0 +1,58 @@
+
+#include "log.h"
+#include "usart.h"
+#include <stdarg.h>
+#include <stdio.h>
+#include "Freertos.h"
+#include "semphr.h"
+
+#include "main.h"
+#include "udp.h"
+
+
+static SemaphoreHandle_t logMutex;
+void LogPrint(logLevel_t logLevel,const char *file, const char *func, const int line, char * fmt, ...)
+{
+	if (xSemaphoreTake(logMutex, 1000))
+	{
+		udp_log_start();
+		va_list args;
+		va_start(args, fmt);
+		char buf[LOG_LEN_MAX];
+		vsnprintf(buf, sizeof(buf), fmt, args);
+		va_end(args);
+		char *p=pvPortMalloc(1024);
+			switch (logLevel)
+			{
+		#ifdef _LOG_INFO
+				case LOG_INFO:
+					sprintf(p,"[%s][%s][%s:%4d] %s\r\n", "INFO",file,func, line, buf);
+					break;
+		#endif
+		#ifdef _LOG_DEBUG
+				case LOG_DEBUG:
+					sprintf(p,"[%s][%s][%s:%4d] %s\r\n", "DEBUG",file, func, line, buf);
+					break;
+		#endif
+		#ifdef _LOG_WARN
+				case LOG_WARN:
+					sprintf(p,"[%s][%s][%s:%4d] %s\r\n", "WARN", file,func, line, buf);
+					break;
+		#endif
+				case LOG_ERROR:
+					sprintf(p,"[%s][%s][%s:%4d] %s\r\n", "ERROR",file, func, line, buf);
+					break;
+				default:
+					break;
+			}
+			udp_send_printf(p);
+			vPortFree(p);
+			udp_log_close();
+			xSemaphoreGive(logMutex);
+		}
+}
+
+void log_init()
+{
+	logMutex = xSemaphoreCreateMutex();//´´½¨Ò»¸ölog»¥³âÁ¿
+}

+ 62 - 78
app/System/source/sys_mqtt.c

@@ -11,78 +11,75 @@
 #include "mqtt_log.h"
 #include "sys_mqtt.h"
 
-
 static void mqtt_publish_task(void *arg);
 /*
-*接收并处理mqtt订阅消息
-*/
-static void topic1_handler(void* client, message_data_t* msg)
+ *接收并处理mqtt订阅消息
+ */
+static void topic1_handler(void *client, message_data_t *msg)
 {
-    (void) client;
-    MQTT_LOG_I("-----------------------------------------------------------------------------------");
-    MQTT_LOG_I("%s:%d %s()...\ntopic: %s\nmessage:%s", __FILE__, __LINE__, __FUNCTION__, msg->topic_name, (char*)msg->message->payload);
-    MQTT_LOG_I("-----------------------------------------------------------------------------------");
+	(void)client;
+	MQTT_LOG_I("topic: %s\nmessage:%s", msg->topic_name, (char *)msg->message->payload);
 }
 /*
-*初始化mqtt连接
-*/
-int8_t mqtt_init(mqtt_client_t *client,char *clientId,char *user_name,char *password,char *ip,char *port,uint16_t keepAlive)
+ *初始化mqtt连接
+ */
+int8_t mqtt_init(mqtt_client_t *client, char *clientId, char *user_name, char *password, char *ip, char *port, uint16_t keepAlive)
 {
-		mqtt_set_client_id(client,clientId);
-    mqtt_set_port(client, port);
-    mqtt_set_host(client, ip);
-    mqtt_set_user_name(client, user_name);
-    mqtt_set_password(client, password);
-    mqtt_set_clean_session(client, 1);
-		mqtt_set_keep_alive_interval(client,keepAlive);
-		return mqtt_connect(client);
+	mqtt_set_client_id(client, clientId);
+	mqtt_set_port(client, port);
+	mqtt_set_host(client, ip);
+	mqtt_set_user_name(client, user_name);
+	mqtt_set_password(client, password);
+	mqtt_set_clean_session(client, 1);
+	mqtt_set_keep_alive_interval(client, keepAlive);
+	return mqtt_connect(client);
 }
-//发送数据队列句柄
+// 发送数据队列句柄
 QueueHandle_t xQueue1;
 void mqtt_task_creat()
 {
-	mqtt_client_t *client = NULL;//创建一个客户端
-  mqtt_log_init();
-  client = mqtt_lease();
+	mqtt_client_t *client = NULL; // 创建一个客户端
+	mqtt_log_init();
+	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, 2, NULL);
+	xQueue1 = xQueueCreate(10, sizeof(struct Pub_Queue *)); // 创建一个mqtt上传的队列
+	xTaskCreate(mqtt_publish_task, "mqtt_publish_task", 1024, client, 4, NULL);
 }
 
 static void mqtt_publish_task(void *arg)
 {
-    mqtt_client_t *client = (mqtt_client_t *)arg;
-		while(1)
+	mqtt_client_t *client = (mqtt_client_t *)arg;
+	while (1)
+	{
+		LogPrint(LOG_INFO,__FILE__,__FUNCTION__,__LINE__,"HELLO");
+//		int rc = mqtt_init(client, "client_id_001", NULL, NULL, "36.134.23.11", "1883", 1000);
+		vTaskDelay(100);
+	}
+	mqtt_subscribe(client, "sub_topic_task", QOS0, topic1_handler);
+	mqtt_message_t msg;
+	memset(&msg, 0, sizeof(msg));
+
+	mqtt_list_subscribe_topic(client);
+	struct Pub_Queue *pxMessage;
+	while (1)
+	{
+		if (xQueue1 != 0)
 		{
-			  int rc=mqtt_init(client,"client_id_001",NULL,NULL,"36.134.23.11","1883",1000);
-				vTaskDelay(100);
+			if (xQueueReceive(xQueue1, &(pxMessage), (TickType_t)10))
+			{
+				// 处理队列内部数据并上传
+				msg.payloadlen = pxMessage->pubLength;
+				msg.qos = pxMessage->qos;
+				msg.payload = (void *)pxMessage->message;
+				mqtt_publish(client, pxMessage->pub_topic, &msg);
+
+				vPortFree(pxMessage->message);
+				vPortFree(pxMessage->pub_topic);
+				vPortFree(pxMessage);
+			}
 		}
-		mqtt_subscribe(client,"sub_topic_task", QOS0, topic1_handler);
-    mqtt_message_t msg;
-    memset(&msg, 0, sizeof(msg));
-	
-    mqtt_list_subscribe_topic(client);
-		struct Pub_Queue *pxMessage;
-    while(1) {
-				if(xQueue1 !=0)
-				{
-					if(xQueueReceive(xQueue1,&(pxMessage),( TickType_t )10))
-					{
-						//处理队列内部数据并上传
-						msg.payloadlen=pxMessage->pubLength;
-						msg.qos=pxMessage->qos;
-						msg.payload=(void *)pxMessage->message;
-						mqtt_publish(client,pxMessage->pub_topic,&msg);
-						
-						vPortFree(pxMessage->message);
-						vPortFree(pxMessage->pub_topic);
-						vPortFree(pxMessage);
-					}
-				}
-				vTaskDelay(100);
-    }
+		vTaskDelay(100);
+	}
 }
 /*
  *  函数名:void mqtt_publish_data(uint8_t *payload,mqtt_qos_t qos,uint16_t pub_length,char *topic)
@@ -92,29 +89,16 @@ static void mqtt_publish_task(void *arg)
  *  函数作用:向队列中写入mqtt上传的消息
  *  TODO:队列满无法写入的情况处理
  */
-void mqtt_publish_data(uint8_t *payload,mqtt_qos_t qos,uint16_t pub_length,char *topic)
+void mqtt_publish_data(uint8_t *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));
-	memcpy(pxMessage->message,payload,pub_length);
-	
-	pxMessage->pub_topic=pvPortMalloc(strlen(topic)+1);
-	memset(pxMessage->pub_topic,0,(strlen(topic)+1));	
-	strcpy(pxMessage->pub_topic,topic);
-
-	xQueueSend( xQueue1, (void *)&pxMessage, ( TickType_t ) 0 );
-}
-
-
-
-
-
-
-
-
-
-
-
+	struct Pub_Queue *pxMessage = pvPortMalloc(sizeof(struct Pub_Queue));
+	pxMessage->message = pvPortMalloc(pub_length + 1);
+	memset(pxMessage->message, 0, (pub_length + 1));
+	memcpy(pxMessage->message, payload, pub_length);
 
+	pxMessage->pub_topic = pvPortMalloc(strlen(topic) + 1);
+	memset(pxMessage->pub_topic, 0, (strlen(topic) + 1));
+	strcpy(pxMessage->pub_topic, topic);
 
+	xQueueSend(xQueue1, (void *)&pxMessage, (TickType_t)0);
+}

+ 71 - 0
app/System/source/tcp_server.c

@@ -0,0 +1,71 @@
+#include "lwip/opt.h"
+#include "lwip/sys.h"
+#include "tcp_server.h"
+#include <string.h>
+#include <stdio.h>
+#include "gd32f30x.h"
+#include "main.h"
+#include "lwip/tcp.h"
+#include "lwip/memp.h"
+#include "lwip/api.h"
+#include "sockets.h"
+#include "log.h"
+
+void tcp_server_task(void *pvParameters)
+{
+    int ret,sockfd;
+    struct sockaddr_in tcpServerSock;
+    struct sockaddr_in client_sock;
+    tcpServerSock.sin_family = AF_INET;
+		inet_aton("192.168.2.222",&(tcpServerSock.sin_addr));
+//    tcpServerSock.sin_addr.s_addr = htonl(IPADDR_ANY);
+    tcpServerSock.sin_port = htons(8080);
+tcp_server_begin:
+    sockfd = socket(AF_INET, SOCK_STREAM, 0);
+    if (sockfd < 0)
+    {
+        goto tcp_server_begin;
+    }
+    ret = bind(sockfd, (struct sockaddr *)&tcpServerSock, sizeof(tcpServerSock));
+    if (ret < 0)
+    {
+        lwip_close(sockfd);
+        sockfd = -1;
+        goto tcp_server_begin;
+    }
+    ret = listen(sockfd, 10);
+    if (ret < 0)
+    {
+        lwip_close(sockfd);
+        sockfd = -1;
+        goto tcp_server_begin;
+    }
+		
+		
+		
+		
+		
+		
+    while (1)
+    {
+				vTaskDelay(1000);
+        socklen_t len = sizeof(client_sock);
+        int client_socket = accept(sockfd, (struct sockaddr*)&client_sock,&len);
+        if (client_socket<0)
+        {
+            printf("error");
+        }
+//        LogPrint(LOG_INFO,);
+    }
+    
+}
+/*!
+    \brief      initialize the tcp_client application
+    \param[in]  none
+    \param[out] none
+    \retval     none
+*/
+void tcp_server_init(void)
+{
+    xTaskCreate(tcp_server_task, "TCP_CLIENT", DEFAULT_THREAD_STACKSIZE, NULL, 1, NULL);
+}

+ 14 - 20
app/USR/source/udp_echo.c

@@ -39,7 +39,7 @@ OF SUCH DAMAGE.
 #include "lwip/opt.h"
 #include "lwip/tcp.h"
 #include "lwip/sys.h"
-#include "udp_echo.h"  
+#include "udp.h"  
 #include <string.h>
 #include <stdio.h>
 #include "gd32f30x.h"
@@ -149,8 +149,6 @@ static void udp_task(void *arg)
 #endif /* ((LWIP_SOCKET == 0) && (LWIP_NETCONN == 1)) */
 
 
-
-#if LWIP_SOCKET
 #include "lwip/sockets.h"
 
 /*!
@@ -164,7 +162,7 @@ volatile int8_t sockfd=-1;
 #define UDP_REMOTE_PORT 54321
 #define SERCER_IP_ADDRESS "192.168.2.22"       //½ÓÊÕ·þÎñÆ÷ip
 struct sockaddr_in remote_addr;
-static int udp()
+int udp_log_start()
 {
 	int ret;
 	struct sockaddr_in local_addr;
@@ -188,29 +186,18 @@ static int udp()
 	remote_addr.sin_family=AF_INET;
 	remote_addr.sin_port=htons(UDP_REMOTE_PORT);
 	inet_aton(SERCER_IP_ADDRESS,&(remote_addr.sin_addr));
+	return 1;
+	
 exit:
 			return -1;
 }
 
-
-
-#endif /* LWIP_SOCKET */
-
-
-/*!
-    \brief      initialize the udp_echo application
-    \param[in]  none
-    \param[out] none
-    \retval     none
-*/
-void udp_echo_init(void)
+void udp_log_close()
 {
-    //xTaskCreate(udp, "UDP", DEFAULT_THREAD_STACKSIZE, NULL, UDP_TASK_PRIO, NULL);
-		udp();	
+	lwip_close(sockfd);
+	sockfd=-1;
 }
 
-
-
 int fputc(int ch, FILE *f)
 {
 	if(sockfd>=0)
@@ -219,3 +206,10 @@ int fputc(int ch, FILE *f)
     return ch;
 	}
 }
+int udp_send_printf(char *p)
+{
+	if(sockfd>=0)
+	{
+		sendto(sockfd, p, strlen(p), 0, (struct sockaddr *)&remote_addr,sizeof(remote_addr));
+	}
+}

+ 3 - 2
app/USR/include/udp_echo.h

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

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

@@ -82,7 +82,7 @@ extern uint32_t SystemCoreClock;
 #define configTICK_RATE_HZ                            ( ( TickType_t ) 1000 )
 #define configMAX_PRIORITIES                          ( 6 )
 #define configMINIMAL_STACK_SIZE                      ( ( unsigned short ) 128 )
-#define configTOTAL_HEAP_SIZE                         ( ( size_t ) ( 30 * 1024 ) )
+#define configTOTAL_HEAP_SIZE                         ( ( size_t ) ( 50 * 1024 ) )
 #define configMAX_TASK_NAME_LEN                       ( 16 )
 #define configUSE_16_BIT_TICKS                        0
 #define configIDLE_SHOULD_YIELD                       1

+ 2 - 2
app/USR/include/main.h

@@ -15,7 +15,7 @@
 #include "gd32f30x.h"
 #include "stdint.h"
 #include "hd_eth.h"
-
-
+#include "FreeRTOS.h"
+//SemaphoreHandle_t logMutex;
 
 #endif /* MAIN_H */

+ 29 - 24
app/USR/source/gd32f30x_it.c

@@ -1,6 +1,6 @@
 /*!
     \file  gd32f30x_it.c
-    \brief interrupt service routines 
+    \brief interrupt service routines
 
     \version 2017-02-10, V1.0.0, firmware for GD32F30x
     \version 2018-10-10, V1.1.0, firmware for GD32F30x
@@ -12,27 +12,27 @@
 
     All rights reserved.
 
-    Redistribution and use in source and binary forms, with or without modification, 
+    Redistribution and use in source and binary forms, with or without modification,
 are permitted provided that the following conditions are met:
 
-    1. Redistributions of source code must retain the above copyright notice, this 
+    1. Redistributions of source code must retain the above copyright notice, this
        list of conditions and the following disclaimer.
-    2. Redistributions in binary form must reproduce the above copyright notice, 
-       this list of conditions and the following disclaimer in the documentation 
+    2. Redistributions in binary form must reproduce the above copyright notice,
+       this list of conditions and the following disclaimer in the documentation
        and/or other materials provided with the distribution.
-    3. Neither the name of the copyright holder nor the names of its contributors 
-       may be used to endorse or promote products derived from this software without 
+    3. Neither the name of the copyright holder nor the names of its contributors
+       may be used to endorse or promote products derived from this software without
        specific prior written permission.
 
-    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 
-AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 
-WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. 
-IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, 
-INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT 
-NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR 
-PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, 
-WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 
-ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY 
+    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
+INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
+WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
 OF SUCH DAMAGE.
 */
 
@@ -66,7 +66,8 @@ void NMI_Handler(void)
 void HardFault_Handler(void)
 {
     /* if Hard Fault exception occurs, go to infinite loop */
-    while (1){
+    while (1)
+    {
     }
 }
 
@@ -79,7 +80,8 @@ void HardFault_Handler(void)
 void MemManage_Handler(void)
 {
     /* if Memory Manage exception occurs, go to infinite loop */
-    while (1){
+    while (1)
+    {
     }
 }
 
@@ -92,7 +94,8 @@ void MemManage_Handler(void)
 void BusFault_Handler(void)
 {
     /* if Bus Fault exception occurs, go to infinite loop */
-    while (1){
+    while (1)
+    {
     }
 }
 
@@ -105,7 +108,8 @@ void BusFault_Handler(void)
 void UsageFault_Handler(void)
 {
     /* if Usage Fault exception occurs, go to infinite loop */
-    while (1){
+    while (1)
+    {
     }
 }
 
@@ -120,7 +124,8 @@ void ENET_IRQHandler(void)
     portBASE_TYPE xHigherPriorityTaskWoken = pdFALSE;
 
     /* frame received */
-    if(SET == enet_interrupt_flag_get(ENET_DMA_INT_FLAG_RS)){ 
+    if (SET == enet_interrupt_flag_get(ENET_DMA_INT_FLAG_RS))
+    {
         /* give the semaphore to wakeup LwIP task */
         xSemaphoreGiveFromISR(g_rx_semaphore, &xHigherPriorityTaskWoken);
     }
@@ -130,7 +135,7 @@ void ENET_IRQHandler(void)
     enet_interrupt_flag_clear(ENET_DMA_INT_FLAG_NI_CLR);
 
     /* switch tasks if necessary */
- //   if(pdFALSE != xHigherPriorityTaskWoken){
-//        portEND_SWITCHING_ISR(xHigherPriorityTaskWoken);
-//    }
+    //   if(pdFALSE != xHigherPriorityTaskWoken){
+    //        portEND_SWITCHING_ISR(xHigherPriorityTaskWoken);
+    //    }
 }

+ 136 - 108
app/USR/source/hello_gigadevice.c

@@ -1,6 +1,6 @@
 /*!
     \file  hello_gigadevice.c
-    \brief TCP server demo program 
+    \brief TCP server demo program
 
     \version 2017-02-10, V1.0.0, firmware for GD32F30x
     \version 2018-10-10, V1.1.0, firmware for GD32F30x
@@ -12,49 +12,47 @@
 
     All rights reserved.
 
-    Redistribution and use in source and binary forms, with or without modification, 
+    Redistribution and use in source and binary forms, with or without modification,
 are permitted provided that the following conditions are met:
 
-    1. Redistributions of source code must retain the above copyright notice, this 
+    1. Redistributions of source code must retain the above copyright notice, this
        list of conditions and the following disclaimer.
-    2. Redistributions in binary form must reproduce the above copyright notice, 
-       this list of conditions and the following disclaimer in the documentation 
+    2. Redistributions in binary form must reproduce the above copyright notice,
+       this list of conditions and the following disclaimer in the documentation
        and/or other materials provided with the distribution.
-    3. Neither the name of the copyright holder nor the names of its contributors 
-       may be used to endorse or promote products derived from this software without 
+    3. Neither the name of the copyright holder nor the names of its contributors
+       may be used to endorse or promote products derived from this software without
        specific prior written permission.
 
-    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 
-AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 
-WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. 
-IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, 
-INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT 
-NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR 
-PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, 
-WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 
-ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY 
+    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
+INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
+WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
 OF SUCH DAMAGE.
 */
 
 #include "lwip/opt.h"
 #include "lwip/tcp.h"
 #include "lwip/sys.h"
-#include "hello_gigadevice.h"  
+#include "hello_gigadevice.h"
 #include <string.h>
 #include <stdio.h>
 #include "gd32f30x.h"
 #include "lwip/api.h"
 
-#define HELLO_TASK_PRIO  ( tskIDLE_PRIORITY + 5 )
-#define MAX_NAME_SIZE      32
+#define HELLO_TASK_PRIO (tskIDLE_PRIORITY + 5)
+#define MAX_NAME_SIZE 32
 
-#define GREETING           "\n\r======= HelloGigaDevice =======\
+#define GREETING "\n\r======= HelloGigaDevice =======\
                             \n\r== GD32 ==\
                             \n\r== Telnet SUCCESS==\
                             \n\rHello. What is your name?\r\n"
-#define HELLO              "\n\rGigaDevice¡¾8000¡¿PORT Hello "
-
-
+#define HELLO "\n\rGigaDevice¡¾8000¡¿PORT Hello "
 
 #if ((LWIP_SOCKET == 0) && (LWIP_NETCONN == 1))
 
@@ -62,61 +60,69 @@ static err_t hello_gigadevice_recv(struct netconn *conn, void *data, u16_t len);
 static err_t hello_gigadevice_accept(struct netconn *conn);
 
 /*!
-    \brief      called when a data is received on the telnet connection 
+    \brief      called when a data is received on the telnet connection
     \param[in]  conn: the TCP netconn over which to send data
     \param[in]  data: pointer to the data received
     \param[in]  len: size of the data
     \param[out] none
     \retval     err_t: error value
-*/ 
+*/
 static err_t hello_gigadevice_recv(struct netconn *conn, void *data, u16_t len)
 {
     int done;
     char *c;
     int i;
-  
+
     done = 0;
     c = (char *)data;
     /* a telnet communication packet is ended with an enter key */
-    for(i=0; i<len && !done; i++){ 
+    for (i = 0; i < len && !done; i++)
+    {
         done = ((c[i] == '\r') || (c[i] == '\n'));
-    } 
-    
-    if(done){ 
-        if(c[len-2] != '\r' || c[len-1] != '\n'){
+    }
+
+    if (done)
+    {
+        if (c[len - 2] != '\r' || c[len - 1] != '\n')
+        {
             /* limit the received data length to MAX_NAME_SIZE - 2('\r' and '\n' will be put into the buffer) */
-            if((c[len-1] == '\r' || c[len-1] == '\n') && (len+1 <= MAX_NAME_SIZE)){ 
+            if ((c[len - 1] == '\r' || c[len - 1] == '\n') && (len + 1 <= MAX_NAME_SIZE))
+            {
                 /* calculate the buffer size to be sent(including '\r' and '\n') */
                 len += 1;
-            }else if(len+2 <= MAX_NAME_SIZE){ 
+            }
+            else if (len + 2 <= MAX_NAME_SIZE)
+            {
                 len += 2;
-            }else{  
+            }
+            else
+            {
                 len = MAX_NAME_SIZE;
             }
             /* save the received data to a new buffer */
-            c[len-2] = '\r';
-            c[len-1] = '\n';
+            c[len - 2] = '\r';
+            c[len - 1] = '\n';
         }
         netconn_write(conn, (void *)&HELLO, sizeof(HELLO), NETCONN_COPY);
         netconn_write(conn, data, len, NETCONN_COPY);
     }
- 
+
     return ERR_OK;
 }
 
 /*!
-    \brief      this function when the telnet connection is established 
+    \brief      this function when the telnet connection is established
     \param[in]  conn: the TCP netconn over which to send data
     \param[out] none
     \retval     err_t: error value
 */
 static err_t hello_gigadevice_accept(struct netconn *conn)
-{     
+{
     u32_t ipaddress;
     u8_t iptxt[50];
     volatile u8_t iptab[4];
     struct tcp_pcb *pcb;
-  
+
     pcb = conn->pcb.tcp;
     ipaddress = pcb->remote_ip.addr;
 
@@ -126,17 +132,17 @@ static err_t hello_gigadevice_accept(struct netconn *conn)
     iptab[2] = (u8_t)(ipaddress >> 8);
     iptab[3] = (u8_t)(ipaddress);
 
-    sprintf((char*)iptxt, "Telnet:%d.%d.%d.%d   ", iptab[3], iptab[2], iptab[1], iptab[0]);
+    sprintf((char *)iptxt, "Telnet:%d.%d.%d.%d   ", iptab[3], iptab[2], iptab[1], iptab[0]);
 
     /* send out the first message */
     netconn_write(conn, (void *)&iptxt, sizeof(iptxt), NETCONN_COPY);
     netconn_write(conn, (void *)&GREETING, sizeof(GREETING), NETCONN_COPY);
- 
+
     return ERR_OK;
 }
 
 /*!
-    \brief      hello task 
+    \brief      hello task
     \param[in]  arg: user supplied argument
     \param[out] none
     \retval     none
@@ -149,119 +155,139 @@ static void hello_task(void *arg)
     void *data;
     u16_t len;
     err_t recv_err;
-        
+
     LWIP_UNUSED_ARG(arg);
 
     conn = netconn_new(NETCONN_TCP);
-    
-    if(NULL != conn){
+
+    if (NULL != conn)
+    {
         /* bind connection to well known port number 8000 */
         err = netconn_bind(conn, NULL, 8000);
-        
-        if(ERR_OK == err){
-        
+
+        if (ERR_OK == err)
+        {
+
             netconn_listen(conn);
-          
-            while(1){ 
-                 /* grab new connection */
-                 accept_err = netconn_accept(conn, &newconn);
-            
+
+            while (1)
+            {
+                /* grab new connection */
+                accept_err = netconn_accept(conn, &newconn);
+
                 /* process the new connection */
-                if(ERR_OK == accept_err){ 
+                if (ERR_OK == accept_err)
+                {
                     hello_gigadevice_accept(newconn);
-                    
+
                     recv_err = netconn_recv(newconn, &buf);
-                    while (ERR_OK == recv_err){ 
+                    while (ERR_OK == recv_err)
+                    {
 
-                        do{        
+                        do
+                        {
                             netbuf_data(buf, &data, &len);
-                        }while (netbuf_next(buf) >= 0); 
+                        } while (netbuf_next(buf) >= 0);
                         hello_gigadevice_recv(newconn, data, len);
                         netbuf_delete(buf);
 
                         recv_err = netconn_recv(newconn, &buf);
                     }
-                
+
                     /* close connection and discard connection identifier */
                     netconn_close(newconn);
                     netconn_delete(newconn);
                 }
             }
-        }else{
+        }
+        else
+        {
             netconn_delete(newconn);
             printf(" can not bind TCP netconn");
         }
-    }else{
+    }
+    else
+    {
         printf("can not create TCP netconn");
     }
 }
 
 #endif /* ((LWIP_SOCKET == 0) && (LWIP_NETCONN == 1)) */
 
-
-
 #if LWIP_SOCKET
 #include "lwip/sockets.h"
 
-struct recev_packet 
+struct recev_packet
 {
     int length;
     char bytes[MAX_NAME_SIZE];
     int done;
-}name_recv;
+} name_recv;
 
 static err_t hello_gigadevice_recv(int fd, void *data, int len);
 
 /*!
-    \brief      called when a data is received on the telnet connection 
+    \brief      called when a data is received on the telnet connection
     \param[in]  fd: the socket id which to send data
     \param[in]  data: pointer to the data received
     \param[in]  len: size of the data
     \param[out] none
     \retval     err_t: error value
-*/ 
+*/
 static err_t hello_gigadevice_recv(int fd, void *data, int len)
 {
     char *c;
     int i;
     int done;
-  
+
     done = 0;
     c = (char *)data;
 
-    /* a telnet communication packet is ended with an enter key, 
+    /* a telnet communication packet is ended with an enter key,
        in socket, here is to check whether the last packet is complete */
-    for(i=0; i<len && !done; i++){ 
+    for (i = 0; i < len && !done; i++)
+    {
         done = ((c[i] == '\r') || (c[i] == '\n'));
-    } 
-    
+    }
+
     /* when the packet length received is no larger than MAX_NAME_SIZE */
-    if(0 == name_recv.done){
+    if (0 == name_recv.done)
+    {
         /* havn't received the end of the packet, so the received data length
            is the configured socket reception limit--MAX_NAME_SIZE */
-        if(0 == done){
+        if (0 == done)
+        {
             memcpy(name_recv.bytes, data, MAX_NAME_SIZE);
             name_recv.length = MAX_NAME_SIZE;
-            name_recv.done = 1; 
-        /* have received the end of the packet */  
-        }else{
+            name_recv.done = 1;
+            /* have received the end of the packet */
+        }
+        else
+        {
             memcpy(name_recv.bytes, data, len);
-            name_recv.length = len;        
+            name_recv.length = len;
         }
     }
 
-    if(1 == done){ 
-        if(c[len-2] != '\r' || c[len-1] != '\n'){
+    if (1 == done)
+    {
+        if (c[len - 2] != '\r' || c[len - 1] != '\n')
+        {
             /* limit the received data length to MAX_NAME_SIZE - 2('\r' and '\n' will be put into the buffer) */
-            if((c[len-1] == '\r' || c[len-1] == '\n') && (len+1 <= MAX_NAME_SIZE)){ 
+            if ((c[len - 1] == '\r' || c[len - 1] == '\n') && (len + 1 <= MAX_NAME_SIZE))
+            {
                 /* calculate the buffer size to be sent(including '\r' and '\n') */
                 name_recv.length += 1;
-            }else if(len+2 <= MAX_NAME_SIZE){ 
+            }
+            else if (len + 2 <= MAX_NAME_SIZE)
+            {
                 name_recv.length += 2;
-            }else{  
+            }
+            else
+            {
                 name_recv.length = MAX_NAME_SIZE;
             }
-            
+
             /* save the received data to name_recv.bytes */
             name_recv.bytes[name_recv.length - 2] = '\r';
             name_recv.bytes[name_recv.length - 1] = '\n';
@@ -269,17 +295,16 @@ static err_t hello_gigadevice_recv(int fd, void *data, int len)
 
         send(fd, (void *)&HELLO, sizeof(HELLO), 0);
         send(fd, name_recv.bytes, name_recv.length, 0);
-        
+
         name_recv.done = 0;
         name_recv.length = 0;
     }
- 
+
     return ERR_OK;
 }
 
-
 /*!
-    \brief      hello task 
+    \brief      hello task
     \param[in]  arg: user supplied argument
     \param[out] none
     \retval     none
@@ -291,34 +316,38 @@ static void hello_task(void *arg)
     uint32_t len;
     int tcp_port = 8000;
     int recvnum;
-    struct sockaddr_in svr_addr, clt_addr;        
+    struct sockaddr_in svr_addr, clt_addr;
     char buf[50];
 
     /* bind to port 8000 at any interface */
     svr_addr.sin_family = AF_INET;
     svr_addr.sin_port = htons(tcp_port);
     svr_addr.sin_addr.s_addr = htons(INADDR_ANY);
-  
+
     name_recv.length = 0;
     name_recv.done = 0;
-         
-    while(1){
+
+    while (1)
+    {
         /* create a TCP socket */
         sockfd = socket(AF_INET, SOCK_STREAM, 0);
-        if (sockfd < 0){
-               continue;
+        if (sockfd < 0)
+        {
+            continue;
         }
-        
+
         ret = bind(sockfd, (struct sockaddr *)&svr_addr, sizeof(svr_addr));
-        if (ret < 0){ 
+        if (ret < 0)
+        {
             lwip_close(sockfd);
             sockfd = -1;
             continue;
         }
 
         /* listen for incoming connections (TCP listen backlog = 1) */
-        ret = listen( sockfd, 1 );
-        if (ret < 0){ 
+        ret = listen(sockfd, 1);
+        if (ret < 0)
+        {
             lwip_close(sockfd);
             continue;
         }
@@ -327,14 +356,17 @@ static void hello_task(void *arg)
 
         /* grab new connection */
         newfd = accept(sockfd, (struct sockaddr *)&clt_addr, (socklen_t *)&len);
-        if (-1 != newfd){ 
+        if (-1 != newfd)
+        {
             send(newfd, (void *)&GREETING, sizeof(GREETING), 0);
         }
 
-        while(-1 != newfd){
+        while (-1 != newfd)
+        {
             /* reveive packets, and limit a reception to MAX_NAME_SIZE bytes */
             recvnum = recv(newfd, buf, MAX_NAME_SIZE, 0);
-            if (recvnum <= 0){
+            if (recvnum <= 0)
+            {
                 lwip_close(newfd);
                 newfd = -1;
                 break;
@@ -344,15 +376,11 @@ static void hello_task(void *arg)
 
         lwip_close(sockfd);
         sockfd = -1;
-    }    
+    }
 }
 
-
-
-
 #endif /* LWIP_SOCKET */
 
-
 /*!
     \brief      initialize the hello application
     \param[in]  none
@@ -361,5 +389,5 @@ static void hello_task(void *arg)
 */
 void hello_gigadevice_init(void)
 {
-    xTaskCreate(hello_task, "HELLO", DEFAULT_THREAD_STACKSIZE, NULL, HELLO_TASK_PRIO, NULL);  
+    xTaskCreate(hello_task, "HELLO", DEFAULT_THREAD_STACKSIZE, NULL, HELLO_TASK_PRIO, NULL);
 }

+ 12 - 4
app/USR/source/main.c

@@ -43,7 +43,6 @@ OF SUCH DAMAGE.
 
 #include "hello_gigadevice.h"
 #include "tcp_client.h"
-#include "udp_echo.h"
 #include "led.h"
 #include "usart.h"
 #include "string.h"
@@ -51,9 +50,16 @@ OF SUCH DAMAGE.
 #include <stdlib.h>
 #include "netconf.h"
 #include "sys_mqtt.h"
+#include "tcp_server.h"
+#include "log.h"
 /*
 *freertos优先级管理
-*
+*管理启动流程任务 init_task        	优先级 1
+*freertos时间任务 prvTimerTask     	优先级 2
+*上位机交互任务   tcp_server        优先级 1
+*可能会开启的任务 dhcp_task        	优先级 4
+*mqtt通信任务			mqtt_publish_task 优先级 4
+*以太网输入任务   ethernetif_input 	优先级 5
 */
 #define INIT_TASK_PRIO   ( tskIDLE_PRIORITY + 1 )
 #define DHCP_TASK_PRIO   ( tskIDLE_PRIORITY + 4 )
@@ -66,6 +72,7 @@ void led_task(void * pvParameters);
 void init_task(void * pvParameters);
 
 
+
 /*!
     \brief      main function
     \param[in]  none
@@ -87,6 +94,7 @@ int main(void)
 		{
 			
     }
+		
 }
 
 /*!
@@ -100,7 +108,7 @@ void init_task(void * pvParameters)
 {
     /* configure ethernet (GPIOs, clocks, MAC, DMA) */ 
     enet_system_setup();
-
+		log_init();
     /* initilaize the LwIP stack */
     lwip_stack_init();
     /* initilaize the tcp server: telnet 8000 */
@@ -108,8 +116,8 @@ void init_task(void * pvParameters)
     /* initilaize the tcp client: echo 1026 */
 //    tcp_client_init();
     /* initilaize the udp: echo 1025 */
-   udp_echo_init();
 
+	 tcp_server_init();
 #ifdef USE_DHCP
     /* start DHCP client */
     xTaskCreate(dhcp_task, "DHCP", 512, NULL, DHCP_TASK_PRIO, NULL);

+ 1 - 1
app/mqttclient/common/mqtt_log.h

@@ -9,7 +9,7 @@
 #define _MQTT_LOG_H_
 
 #include "mqtt_defconfig.h"
-
+#include "log.h"
 #ifdef __cplusplus
 extern "C" {
 #endif