• @Gordon I've posted some main parts of my code base. Hope this helps!

    var wifi,
        wifiAPs = {},
        f = new (require("FlashEEPROM"))(),
        apServer,
        isProduction = true; // use this for debugging
    
    function clog(s) {
      console.log(s);
    }
    
    /**
     * the MQTT broker server configurations
     */
    var server = '192.168.1.14', // the ip of MQTT broker
        options = {
            client_id : UUID,
            //keep_alive: 60, // keep alive time in seconds
            port: 1883, // port number
            clean_session: true,
            username: "username", // name for auth that happens in the broker server
            password: "password",  // pwd for auth that happens in the broker server
            protocol_name: "MQTT", // or MQIsdp, etc..
            protocol_level: 4, // protocol level
        },
        client = require("MQTT").create(server, options /*optional*/);
    
    
    /**
     * throwing error exceptions
     */
    function throwError(err) {
        if (err) {
            progress = false;
            throw err;
        }
    }
    
    /**
     * Temporary server to collect the WiFi credentials like SSID, pwd etc
     * @method hsInit
     */
    function hsInit() {
        apServer = require("http").createServer(hsRouter).l­isten(80);
    }
    
    /**
     * all the requests will be routed thro this
     * @method hsRouter
     */
    function hsRouter(req, res) {
        getIndexHTML(req, res);
    }
    
    /**
     * index/home page of the Hula Server where we collect the WiFi credentials
     * @method getIndexHTML
     */
    function getIndexHTML(req, res) {
        var pURL = url.parse(req.url, true);
        if (req.method === 'POST') {
            var postData = '',
                parsedData;
    
            req.on('data', function(d) {
                postData += d;
            });
    
            req.on('end', function(d) {
                parsedData = parseQuery(postData);
                clog(parsedData);
    
                // clear absolutely everything out of memory
                f.erase();
    
                // if there is a WiFi SSID given (required)
                if (parsedData.ap) {
                    f.write(0, parsedData.ap);   
                    clog(E.toString(f.read(0)));
                }
    
                 // if there is a WiFi PWD given (required)
    
                // lets setup as we got the WiFi creds
                apServer.close();
                sTHandlerSetup = setTimeout(setup, 5000);
            });
        }
    
        // default/index route to display the web page
        if (pURL.pathname == '/') {
    
            // the HTML page that collects the WiFi creds
            res.writeHead(200, {'Content-Type': 'text/html'});
            // HTML Form to collect the required info 
            res.end('</body></html>'); 
        }
    }
    
    
    /**
     * initiate the required functions while booting the pico
     * @method onInit
     */
    function onInit() {
        var setWatchId,
            pTime;
    
        // the external button for setting up 
        pinMode(B3, "input_pulldown");
        setWatchId = setWatch(function(e) {
            pTime = e.time - e.lastTime;
    
            // do not accept if it happens within 2 secs
            if(!progress && (isNaN(pTime) || pTime > 2)) {
                clearWatch(setWatchId);
                clog('Got you! Hang on! Im booting up.');
                progress = true;
                setup();
            }
        }, B3, { repeat: true, debounce : 150, edge: "rising" });
    }
    
    function setup() {
    
        if (sTHandlerSetup) {
          clog('clearing the setup timeout ...');
          clearTimeout(sTHandlerSetup);
        }
        Serial2.setup(115200, { rx: A3, tx : A2 });
        Serial2.removeAllListeners();
        wifi = require("ESP8266WiFi_0v25").connect(Seri­al2, function(err) {
            throwError(err);
    
            // reset the n/w before the connection
            wifi.reset(function(err) {
                throwError(err);
                // SSID, Access Point PWD, Email id, Token Details, Session Token
                var apSSID = typeof f.read(0) !== 'undefined' ? E.toString(f.read(0)) : '',
                    apPWD = typeof f.read(1) !== 'undefined' ? E.toString(f.read(1)) : '';
    
                if (apSSID) {
                    wifi.connect(apSSID, apPWD, function(err) {
                        throwError(err);
                        clog('Device is successfully connected to the WiFi.');
                        progress = false;
                        var sTHandlerMQTT;
    
                        sTHandlerMQTT = setTimeout(function() {
                            clog('clearing the MQTT timeout ...');
                            clearTimeout(sTHandlerMQTT);
    
                            // MQTT starts here
                            client.connect();
    
                            // MQTT: if there is any error 
                            client.on('error', function () {
                                clog('connection to the MQTT broker server failed');
                            });
    
                            // MQTT: while connecting
                            client.on('connected', function () {
                                clog('MQTT connected ...');
                            });
    
                            // MQTT: watching out for the messages that come in from the MQTT broker
                            client.on('message', function (topic, message) {
                                // logic for handling the messages
                            });
    
                            // in case, the MQTT broker server is down, reconnect
                            client.on('disconnected', function() {
                                clog("MQTT disconnected... reconnecting.");
    
                                // reconnect 3 times in every 5s
                                // 4 times in every 15s and 10 times in every 60s
                                client.connect();
                            });
                        }, 3000);
                    });
                } else {
    
                    // only if there is any WiFi SSID (Service Set IDentifier) in the EEPROM memory
                    new Promise(function(resolve, reject) {
    
                        wifi.getAPs(function(err, aps) { 
                            for (var i in aps) {
                                for (var j in aps[i]) {
                                    wifiAPs[aps[i][j]] = aps[i];
                                    break;
                                }
                            }
                            resolve();
                        });
                    }).then(function () {
    
                        // setup the WiFi access point
                        var SSID = 'sureshkm',
                            pwd = 'password';
    
                        wifi.createAP(SSID, pwd, 5, 'wpa_wpa2_psk', function(err) {
                            throwError(err);
                            clog('WiFi access point is successfully created.'); 
                        });
    
                        hsInit();
                    }, function(err) {
                        throwError(new Error('Failed to collect the WiFi APs'));
                    });
                }
            });
        });
    }
    
    // save the program into the micro controller 
    save();
    
About

Avatar for sureshkm @sureshkm started