向智者致敬华南理工大学无线电爱好者协会软件小组

ESP8266学习笔记(四)

2016-10-17  本文已影响0人  JaydenOnly

通过上次讲了ESP8266的SDK基础开发和之前的介绍,相信大家对这块芯片已经有了比较详细的了解了,这一周我们就来讲讲更深一层的问题——网络开发。

网络通讯协议

网络通信协议是一种网络通用语言,为连接不同操作系统和不同硬件体系结构的互联网络引提供通信支持,是一种网络通用语言。

在单片机开发的项目中,我们一般会用到的是下面几种通讯协议:

TCP接口函数详解

由于TCP协议应用的广泛性和可靠性,所以我采用的是TCP通讯方式,因此这里我只讲TCP协议的开发。

ESP8266的SDK给我们提供的网络函数接口为 espconn 接口,以下所有接口函数都定义在(工程目录\include\espconn.h)
先介绍一个重要的结构体:

<pre><code>struct espconn {
/* espconn的类型 (TCP, UDP) */
enum espconn_type type;
/* espconn目前的模式 */
enum espconn_state state;
union {
esp_tcp *tcp;
esp_udp *udp;
} proto;
/* 与espconn 有关的回调函数 */
espconn_recv_callback recv_callback;
espconn_sent_callback sent_callback;
espconn_handle esp_pcb;
uint8 *ptrbuf;
uint16 cntr;
}; </pre></code>
下面是我们一般会用到的接口函数:

TCP连接

基本的接口函数讲完,就来看看实例吧。
有认真看过我上次教程的读者肯定会发现我在user_set_station_config函数中调用了user_check_ip函数,那么该函数是干什么的呢?下面我就放出源代码:

<pre><code>user_check_ip(void)
{

struct ip_info ipconfig;

//disarm timer first

   os_timer_disarm(&client_timer);

//get ip info of ESP8266 station

   wifi_get_ip_info(STATION_IF, &ipconfig);

if (wifi_station_get_connect_status() ==
STATION_GOT_IP &&

ipconfig.ip.addr != 0)

   {
    os_printf("got ip !!! \r\n");

    os_timer_disarm(&test_timer1);
    os_timer_setfn(&test_timer1, (os_timer_func_t *)dns_found, NULL);
    os_timer_arm(&test_timer1, 1000, 0);
} 
else 
{
    if ((wifi_station_get_connect_status() == STATION_WRONG_PASSWORD ||
        wifi_station_get_connect_status() == STATION_NO_AP_FOUND ||
        wifi_station_get_connect_status() == STATION_CONNECT_FAIL)) 
    {
        os_printf("connect fail !!! \r\n");
    } 
    else 
    {
        //re-arm timer to check ip
        os_timer_setfn(&client_timer, 
                 (os_timer_func_t *)user_check_ip, NULL);
        os_timer_arm(&client_timer, 100, 0);
    }
}

}</pre></code>
其中
<pre><code>

dns_found(void)
{

  //   if use http,put the url into “URL” next line 

espconn_gethostbyname(&socket, URL , &address, dns_found);

  /*   if use the basic tcp mode  
   (you can change the esp_server_ip and remote_port as your mind)*/

const char esp_server_ip[4] = {xxx, xxx, xxx, xxx};

  os_memcpy(user_conn.proto.tcp->remote_ip, esp_server_ip, 4);
  user_conn.proto.tcp->local_port = espconn_port();

user_conn.proto.tcp->remote_port = xxxx;

  espconn_regist_connectcb(&user_conn, user_esp_platform_connect_cb);
  espconn_regist_reconcb(&user_conn, user_esp_platform_recon_cb);
  user_esp_platform_connect(&user_conn);

}</pre></code>

总结

通过今天的介绍,大家对网络通讯也有了比较基础的了解了,可以根据自己的需要修改远程服务器的ip地址和端口来建立自己的tcp连接了,下期将带给大家带来云平台的选择和服务器通讯讲解。

上一篇下一篇

猜你喜欢

热点阅读