LwIP+ STM32+HTTP例程參考
#include <RTL.h>
#include <rtthread.h>
#include <lwip/netdb.h>
#include <lwip/sockets.h>
#include <led.h>
// Http請求內容
static const char send_data[] =
"GET /v1.0/device/1949/sensor/2511/datapoints HTTP/1.1\r\n"
"U-ApiKey:[your apikey]\r\n"
"Host: api.yeelink.net\r\n\r\n";
void tcpclient(const char* host_name, int port)
{
(void)port;
char *recv_data;
int sock, bytes_received;
struct hostent *yeelink_host;
struct in_addr yeelink_ipaddr;
struct sockaddr_in yeelink_sockaddr;
recv_data = rt_malloc(1024);
if (recv_data == RT_NULL)
{
rt_kprintf("No memory\r\n");
return;
}
// 第一步 DNS地址解析
rt_kprintf("calling gethostbyname with: %s\r\n", host_name);
yeelink_host = gethostbyname(host_name);
yeelink_ipaddr.s_addr = *(unsigned long *) yeelink_host->h_addr_list[0];
rt_kprintf("Yeelink IP Address:%s\r\n" , inet_ntoa(yeelink_ipaddr));
yeelink_sockaddr.sin_family = AF_INET;
yeelink_sockaddr.sin_port = htons(80);
yeelink_sockaddr.sin_addr = yeelink_ipaddr;
rt_memset(&(yeelink_sockaddr.sin_zero), 0, sizeof(yeelink_sockaddr.sin_zero));
while(1)
{
// 第二步 建立套接字
if ((sock = socket(AF_INET, SOCK_STREAM, 0)) == -1)
{
rt_kprintf("Socket error\n");
rt_free(recv_data);
return;
}
// 第三步 連線yeelink
if (connect(sock, (struct sockaddr *)&yeelink_sockaddr, sizeof(struct sockaddr)) == -1)
{
rt_kprintf("Connect fail!\n");
lwip_close(sock);
rt_free(recv_data);
return;
}
// 第4步 傳送Http請求
send(sock,send_data,strlen(send_data), 0);
// 第5步 獲得Http響應
bytes_received = recv(sock, recv_data, 1024 - 1, 0);
recv_data[bytes_received] = '\0';
// 響應內容為 {"timestamp":"2013-11-19T08:50:11","value":1}
// 擷取“value”之後的內容
char* actuator_info = rt_strstr( recv_data , "\"value\"");
int offset = rt_strlen("\"value\":");
actuator_status = *(actuator_info + offset);
rt_kprintf("actuator status :%c\r\n",actuator_status);
// 獲得開關狀態,並設定LED指示燈
char actuator_status;
(actuator_status == '1')?rt_hw_led_on(0):rt_hw_led_off(0);
rt_memset(recv_data , 0 , sizeof(recv_data));
// 關閉套接字
closesocket(sock);
// 延時5S之後重新連線
rt_thread_delay( RT_TICK_PER_SECOND * 5 );
}
}
---------------------
作者:Lolwuj
來源:CSDN
原文:https://blog.csdn.net/mikewu_helloworld/article/details/52769650
版權宣告:本文為博主原創文章,轉載請附上博文連結!