Webdesign: Javascript to detect Domoticz switch status, and onclick action for toggle switch

1.2k Views Asked by At

I'm running a simple Apache web server on Raspberry Pi. The same Pi also has Domoticz installed.

I'm currently developing a web front end for Domoticz.

For test purposes I've set up a dummy switch in Domoticz, and I can toggle it on/off via this JSON URL:

http://10.0.0.104:6060/json.htm?type=command&param=switchlight&idx=2&switchcmd=Toggle

On the webpage I've developed, I've made some nice toggle switch buttons using bootstrap;

Kitchen:<input type="checkbox" checked data-toggle="toggle" data-onstyle="primary" data-on="On" data-off="Off">

I'm trying to achieve two things, but I'm a newbie programmer and don't know enough about programming to Google for the correct code:

  1. Some type of script (I presume JavaScript) that, when the page loads, detects if the light is turned on or off and sets the button accordingly.
  2. Help with the button onlick code. When the button is clicked I want the browser to send the JSON call and change the button without seeing the text output I get when I enter the above mentioned URL.
1

There are 1 best solutions below

0
On

For a light switch, at the fundamental level, you need a UI widget that can represent two states - on and off.

HTML has a few built-in UI widgets (text boxes, buttons, lists, checkboxes). Many JavaScript libraries exist that add countless other widgets, or make the existing ones prettier. But for the start let's stick with the basics.

The widget that fits the "on/off" behavior most closely is the checkbox.

<input type="checkbox" id="lightKitchen">
<label for="lightKitchen">Kitchen</label> 

First we need something that detects state changes on that widget. We can add a script that listens to "click" events on that checkbox (we will implement switchLight() in the next step):

var lightKitchen = document.getElementById("lightKitchen");

lightKitchen.addEventListener("click", function (event) {
    console.log("Kitchen Light: " + this.checked);
    switchLight(2, this.checked);
});

Next we add a function that can set a certain light to a certain state. The function needs the light ID and the desired state so it can construct the proper parameter string (we will implement sendCommand() in the next step). For the sake of simplicity, let's not care about the server's response right now.

function switchLight(idx, state) {
    var value = state ? "On" : "Off";
    sendCommand("type=command&param=switchlight&idx=" + idx + "&switchcmd=" + value);
}

Now we need a worker function that sends HTTP commands to the Domoticz instance. Since that always has the same basic form, we can attach the parameters to a constant base URL here. The response will be in JSON format, so we need to parse that before we can pass any contained data to the caller.

function sendCommand(parameters, onLoad) {
    var url = "http://10.0.0.104:6060/json.htm?" + parameters;
    var request = new XMLHttpRequest();

    request.open("get", url);
    request.addEventListener("load", function (response) {
        var data;
        try {
            data = JSON.parse(response);
        } catch (ex) {
            console.log("Server responded with invalid JSON to: " + url);
        }
        if (onLoad) onLoad(data);
    });
    request.send();
}

And of course we need something that retrieves the current state of a device. We can re-use sendCommand for that, but this time we actually are interested in the response, so we allow passing in a callback function.

function getDevice(idx, onLoad) {
    sendCommand("type=devices&rid=" + idx, onLoad);
}

Finally we can use getDevice to initialize our lightKitchen checkbox, with a callback function that sets the element's checked property:

getDevice(2, function (device) {
    var lightKitchen = document.getElementById("lightKitchen");
    var lightKitchen.checked = (device.Status  === "On");
});

Notes / disclaimers:

  • I tried to write self-explanatory code, so there are no code comments.
  • I don't know anything about domoticz, really. All of the above is extracted from reading the source code and making educated guesses.
  • There probably are errors, bad assumptions and other mistakes in there. The documentation of domoticz is lackluster and incomplete and I have no way of testing any of this. The above is meant to be educational, not copy-and-paste-ready.
  • You can use jQuery (among other things) to make the JS code quite a lot nicer. I did not do that deliberately, to provide a complete picture of the basic steps you need in order to bind an HTML checkbox to some remote state (in this case, a light switch as provided by a JSON API) while keeping the learning curve as shallow as possible.
  • You will need to experiment with the API. I recommend a tool like Postman for that. Figure out what parameter it supports, what values those parameters can have and how the responses look like.
  • You will need to learn to use the browser's developer tools, integrated debugger, and network analyzer.
  • You will need to read a lot of documentation. Hours, days of reading. I'm not trying to deter you, but since you are a beginner - that's what things are like. For anthing HTML, JavaScript and basic web APIs, MDN is awesome.
  • You will probably rewrite most of the above. In doing so, avoid to copy and paste code. Try to abstract and parameterize, like I did.