OpenHAB and HTTP Toggle Buttons

Yesterday, one of my readers contacted me to ask:

do you have en example of a switch calling a url? failing quite badly at getting it to work

So, herewith I oblige:   Here’s how I would set it up:

 sudo vi /opt/openhab/configurations/items/dolphin.items

In my Items file, I add an item:

Switch Toggle "Toggle" (all) { autoupdate="true" }

Next, I add this item to my Sitemap:

sudo vi /opt/openhab/configurations/sitemaps/dolphin.sitemap

and add it like:

 Switch item=Toggle label="Toggle"

Next, we need to create a rule to manage this toggling action into HTTP requests:

sudo vi /opt/openhab/configurations/rules/httpreq.rules

and inside this file I add two rules, one to catch the ON and one to catch the OFF:

rule updateToggleOn
when
 Item Toggle received command ON
then
 sendHttpGetRequest("http://192.168.1.5/?pin=ON")
end
rule updateToggleOff
when
 Item Toggle received command OFF
then
 sendHttpGetRequest("http://192.168.1.5/?pin=OFF")
end

Now, in this case the device I am controlling is a simple ESP8266 WebApp from https://github.com/nodemcu/nodemcuirmware/blob/master/lua_examples/webap_toggle_pin.lua to demonstrate the idea to Michael.  Since its this simple sketch, you can expect a cosmetic error to popup in openhab.log:

05:37:12.169 ERROR o.openhab.io.net.http.HttpUtil[:230]- Fatal protocol violation: org.apache.commons.httpclient.ProtocolException: The server 192.168.1.5 failed to respond with a valid HTTP response

05:37:12.169 ERROR o.openhab.io.net.http.HttpUtil[:230]- Fatal protocol violation: org.apache.commons.httpclient.ProtocolException: The server 192.168.1.5 failed to respond with a valid HTTP response

The ESP8266 sketch doesnt return a valid HTTP header. No worries though, ignore the error – it still works!

So, the above example takes care of a device needing an “on” and “off” …

But what about a a “toggle” or “momentary” button (Garage door opener for example?)

Easy:  One simple change in the Items file and one less rule:

Switch Toggle "Toggle" (all) { autoupdate="false" }

Setting Autoupdate to False it will automatically revert to the OFF position after clicking the switch…

and in the rules:

rule updateToggleOn
when
 Item Toggle received command ON
then
 sendHttpGetRequest("http://192.168.1.5/?toggle=TRUE")
end

We only need the first rule, the On state – handle the on as your toggle command…

Easy!

Advertisements