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¶m=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:
- 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.
- 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.
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.
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):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.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.
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.Finally we can use
getDevice
to initialize ourlightKitchen
checkbox, with a callback function that sets the element'schecked
property:Notes / disclaimers: