A question about onInit function

Posted on
  • Hello there,
    I have written a piece of code that fetches base64 encoded images from the web and displays on a 128x64 OLED (Web2OLED)
    And following is the piece of code:

    const ssd1306 = require('SSD1306');
    const wifi = require('Wifi');
    const mqtt = require('tinyMQTT');
    const http = require('http');
    
    const config = {
      wifi: {
        ssid: "XXXXXX",
        password: "XXXXXXXX"
      },
      oledPins: {
        scl:NodeMCU.D1,
        sda:NodeMCU.D2
      },
      mqtt: {
        host: 'test.mosquitto.org',
        port: 1883,
        subTopic: "XXXXXXXX/data"
      },
      imageEndPoint: "http://web2oled.herokuapp.com/XXXXXXXX"­
    };
    
    let mqttClient = null;
    let g = null;
    
    function createImage(imageString) {
      let buffer = null;
      try {
        buffer = E.toArrayBuffer(atob(imageString));
      }
      catch(e) {
        buffer = E.toArrayBuffer(atob(errorImage));
      }
      return {
      width : 128, height : 64, bpp : 1,
      transparent : 0,
      buffer: buffer
    };
    
    }
    function draw(opt) {
      const image = opt.image;
      const data = opt.data;
    
      g.clear();
      if (image) {
        g.drawImage(createImage(data), 0,0);
      }
      else {
        g.setFont('4x6', 2);
        g.drawString(data, 0, 0);
      }
      g.flip();
    }
    
    function setupMQTTClient() {
      mqttClient = mqtt.create(config.mqtt.host, {port: config.mqtt.port});
    
      mqttClient.on("disconnected", ()=>{
        draw({data: "Disconnected from\nMQTT Broker"});
        mqttClient.connect();
      });
    
      mqttClient.on('connected', ()=> {
        draw({data: "Connected to\nMQTT broker"});
        mqttClient.subscribe(config.mqtt.subTopi­c);
        fetchImage();
      });
    
      mqttClient.on('message', (msg)=>{
        fetchImage();
      });
    
      mqttClient.connect();
    }
    
    function fetchImage() {
      http.get(config.imageEndPoint, (res) => {
          let content = "";
          res.on('data', (data)=>{
            content += data;
          });
          res.on('close', () => {
            draw({image: true, data: content});
          });
        });
    }
    
    function connectToWifi() {
      wifi.connect(config.wifi.ssid, {password: config.wifi.password}, (err) => {
        if (err) {
          draw({data: "Could not connect\nto Wi-Fi\n\nWill retry in\n 5 seconds"});
          setTimeout(connectToWifi, 5000);
        }
        else {
          draw({data: "Connected to\nWi-Fi"});
          setupMQTTClient();
        }
      });
    }
    
    function onInit() {
      I2C1.setup(config.oledPins);
      g = ssd1306.connect(I2C1, ()=>{}, {width: 128, height: 64});
    
      connectToWifi();
    }
    
    

    I upload this to the board and save it (using save()).

    Now I am under the assumption that the code inside onInit is only executed once (and not looped).
    The weird thing that's happening is that when I turn off/on my WiFi router(after the NodeMCU is connected to the WiFi), it automatically tries to reconnect to the WiFi.
    But you can see above that nowhere there is a loop that checks for WiFi disconnect event. The setTimeout will only work as long as it is switched on for the first time and is not able to connect to the WiFi.
    After it has connected to the WiFi the control should not go to the if block where setTimeout is called.

    Please help me understand this (I am a newbie to Espruino, please let me know if I have missed out something very trivial 😊)

    Thanks

  • Well I guess you did wifi.save() in the past, so your wifi config is saved.

    Boot process: If there is a .wificfg file in storage it will we used at boot time try to connect.

  • Use same pattern for lines 96 and 97 as you use for mqtt: pack them in the connected event for wifi... you may need to keep track of the things that have successfully initialized / connected and need not to be initialized / connected again.

  • @MaBe Nope, I haven't saved the credentials at any point in time nor I have a .wificfg in the storage.
    @allObjects I see what you are getting at, but my question is different. I am unable to understand how WiFi is getting reconnected after I reboot my router (and keep the NodeMCU on). I have not defined that it should reconnect to WiFi happen when WiFi is disconnected, and still I see it connects to WiFi flawlessly when the router comes up.

  • Nope, I haven't saved the credentials at any point in time nor I have a .wificfg in the storage.

    Ok, as long as you connected to power, wifi connection is still up.

  • @MaBe Yes exactly. It disconnects when I switch off my router. But again when I switch it on, NodeMCU magically reconnects to it, and I am not able to understand how.

  • Figured I'd drop a note here in case someone else wondered about this: WiFi on ESP8266 is managed by the ESP8266's SDK. Arduino and Espruino are essentially "remote controlling" the chip's built-in functionality by sending AT commands that tell it what to do. You can see these commands in the JavaScript source for Espruino's Wifi library.

    With that in mind, one of the features of the ESP8266 SDK is that it automatically reconnects to networks after a connection drops. It's mentioned here in the Arduino documentation for the ESP8266.

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

A question about onInit function

Posted by Avatar for RajaNandSharma @RajaNandSharma

Actions