http server and mqtt client problem

Posted on
  • I have a problem when http and mqtt live together:
    This is my code:

    var http = require('http');
    var wifi = require('Wifi');
    var mqtt = require("tinyMQTT").create("............­.........",{username:"owntracks",passwor­d:"........",port:1883});
    
    
    E.on("init", function(){
      var connectWifi = function(ssid, password){
          wifi.connect("Newbiz",{password: "pwdinewbiz"}, function(err) {
                  if (err) throw err;
                  wifi.save();
    
                  console.log(wifi.getIP());
    
                  console.log(wifi.getDetails());
    
                  wifi.startAP("NewbizCentral",{authMode:"­wpa", password:"pwdinewbiz",channel:5},functio­n(a){console.log("AP created");});
    
                  setTimeout(function(){      
                    console.log(wifi.getAPIP());
                    http.createServer(
    
                      function (req, res) {
                                var a = url.parse(req.url, true);
                                if(req.url.length>15){
                                  var wifiSetterPageContent = "<h3>Credendiali AP settate. Staccare dalla presa il dispositivo e riattaccarlo dopo qualche secondo<h3>";
                                  res.writeHead(200, {'Content-Type': 'text/html'});
                                  res.end(wifiSetterPageContent);
                                  var pressid = req.url.replace("/setWifiCredentials/?",­ "");
                                  var UsrPwd = pressid.split("&");
                                  ssid = UsrPwd[0];
                                  password = UsrPwd[1];
                                  console.log("from onPageRequest " + ssid + " " + password);
                                  message =  message + " ssid is: "+ssid + " password is: "+ password;
                                  connectWifi(ssid, password);
                                }
                                else{
                                  var pageContent = "<h1>Newbiz s.r.l.<h1><h2>Seleziona le credenziali del tuo Access Point<h2><p>Nome Wifi</p> <input type='text' name='wifiid' id='wifiid'> <p>Password</p> <input type='text' name='passwd' id='passwd'></br></br> <button onclick='setWifiCredentials()'>Setta le credenziali e riavvia</button> <script> function setWifiCredentials(){location.href = '../setWifiCredentials/?'+document.getEl­ementById('wifiid').value+'&'+document.g­etElementById('passwd').value;} </script>";
                                  res.writeHead(200, {'Content-Type': 'text/html'});
                                  res.end(pageContent);
                                }
                      }
    
                    ).listen(8080);
    
    
                  },5000);
          });
      };
    });
    
    save();
    

    when i put mqtt just after the http.createserver code and flash... everuthing stops working... even console prompt stops working at next boot.
    The strange thing is that trying to reflash completely espruino framework and reflashing the code even without mqtt code... prompt does not execute any code.

    Has someone ever faced this problem?!
    Please help me...

    I'm using ESP12e on Espruino 1v88

    PS the code i posted is just the result of many other tries i made putting everything outside E.on method and other ways of writing the code differently, each time starting with one module at a time.
    And btw i always get: ERROR: Prompt not detected - upload failed. Trying to recover... is there something wrong i'm doing or a way to solve this?

  • Maybe a lack of memory to run, or free space in which to save your program. There is quite a lot going on.

    I would start by removing the save() instruction and seeing if I can upload the sketch. Then I'd try to save the sketch by keying save() in the console on left of Wen IDE, and if both ok, try run the sketch - and for this it is useful to wrap all your init code in a named function you can specify as the E.on("init", ...) callback, instead of using anonymous function. You can them comment out, and call your init function from the console.

  • Hi Ollie,
    thanks for your reply. So this is my new code:

    var http = require('http');
    var wifi = require('Wifi');
    var mqtt = require("tinyMQTT").create("............­.",{username:"owntracks",password:".....­.........",port:1883});
    
    var server = function(ssid, password){
          wifi.connect("Newbiz",{password: "pwdinewbiz"}, function(err) {
                  if (err) throw err;
                  wifi.save();
    
                  console.log(wifi.getIP());
    
                  console.log(wifi.getDetails());
    
                  wifi.startAP("NewbizCentral",{authMode:"­wpa", password:"pwdinewbiz",channel:5},functio­n(a){console.log("AP created");});
    
                  setTimeout(function(){      
                    console.log(wifi.getAPIP());
                    http.createServer(
    
                      function (req, res) {
                                var a = url.parse(req.url, true);
                                if(req.url.length>15){
                                  var wifiSetterPageContent = "<h3>Credendiali AP settate. Staccare dalla presa il dispositivo e riattaccarlo dopo qualche secondo<h3>";
                                  res.writeHead(200, {'Content-Type': 'text/html'});
                                  res.end(wifiSetterPageContent);
                                  var pressid = req.url.replace("/setWifiCredentials/?",­ "");
                                  var UsrPwd = pressid.split("&");
                                  ssid = UsrPwd[0];
                                  password = UsrPwd[1];
                                  console.log("from onPageRequest " + ssid + " " + password);
                                  message =  message + " ssid is: "+ssid + " password is: "+ password;
                                  connectWifi(ssid, password);
                                }
                                else{
                                  var pageContent = "<h1>Newbiz s.r.l.<h1><h2>Seleziona le credenziali del tuo Access Point<h2><p>Nome Wifi</p> <input type='text' name='wifiid' id='wifiid'> <p>Password</p> <input type='text' name='passwd' id='passwd'></br></br> <button onclick='setWifiCredentials()'>Setta le credenziali e riavvia</button> <script> function setWifiCredentials(){location.href = '../setWifiCredentials/?'+document.getEl­ementById('wifiid').value+'&'+document.g­etElementById('passwd').value;} </script>";
                                  res.writeHead(200, {'Content-Type': 'text/html'});
                                  res.end(pageContent);
                                }
                      }
    
                    ).listen(8080);
    
                    setTimeout(function(){
                        var message = JSON.stringify(wifi.getIP()) + JSON.stringify(wifi.getDHCPHostname()) + JSON.stringify(wifi.getHostname());
                        mqtt.on("connected", function(){
                          mqtt.subscribe("owntracks");
                          var topic = "owntracks";
                          mqtt.publish(topic, message);
                        });
    
                        mqtt.on("message", function(msg){
                          console.log(msg.topic);
                          console.log(msg.message);
                        });
    
                        mqtt.on("published", function(){
                          console.log("message sent");
                        });
    
                        mqtt.on("disconnected", function(){
                          console.log("disconnected");
                        });
    
                        mqtt.connect();
                    }, 5000);
    
                  },5000);
          });
    };
    
    E.on("init", server);
    
    
    

    everything is perfectly working before saving...
    This is the correct and expected reponse:

    { "ip": "192.168.1.54", "netmask": "255.255.255.0", "gw":
    "192.168.1.1", "mac": "5c:cf:7f:19:e0:c7" } { "status":
    "connected", "ssid": "Newbiz", "password": "pwdinewbiz", "rssi":
    -71, "savedSsid": null } AP created { "ip": "192.168.4.1", "netmask": "255.255.255.0", "gw": "192.168.4.1", "mac":
    "5e:cf:7f:19:e0:c7" } message sent

    as soon as i save() on the console, unplug and replug usb i see this in the console:

    { "ip": "192.168.1.54", "netmask": "255.255.255.0", "gw":
    "192.168.1.1", "mac": "5c:cf:7f:19:e0:c7" } { "status":
    "connected", "ssid": "Newbiz", "password": "pwdinewbiz", "rssi":
    -71, "savedSsid": null } AP created { "ip": "192.168.4.1", "netmask": "255.255.255.0", "gw": "192.168.4.1", "mac":
    "5e:cf:7f:19:e0:c7" }

    You can notice that everything is working but not the last "message sent".
    The other strange thing that happends is that while you would think that message has not been sent(and usually on another mqtt client when message is published the client get immediately updated) if from another mqtt client i unsubscribe and subscribe again i get that message there.

    so qhat can it be??!!

  • I would bring the var mqtt= line, into the server>setTimeout callback, so that mqtt.create() happens in E.on("init", ...) too? Does that help?

  • Hi Ollie,
    thanks... now it seams working even if i don't understand why as mqtt connects only after wifi is up so mqtt object is just creating something that is been "called" on wifi up.

    Can you just tell me last thing about why i'm getting "ERROR: Prompt not detected - upload failed" everytime i was executing my previous code?

  • Re first point - if I'm honest I can't give you a definitive answer. I think it's down to what save() actually does combined with the MQTT modules design. Someone more expert than me will tell you, and I think there are some good threads in the forum which explain, but I always try ensure that anything which does more than a simple require of a module is part of the code I explicitly run again at start up through an init function. Obviously the MQTT module calls create on the back of the require piece.

    Re your last point, you can see this for a number of reasons. The IDE will look for an indication that the board is ready by looking for a console prompt. You may not have that perhaps because your first version saved code had started and already crashed the board? I am only guessing but it would seem likely.

  • Ok so in case i would like to require mqtt where it was i still can do it but the create function should be placed inside the wifi callback function.

    Ok Ollie very glad you help me.

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

http server and mqtt client problem

Posted by Avatar for AlessioBacin @AlessioBacin

Actions