Errors once code has been saved onto ESP8266

Posted on
  • Hi there, I am playing around with my DHT11 temperature sensor and my websocket server, I am using the Wemos d1 mini.

    Here is my code:

    var dht = require("DHT11").connect(D4);
    var WebSocket = require("ws");
    var wifi = require("Wifi");
    
    var WIFI_NAME = "MY WIFI NAME";
    var WIFI_OPTIONS = { password : "MY WIFI PASSWORD" };
    
    wifi.connect(WIFI_NAME, WIFI_OPTIONS, function(err) {
      if (err) {
        console.log("Connection error: "+err);
        return;
      }
      console.log("Connected!");
      
      var host = "MY IP";
      var ws = new WebSocket(host,
        {
          path: '/',
          port: 80, // default is 80
          protocol : "echo-protocol", // websocket protocol name (default is none)
          protocolVersion: 13, // websocket protocol version, default is 13
          origin: 'Espruino',
          keepAlive: 600,
    (default is none)
        }
      );
    
      ws.on('open', function() {
        console.log("Connected to server");
    
    
        setInterval(function(){
          dht.read(function (a) {
            ws.send('{"temp":"'+a.temp.toString()+'"­,"rh":"'+a.rh.toString()+'"}');
          });
        },10000);
      });
    });
    

    Note: I have obviously hidden my wifi ssid, password and my IP in the code, just in case :)

    If I upload this to the Wemos it will work as it should, my websocket server is receiving the messages and will display the temperature and the humidity every 10 second the message is sent.

    But then once i save() this code onto the Wemos and reboot it, it starts showing this message every 10 second:

    Uncaught Error: This socket is closed.
     at line 2 col 26
    b,c+(this.masking?128:0)));126==c&&(this­.socket.write(h(a.le...
                             ^
    in function "send" called from line 1 col 69
    ...rh":"'+b.rh.toString()+'"}');
                                  ^
    in function "c" called from line 2 col 173
    ...or:0<e,raw:b,temp:-1,rh:-1})
                                  ^
    in function called from system
    

    What causes this problem? Seems like it has to do with the wifi module?
    I have tried restarting the server and also the Wemos but the problem persists.

    Thanks

  • While you upload the code, some initializations happen which do not when you run the saved state after those.

    Try to put the 'connectsinto anonInit()` function and it should work:

    var dht = null, dhtMod = require("DHT11");
    var WebSocket = require("ws");
    var wifi = require("Wifi");
    var WIFI_NAME = "MY WIFI NAME";
    var WIFI_OPTIONS = { password : "MY WIFI PASSWORD" };
    
    function onInit() {
    
    dht = dhtMod.connect(D4);
    
    wifi.connect(WIFI_NAME, WIFI_OPTIONS, function(err) {
      if (err) {
        console.log("Connection error: "+err);
        return;
      }
      console.log("Connected!");
      
      var host = "MY IP";
      var ws = new WebSocket(host,
        {
          path: '/',
          port: 80, // default is 80
          protocol : "echo-protocol", // websocket protocol name (default is none)
          protocolVersion: 13, // websocket protocol version, default is 13
          origin: 'Espruino',
          keepAlive: 600,
    (default is none)
        }
      );
      ws.on('open', function() {
        console.log("Connected to server");
        setInterval(function(){
          dht.read(function (a) {
            ws.send('{"temp":"'+a.temp.toString()+'"­,"rh":"'+a.rh.toString()+'"}');
          });
        },10000);
      });
    });
    
    } // /onInit()
    

    If you now 'just' upload, nothing happens...

    To get it running, enter onInit() in the console - left side - of the Espruino IDE.

    When the code works as you expect, upload again, and then enter save() in the console - left side - of the Espruino IDE. This will save the code and run the onInit() and you should be fine. Any power cycle after that will run onInit() and do what you expect.

  • Ah I see, everything works now as it should. Thank you very much!

    Do you recommend I always use onInit when I want to save code?

  • Yes, my personal recommendation.

    The onInit() function is (one of) the entry point(s) into the application as the 'last' step of power-up and initialization of Espruino. I prefer onInit(){} over E.on("init",function(){...}) because I can better control eventual init sequence when putting things together (rather than using the thing's individual E.on("init",...). Take a look at Saving code on Espruino.

    @Gordon made lots of strides to make things easy and worry free, but some is outside of control of Espruino system, because a module can do what it wants when connecting. Some modules get some states/values initialized which save on save(), but are not valid anymore when restored, because the states/values depend (also) on external systems, such as session/connection/socket IDs.

    When designing the structure of my code, I separate the runtime/variable dependent things from the static/fixed things... and always run the runtime dependent things in the onInit(). This goes even as far as pinMode(), setInterval()s, setTimeout()s, etc., even though they can be saved and restored. With that I make sure that what ever happened to get to a particular state, is re-doable at the later power-cycle. Important is to save the code - after development concluded - before executing onInit() or a-like - manually (or by timeout, as described in next paragraph).

    Also - to simplify development (not to have to enter after every upload onInit() - I put a last line in reading

    setTimeout(onInit,500); // remove this line before 'final' upload for  save()
    

    (@Gordon, I'm sure this line could be made conditional on some Espruino system info which indicates 'load an start of code' by a plain power up vs an upload on a connected and running Espruino. Which such distinction, the line would not have to be removed before final upload for save().)

    @Hapseleg, structuring code in your particular case would extract the (nested) anonymous functions into named functions (or methods of an object). This results in a flatter hierarchy - less levels - and allows to give names to 'things' and foster reuse. You already do it for storing 'configuration things', such as WIFI NAME and OPTIONS, as 'variabe' values. Same you can to for functions, such as for the function in ws.on("open",function(){...}), as well as within its (nested) functions. It is helpful when application code grows in size and complexity.

  • Thank you so much for the very thorough explanation and the great tips. People such as you are those who make communities great :)

  • Post a reply
    • Bold
    • Italics
    • Link
    • Image
    • List
    • Quote
    • code
    • Preview
About

Errors once code has been saved onto ESP8266

Posted by Avatar for Hapseleg @Hapseleg

Actions