Accepting incoming tcp connections on the esp8266 (trivial example)

I’ve been working on some code that accepts incoming connections on the esp8266, if your looking for a full HTTP server take a look at sprite_tm’s code. But these are my notes on accepting a TCP connection.

As with TCP transmissions, you register a bunch of callbacks which process connections. So the first step is to initialize the TCP system with your connect callback:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include "ets_sys.h"
#include "osapi.h"
#include "os_type.h"
 
static struct espconn httpconfig_conn;
static esp_tcp httpconfig_tcp_conn;
 
void ICACHE_FLASH_ATTR httpconfig_conn_init() {
 
        httpconfig_conn.type=ESPCONN_TCP;
        httpconfig_conn.state=ESPCONN_NONE;
        httpconfig_tcp_conn.local_port=80;
        httpconfig_conn.proto.tcp=&httpconfig_tcp_conn;
 
        espconn_regist_connectcb(&httpconfig_conn, httpconfig_connected_cb);
        espconn_accept(&httpconfig_conn);
}

When a connection is received on the specified port, httpconfig_connected_cb will be called. In this function you can send data to the client, and register other functions to trigger when data is received/disconnect etc.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
static void ICACHE_FLASH_ATTR httpconfig_recv_cb(void *arg, char *data, unsigned short len) {
  struct espconn *conn=(struct espconn *)arg;
 
  espconn_disconnect(conn);
}
 
static void ICACHE_FLASH_ATTR httpconfig_recon_cb(void *arg, sint8 err) {
}
 
static void ICACHE_FLASH_ATTR httpconfig_discon_cb(void *arg) {
}
 
static void ICACHE_FLASH_ATTR httpconfig_sent_cb(void *arg) {
}
 
static void ICACHE_FLASH_ATTR httpconfig_connected_cb(void *arg) {
  struct espconn *conn=arg;
 
  espconn_regist_recvcb  (conn, httpconfig_recv_cb);
  espconn_regist_reconcb (conn, httpconfig_recon_cb);
  espconn_regist_disconcb(conn, httpconfig_discon_cb);
  espconn_regist_sentcb  (conn, httpconfig_sent_cb);
 
  char *transmission = "OK\r\n\r\nOK!\n";
  sint8 d = espconn_sent(conn,transmission,strlen(transmission));
}

I currently don’t fully understand what the reconnect callback does. If you know, please mail me.

One Comment

  1. Geoffrey McRae says:

    Seems the ‘reconnect’ callback was named very poorly, it is actually the error callback.

Leave a Reply