You are reading a single comment by @user82278 and its replies. Click here to read the full conversation.
  • Hello @allObjects,

    Sorry, I didn't exposed my "project" here :

    I'm just trying to reproduce Gordon's Home automation project, so this is the code I try :
    (available here : https://www.espruino.com/Home+Automation­)

    Naturally I've changed the Wifi ssid and password.

    var WIFI_NAME = "Espruino";
    var WIFI_OPTIONS = { password : "helloworld" };
    var MQTT_HOST = "raspberrypi";
    var PATH = "/mydevice/";
    var LED = D13;
    var RELAY = D12;
    var BTN = D0;
    var mqtt;
    var wifi;
    
    function setState(v) {
      RELAY.write(v);
      LED.write(!v);
      mqtt.publish(PATH+"status", v?1:0);
    }
    
    function mqttMessage(pub) {
      console.log("MQTT=> ",pub.topic,pub.message);
    
      if (pub.topic == PATH+"set") {
        setState(pub.message!=0);
      }
      if (pub.topic == PATH+"eval") {
        try {
          mqtt.publish(PATH+"response", eval(pub.message));
        } catch(e) {
          mqtt.publish(PATH+"exception", e.toString());
        }
      }
    }
    
    function mqttConnect() {
      mqtt = require("MQTT").connect({
        host: MQTT_HOST,
      });
      mqtt.on('connected', function() {
        console.log("MQTT connected");
        setTimeout(function() {      
          mqtt.subscribe(PATH+"#");
        }, 1000);
      });
      mqtt.on('publish', mqttMessage);
    }
    
    
    function onInit() {
      console.log("Connecting WiFi");  
      setInterval(function() {
        if (!mqtt) return;
        if (!mqtt.connected) {
          console.log("MQTT disconnected... reconnecting.");
          mqtt.connect();
        }
      }, 60*1000);
    
      wifi = require("Wifi");
      wifi.on('connected',function() {
        console.log("Connected to WiFi");  
      });
      wifi.on('disconnected',function() {
        console.log("Disconnected from WiFi");  
      });
      wifi.setHostname("MYDEVICE");
      wifi.stopAP();
      wifi.connect(WIFI_NAME, WIFI_OPTIONS,
                   function(ap){ 
        console.log("Successful connect.");
      });
      // wait, and connect MQTT
      setTimeout(function() {
        console.log("MQTT connecting");
        mqttConnect();
      }, 10000);
    }
    
About

Avatar for user82278 @user82278 started