• The normal JS way of doing network connections is like this:

    client = require("net").connect({host : IP, port: 80}, function() {
        console.log('client connected');
        client.write("Hello World");
        client.end();    
      });
    

    That's all already implemented and would call into the network-related functions you implement. It actually works like this:

    • JS: calls connect
    • Espruino: call esp8266 connect
    • esp8266: starts connection, stores that it's busy
    • JS: connect callback is called
    • JS: calls write
    • Espruino: buffers written data
    • JS: calls end
    • Espruino: stores that it must close connection after data sent
    • Espruino: next time around the idle loop....
    • Espruino: calls esp8266 write with buffered data
    • esp8266: write return 0 - saying it's busy
    • Espruino: repeats above each time around idle loop
    • esp8266: gets callback saying it's connected, sets state to not busy
    • Espruino: calls esp8266 write with buffered data
    • esp8266: write is ok, returns number of bytes written
    • Espruino: calls esp8266 write with buffered data, if there is any
    • esp8266: write is ok, returns number of bytes written
    • Espruino: no more data, call close connection
    • esp8266: closes connection
    • We're done...

    So the buffering is all built in, and it all 'just works' - including a 'drain' event that allows you to 'pipe' lots of data in without filling up buffers. All you have to do is implement the code from post 8.

    So the 'connected' callback is called before the ESP8266 is completely connected (which is a shame, but not a huge problem). In the case of HTTP is all 'just works' correctly though, because the request is only called when an HTTP response is received.

    Hopefully at some point in the future this could be changed, but there's absolutely no reason to re-write it just for this, when it's trivial to make it work as-is.

About

Avatar for Gordon @Gordon started