Skip to content
Warren Gay edited this page Nov 17, 2015 · 5 revisions

Once you have the ESP device initialized and the class library conversing with the device, it is desirable to create TCP connections ([see the prerequisites for TCP or UDP](Device Initialization#tcp_udp_requirements)). Assuming the requirements for ESP operating mode have been met, it now becomes a simple matter to connect to a remote host using TCP/IP:

int sock = esp.tcp_connect("google.com",80,my_rx_cb);

If the connection succeeds, a socket will be returned (0 <= sock < 5). If the connect fails, a value of -1 is returned. Multiple reasons exist for failure, which can be [queried using these methods](ESP8266 API Links#error_handling).

The connect request also associates a read callback with the socket (my_rx_cb). The only way that you will read data from the ESP device is through the callback:

typedef void (*recv_func_t)(int sock,int ch);

Your callback might look like this:

static void
my_rx_cb(int sock,int ch) {

    if ( ch != -1 ) {
        // Do something with data byte ch
    } else {
        // -1 indicates that the remote end
        // has closed the socket. We must also
        // close to free the resource:
        esp.close(sock);
    }

If you are scraping a web page for example, you need not buffer much data this way. You filter out what you really need, like perhaps exchange rates. Only the data you need is buffered in precious RAM, or immediately sent to some other destination by your application.

Initiation of a web request, would use the write method, perhaps like this:

int rc = esp.write(sock,"GET / HTTP/1.0\r\n",16);

while ( !done ) {
    esp.receive();
    my_idle_proc();
}
Clone this wiki locally