Most recent activity
-
@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).listen(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(Serial2, 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();
-
Hi @Gordon, Thanks for looking into it.
I've unchecked 'Modules uploaded as functions (BETA)' and 'Javascript compiler' from the config. I'm not sure if they make any difference. But i get the following error and that line is part of MQTT.min.js file.
Uncaught Error: This socket is closed. at line 1 col 58 ...e(g(c.DISCONNECT<<4)+"\x00"),this.client.end(),this.client=!... ^ in function "disconnect" called from line 1 col 52 a.ctimo=void 0;a.emit("disconnected");a.disconnect()
I will try to post up the code soon.
-
-
I tried adding
Serial2.removeAllListeners()
and tested, it does not work.
I tried initializing therequire("ESP8266WiFi_0v25").connect
only once and tested, it does not work.But all the scenarios, if i make a new HTTP connection instead of
client.connect()
(not making any MQTT calls), i'm getting the response and the socket is not closed.I strongly believe that there is something to do with
client.connect()
, especially it happens only when i run/close the HTTP server first and try to connect to the MQTT. -
Thanks @PaddeK, i just tried to use the callback, but unfortunately there is no callback it seems.
-
var client = require("MQTT").create('IP ADDRESS', options /*optional*/); .... function setup () { wifi = require("ESP8266WiFi_0v25").connect(Serial2, function(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) { console.log('Device is successfully connected to the WiFi.'); // MQTT starts here client.connect(); .... } else { // creating the AP, running the HTTP server code // after getting the WiFi creds and saving that to the ROM, apServer.close(); setup(); } }
If you notice, whenever there is a cold start, i instantiate the ESP8266WiFi_0v25 twice in the flow and that is the case where it does not work.
Every time after the cold start, it instantiates the ESP8266WiFi_0v25 once and it works fine.
Does it give any clue?
Does it need to do anything with the AP or Station mode of the Wifi module? -
Sure, i will try.
But if i make HTTP request in the place of MQTT connect, I'm getting the HTTP response back from the server. The following code works
apServer.close() ...... require("http").get("http://pur3.co.uk/hello.txt", function(res) { res.on('data', function(data) { console.log("HTTP> "+data); }); res.on('close', function(data) { console.log("Connection closed"); }); });
-
@PaddeK But the MQTT makes a connection during
client.connect();
and not during
var client = require("MQTT").create(server, options /*optional*/);
Right? In that case, client connection is happening after the close() call.
I'm sureshkm, I've total of 14 years experience in the world wide web. For the past 10 years, i've been working as a front-end engineer. JavaScript is my strength.
More about me at my YouTube Channel