• // REQUIRE
    const D1 = NodeMCU.D1;
    const D2 = NodeMCU.D2;
    
    const wifi = require("Wifi");
    
    // CONSTS
    const MQTT_SERVER_IP = "";
    const SSID = "";
    const PASS = "";
    
    // FNS
    const connectWifi = () =>
      new Promise((resolve, reject) => {
        wifi.connect(SSID, { password: PASS }, function(e) {
          if (e) {
            console.log("error during connect:", e);
            wifi.disconnect();
            reject(e);
          } else {
            console.log("connected to", SSID);
            wifi.stopAP();
            resolve(wifi);
          }
        });
      });
    
    const connectDisplay = () =>
      new Promise((resolve, reject) => {
        console.log(1);
        I2C1.setup({ scl: D1, sda: D2 });
        console.log(2);
        // OLED driver and graphic library
        const g = require("SSD1306").connect(I2C1, () => {
          resolve(g);
        });
      });
    
    let g = null;
    const writeText = text => {
      g.clear();
      g.setRotation(2);
      g.setColor(1);
      g.setFontVector(15);
      g.drawString(text, 0, 10);
      g.flip();
    };
    
    const startApp = () => {
      connectDisplay()
        .then(newG => {
          g = newG;
          writeText("Init...");
        })
        .then(() => {
          return connectWifi();
        })
        .then(() => {
          writeText("Wifi - OK");
          const mqtt = require("MQTT").connect({
            host: MQTT_SERVER_IP
          });
    
          mqtt.on("disconnected", () => {
            writeText("Disconnected");
          });
    
          mqtt.on("connected", () => {
            writeText("MQTT - OK");
            mqtt.subscribe("wemos/#");
    
            const topic = "wemos/start";
            const message = "Demo!";
            mqtt.publish(topic, message);
    
            mqtt.on("publish", pub => {
               writeText(pub.message);
            });
          });
        })
        .catch(() => {
          writeText("Error!");
        });
    };
    
    //startApp();
    E.on("init", startApp);
    save();
    
About

Avatar for michalt @michalt started