Connections

Connections are essential feature of WiFi device and middleware. It is developed with strong focus on its performance and since it may interact with huge amount of data, it tries to use zero-copy (when available) feature, to decrease processing time.

ESP AT Firmware by default supports up to 5 connections being active at the same time and supports:

  • Up to 5 TCP connections active at the same time

  • Up to 5 UDP connections active at the same time

  • Up to 1 SSL connection active at a time

Note

Client or server connections are available. Same API function call are used to send/receive data or close connection.

Architecture of the connection API is using callback event functions. This allows maximal optimization in terms of responsiveness on different kind of events.

Example below shows bare minimum implementation to:

  • Start a new connection to remote host

  • Send HTTP GET request to remote host

  • Process received data in event and print number of received bytes

Client connection minimum example
  1#include "client.h"
  2#include "lwesp/lwesp.h"
  3
  4/* Host parameter */
  5#define CONN_HOST           "example.com"
  6#define CONN_PORT           80
  7
  8static lwespr_t   conn_callback_func(lwesp_evt_t* evt);
  9
 10/**
 11 * \brief           Request data for connection
 12 */
 13static const
 14uint8_t req_data[] = ""
 15                     "GET / HTTP/1.1\r\n"
 16                     "Host: " CONN_HOST "\r\n"
 17                     "Connection: close\r\n"
 18                     "\r\n";
 19
 20/**
 21 * \brief           Start a new connection(s) as client
 22 */
 23void
 24client_connect(void) {
 25    lwespr_t res;
 26
 27    /* Start a new connection as client in non-blocking mode */
 28    if ((res = lwesp_conn_start(NULL, LWESP_CONN_TYPE_TCP, "example.com", 80, NULL, conn_callback_func, 0)) == lwespOK) {
 29        printf("Connection to " CONN_HOST " started...\r\n");
 30    } else {
 31        printf("Cannot start connection to " CONN_HOST "!\r\n");
 32    }
 33
 34    /* Start 2 more */
 35    lwesp_conn_start(NULL, LWESP_CONN_TYPE_TCP, CONN_HOST, CONN_PORT, NULL, conn_callback_func, 0);
 36
 37    /*
 38     * An example of connection which should fail in connecting.
 39     * When this is the case, \ref LWESP_EVT_CONN_ERROR event should be triggered
 40     * in callback function processing
 41     */
 42    lwesp_conn_start(NULL, LWESP_CONN_TYPE_TCP, CONN_HOST, 10, NULL, conn_callback_func, 0);
 43}
 44
 45/**
 46 * \brief           Event callback function for connection-only
 47 * \param[in]       evt: Event information with data
 48 * \return          \ref lwespOK on success, member of \ref lwespr_t otherwise
 49 */
 50static lwespr_t
 51conn_callback_func(lwesp_evt_t* evt) {
 52    lwesp_conn_p conn;
 53    lwespr_t res;
 54    uint8_t conn_num;
 55
 56    conn = lwesp_conn_get_from_evt(evt);          /* Get connection handle from event */
 57    if (conn == NULL) {
 58        return lwespERR;
 59    }
 60    conn_num = lwesp_conn_getnum(conn);           /* Get connection number for identification */
 61    switch (lwesp_evt_get_type(evt)) {
 62        case LWESP_EVT_CONN_ACTIVE: {             /* Connection just active */
 63            printf("Connection %d active!\r\n", (int)conn_num);
 64            res = lwesp_conn_send(conn, req_data, sizeof(req_data) - 1, NULL, 0); /* Start sending data in non-blocking mode */
 65            if (res == lwespOK) {
 66                printf("Sending request data to server...\r\n");
 67            } else {
 68                printf("Cannot send request data to server. Closing connection manually...\r\n");
 69                lwesp_conn_close(conn, 0);        /* Close the connection */
 70            }
 71            break;
 72        }
 73        case LWESP_EVT_CONN_CLOSE: {              /* Connection closed */
 74            if (lwesp_evt_conn_close_is_forced(evt)) {
 75                printf("Connection %d closed by client!\r\n", (int)conn_num);
 76            } else {
 77                printf("Connection %d closed by remote side!\r\n", (int)conn_num);
 78            }
 79            break;
 80        }
 81        case LWESP_EVT_CONN_SEND: {               /* Data send event */
 82            lwespr_t res = lwesp_evt_conn_send_get_result(evt);
 83            if (res == lwespOK) {
 84                printf("Data sent successfully on connection %d...waiting to receive data from remote side...\r\n", (int)conn_num);
 85            } else {
 86                printf("Error while sending data on connection %d!\r\n", (int)conn_num);
 87            }
 88            break;
 89        }
 90        case LWESP_EVT_CONN_RECV: {               /* Data received from remote side */
 91            lwesp_pbuf_p pbuf = lwesp_evt_conn_recv_get_buff(evt);
 92            lwesp_conn_recved(conn, pbuf);        /* Notify stack about received pbuf */
 93            printf("Received %d bytes on connection %d..\r\n", (int)lwesp_pbuf_length(pbuf, 1), (int)conn_num);
 94            break;
 95        }
 96        case LWESP_EVT_CONN_ERROR: {              /* Error connecting to server */
 97            const char* host = lwesp_evt_conn_error_get_host(evt);
 98            lwesp_port_t port = lwesp_evt_conn_error_get_port(evt);
 99            printf("Error connecting to %s:%d\r\n", host, (int)port);
100            break;
101        }
102        default:
103            break;
104    }
105    return lwespOK;
106}

Sending data

Receiving data flow is always the same. Whenever new data packet arrives, corresponding event is called to notify application layer. When it comes to sending data, application may decide between 2 options (this is valid only for non-UDP connections):

  • Write data to temporary transmit buffer

  • Execute send command for every API function call

Temporary transmit buffer

By calling lwesp_conn_write() on active connection, temporary buffer is allocated and input data are copied to it. There is always up to 1 internal buffer active. When it is full (or if input data length is longer than maximal size), data are immediately send out and are not written to buffer.

ESP AT Firmware allows (current revision) to transmit up to 2048 bytes at a time with single command. When trying to send more than this, application would need to issue multiple send commands on AT commands level.

Write option is used mostly when application needs to write many different small chunks of data. Temporary buffer hence prevents many send command instructions as it is faster to send single command with big buffer, than many of them with smaller chunks of bytes.

Write data to connection output buffer
 1size_t rem_len;
 2lwesp_conn_p conn;
 3lwespr_t res;
 4
 5/* ... other tasks to make sure connection is established */
 6
 7/* We are connected to server at this point! */
 8/*
 9 * Call write function to write data to memory
10 * and do not send immediately unless buffer is full after this write
11 *
12 * rem_len will give us response how much bytes
13 * is available in memory after write
14 */
15res = lwesp_conn_write(conn, "My string", 9, 0, &rem_len);
16if (rem_len == 0) {
17    printf("No more memory available for next write!\r\n");
18}
19res = lwesp_conn_write(conn, "example.com", 11, 0, &rem_len);
20
21/*
22 * Data will stay in buffer until buffer is full,
23 * except if user wants to force send,
24 * call write function with flush mode enabled
25 *
26 * It will send out together 20 bytes
27 */
28lwesp_conn_write(conn, NULL, 0, 1, NULL);

Transmit packet manually

In some cases it is not possible to use temporary buffers, mostly because of memory constraints. Application can directly start send data instructions on AT level by using lwesp_conn_send() or lwesp_conn_sendto() functions.

group LWESP_CONN

Connection API functions.

Typedefs

typedef struct lwesp_conn *lwesp_conn_p

Pointer to lwesp_conn_t structure.

Enums

enum lwesp_conn_type_t

List of possible connection types.

Values:

enumerator LWESP_CONN_TYPE_TCP

Connection type is TCP

enumerator LWESP_CONN_TYPE_UDP

Connection type is UDP

enumerator LWESP_CONN_TYPE_SSL

Connection type is SSL

enumerator LWESP_CONN_TYPE_TCPV6

Connection type is TCP over IPv6

enumerator LWESP_CONN_TYPE_UDPV6

Connection type is UDP over IPv6

enumerator LWESP_CONN_TYPE_SSLV6

Connection type is SSL over IPv6

Functions

lwespr_t lwesp_conn_start(lwesp_conn_p *conn, lwesp_conn_type_t type, const char *const remote_host, lwesp_port_t remote_port, void *const arg, lwesp_evt_fn conn_evt_fn, const uint32_t blocking)

Start a new connection of specific type.

Parameters
  • conn[out] Pointer to connection handle to set new connection reference in case of successfully connected

  • type[in] Connection type. This parameter can be a value of lwesp_conn_type_t enumeration. Do not use this method to start SSL connection. Use lwesp_conn_startex instead

  • remote_host[in] Connection host. In case of IP, write it as string, ex. “192.168.1.1”

  • remote_port[in] Connection port

  • arg[in] Pointer to user argument passed to connection if successfully connected

  • conn_evt_fn[in] Callback function for this connection

  • blocking[in] Status whether command should be blocking or not

Returns

lwespOK on success, member of lwespr_t enumeration otherwise

lwespr_t lwesp_conn_startex(lwesp_conn_p *conn, lwesp_conn_start_t *start_struct, void *const arg, lwesp_evt_fn conn_evt_fn, const uint32_t blocking)

Start a new connection of specific type in extended mode.

Parameters
  • conn[out] Pointer to connection handle to set new connection reference in case of successfully connected

  • start_struct[in] Connection information are handled by one giant structure

  • arg[in] Pointer to user argument passed to connection if successfully connected

  • conn_evt_fn[in] Callback function for this connection

  • blocking[in] Status whether command should be blocking or not

Returns

lwespOK on success, member of lwespr_t enumeration otherwise

lwespr_t lwesp_conn_close(lwesp_conn_p conn, const uint32_t blocking)

Close specific or all connections.

Parameters
  • conn[in] Connection handle to close. Set to NULL if you want to close all connections.

  • blocking[in] Status whether command should be blocking or not

Returns

lwespOK on success, member of lwespr_t enumeration otherwise

lwespr_t lwesp_conn_send(lwesp_conn_p conn, const void *data, size_t btw, size_t *const bw, const uint32_t blocking)

Send data on already active connection either as client or server.

Parameters
  • conn[in] Connection handle to send data

  • data[in] Data to send

  • btw[in] Number of bytes to send

  • bw[out] Pointer to output variable to save number of sent data when successfully sent. Parameter value might not be accurate if you combine lwesp_conn_write and lwesp_conn_send functions

  • blocking[in] Status whether command should be blocking or not

Returns

lwespOK on success, member of lwespr_t enumeration otherwise

lwespr_t lwesp_conn_sendto(lwesp_conn_p conn, const lwesp_ip_t *const ip, lwesp_port_t port, const void *data, size_t btw, size_t *bw, const uint32_t blocking)

Send data on active connection of type UDP to specific remote IP and port.

Note

In case IP and port values are not set, it will behave as normal send function (suitable for TCP too)

Parameters
  • conn[in] Connection handle to send data

  • ip[in] Remote IP address for UDP connection

  • port[in] Remote port connection

  • data[in] Pointer to data to send

  • btw[in] Number of bytes to send

  • bw[out] Pointer to output variable to save number of sent data when successfully sent

  • blocking[in] Status whether command should be blocking or not

Returns

lwespOK on success, member of lwespr_t enumeration otherwise

lwespr_t lwesp_conn_set_arg(lwesp_conn_p conn, void *const arg)

Set argument variable for connection.

Parameters
  • conn[in] Connection handle to set argument

  • arg[in] Pointer to argument

Returns

lwespOK on success, member of lwespr_t enumeration otherwise

void *lwesp_conn_get_arg(lwesp_conn_p conn)

Get user defined connection argument.

Parameters

conn[in] Connection handle to get argument

Returns

User argument

uint8_t lwesp_conn_is_client(lwesp_conn_p conn)

Check if connection type is client.

Parameters

conn[in] Pointer to connection to check for status

Returns

1 on success, 0 otherwise

uint8_t lwesp_conn_is_server(lwesp_conn_p conn)

Check if connection type is server.

Parameters

conn[in] Pointer to connection to check for status

Returns

1 on success, 0 otherwise

uint8_t lwesp_conn_is_active(lwesp_conn_p conn)

Check if connection is active.

Parameters

conn[in] Pointer to connection to check for status

Returns

1 on success, 0 otherwise

uint8_t lwesp_conn_is_closed(lwesp_conn_p conn)

Check if connection is closed.

Parameters

conn[in] Pointer to connection to check for status

Returns

1 on success, 0 otherwise

int8_t lwesp_conn_getnum(lwesp_conn_p conn)

Get the number from connection.

Parameters

conn[in] Connection pointer

Returns

Connection number in case of success or -1 on failure

lwespr_t lwesp_conn_set_ssl_buffersize(size_t size, const uint32_t blocking)

Set internal buffer size for SSL connection on ESP device.

Note

Use this function before you start first SSL connection

Parameters
  • size[in] Size of buffer in units of bytes. Valid range is between 2048 and 4096 bytes

  • blocking[in] Status whether command should be blocking or not

Returns

lwespOK on success, member of lwespr_t enumeration otherwise

lwespr_t lwesp_get_conns_status(const uint32_t blocking)

Gets connections status.

Parameters

blocking[in] Status whether command should be blocking or not

Returns

lwespOK on success, member of lwespr_t enumeration otherwise

lwesp_conn_p lwesp_conn_get_from_evt(lwesp_evt_t *evt)

Get connection from connection based event.

Parameters

evt[in] Event which happened for connection

Returns

Connection pointer on success, NULL otherwise

lwespr_t lwesp_conn_write(lwesp_conn_p conn, const void *data, size_t btw, uint8_t flush, size_t *const mem_available)

Write data to connection buffer and if it is full, send it non-blocking way.

Note

This function may only be called from core (connection callbacks)

Parameters
  • conn[in] Connection to write

  • data[in] Data to copy to write buffer

  • btw[in] Number of bytes to write

  • flush[in] Flush flag. Set to 1 if you want to send data immediately after copying

  • mem_available[out] Available memory size in current write buffer. When the buffer length is reached, current one is sent and a new one is automatically created. If function returns lwespOK and *mem_available = 0, there was a problem allocating a new buffer for next operation

Returns

lwespOK on success, member of lwespr_t enumeration otherwise

lwespr_t lwesp_conn_recved(lwesp_conn_p conn, lwesp_pbuf_p pbuf)

Notify connection about received data which means connection is ready to accept more data.

Once data reception is confirmed, stack will try to send more data to user.

Note

Since this feature is not supported yet by AT commands, function is only prototype and should be used in connection callback when data are received

Note

Function is not thread safe and may only be called from connection event function

Parameters
  • conn[in] Connection handle

  • pbuf[in] Packet buffer received on connection

Returns

lwespOK on success, member of lwespr_t enumeration otherwise

size_t lwesp_conn_get_total_recved_count(lwesp_conn_p conn)

Get total number of bytes ever received on connection and sent to user.

Parameters

conn[in] Connection handle

Returns

Total number of received bytes on connection

uint8_t lwesp_conn_get_remote_ip(lwesp_conn_p conn, lwesp_ip_t *ip)

Get connection remote IP address.

Parameters
  • conn[in] Connection handle

  • ip[out] Pointer to IP output handle

Returns

1 on success, 0 otherwise

lwesp_port_t lwesp_conn_get_remote_port(lwesp_conn_p conn)

Get connection remote port number.

Parameters

conn[in] Connection handle

Returns

Port number on success, 0 otherwise

lwesp_port_t lwesp_conn_get_local_port(lwesp_conn_p conn)

Get connection local port number.

Parameters

conn[in] Connection handle

Returns

Port number on success, 0 otherwise

lwespr_t lwesp_conn_ssl_set_config(uint8_t link_id, uint8_t auth_mode, uint8_t pki_number, uint8_t ca_number, const lwesp_api_cmd_evt_fn evt_fn, void *const evt_arg, const uint32_t blocking)

Configure SSL parameters.

Parameters
  • link_id[in] ID of the connection (0~max), for multiple connections, if the value is max, it means all connections. By default, max is LWESP_CFG_MAX_CONNS.

  • auth_mode[in] Authentication mode 0: no authorization 1: load cert and private key for server authorization 2: load CA for client authorize server cert and private key 3: both authorization

  • pki_number[in] The index of cert and private key, if only one cert and private key, the value should be 0.

  • ca_number[in] The index of CA, if only one CA, the value should be 0.

  • evt_fn[in] Callback function called when command has finished. Set to NULL when not used

  • evt_arg[in] Custom argument for event callback function

  • blocking[in] Status whether command should be blocking or not

Returns

lwespOK on success, member of lwespr_t enumeration otherwise

struct lwesp_conn_start_t
#include <lwesp_types.h>

Connection start structure, used to start the connection in extended mode.

Public Members

lwesp_conn_type_t type

Connection type

const char *remote_host

Host name or IP address in string format

lwesp_port_t remote_port

Remote server port

const char *local_ip

Local IP. Optional parameter, set to NULL if not used (most cases)

uint16_t keep_alive

Keep alive parameter for TCP/SSL connection in units of seconds. Value can be between 0 - 7200 where 0 means no keep alive

struct lwesp_conn_start_t::[anonymous]::[anonymous] tcp_ssl

TCP/SSL specific features

lwesp_port_t local_port

Custom local port for UDP

uint8_t mode

UDP mode. Set to 0 by default. Check ESP AT commands instruction set for more info when needed

struct lwesp_conn_start_t::[anonymous]::[anonymous] udp

UDP specific features

union lwesp_conn_start_t::[anonymous] ext

Extended support union