R&D Publishing‎ > ‎

Raspberry Pi Arduino Openhab


Raspberry Pi Program Arduino Over Serial/ttyAMA0 by avrdude with auto reset

posted 27 Feb 2017, 09:20 by Nhan Le Duy   [ updated 27 Feb 2017, 09:20 by Lê Duy Nhân ]

1. Googge it to enable serial port uart on Rpi (look at /boot/config.txt and /boot/cmdline.txt)
2. Install Avrdude as this $sudo apt-het install avrdude
    the avrdude.conf is in /etc/avrdude.conf, take a look to read it for extend control later
3. If you need auto reset on programming please install wiringPi for GPIO conrol
4. Create a folder name arduino and create a 'bash' file upload (For eample file below is using for program Arduino Pro Mini at baud=57600)

#!/bin/bash
gpio mode 28 out
gpio write 28 1
gpio write 28 0
gpio write 28 1
avrdude /etc/avrdude.conf -v -V -patmega328p -carduino -P /dev/ttyAMA0 -b57600 -D -Uflash:w:$1:i
gpio mode 28 in

5. Connect Reset Pin to GPIO28
6. For example you need to program modbus.hex to Arduino Pro: 
        pi@raspberrypi:~/arduino $ nano upload modbus.hex
7. Complete


 

Remote upload Hex to Arduino over Raspberry Pi

posted 18 Feb 2017, 22:29 by Nhan Le Duy   [ updated 18 Feb 2017, 22:31 by Lê Duy Nhân ]

1. Remote upload code(Hex file) to Arduino over Rpi with auto reset
-  Install Wiringpi
- Install Avrdude
- Create a folder Arduino on home/pi
- Copy file hex to this folder by using WINCSP
- Create a file such as upload.sh with content like this

#!/bin/bash
gpio mode 26 out
gpio write 26 1
gpio write 26 0
gpio write 26 1
gpio mode 26 in
/usr/bin/avrdude -q -V -D -p atmega328p -C /etc/avrdude.conf -c arduino -b 57600 -P /dev/ttyAMA0 -U flash:w:$1:i

We use GPIO26 for DTR pin to reset Arduino
Remember replacing parameter MCU type for your case

2. GPIO Raspberry and WiringPi pin Map




OpenHAB/MQTT Tips & Hints

posted 1 May 2015, 23:45 by Lê Duy Nhân   [ updated 1 May 2015, 23:45 ]

  • OpenHAB/MQTT Tips & Hints


    This topic was split off http://forum.mysensors.org/topic/301/the-best-way-to-connect-to-openhab to discuss tips and hints specific to using MySensors together with MQTT middleware and OpenHAB.
    If you made something nice using this combination or have some questions/issues please post them in here!


    @kolaf I just started experimenting with openhab and find it quite hard to get started. There's some documentation ( far from complete, especially when you're just starting) but the general impression is that it's very powerful, mainly due to all the programming options. I'm quite sure you could directly talk to a mysensors gateway using the serial protocol, using e.g. rules, if you want.
    I doubt however if you want to write your own protocol handler...
    Anyway, I'm currently using an Ethernet gateway which tasks to a Perl script I wrote (https://github.com/Yveaux/MySensors_MQTTGateway) that does the conversion to and from MQTT. This script is a MQTT client that runs on the same server I run openhab and the mosquitto broker on. This is the only difference compared to @Damme solution who runs a broker on the gateway.
    I like the flexibility of storing & accessing all data through an MQTT broker which makes up for the apparent overkill going through MQTT just to connect mysensors to openhab.
    As long as your server has enough resources to run it all its not really worth the effort to directly talk to my sensors or create an openhab binding for it.

     Yveaux posted 8 months ago , last edited by Yveaux 8 months ago
     •  0
  • Posts 24 | Views 4.5k
  • @kolaf said:

    how do you use the mqtt binding to talk to the sensors?

    I'm not at my PC right now so I can't add any actual code, but let's take the switch as an example.
    A sensor (with say, id 100) which has the switch connected sends a 1 when pressed and a 0 when released to the gateway, with child I'd 7. This comes out the gateway and is picked up by the perl script. The script publishes this to /mysensors/100/7/V_LIGHT.
    You define a switch item in openhab which subscribes to this topic. To read the state of the switch openhab expects either ON or OFF from MQTT instead of 1 or 0 sent by the sensor. I could have changed this on the sensor side, but I choose to implement a map-transformation on the openhab-side. Now the state of the switch changes to ON when pressed on the sensor.

    I also implemented a dimmer which can be controlled by 1or 2 momentary switches (on different nodes) and an rgb dimmer so far. Maybe we can start a separate topic on MQTT & openhab usage for different sensors so we can all benefit from it.

     Yveaux posted 8 months ago , last edited by Yveaux 8 months ago
     •  1
  • @Yveaux said:

    I also implemented a dimmer which can be controlled by 1or 2 momentary switches (on different nodes) and an rgb dimmer so far. Maybe we can start a separate topic on MQTT & openhab usage for different sensors so we can all benefit from it.

    Good idea. If someone made a good, or at least workable and well-documented, solution than I am sure this project would be much utilised by the openHAB crowd as well. Maybe explaining it to me could be a good start for a how to/guide which could also be utilised in their wiki?

    I hope I'm not stepping on any Vera toes when saying this?

     kolaf posted 8 months ago
     •  0
  • @kolaf said:

    I hope I'm not stepping on any Vera toes when saying this?

    Not everybody owns a vera and IMHO it's only beneficial for this project when multiple home automation systems are supported. Finding a greatest common divider for e.g. the types of variables will only improve things.

     Yveaux posted 8 months ago
     •  0
  • @Yveaux good, I agree, and I am glad to hear it.

    How would you solve a toggle switch? The sensor does not know whether the light is on or off since it may be toggled through the controller separately. This means that in my head it will simply send "on" every time and it is up to the item/map to figure out whether it should be turned on or off depending on its current state. I guess this may be required as a rule. Or does your server support sending items dated back to the sensor so that it knows whether the light is off or on currently? In that case it can make the decision itself and send the correct on or off command. Maybe I should ask this question in the openhab group...

     kolaf posted 8 months ago , last edited by kolaf 8 months ago
     •  0
  • @kolaf : I´m not very experienced in Java, so the code reflects my missing knowledge and is much longer than it should be.

    The purpose of "Split Message" is to split multilpe messages into single messages and afterward split this single messages into useful informations to set the OpenHAB items accordingly.

    First part: common declarations

    import org.openhab.core.library.types.*
    import org.openhab.core.persistence.*
    import org.openhab.model.script.actions.*
    
    var String[] buffer
    var String[] linebuffer
    var int SensorID
    var int transmissions_old = 0
    var int transmissions_new = 0  
    var int transmissions_missed = 0 
    var int RadioID
    

    Second part: Splitting multiple Messages

    rule SplitMessage
    when 
        Item Arduino changed
     then
     /* Split messages separated with NEWLINE */
    linebuffer=  Arduino.state.toString.split("\n")
    

    Third part: Splitting messages according to the serial protocol
    buffer(0) = NODE_ID
    buffer(1) = CHILD_ID
    buffer(2) = MESSAGE_TYPE
    buffer(3) = SUB_TYPE
    buffer(4) = Message

     for (String element : linebuffer) {
        buffer = element.split(";")
        RadioID = new Integer(buffer.get(0))
        
        switch (RadioID) {
        case 7: {
                SensorID = new Integer(buffer.get(1))
                switch (SensorID) {
                    case 0 : postUpdate (MySensorsT0, buffer.get(4))
                    case 1 : postUpdate (MySensorsT1, buffer.get(4))
                    case 2 : postUpdate (MySensorsT2, buffer.get(4))
                    case 3 : postUpdate (MySensorsT3, buffer.get(4))
                    } /*switch (SensorID) */
                    
                }  /* case 7 */
        case 6: {                                                    /* ExperimentalNode 6 - soll mal NODE 1 werden */
                if (buffer.get(1)== "10") {                          /* child 10 ist der Homematic Anschluss */
                    postUpdate (HMSerialOut, buffer.get(4)) 
                } /* if */
        } /* case 6 */
        case 9: {                                                      /* eigentlich war das mal NODE 6 */
                if (buffer.get(1) == "2") {                            /* Child 2 ist der Schrittmacher      */
                    transmissions_new = new Integer(buffer.get(4))
                    logInfo ("TRANS","Transmissions new " + transmissions_new.toString() )
                    logInfo ("TRANS","Transmissions old " + transmissions_old.toString() )
                    if (transmissions_old == 0) {transmissions_old = transmissions_new -1 } /* beim ersten mal passiert nichts */
                    transmissions_missed = transmissions_missed + (transmissions_new - transmissions_old - 1)
                    transmissions_old = transmissions_new 
                    postUpdate (Missed_Transmissions, transmissions_missed.intValue.toString)
                    postUpdate (Transmission_Count, transmissions_new.toString())
                    }
                } /* case 9 */
        case 5: {
                    if (buffer.get(1) == "0") {                         /* Child 0 ist die Luftfeuchte */
                        postUpdate (MySensorsMobHum, buffer.get(4))
                        }
                    if (buffer.get(1) == "1") {                         /* Child 1 ist die Temperatur */
                        postUpdate (MySensorsMobTemp, buffer.get(4))
                        }
                                
                } /*case 5: */
        default:    {
                postUpdate (MySensorsNode, buffer.get(0))
                postUpdate (MySensorsChild, buffer.get(1))
                postUpdate (MySensorsMtype, buffer.get(2))
                postUpdate (MySensorsStype, buffer.get(3))
                postUpdate (MySensorsMessage, buffer.get(4)) 
                }
                
          }   /*switch(RadioID) */          
        } /*for (String element) */
        
    end
    

    So the drawback of the serial binding becomes obvious - every action has to be coded separately. On the other hand it offers enormous controlling possibilities (eg scene configurations),

    Fourth part: some actions triggerd from OpenHAB GUI/Webinterface:

    rule ArdSwon
    when 
        Item ArduinoSwitch changed from OFF to ON
    then
        sendCommand(Arduino, "4;2;1;0;2;1\n")
    end
    
    rule ArdSwoff
    when 
        Item ArduinoSwitch changed from ON to OFF
    then
        sendCommand(Arduino, "4;2;1;0;2;0\n")
    end
    
    rule HmArdon
    when
     Item ArduinoHMSw1  changed from ON to OFF
    then
        sendCommand(Arduino, "1;10;1;0;24;HD01004000000\n")
    end
    
    rule HmArdoff
    when
     Item ArduinoHMSw1  changed from OFF to ON
    then
        sendCommand(Arduino, "1;10;1;0;24;HD01004010000\n")
    end
    

    To send commands to the MySensors Network you have to use the same "Arduino"Item. In my oppinion another drawback. A separate way out would be nicer. Despite of my oppinion there is no interference between input and output - so i can live with this.

    The above example illustrates controlling a LED connected to an Arduino-UNO with the original Relais-Sketch, the second part controls some of my Homematic devices via another MySensors node (connected to Homematic via USB) .

    So at last I got a 2.4Ghz network to communicate with my Homematic and an ethernet connection via OpenHAB. In combination with direct interaction between certain MySensor nodes this results in a very redundant and stress-resistant home controlling network.

     tboha posted 8 months ago
     •  0
  • @kolaf said:

    Or does your server support sending items dated back to the sensor so that it knows whether the light is off or on currently?

    To make sure I understand you right, are both the switch & light located at the same node or do you have a sensor node (switch) and actuator node (light) ?

     Yveaux posted 8 months ago
     •  0
  • @Yveaux said:

    @kolaf said:

    Or does your server support sending items dated back to the sensor so that it knows whether the light is off or on currently?

    The light is entirely separate from the switch. In my specific case it will typically be a Z-wave relay controlling the light, so I will have to map the toggle switch to the light relay in openhab. This is why I assume I have to use a rule to achieve this.

     kolaf posted 8 months ago
     •  0
  • @kolaf Here's my code to use one or two switches to dimm. I hope it gives you some inspiration to connect your zwave switch.

    MQTT topics (exposed by the MQTT perl script. Node 120 = switch sensor, node 119 = dimmable light):

    /mySensors/120/0/V_LIGHT           switch, reporting 1 when pressed, 0 when released
    /mySensors/120/1/V_LIGHT           switch, reporting 1 when pressed, 0 when released
    /mySensors/120/2/V_LIGHT           switch, reporting 1 when pressed, 0 when released
    /mySensors/119/0/V_DIMMER          dimmable light, accepting integer value between 0 and 100
    

    Items:

    Switch Switch_Up               {mqtt="<[server:/mySensors/120/0/V_LIGHT:state:MAP(switchFromMqtt.map)]"}
    Switch Switch_Down             {mqtt="<[server:/mySensors/120/1/V_LIGHT:state:MAP(switchFromMqtt.map)]"}
    Switch Switch_UpDown           {mqtt="<[server:/mySensors/120/2/V_LIGHT:state:MAP(switchFromMqtt.map)]"}
    Dimmer Light_Dimmed   (Lights) {mqtt=">[server:/mySensors/119/0/V_DIMMER:state:*:default]"}
    

    switchFromMqtt.map: (in transform folder)

    0=OFF
    1=ON 
    

    Rules for 2-switch dimmer control (short press Switch_Up switches light on, short press Switch_Down switches light off, keep pressed to increase/decrease light level):

    val Long DimmerDelayMs = 333L 
    
    rule "DimUp"
    when
      Item Switch_Up received update ON
    then
      var Boolean dimmed = false
      do
      {
        Thread::sleep(DimmerDelayMs) 
        if (Switch_Up.state == ON)
        {
          sendCommand( Light_Dimmed, INCREASE )
          dimmed = true;
        }
      } while (dimmed)
      if (!dimmed) sendCommand( Light_Dimmed, ON )
    end
    
    rule "DimDown"
    when
      Item Switch_Down received update ON
    then
      var Boolean dimmed = false
      do
      {
        Thread::sleep(DimmerDelayMs) 
        if (Switch_Down.state == ON)
        {
          sendCommand( Light_Dimmed, DECREASE )
          dimmed = true;
        }
      } while (dimmed)
      if (!dimmed) sendCommand( Light_Dimmed, OFF )
    end
    

    Rules for 1-switch dimmer control (short press switches light on/off (depending on current state), keep pressed to increase/decrease light level):

    rule "DimUpDown"
    when
      Item Switch_UpDown received update ON
    then
      var Boolean dimmed = false
      var Number percent = 0
      if (Light_Dimmed.state instanceof DecimalType) percent = Light_Dimmed.state as DecimalType 
      do
      {
        Thread::sleep(DimmerDelayMs) 
        if (Switch_UpDown.state == ON)
        {
          // Start cycling up/down until released
          var Boolean dimmUp = percent < 100
          do
          {
            if (Light_Dimmed.state instanceof DecimalType) percent = Light_Dimmed.state as DecimalType 
            if (dimmUp) sendCommand( Light_Dimmed, INCREASE )
            else        sendCommand( Light_Dimmed, DECREASE )
            if (percent >= 100) dimmUp = false;
            if (percent <= 0)   dimmUp = true;
            dimmed = true;
            Thread::sleep(DimmerDelayMs) 
          } while (Switch_UpDown.state == ON)
        }
      } while (dimmed)
      if (!dimmed)
      {
        // Short press: switch on or off, depending on current state
        if (percent > 0)    sendCommand( Light_Dimmed, OFF )
        else                sendCommand( Light_Dimmed, ON )
      }
    end
    

    Rule for the dimmable light:

    rule "MyDimmer0"
      when
        Item Light_Dimmed received command
      then
        var Number percent = 0
      
        if(Light_Dimmed.state instanceof DecimalType) percent = Light_Dimmed.state as DecimalType 
        if(receivedCommand==INCREASE) percent = percent + 5
        if(receivedCommand==DECREASE) percent = percent - 5
        if(receivedCommand==ON) percent = 100       
        if(receivedCommand==OFF) percent = 0        
        if(percent<0)   percent = 0
        if(percent>100) percent = 100
        postUpdate(Light_Dimmed, percent)
    end
    

    Some stuff I'm still struggling with (any help/ideas appreciated):

    • Not sure if I can wrap (parts of) rules in a function to make re-use easier
    • Getting the current value of an item seems complicated first testing for DecimalType, then getting it. Maybe this can be done more efficient?
    • I use Thread::sleep to determine the timing of the buttons on the sensor node (pressed short/long). This will be influenced by the jitter on the sensor values received, but currently it seems to work fine. Furthermore Thread::sleep (probably) blocks whole rule processing, so this isn't a nice solution. The short/long presses can also be dermined on the sensor node and reported with different values, but then the sensor node is no longer a dumb switch and has to have knowledge of short/long presses....
     Yveaux posted 8 months ago
     •  1
  • @Yveaux Excellent, this is just what I needed, thank you.

    I started looking at your Perl script since this seems like the most active solution for openhab integration. I have a couple questions if you don't mind.

    Why do you have two versions of the gateway script, and which version should I use as a basis when adding serial support?

    Does your gateway take care of node ID assignments? I guess I will figure out that by reading more of code :-)

    I'm thinking that I will fork your project to add a serial option to your script, controlled by some kind of commandline argument.

     kolaf posted 8 months ago
     •  0
  • @kolaf said:

    @Yveaux Excellent, this is just what I needed, thank you.

    Glad I could help!

    Why do you have two versions of the gateway script, and which version should I use as a basis when adding serial support?

    The serial format changed from MySensors 1.3 (protocol 1) to 1.4beta (protocol 2). I was lazy and just cloned the 1.3 version to add 1.4 support (the 2-version). Wouldn't be hard to support both, but I really wrote this script for my own usage. It's not documented and I tried to help Damme in the past to build MQTT support. I'm primarily on 1.4b btw, with some 1.3 setup for backwards sniffer support...
    If more people start using it I should do some things the nice way ;-)

    Does your gateway take care of node ID assignments? I guess I will figure out that by reading more of code :-)

    Not at the moment. Shouldn't be hard to implement though, but when you implement it you run into another issue of mapping the node-ID's onto the MQTT topic tree, or accessing the right topic from OpenHAB.
    Sticking to fixed Node ID's seemed to make more sense to me.

    I'm thinking that I will fork your project to add a serial option to your script, controlled by some kind of commandline argument.

    Feel free to fork, but the current code is based on AnyEvent. Not that I like it, but it seemed to have the best MQTT support. There is some hacking in the script to get things working, for which I don't know how they behave when switching to serial.

     Yveaux posted 8 months ago
     •  0
  • Btw. there's one important thing to understand when using the Perl script. When it receives values from a sensor node through the gateway it's easy to publish the value in the topic-tree.
    When a value has to be sent to an actuator node, the story is different as the script has to know which topic to subscribe to at the MQTT broker.
    Currently when a mysensor node requests a value from the gateway the script automagically translates this into a subscription of the corresponding topic with the MQTT broker. The dimmer node for example, calls gw.request(childID, V_DIMMER) from setup to subscribe itself to dimmer messages.
    Note that sometimes this request gets lost (CRC error or so) and the subscription fails. While not supported by the MySensors library, a robust implementation should wait for a response after requesting this value and retry when it doesn't come.
    The Perl script stores all current subscriptions persistent (file subscriptions.storage) so restarting the Perl script will not force you to restart all nodes to subscribe again.

     Yveaux posted 8 months ago , last edited by Yveaux 8 months ago
     •  0
  • And another small one; an RGB dimmer!

    MQTT topics (exposed by the MQTT perl script. Node 118 = 3-channel dimmable light):

    /mySensors/118/0/V_DIMMER          dimmable light RED, accepting integer value between 0 and 100
    /mySensors/118/1/V_DIMMER          dimmable light GREEN, accepting integer value between 0 and 100
    /mySensors/118/2/V_DIMMER          dimmable light BLUE, accepting integer value between 0 and 100
    

    Items:

    Dimmer Light_R      {mqtt=">[server:/mySensors/118/0/V_DIMMER:state:*:default]"}
    Dimmer Light_G      {mqtt=">[server:/mySensors/118/1/V_DIMMER:state:*:default]"}
    Dimmer Light_B      {mqtt=">[server:/mySensors/118/2/V_DIMMER:state:*:default]"}
    Color Light_RGB     "RGB Dimmer"    (Lights)
    

    Rules to distribute colorwheel value over R,G,B dimmers:

    rule "Set RGB value"
    when
            Item Light_RGB changed
    then
            var HSBType hsbValue = Light_RGB.state as HSBType
            postUpdate( Light_R, hsbValue.red.intValue )
            postUpdate( Light_G, hsbValue.green.intValue )
            postUpdate( Light_B, hsbValue.blue.intValue )
    end
    

    No button control here; just using the colorwheel and on/off buttons in the GUI.

    Enjoy!

     Yveaux posted 8 months ago
     •  0
  • rule to calculate absolute humidity and dew point from degree Celsius and rH%

    import java.lang.Math
    import java.lang.Integer
    import java.lang.Double
    
    
    rule "Calculate absolute humidity (g h2o / m3 air) and dew point"
    when
        Item temp1 changed or
        Item hum1 changed
    then
        var temp = temp1.state as DecimalType
        var hum = hum1.state as DecimalType
        
        var t1 = (17.271*temp.floatValue) / (237.7+temp.floatValue) + Math::log(hum.floatValue*0.01)
        var dew = (237.7 * t1) / (17.271 - t1)
        var Number c1 = ((17.67*temp.floatValue)/(temp.floatValue+243.5))
        var abs = (Math::pow(Math::E,c1.doubleValue)*6.112*2.1674*hum.floatValue) /(273.15+temp.floatValue)
        
        Dewpoint1.postUpdate(dew)
        AbsHum1.postUpdate(abs)
    end
     Damme posted 8 months ago , last edited by Damme 8 months ago
     •  0
  • @Damme Nice calculation example! Thanks!

     Yveaux posted 8 months ago
     •  0
  • Hi everyone!

    I'm new in the topic. I find it very interesting the world of mysensors.
    I would like to ask whether there is a description of someone that I can set my mqtt openHAB bindings eg .: an Arduino LED dimmer ?

    I already read http://forum.mysensors.org/topic/303/mqtt broker-gateway
    I made a Humidity sensor node, and Relay node, too.

    It would be good if we had a basic description or example project for beginners from all sensor type. :)

     Dany posted 6 months ago
     •  0
  • It is not rocket science to get the openHAB running w/MQTT gateway, see for example my post with DS/Light/Relay inhttp://forum.mysensors.org/topic/115/implementing-multiple-sensors/60

    But sure, it would be great to put a wiki with all sensor settings for openHAB together on one page. I needed to read/search for some days to put the knowledge together...

    Example of the openhab screenshots on mobile https://github.com/pgo-sk/mysensors/wiki/Home-automation-using-mysensors-and-openHAB
    There you see also the mapping of the sensor

     pgo posted 6 months ago , last edited by pgo 6 months ago
     •  1
  • How can I make openhad respod to gw.request(sensor, V_HEATER_SW,0);

    I have a relay actuator sketch and in setup() I have this

    for (int sensor=1 ; sensor<=NUMBER_OF_RELAYS;sensor++)
    {
    gw.present(sensor, S_HEATER);
    gw.request(sensor, V_HEATER_SW,0);
    }

    practically I would like openhab to respond to the gw.request with the actual state of the relay.

    My item definition is the follwing. I am able to ON and OFF the relay, but I need to find a way to get the values from openhab of the relays when the relay actuator arduino reboots.

    Switch Incalzire_Releu_GF_Living2 "Incalzire Releu Living 2" <heating> (Incalzire) {mqtt=">[mysensor:MyMQTT/3/2/V_HEATER_SW:command:ON:1],>[mysensor:MyMQTT/3/2/V_HEATER_SW:command:OFF:0]"}

     adi32k posted 5 months ago
     •  0
  • is there any sample code for controlling RGB led here?

     raditv posted 5 months ago
     •  0
  • Sorry to Necro this thread but had a question,

    I believe I read somewhere that you can use a serial gateway connected to a pi and have openhab/mqtt run on the pi?

    How would one go about setting this up? Currently I have 2 Unos one running as the serial gateway. I plan to replace the serial gateway with a nano I'm still waiting on that.

    I just got the pi last night so I'm still working on getting everything up and running on that but I'd rather just connect the gateway directly to the pi rather than have to get a wifi/ethernet module for one of the arduinos.

    Also probably outside the scope of this thread (and thats fine) but anyone have a good guide for setting up the pi for openhab/MQTT?

     Chaotic posted 2 months ago
     •  0
  •  mhortman posted about a month ago
     •  0
  • @mhortman Didn't work for me:

    sudo wget http://repo.mosquitto.org/debian/mosquitto-wheezy.list~
    --2015-03-27 10:46:51--  http://repo.mosquitto.org/debian/mosquitto-wheezy.list~
    Resolving repo.mosquitto.org (repo.mosquitto.org)... 85.119.83.194, 2001:ba8:1f1:f271::2
    Connecting to repo.mosquitto.org (repo.mosquitto.org)|85.119.83.194|:80... connected.
    HTTP request sent, awaiting response... 403 Forbidden
    2015-03-27 10:46:51 ERROR 403: Forbidden.'
    
     Sweebee posted about a month ago
     •  0
  • My house have 4 floor, i have plan build one gateway for each floor. Each floor has 4-5 sensors (temp, hum, relay, light, door, RF light). Each sensors use NRF24 to connect with gateway. Gateway connect to RAS by ethernet.
    My question:

    • Can i build 2 gateway mqtt connect to openhab?
      if not, what my solution to solve ?
      Thanks
     quocanhcgd posted 27 days ago
     •  0
  • you can build more than 1 gateway for that, but rather than mqtt. I think it's better to use ethernet or serial gateway because mqtt gateway has lot of problem, I tried it for months. You can forward mqtt from fhem to mosquito.

Demonstration Openhab and MQTT about Sendcommand, PostUpdate

posted 1 May 2015, 23:43 by Lê Duy Nhân   [ updated 1 May 2015, 23:43 ]

A friend of mine had a bus system installed in his apartment twenty odd years ago to control the lights, and I was suitably impressed. He raved about being able to switch on the light in the loo from the kitchen, if he so wanted. When I asked him why he'd want to do that he knew no answer, and when I asked him what the system cost, I was aghast. As I said, that was twenty years ago, but since then I associated switching lights with home automation.

In today's Internet-connected world there are an ever-growing number of nice gadgets (some of them are soo sweet -- it's hard to resist, but I tend to) that control something or other. From lights and power sockets over smoke detectors to bathroom scales and kettles, these things have Internet connectivity, and each of them has an individual supercool smartphone app that controls it. The result: a bunch of connected (but disconnected, if you know what I mean) "Things of the Internet" and a large number of Apps, one for each "Thing". (Which app do I need to switch on the kettle? Oh, no: that's the scales app, ...)

Home automation to me is more than just switching lights. Home automation is switching lights, controlling heating and other appliances, and having an intelligent system decide when to do what (from human input, of course). Lights, for example, should extinguish when everybody's left the house. On the other hand, certain lights should go on when it gets dark, even if nobody's at home, and the heating in the living room should power up just as I leave work, except when I'm on holiday. I should be able to override all of this (and much more) when on the road, and the system must be extensible, allowing integration of new appliances and "things".

openHAB Web interface

Home automation here at Casa Mens has one absolute requirement: the WAF must be extremely high; anything else just won't cut it. It's OK for me to have to reboot/restart the odd component, but if I have to tell the "CEO" over the phone to do that, I needn't return home.

Getting an automation project past the "management" was astonishingly easy: I said we could save money on the cost of energy (without actually having calculated how much we'd save... I also kind of forgot to mention a startup investment), and the project commenced.

I spent many hours scourging the internets on information about thermostats, and got fed up. Along the way I heard of openHAB and got sidetracked in a test drive on my laptop whilst sitting in a hotel room. I didn't have hardware I could control, but a couple of openHAB's "bindings" (HTTP and MQTT in particular) allowed me to get a first impression of what the system was capable of. Returning home, I hooked up our Fritz!Box and the Sonos, and it all worked.

So now it was time to re-investigate hardware which could be controlled with openHAB. To cut a very long story short, I decided to ignore automating the heating (for the moment), and I settled on ELV MAX! as an entry-level system: their radiator thermostats are practical and good-looking, and the startup price was reasonable. I kept in mind that openHAB would be able to drive MAX! if I so wanted.

The MAX! system was set up and ready to roll in half an hour, and I was congratulated the following week when the bathroom was crispy warm in the morning (Winter is a good season to implement heating automation.) This would have been the end of the story, but I couldn't stop thinking about some neat things we could do with openHAB...

openHAB

openHAB controls "things", and it can talk to the outside world: it sends e-mail, speaks XMPP, launches programs, stores state in SQL (or other) databases, but it does only what you want it to; you don't need a database if you don't want it, and you don't have to invest the EUR 10,000 in a special home-automation thing if you can't. (Other systems come to mind: Fhemthe thing system, and many more, and no: I cannot compare them.)

openHAB can do things like execute a program when a particular event is detected (press a switch on the UI, fire up a UNIX program), send an e-mail or even use Twitter for notifications. I've decided to use MQTT as my notification "bus" of choice (reasons below).

If you want to mute your Sonos when the phone rings on the Fritz!BoxopenHAB can accomplish that.

openHAB runs on small hardware (yes, also a Raspberry Pi) which means you don't need an expensive, power-hungry server to run it on.

Z-Wave

That's all fine and dandy, but how do I control appliances such as lights, etc.? I spent a bit of time investigating home automation networks of which there are probably dozens. Names such ashomematicZ-WaveKNX, are readily available, and they all have all sorts of actuators and sensors. They also have one thing in common: none of those are particularly inexpensive.

Ben Jones convinced me to look into Z-Wave, and I took the plunge and started very modestly with an Aeon Z-Wave USB stick and three Fibaro wall-socket plugs. Ben warned me that Z-Wave is addictive, and Jakob Schlyter said I was embarking on a potentially expensive journey. Both gentlemen are right. :-)

AEON USB

The USB thing is the Z-Wave controller which, in disconnected state, is used to include the Z-Wave nodes with the controller. Once plugged in to a USB host port, it hopefully starts chatting to the nodes which, together, create a mesh network. A Z-Wave controller can, say, tell a wall plug to switch itself on, and it receives feedback from the node whether the operation was completed.

Z-Wave architecture

Z-Wave consists of controllers and slaves. Slaves are sensors which transmit metered data or they are actuators which are capable of executing an action, such as turning a lamp on. To complicate the issue, some actuators contain sensors (for example, the Fibaro plugs report current consumption of the plug as well as being able to switch it on or off). Controllers (sometimes called gateways) are typically mains-powered. Further, we have battery-operated remote controllers. All this results in a large number of possible communication patterns, not all of which are supported by all devices! Basically

  • Controllers control actuators
  • Actuators report change of status back to the controller. In other words, switching, say, a lamp, will cause that switch to report back whether it actually switched -- it reports a state.
  • Sensors control actuators and actuators can control other actuators.
  • Remote controls send signals to actuators or controllers.

Still with me?

So, after associating ("including") all nodes onto the Aeon USB stick I was a bit stuck: Z-Wave nodes have numbers, but which is which?

I used DomotiGa with its Z-Wave Commander to see what my small Z-Wave network consits of:

domotina zwave explorer

Once I knew that the Z-Wave stuff was working and nodes were seeing each other, I wired up an initial openHAB configuration for the three wall plugs. openHAB immediately saw the plugs and I could play blinkenlights.

openHAB consists of a headless program (called the 'runtime') which provides an event bus. This receives events and sets states and timers from "items". An item is something connected to that bus; it can be a toaster, the temperature in a particular room, a light switch, an MQTT topic, or an SNMP event. Items states are obtained from an ever-increasing number of "bindings" provided by the project and I can surface individual switches from those bindings onto a UI if I so desire.

openHAB architecture

Configuring openHAB

openhab.cfg contains what I call base-level configuration of the bindings. This is a snippet from myopenhab.cfg in which I configure how the sonos binding should find our Sonos system, how the mqttbinding should talk to my MQTT broker, where my Fritz!Box is, and where the Z-Wave port is.

sonos:office.udn=RINCON_000xxxxxxxxxxxxxx
...
mqtt:hippo.url=tcp://hippo.ww.mens.de:1883
mqtt:hippo.clientId=ohab1
mqtt:hippo.qos=1
...
fritzbox:ip=192.168.1.1
...
zwave:port=/dev/ttyUSB2

(While I'm at it: I'll be using a bit of MQTT in this account, but it's not a requirement: openHABdoesn't require MQTT -- it's a possible transport which I'm using because it fascinates me.)

openHAB's item and sitemap configuration is stored in plain text files which I can edit with a text editor or via a tool called the Designer, which does syntax checks etc. The runtime detects changes to the configuration and reloads them on the fly. (openHAB has Dropbox support, so I can also change configuration when en-route and have that reloaded as soon as I synchronize, but a Samba share also does the trick.) I quickly tired of the Designer and just use a text editor: openHAB reports syntax errors when it loads its configuration, and that's fine for me.

This is the configuration for a so-called item which "reads" from the MQTT binding. It translates to a number. The syntax is a bit strange-looking, but one does get used to it after a while.

Number YoulessPower
        "YouLess [%.1f W]"
        <energy>
        (zPower)
        { mqtt="<[hippo:hw/youless:state:REGEX((.*))]" }

It obtains the current energy consumption from my YouLess meter which I periodically publish to an MQTT topic.

The Fibaro wall plug, is an example of a Z-Wave actuator which has a bit more complex configuration with a switch and two numbers; the former switches the power proper, and the latter return current utilization and total energy consumption on the device.

Fibaro wall plug

Switch Z_Kitchen
    "Kitchen plug"
    (Lights)
    {zwave="2:command=switch_binary"}
Number Z_Kitchen_Power
    "Kitchen power  [%.1f W]"
    (zPower)
    { zwave="2:command=sensor_multilevel" }
Number Z_Kitchen_Energy
    "Kitchen consumption  [%.2f KWh]"
    (zPower)
    { zwave="2:command=meter" }

So far we've seen a few item configurations. These I assemble into a so-called sitemap which looks like this and which renders to the Web interface shown up top:

sitemap blog label="Main Menu" {
   Frame label="Info" {
        Text item=Temp_Sensor_Balcony
   }

   Frame label="Lights" {
        Switch item=Z_Kitchen label="Kitchen"
   }

   Frame {
        Text item=currenttitle
   }

   Frame {
        Text item=YoulessPower
   }

 }

Rules

openHAB has a very powerful rules system with which people do all sorts of stuff such as querying if it's dark (sensor) and if it's summer (weather service over XML) switch the lights off in the garden if the owner isn't there (presence).

My trivial example switches the kitchen light off at 22:15.

rule "Switch lights off"
when
    Time cron "0 15 22 * * ?"
then
    sendCommand(Z_Kitchen, OFF)
end

Moar Z-Wave

Remember Ben & Jakob saying "addictive" and "expensive" respectively. Damn right! I'd read about a KFOB (I still don't really know what that abbreviation means), a small remote controller on a key chainand considered that ideal to increase the WAF; it wouldn't be necessary to fire up an app on an iPad to switch lights.

This battery-operated device was a nightmare for me. I wanted it to talk to openHAB so that I could configure the latter to react to a key press on the former. Nothing doing. I gave up and re-read the light instruction manual for the 9th time to set up associations. An association (which isn't the same as an inclusion) means I can configure particular Z-Wave devices to talk directly to actuations. So, after clicking a lot of buttons, the KFOB thing told a Fibaro wall switch directly to turn itself on or off, without openHAB's intervention. (I understand this has been solved meanwhile in the Z-Wave binding, but I don't care to test it at this point.)

KFOB

So, how do I control in-wall switches? Fibaro has micro-switches (called relays) which are built in to the switch directly in the wall. The switch, which doesn't have to be a toggle, any will do) tells the relay to switch, and the relay then controls the load.

Installing micro switch

They're brilliant, and they worked immediately, just like the Fibaro wall plugs. Lovely kit!

If I thought the KFOB was a nightmare, I wasn't prepared for the Aeotec MultiSensor 4-in-1.

Aeotec MultiSensor

A really nice device, theoretically anyway, but I did loose a lot of hair and sleep (full story).

The sensor is able to report four different values, and we account for that in our configuration (here just two): the Z-Wave device I use remains the same (node 10), but we use different sensor types:

Number Temp_Sensor_Balcony
        "Outside [%.1f °C]"
        <temperature>
        (Balcony, All_Sensors)
        {zwave="10:1:command=SENSOR_MULTILEVEL,sensor_type=1"}
Number Humid_Sensor_Balcony
        "Relative humidity: [%.0f %%]"
        <water>
        (Balcony, All_Sensors)
        {zwave="10:1:command=SENSOR_MULTILEVEL,sensor_type=5"}

The end result, all on a single sitemap looks like this, and believe me, was I happy to finally see this data being reported by the device.

multisensor has multiple sensors

Persistence

Persistence support in openHAB allows me to store item states over time using a data store (of which there are several). I can configure which items to persist (on an item- or group-basis) and how often values should be persisted.

Strategies {
    everyHour : "0 0 * * * ?"
    default = everyChange, everyUpdate, restoreOnStartup
}

Items {
    zPower* : strategy = everyChange, restoreOnStartup
    ...
}

Using HABmin (a sub-project of openHAB, hopefully soon to be integrated) I can view graphs from the persistence databases, produce tables, etc.

HABmin persistance

MQTT in openHAB

You may be wondering about my liberal use of MQTT in openHAB. I'll admit to being addicted toMQTT, and this "twitter for my network" (self-quote) allows me to easily talk to or listen to openHAB without bothering with specific binding configurations of the latter.

  1. Alerts from openHAB are posted to MQTT, and I can notify external parties.
  2. openHAB has a Twitter action, but I already have that using MQTT, so I don't have to worry about specific Twitter configuration for openHAB.
  3. I can use MQTT inbound messages in openHAB to update items (i.e. flick switches).

The transport for the MQTT binding is configured as above in openhab.cfg, but I can also add what is called an Event Bus configuration.

mqtt-eventbus:broker=hippo
mqtt-eventbus:commandPublishTopic=home/openHAB/out/${item}/command
mqtt-eventbus:statePublishTopic=home/openHAB/state/${item}/state

this causes all commands and states to be published to an MQTT broker. (Additionally, I can configureopenHAB to receive status updates from a broker e.g. for linking two openHAB instances together.)

With above snippet, whenever openHAB sees something happening on its event bus, it will publish a message to my broker:

home/openHAB/state/YoulessPower/state 627
home/openHAB/state/currenttrack/state Patricia Kaas - Je Te Dis Vous - Reste Sur Moi
home/openHAB/state/JPhttp/state 17
home/openHAB/state/Z_Dining_Energy/state 11.5
home/openHAB/state/Motion_Sensor_Balcony/state CLOSED
...
home/openHAB/out/Z_Kitchen/command ON
home/openHAB/state/Z_Kitchen/state ON
home/openHAB/state/Z_Kitchen_Power/state 183.2
...

If you look at the last three lines, the following happened:

  1. I switched on the kitchen lamp (command)
  2. The Fibaro switch reported its current state
  3. The Fibaro switch reported a value for power consumption

(I haven't tried yet, but my use of MQTT ought to enable a different interface to the hardware (via openHAB and MQTT) using homA.)

REST API

openHAB REST API allows me to access its sitemaps, and it allows me read access to items and theirstates as well as submitting commands to items. For example, the following item subscribes to anMQTT topic, and I would presumably display the resulting string on a sitemap (e.g. as an information display)

String mqstr1
    "MQTT input [%s]"
    { mqtt="<[hippo:hab/mystr:state:default]" }

If I now publish a value onto that openHAB item (mosquitto_pub -t hab/mystr -m "Hello MQTT!") I could use the HTTP REST API to read it back:

curl http://localhost:8080/rest/items/mqstr1
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<item>
  <type>StringItem</type>
  <name>mqstr1</name>
  <state>Hello MQTT!</state>
  <link>http://localhost:8080/rest/items/mqstr1</link>
</item>

or in JSON by appending ?type=json to the query

{
  "link": "http://localhost:8080/rest/items/mqstr1",
  "name": "mqstr1",
  "state": "Hello MQTT!",
  "type": "StringItem"
}

(I have formatted the output for clarity.)

I can also query the state which is returned as a plain string

$ curl http://localhost:8080/rest/items/mqonoff/state     # a switch
ON
$ curl http://localhost:8080/rest/items/mqstr1/state      # a text string
Hello MQTT!

and I can update that state:

$ curl -XPUT -H "Content-Type:text/plain"  http://localhost:8080/rest/items/mqonoff/state -d OFF

or send a command to, say, switch the kitchen lamp off

curl -XPOST -H "Content-Type:text/plain"  http://localhost:8080/rest/items/Z_Kitchen -d OFF

Mobile

openHAB has provision for securing access to it with TLS and basic user/password authentication, and it can be configured to insist on both for a particular interface. Coupled with one of the mobile apps (for iOS and Android) this enables people to control their home from en-route.

openHAB on iPhone

The mobile apps display one or more of the sitemaps configured in openHAB which is good: I create a sitemap which is can be controlled by a Web browser or the mobile apps.

I personally don't want to be able to control my home from the Internet (I'm a little paranoid, I admit), but many people want to be able to do that.

Wrapping up

openHAB isn't easy to learn (and I'm far from understanding all that is going on under the hood), but it certainly is very powerful. I'll admit to groaning at the fact that it's pure Java, but it really does run on a small platform. (Even so, I recommend something faster than a Raspberry Pi, at least at the beginning when you will be stopping/starting openHAB frequently, because startup times on the Pi are abysmal.) openHAB's documentation is sufficient, but the really good configuration examples are strewn over the mailing-list; that's where to get help -- there are some really experienced people who are willing to help.

I'm very pleased with the hardware; Z-Wave works well with good devices, but you need a bit of patience to get it all going smoothly. Once everything is correctly set up, it seems to just work. (Remind me about the battery-powered MultiSensor to get my blood boiling...) The kit isn't cheap, but I think it's there to last; even if I decide to no longer use openHAB (which I doubt at this time), there's plenty of software support for Z-Wave devices.

Related:

OpenHAB - Explanation of items

posted 1 May 2015, 06:04 by Lê Duy Nhân   [ updated 1 May 2015, 06:04 ]

introduction

  • Items are objects that can be read from or written to in order to interact with them.

  • Items can be bound to bindings i.e. for reading the status from e.g. KNX or for updating them. Read the wiki page for the respective binding for more help and examples.

  • Items can be defined in files in folder ${openhab_home}/configurations/items.

  • All item definition files have to have the file extension .items Just create a new file called thenameyouwish.items.

  • Groups are also defined in the .items files. Groups can be inside groups, and items can be in none, one or more groups.

Typically items are defined using the openHAB Designer by editing the items definition files. Doing so you will have full IDE support like syntax checking, context assist etc.

syntax

Items are defined in the followng syntax:

itemtype itemname ["labeltext"] [<iconname>] [(group1, group2, ...)] [{bindingconfig}]

Parts in square brackets [are optional.

Example:

Number Temperature_GF_Living "Temperature [%.1f °C]" <temperature> (GF_Living) {knx="1/0/15+0/0/15"}

Above example defines an item...

  • of type Number
  • with name Temperature_GF_Living
  • formatting its output in format xx.y °C
  • displaying icon temperature
  • belonging to group GF_Living
  • bound to openHAB binding knx with write group address 1/0/15 and listening group address 0/0/15

itemtype

The following item types are currently available (alphabetical order):

ItemtypeDescriptionCommand Types
ColorColor information (RGB)OnOff, IncreaseDecrease, Percent, HSB
ContactItem storing status of e.g. door/window contactsOpenClosed
DateTimeStores date and time (see NTP binding for details)
DimmerItem carrying a percentage value for dimmersOnOff, IncreaseDecrease, Percent
GroupItem to nest other items / collect them in groups-
NumberStores values in number formatDecimal
RollershutterTypically used for blindsUpDown, StopMove, Percent
StringStores textsString
SwitchTypically used for lights (on/off)OnOff

Group items can also have a summary value displayed.

  • AVG displays the average of the items in the group.
  • OR displays an OR of the group, typically used to display whether any item in a group has been set.
  • other summaries: AND, SUM, MIN, MAX, NAND, NOR

Example for a group summary:

Group:Number:AVG() itemname ["labeltext"] [<iconname>] [(group1, group2, ...)] [{bindingconfig}]
Group:Switch:OR(ON, OFF) itemname ["labeltext"] [<iconname>] [(group1, group2, ...)] [{bindingconfig}]

itemname

The item name is the unique name of the object which is used e.g. in the sitemap definition or rule definition files to access the specific item.

labeltext

The label text is used on the one hand side to display a description for the specific item e.g. in the sitemap, on the other hand to format the output of number or string item types.

Formatting is done applying standard Java formatter class syntax.

Example:

An item defined like Number MyTemp "Temperature [%.1f] °C" would be formatted for output as: "Temperature 23.2 °C"

Another possibility in labeltexts is to use so-called maps for replacing the item status name by e.g. human-readable words:

Example:

An item defined like Number WindowBathroom "Window is [MAP(en.map):%s]" would be formatted for output as: "Window is open" if there is a file called en.map in folder configurations/transform.

These map files have to be structured as simple key/value pairs: 0=closed 1=opened UNDEFINED=unknown

See the sample map files in the source code repository online here:https://github.com/openhab/openhab/tree/master/distribution/openhabhome/configurations/transform

Example:

An item defined like DateTime Weather_LastUpdate "Last Update [%1$ta %1$tR]" outputs two components which both are taken from the DateTime variable itself. So both have to reference the variable. This is done by 1$. Following t marks a time objecta and Rrepresent the date formatter "abbreviated month name" and "24-hour clock", respectively.

Note: The first 1$ is optional, as the first components always takes the first input argument. However, as the second components would take the second input argument by default but there is only one input argument (namely the DateTime variable itself), the second 1$ is essential.

iconname

The icon name is used to reference a png image file from folder${openhab_home}/webapps/images/. These icons are used in the openHAB frontends.

Please use the filename (without extension) of icons in above mentioned folder. If you append e.g. "-on" and "-off" to the file name the icon will change its appearance depending on the switch item state. Resp. you can add "-0", "-1" etc. to the filename for number items, "-on" / "-off" for switches and anything else for string items etc. A file amongst files having such additions that has no addition representes an uninitialized state. Make shure to to use small letters for filenames only.

Example:

You can use two icons "present-on.png" and "present-off.png" like this:

Switch DanHome "Dan at home" <present>

groups

Items can be linked to specific groups by referencing these in a comma separated list embraced by round brackets.

Example:

An item defined like Number MyTemp (gTempOutside, gTemperatures) would be member of the groups gTempOutside and gTemperatures

bindingconfig

Items can be bound to specific openHAB bindings by adding a binding definition in curly brackets at the end of the item definition:

{ ns1="bindingconfig1", ns2="bindingconfig2", ...}

where "nsx" is the namespace for a certain binding (e.g. "knx", "bluetooth", "serial" etc.).

For detailed binding configuration syntax of openHAB bindings please see the openHABBindings configuration section.

Example:

Switch Light_GF_Living_Table "Table" (GF_Living, Lights) { knx="1/0/15+0/0/15" }
Switch Presence { bluetooth="123456ABCD" }
Switch Doorbell "Doorbell" <bell> { serial="/dev/usb/ttyUSB0" }

examples

from the demo file

The openHAB runtime comes with a demo items file, here is a short excerpt from it:

Group            gAll
Group            Status                                                 (gAll)
Group            gGF                                                (gAll)
Group            gLights                                                (gAll)
Group            gShutters                                              (gAll)
Group            gGF_Living       "Living room"                  <video>        (gGF)
Group:Number:AVG gTemperature     "Avg. Room Temp. [%.1f °C]" <temperature> 

/* Lights */
Switch Light_GF_Living_Table     "Table"                                   (gGF_Living, gLights)

/* Rollershutters */
Rollershutter Shutter_GF_Living  "Shutter"                                 (gGF_Living, gShutters)

/* Indoor Temperatures */
Number Temperature_GF_Living     "Temperature [%.1f °C]"   <temperature>   (gTemperature, gGF_Living)
Number Temperature_GF_Kitchen    "Temperature [%.1f °C]"   <temperature>   (gTemperature, gGF_Kitchen)

Groups can be inside groups, and items can be in none, one or more groups. For example:

  • Group gGF (All) This statement defines the gGF group and states that it belongs to the All group.
  • Group GF_Living "Living room" <video> (gGF) This statement defines the group GF_Living, defines that the user interface will show it as "Living room", defines the icon to be shown and states that it belongs to (gGF). Notice that the gGF group belongs to the ALL group, hence GF_Living inherits that group, and it belongs to the All group too.
  • Group:Number:AVG Temperature "Average lighting [Lux](%.1f)" <temperature> (Status): this statement means that there is a group called Temperature, which has a value calculated as an average of all its members, and its value is a float with one decimals. It will show a temperature icon and it belongs to the Status group.

knx example

The items may include the KNX group address to use them. They might be actively read by openHAB or not. They look like this:

  • Number Lighting_Room_Sensor "Lighting in the Room [Lux](%.2f)" <switch> (Room,Lighting) { knx = "<0/1/1" }: This is a sensor item. It uses the 0/1/1 group address and openHAB will ask for its value periodically because there is a "<" sign before the address. It is a number item, called Lighting_Room_Sensor, and belongs to Room and Lighting groups.
  • Switch Light_Room_Table "Table Light" (Room, Lights) { knx = "<0/1/10+0/1/30"}: This is a switch item that has two addresses. openHAB may responds to events in any of them, but may actively read the first one.

For more info about other options have a look at the demo.items file and the wiki bindings pages.

Further examples for defining items can be found in our openHAB-samples section.

The currently implemented item types can be found in source code.

OpenHAB - Explanation of Sitemaps

posted 1 May 2015, 06:02 by Lê Duy Nhân   [ updated 1 May 2015, 06:02 ]

Introduction

Sitemaps are used to create elements of a user interface for making openHAB items accessible to various frontends.

Sitemaps are a declarative UI definition. With a few lines it is possible to define the structure and the content of your UI screens. Sitemap files are stored in${openhab_home}/configurations/sitemaps. (Syntax: yourSitemapName.sitemap)

If you create a sitemap with the name default.sitemap and the sitemap element 'default' then you do not need to specify a sitemap parameter in your URL. The URL "http://localhost:8080/openhab.app" has the same behaviour as "http://localhost:8080/openhab.app?sitemap=default".

The openHAB runtime comes with a demo sitemap file, which should let you easily understand its structure.

For easy editing, the openHAB Designer brings full IDE support for these files, so you can easily check the syntax and find out about the options you have. (Again, for the technically interested, this is also an Xtext DSL.)

Syntax

Sitemaps can be composed by grouping various user interface elements into areas, which will be rendered by openHAB.

This element is mandatory in a sitemap definition file:

Element nameDescription
sitemapThis will be the first line. It is mandatory and it states the name of your sitemap (demo) and the title of the main screen.

Element 'Sitemap'

Syntax:

sitemap [sitemapname] [label="<title of the main screen>"]

The following elements can be used optionally in a sitemap definition file (alphabetical order):

Element nameDescription
ColorpickerAllows the user to choose a color from a color wheel.
ChartAdds a time-series chart object for displaying logged data.
FrameArea with either various other sitemap elements or further nested frames
GroupRenders all elements of a given group defined in an items definiton file
ImageRenders an image
List
SelectionGives access to a new page where the user can choose among values defined in the mappings parameter.
SetpointShows a value and allows the user to modify it. Optionally, it is possible to specify maximum and minimum allowed values, as well as a step.
SliderRenders a slider
SwitchRenders a switch item
TextRenders a text element
VideoDisplays a video
Webview

Element 'Colorpicker'

Syntax:

Colorpicker [item=<itemname>] [label="<labelname>"] [icon="<iconname>"] [sendFrequency=""]

Element 'Chart'

Syntax:

Chart [item=<itemname>] [icon="<iconname>"] [label="<labelname>"] [service="<service>"] [period=xxxx] [refresh=xxxx]
  • refresh is the refresh period of the image in milliseconds
  • service sets the persistence service to use. If no service is set, openHAB will use the first queryable persistence service it finds. Therefore, for an installation with only a single persistence service, this is not required.
  • period sets the length of the time axis of the chart. Valid values are h, 4h, 8h, 12h, D, 3D, W, 2W, M, 2M, 4M, Y
  • The following parameters are only available in v1.5 and over the HTTP(S) request:
    begin / end sets the begin / end of the time axis of the chart. Valid values are in this format: yyyyMMddHHmm (yyyy := year, MM := month, dd := day, HH := hour (0-23), mm := minutes).

Note that charts are rendered by a chart provider. By default, openHAB provides a default chart provider which will work with all queryable persistence services. Other chart providers can be user to render the chart by changing the chart:provider=defaultconfiguration in openhab.cfg to the name of the alternative provider. Currently, the only alternative is to use the rrd4j provider to render the graphs.

A few technical constraints and details to be aware of:

  • When using rrd4j persistence, you must use the everyMinute (60 seconds) logging strategy otherwise rrd4j thinks that there is no data and will not properly draw the charts
  • Despite the chart refresh option, charts do not appear to refresh properly according to this setting
  • The visibility of multiple chart objects can be toggled to simulate changing the chart period, and the non-visible chart widgets are NOT generated behind the scenes until it becomes visible.
  • When charting a group of items make sure every label is unique. Identical labels result in an empty chart (as of 1.7.0).

Charts from rrd4j can also be generated and shown as images. Visit Charts in the Wiki for examples.

Element 'Frame'

Frames are used to create a visually separated area of items.

Syntax:

Frame [label="<labelname>"] [icon="<icon>"] [item=<item>]
{
    [additional sitemap elements]
}

Element 'Group'

A Group element creates a clickable area that opens up on a new page, where you can show various elements (including nested Groups).

Syntax:

Group [item=<itemname>] [label="<labelname>"] [icon="<iconname>"]

Note that all the parameters are optional, but if you don't specify at least one of them, the group will not appear in the interface (unlike the frame).

If you specify at least one parameter, the Group item will appear as a clickable white box. By clicking, you access a new page that shows the contents inside the group. Group items can be nested and mixed with frames: this gives a very powerful method to organise your information.

itemname can be a single item, or a item group: in the latter case, the new page will contain all items belonging to it.

If you don't set labelname but specify itemname, the group will get the label from the item. If you don't set both labelname and itemname, the group will appear as a blank box. You can see another effect of setting a labelname in the interface navigation bar: the left link that moves you to the previous level shows the text of labelname, or "Back" if the label is not specified.

Element 'Image'

Syntax:

Image [item=<itemname>] [icon="<iconname>"] url="<url of image>" [label="<labelname>"] [refresh=xxxx]

refresh is the refresh period of the image in milliseconds

Element 'List'

Syntax:

List item=<itemname> [label="<labelname>"] [icon="<iconname>"] [separator=""]

Element 'Selection'

Syntax:

Selection item=<itemname> [label="<labelname>"] [icon="<iconname>"] [mappings="<mapping definition>"]

An explanation for mappings you can find here.

Note: Selection renders the elements in the mappings as a list of texts in a separated page. If you prefer a list of buttons in the same page, then use Switch with an associated mapping.

Element 'Setpoint'

Syntax:

Setpoint item=<itemname> [label="<labelname>"] [icon="<iconname>"] minValue="<min value>" maxValue="<max value>" step="<step value>"

Element 'Slider'

Syntax:

Slider item=<itemname> [label="<labelname>"] [icon="<iconname>"] [sendFrequency="frequency"] [switchSupport]
  • sendFrequency: Used for distinguishing between long and short button presses in the classic (web) frontend; this parameter defines the interval in miliseconds for sending increase/decrease requests

  • switchSupport: If specified a short press on the "up" or "down" button/arrow in the classic (web) frontend switched the item on/off completely

Element 'Switch'

Syntax:

Switch item=<itemname> [label="<labelname>"] [icon="<iconname>"] [mappings="<mapping definition>"]

You can find an explanation for mappings you can here. Also note that Switch elements with and without mapping are rendered differently in the interface.

Element 'Text'

Syntax:

Text item=<itemname> [label="<labelname>"] [icon="<iconname>"]

Element 'Video'

Syntax:

Video item=<itemname>  [icon="<iconname>"] url="<url of video to embed>" [encoding="<video encoding>"]

encoding is the video encoding. Be sure to specify "mjpeg" for MJPEG video. Leave empty for autoselection, but autoselection does not work properly for MJPEG.

Element 'Webview'

Syntax:

Webview item=<itemname> [label="<labelname>"] [icon="<iconname>"] url="<url>" [height="<heightvalue"]

Mappings

Mappings can be used to let the user chose an item from a list.

Syntax:

 mappings = [ "value1"="name1", "value2"="name2" ]

Quotes can be omitted if the value string and name string do not contain spaces.

Examples:

mappings = [ "1"="ON", "0"="OFF" ]
mappings = [ 1="BBC", 2="CNN", 3="BLOOMBERG" ]

Dynamic Sitemaps

Note The following is only available in v1.4 and above.

Sitemaps can be designed to show items dynamically, or add colors depending on their state, or the state of another item. A few use cases for this are:

  • Hide elements of a heating system depending on its mode
  • Display different charts or URLs depending on the state of an item
  • Show a battery warning if the voltage is low
  • Highlight a value with a warning color if it's above or below limits

All widgets in the sitemap have the following three parameters available -:

  • visibility
  • labelcolor
  • valuecolor

It is important to note that in all cases rules are parsed from left to right, and the first rule that returns true will take priority.

Visibility

To dynamically show or hide an item, the visibility tag is used. By default, an item is visible if the visibility tag is not provided. If provided, a set of rules are used to indicate the items visibility status. If any of the rules are true then the item will be visible, otherwise it will be hidden.

The format of the visibility tag is as follows -:

visibility=[item_name operator value, ... ]

Multiple rules can be provided using a comma as a delimiter. Valid operators are the ==, >=, <=, !=, >, <.

Examples

visibility=[Weather_Chart_Period!=ON]
visibility=[Weather_Chart_Period=="Today"]
visibility=[Weather_Chart_Period>1, Weather_Temperature!="Uninitialized"]

Colors

Colors can be used to emphasise an items label or its value.

The format of the labelcolor and valuecolor tags are as follows -:

labelcolor=[item_name operator value = "color", ... ]

Multiple rules can be provided using a comma as a delimiter. Valid operators are the ==, >=, <=, !=, >, <.

itemname and operator are optional - if not provided, itemname will default to the current item and operator will default to ==. So the following three rules will all do the same thing, and all are valid.

Text item=Weather_Temperature valuecolor=[22="green"]
Text item=Weather_Temperature valuecolor=[==22="green"]
Text item=Weather_Temperature valuecolor=[Weather_Temperature==22="green"]

openHAB supports a standard set of colors, based on the CSS definitions. This is a set of 17 colors that should be supported by any UI. The colors are defined by name, and within openHAB they are translated to the CSS color format (ie "#xxxxxx"). This should ensure a standard interface for these colors.

Below is a list of the standard colors and their respective CSS definitions. Note that case is not important.

Name used in sitemapColor provided in REST interface
MAROON#800000
RED#ff0000
ORANGE#ffa500
YELLOW#ffff00
OLIVE#808000
PURPLE#800080
FUCHSIA#ff00ff
WHITE#ffffff
LIME#00ff00
GREEN#008000
NAVY#000080
BLUE#0000ff
AQUA#00ffff
TEAL#008080
BLACK#000000
SILVER#c0c0c0
GRAY#808080

For any color other than those defined above, "color" is passed directly through to the UI, so its exact implementation is up to the UI. It is generally expected that valid HTML colors can be used (eg "green", "red", "#334455") but a UI could for example define abstract colors that are defined internally depending on the theme. For example, "warning" could be defined and used in a UI dependant way, but there is currently no standardisation of these terms.

Examples

valuecolor=[>25="orange",>15="green",>5="orange",<5="blue"]
valuecolor=[Weather_LastUpdate=="Uninitialized"="lightgray",Weather_LastUpdate>600="lightgray",>15="green",>=10="orange",<10="red"]

Hint: for dynamic icons see the section on icons on the items page.

Example

You may find descriptions like:

    Frame label="Demo" {
         Text label="Group Demo" icon="1stfloor" {
                Switch item=Lights mappings=[OFF="All Off"]
                Group item=Heating
                Group item=Windows
                Text item=Temperature
         }
         Text label="Multimedia" icon="video" {
                Selection item=Radio_Station mappings=[0=off, 1=HR3, 2=SWR3, 3=FFH, 4=Charivari]
                Slider item=Volume
            }
    }
  • This means that you want a frame with a visual label "Demo". Then, inside the frame you want two elements:
  • An item called Group Demo with 1stfloor icon that contains 4 items.
  • The first one is the group Lights, that has a mapping. It means that when it receives a value of OFF, it might show a "All off" text.
  • The second one will be the Heating group.
  • etc.
  • An item called Multimedia with icon video. It has two elements:
  • The Radio_station item that has several mappings
  • The Volume item, shown as an Slider.

A note about rule comparison

  • String comparisons are case sensitive, so ==ON is not the same a ==on.
  • DateTime comparisons are relative to the current time and specified in seconds. So a rule >300 will return true if the DateTime item is set to a value that's newer than the past 5 minutes (300 seconds).

Further examples for defining sitemaps can be found in our openHAB-Samples section

OPENHAB MQTT Binding

posted 1 May 2015, 03:01 by Lê Duy Nhân   [ updated 1 May 2015, 03:19 ]

Documentation of the MQTT binding Bundle

Introduction

The MQTT binding bundle is available as a separate (optional) download. This binding allows openHAB to act as an MQTT client, so that openHAB items can send and receiveMQTT messages to/from an MQTT broker. It does not provide MQTT broker functionality, for this you may want to have a look at Mosquitto. There are test servers available at m2m.eclipse.org and test.mosquitto.org. To install, place this bundle in the folder ${openhab_home}/addons and add binding information to your configuration. See the following sections on how to do this.

OpenHAB provides MQTT support on different levels. The table below gives a quick overview:

LevelDescriptionUsageBundle
TransportShared transport functions for setting up MQTT broker connections.Ideal if you want to roll your own binding using MQTT as the transport.o.o.io.transport.mqtt
Item bindingAllows MQTT publish/subscribe configuration on item levelIdeal for highly customized in and outbound message scenarios.o.o.binding.mqtt
Event bus bindingPublish/receive all states/commmands directly on the openHAB eventbus.Perfect for integrating multiple openHAB instances or broadcasting all events.o.o.binding.mqtt
PersistenceUses persistent strategies to push messages on change or a regular interval.Perfect for persisting time series to a public service like Xively. (See MQTT persistence.)o.o.persistence.mqtt

The Mqttitude binding is also available which is an extension of this binding.

Configuration

Transport Configuration

In order to consume or publish messages to an MQTT broker, you need to define all the brokers which you want to connect to, in your openhab.cfg file. The following properties can be configured to define a broker connection:

mqtt:<broker>.url=<url>
mqtt:<broker>.clientId=<clientId>
mqtt:<broker>.user=<user>
mqtt:<broker>.pwd=<password>
mqtt:<broker>.qos=<qos>
mqtt:<broker>.retain=<retain>
mqtt:<broker>.async=<async>

The properties indicated by <...> need to be replaced with an actual value. The table below lists the meaning of the different properties.

PropertyDescription
brokerAlias name for the MQTT broker. This is the name you can use in the item binding configurations afterwards.
urlURL to the MQTT broker, e.g. tcp://localhost:1883 or ssl://localhost:8883
clientIdOptional. Client id (max 23 chars) to use when connecting to the broker. If not provided a default one is generated.
userOptional. User id to authenticate with the broker.
pwdOptional. Password to authenticate with the broker.
qosOptional. Set the quality of service level for sending messages to this broker. Possible values are 0 (Deliver at most once),1 (Deliver at least once) or 2 (Deliver exactly once). Defaults to 0.
retainOptional. True or false. Defines if the broker should retain the messages sent to it. Defaults to false.
asyncOptional. True or false. Defines if messages are published asynchronously or synchronously. Defaults to true.

Example Configurations

Example configuration of a simple broker connection:

mqtt:m2m-eclipse.url=tcp://m2m.eclipse.org:1883

Example configuration of a encrypted broker connection with authentication:

mqtt:mosquitto.url=ssl://test.mosquitto.org:8883
mqtt:mosquitto.user=administrator
mqtt:mosquitto.pwd=mysecret
mqtt:mosquitto.qos=1
mqtt:mosquitto.retain=true
mqtt:mosquitto.async=false

Item Binding Configuration for Inbound Messages

Below you can see the structure of the inbound mqtt configuration string. Inbound configurations allow you to receive MQTT messages into an openHAB item. Every item is allowed to have multiple inbound (or outbound) configurations.

Item myItem {mqtt="<direction>[<broker>:<topic>:<type>:<transformer>], <direction>[<broker>:<topic>:<type>:<transformation>], ..."} 

Since 1.6 it is possible to add an optional 5th configuration like:

Item myItem {mqtt="<direction>[<broker>:<topic>:<type>:<transformer>:<regex_filter>], <direction>[<broker>:<topic>:<type>:<transformation>], ..."} 
PropertyDescription
directionThis is always "<" for inbound messages.
brokerThe broker alias as it is defined in the openHab configuration.
topicThe MQTT Topic to subscribe to.
typeDescribes what the message content contains: a status update or command. Allowed values are 'state' or 'command'.
transformationRule defining how to transform the received message content into something openHab recognizes. Transformations are defined in the format of TRANSFORMATION_NAME(transformation_function). Allowed values are 'default' or any of the transformers provided in the org.openhab.core.transform bundle. Custom transformations can be contributed directly to the transform bundle by making the Transformation available through Declarative Services. Any other value than the above types will be interpreted as static text, in which case the actual content of the message is ignored.
regex_filter(optional, since 1.6)A string representing a regular expression. Only messages that match this expression will be further processed. All other messages will be dropped. Use Case: If multiple different data is sent over one topic (for example multiple sensors of one device), it is possible to distinguish the messages for different items. Example ".*" will match every message, ".*\"type\"=2\n.*" will match every message including type=2.

Example Inbound Configurations

Number temperature {mqtt="<[publicweatherservice:/london-city/temperature:state:default]"}
Number waterConsumption {mqtt="<[mybroker:/myHome/watermeter:state:XSLT(parse_water_message.xslt)]"} 
Switch doorbell {mqtt="<[mybroker:/myHome/doorbell:command:ON]"}
Number mfase1 {mqtt="<[flukso:/sensor/9cf3d75543fa82a4662fe70df5bf4fde/gauge:state:REGEX(.*,(.*),.*)]"}

Item Binding Configuration for Outbound Messages

Below you can see the structure of the outbound mqtt configuration string. Outbound configurations allow you to send an MQTT message when the an openHAB item receives a command or state update.

Item itemName {mqtt="<direction>[<broker>:<topic>:<type>:<trigger>:<transformation>]" }
PropertyDescription
directionThis is always ">" for outbound messages.
brokerThe broker alias as it was defined in the openHAB configuration.
topicThe MQTT Topic to publish messages to.
type'state' or 'command'. Indicates whether the receiving of a status update or command triggers the sending of an outbound message.
triggerSpecifies a specific OpenHAB command or state (e.g. ON, OFF, a DecimalType, ..) which triggers the sending of an outbound message. Use `*` to indicate that any command or state should trigger the sending.
transformationRule defining how to create the message content. Transformations are defined in the format of TRANSFORMATION_NAME(transformation_function). Allowed values are 'default' or any of the transformers provided in the org.openhab.core.transform bundle. Custom transformations can be contributed directly to the transform bundle by making the Transformation available through Declarative Services. Any other value than the above types will be interpreted as static text, in which case this text is used as the message content.

When the message content for an outbound message is created, the following variables are always replaced with their respective value:

  • ${itemName} : name of the item which triggered the sending
  • ${state} : current state of the item
  • ${command} : command which triggered the sending of the message

Example Outbound Configurations

Switch mySwitch {mqtt=">[mybroker:/myhouse/office/light:command:ON:1],>[mybroker:/myhouse/office/light:command:OFF:0]"}
Switch mySwitch {mqtt=">[mybroker:/myhouse/office/light:command:ON:1],>[mybroker:/myhouse/office/light:command:*:Switch ${itemName} was turned ${command}]"}

Event Bus Binding Configuration

In addition to configuring MQTT publish/subscribe options for specific openHAB items, you can also define a generic configuration in the openhab.cfg file which will act on ALL status updates or commands on the openHAB event bus.

The following properties can be used to configure MQTT for the openHAB event bus:

mqtt-eventbus:broker=<broker>
mqtt-eventbus:statePublishTopic=<statePublishTopic>
mqtt-eventbus:commandPublishTopic=<commandPublishTopic>
mqtt-eventbus:stateSubscribeTopic=<stateSubscribeTopic>
mqtt-eventbus:commandSubscribeTopic=<commandSubscribeTopic>

The properties indicated by <...> need to be replaced with an actual value. The table below lists the meaning of the different properties.

PropertyDescription
brokerName of the broker as it is defined in the openhab.cfg. If this property is not available, no event bus MQTT binding will be created.
statePublishTopicWhen available, all status updates which occur on the openHAB event bus are published to the provided topic. The message content will be the status. The variable ${item} will be replaced during publishing with the item name for which the state was received.
commandPublishTopicWhen available, all commands which occur on the openHAB event bus are published to the provided topic. The message content will be the command. The variable ${item} will be replaced during publishing with the item name for which the command was received.
stateSubscribeTopicWhen available, all status updates received on this topic will be posted to the openHAB event bus. The message content is assumed to be a string representation of the status. The topic should include the variable ${item} to indicate which part of the topic contains the item name which can be used for posting the received value to the event bus.
commandSubscribeTopicWhen available, all commands received on this topic will be posted to the openHAB event bus. The message content is assumed to be a string representation of the command. The topic should include the variable ${item} to indicate which part of the topic contains the item name which can be used for posting the received value to the event bus.

Example Configurations

Example configuration for a event bus binding, which sends all commands to an MQTT broker and receives status updates from that broker. This scenario could be used for example to link 2 openHAB instances together where the master instance sends all commands to the slave instance and the slave instance sends all status updates back to the master. The example below shows an example configuration for the master node.

mqtt-eventbus:broker=m2m-eclipse
mqtt-eventbus:commandPublishTopic=/openHAB/out/${item}/command
mqtt-eventbus:stateSubscribeTopic=/openHAB/in/${item}/state

Using the org.openhab.io.transport.mqtt bundle

When the default MQTT binding configuration options are not sufficient for your needs, you can also use the MQTT transport bundle directly from within your own binding.

MqttService

Using the MqttService, your binding can add custom message consumers and publishers to any of the defined MQTT brokers. You don't have to worry about (re)connection issues, all of this is done by the transport.mqtt bundle. The MqttService class is available to your binding through Declarative Services. A good example on how to use the MqttService can be found in the org.openhab.persistence.mqtt bundle.

Eclipse Paho

If the above service doesn't provide all the flexibility you need, you can also use the Eclipse Paho library directly in your binding. To make the library available, it's sufficient to add a dependency to the org.openhab.io.transport.mqtt bundle and to add org.eclipse.paho.client.mqtttv3 to your list of imported packages.


1)  Under /configurations/openhab.cfg


######################## Mail Action configuration ############################$

mail:hostname=smtp.gmail.com

mail:port=587

mail:username=????? without the @gmail
mail:password=?????

mail:from=??? yourname@gmail.com

mail:tls=true





################################### MQTT Transport #########################################
#

mqtt:mymosquitto.url=tcp://localhost:1883

mqtt:mymosquitto.qos=0

mqtt:mymosquitto.retain=true

mqtt:mymosquitto.async=true


-----------------------------------------------------------------------------------------

2)  Under /configurations/items/demo.items


Switch itm_mailbox "Switch" (ALL)
Number itm_mailboxmqtt "Mailbox RSSI [%.1f]" (ALL) {mqtt="<[mymosquitto:4124:state:default]"}
Number itm_mailboxcnt "Mail Count [%.1f]" (ALL) {mqtt="<[mymosquitto:4122:state:default]"}
DateTime itm_mailbox_time "Mailbox Last Updated [%1$tA, %1$tm/%1$td, %1$tI:%1$tM %1$tp]"
Number itm_mailboxbat "Mailbox Battery [%.1f Volt]" (ALL) {mqtt="<[mymosquitto:4123:state:default]"}




-----------------------------------------------------------------------------------
3)  Under /configurations/sitemap/demo.sitemap

        Frame label="Mailbox"
        {
                Switch item=itm_mailbox label="Mailbox" mappings=[OFF="Off"]
                Text item=itm_mailbox_time
                Text item=itm_mailboxmqtt
                Text item=itm_mailboxcnt
                Text item=itm_mailboxbat
        }


--------------------------------------------------------------------------------
4)  Under /configurations/rules/demo.rules

rule "send email and talk"
        when
                Item itm_mailbox changed from OFF to ON
        then
                playSound("aolmail.mp3")
                sendMail("myemailaddress@gmail.com", "subject line here" , "email body text")


end


rule "update mailbox"
        when
                Item itm_mailboxmqtt received update
        then
                sendCommand(itm_mailbox, ON)
                postUpdate(itm_mailbox_time, new DateTimeType())
end




--------------------------------------------------------------------------------------
END OF CONFIGURATIONS



//OpenHAB Configuration for UberSensor.ino


/* Item Definition Uber sensor Alarms and Notifications Control*/
Switch itm_NAA_auto "Auto Schedule Alarms/Notifications"

Switch itm_uber1_gas_alm_enb "Gas / Smoke Notifer"
Switch itm_uber1_flame_alm_enb "Flame Notifier"
Switch itm_uber1_bark_alm_enb "Bark Notifier"
Switch itm_uber1_pir_alm_enb "Presence Notifier"

Switch itm_uber1_gas_alm_sta "Gas / Smoke Alarm Status"
Switch itm_uber1_flame_alm_sta "Flame Alarm Status"
Switch itm_uber1_bark_alm_sta "Bark Alarm Status"
Switch itm_uber1_pir_alm_sta "PIR Presence Status"

Switch itm_uber1_light_sta "Living Room Light"

DateTime itm_uber1_gas_time "Gas Alarm Time [%1$tA, %1$tm/%1$td, %1$tI:%1$tM %1$tp]"
DateTime itm_uber1_flame_time "Flame Alarm Time [%1$tA, %1$tm/%1$td, %1$tI:%1$tM %1$tp]"
DateTime itm_uber1_bark_time "Bark Alarm Time [%1$tA, %1$tm/%1$td, %1$tI:%1$tM %1$tp]"
DateTime itm_uber1_pir_time "PIR Presence Alarm Time [%1$tA, %1$tm/%1$td, %1$tI:%1$tM %1$tp]"

Number itm_uber1_gas_mqtt "Gas [%.1f]" (ALL) {mqtt="<[mymosquitto:1222:state:default]"}
Number itm_uber1_flame_mqtt "Flame [%.1f]" (ALL) {mqtt="<[mymosquitto:1232:state:default]"}
Number itm_uber1_pir_mqtt "PIR [%.1f]" (ALL) {mqtt="<[mymosquitto:1242:state:default]"}
Number itm_uber1_bark_mqtt "Bark [%.1f]" (ALL) {mqtt="<[mymosquitto:1252:state:default]"}
Number itm_uber1_temp_mqtt "Uber Temperature [%.1f]" (ALL) {mqtt="<[mymosquitto:1262:state:default]"}
Number itm_uber1_hum_mqtt "Uber Humidity [%.1f]" (ALL) {mqtt="<[mymosquitto:1263:state:default]"}
Number itm_uber1_light_mqtt "Light Sensor [%.1f]" (ALL) {mqtt="<[mymosquitto:1272:state:default]"}


---------------------------------------------------------------------------------


/* Uber sensor rules */
/* -------------  Uber Sensor -------------------- */
rule "Uber Lighs"
        when
                Item itm_uber1_light_mqtt received update
        then
                if(itm_uber1_light_mqtt.state < 350)
                {
                        sendCommand(itm_uber1_light_sta, OFF)
                }
                else
                {
                         sendCommand(itm_uber1_light_sta, ON)
                }
end


/*-----  uber - gas/smoke ---------- */
rule "Uber gas smoke threshold"
        when
                Item itm_uber1_gas_mqtt received update
        then
                if((itm_uber1_gas_mqtt.state > 220) && (itm_uber1_gas_alm_enb.state == ON))
                {
                        sendCommand(itm_uber1_gas_alm_sta, ON)
                }
end

rule "Uber gas smoke response"
        when
                Item itm_uber1_gas_alm_sta changed from OFF to ON
        then
		sendMail("ArduinoHomeAutomationOpenHAB@gmail.com", "gas / smoke" , "gas or smoke detected")
                //playSound("ding.mp3")
                postUpdate(itm_uber1_gas_time, new DateTimeType())
end

/* --------- uber flame ---------- */
rule "Uber flame threshold"
        when
                Item itm_uber1_flame_mqtt received update
        then
                if((itm_uber1_flame_mqtt.state < 900) && (itm_uber1_flame_alm_enb.state == ON))
                {
                        sendCommand(itm_uber1_flame_alm_sta, ON)
                }
end

rule "Uber flame response"
        when
                Item itm_uber1_flame_alm_sta changed from OFF to ON
        then
                sendMail("ArduinoHomeAutomationOpenHAB@gmail.com", "fire detected" , "fire detected")
                //playSound("ding.mp3")
                postUpdate(itm_uber1_flame_time, new DateTimeType())
end


/* --------- uber bark ---------- */
rule "Uber bark threshold"
        when
                Item itm_uber1_bark_mqtt received update
        then
                if(itm_uber1_bark_alm_enb.state == ON)
                {
                        sendCommand(itm_uber1_bark_alm_sta, ON)
                }
end

rule "Uber bark response"
        when
                Item itm_uber1_bark_alm_sta changed from OFF to ON
        then
                sendMail("ArduinoHomeAutomationOpenHAB@gmail.com", "bark detected" , "dog barked!!!")
                //playSound("ding.mp3")
                postUpdate(itm_uber1_bark_time, new DateTimeType())
end

/* --------- uber pir ---------- */
rule "Uber pir threshold"
        when
                Item itm_uber1_pir_mqtt received update
        then
                if(itm_uber1_pir_alm_enb.state == ON)
                {
                        sendCommand(itm_uber1_pir_alm_sta, ON)
                }
end

rule "Uber pir response"
        when
                Item itm_uber1_pir_alm_sta changed from OFF to ON
        then
                sendMail("ArduinoHomeAutomationOpenHAB@gmail.com", "pir detected" , "dog pired!!!")
                //playSound("ding.mp3")
                postUpdate(itm_uber1_pir_time, new DateTimeType())
end


-----------------------------------------------------------------
    Frame label="Uber Sensor" {
            Text item=itm_uber1_temp_mqtt
            Text item=itm_uber1_hum_mqtt
            Switch item=itm_uber1_light_sta
            Switch item=itm_NAA_auto
    }
    Frame label="Uber Sensor Alarm Status" {
            Switch item=itm_uber1_gas_alm_sta mappings=[OFF="Off"]
            Switch item=itm_uber1_flame_alm_sta mappings=[OFF="Off"]
            Switch item=itm_uber1_bark_alm_sta mappings=[OFF="Off"]
            Switch item=itm_uber1_pir_alm_sta mappings=[OFF="Off"]
    }
    Frame label="Uber Sensor Alarm Enable" {
            Switch item=itm_uber1_gas_alm_enb
            Switch item=itm_uber1_flame_alm_enb
            Switch item=itm_uber1_bark_alm_enb
            Switch item=itm_uber1_pir_alm_enb
    }

OPENHAB MQTT TRANSCEIVER CONFIG EXAMPLE

posted 1 May 2015, 02:44 by Lê Duy Nhân   [ updated 1 May 2015, 02:49 ]




1. Config Site Map
sitemap demo label="Garage Door"
{
   Frame label="Sensors" {
      Text item=Yun_Temperature {
        Frame label="Garage Temperature" {
           Switch item=yun_Chart_Period label="Chart Period" mappings=[0="Hour", 1="Day", 2="Week"]
           Chart item=Yun_Temperature period=h refresh=6000 visibility= yun_Chart_Period==0,yun_Chart_Period=="Uninitialized"]
           Chart item=Yun_Temperature period=D refresh=30000 visibility=[yun_Chart_Period==1]
           Chart item=Yun_Temperature period=W refresh=30000 visibility=[yun_Chart_Period==2]
            }
         }
      Text item=Switch1
      Switch item=Relay1 mappings=[ON="Go!"]
   }

2. Config Item
Group All
Group Weather (All)
Group Sensors (All)

/*Sensors */
Group Sensors
Number Yun_Temperature "Garage Temperature [%.1f °F]" <temperature> (Temperature, Sensors) {mqtt="<mqttbroker:openhab/garage/temperature:state:default]"}
Number yun_Chart_Period             "Chart Period"
Number Switch1         "Door Status [MAP(switch.map):%d]"    <garagedoor>       (Sensors) {mqtt="<[mqttbroker:openhab/garage/switch1:state:default]"}
Switch Relay1 "Garage Door"           <garagedoor>    (All) {mqtt=">[mqttbroker:openhab/garage/relay1:command:ON:GO]"}

3. Arduino Code

// garagedoor
// January, 2015
// Interface YUN to SHT11 temperature/humidity sensor
// Report reading to mosquitto mqtt broker server
// pete@hoffswell.com

#include <SPI.h>
#include <SHT1x.h>
#include <Bridge.h>
#include <YunClient.h>
#include <PubSubClient.h>

// Variables and Arduino YUN connections

// shtx11 to Yun connection -----------
// YUN  > SHT11
// 3.3v > VCC 8
// GND  > GND 4
// 10   > DATA 1
// 11   > CLK 3
#define dataPin  10
#define clockPin 11
// YUN to Relay ---------
// 8 >  In1
// GND > GND
// 5v > VCC
#define relay1 8 // Banggood dual relay module
#define led 13 // Onboard LED

// YUN to Switch ---------------
// 5v > Switch NO
// 2 > Switch Comm
// 2 > GND via pulldown resistor
const int switch1 = 2;

// MQTT Server
#define MQTT_SERVER "192.168.15.22"

unsigned long time;
char message_buff[100];
float temp;
float humidity;
int switch1State = 0;

// Systems Initalization
YunClient yun;
PubSubClient mqtt(MQTT_SERVER, 1883, callback, yun);
SHT1x sht1x(dataPin, clockPin);


void setup() {
  pinMode(led,OUTPUT);
  pinMode(switch1, INPUT);
  pinMode(relay1,OUTPUT);
  digitalWrite(led, LOW);
  Serial.begin(9600);
  Bridge.begin();
  digitalWrite(relay1,LOW);
  digitalWrite(led, HIGH);
}

void loop() {

  if (!mqtt.connected())  {
    // Connect (or reconnect) to mqtt broker on the openhab server
    mqtt.connect("yun1");
    mqtt.publish("openhab/garage/temperature", "I'm alive!");
    mqtt.publish("openhab/garage/switch1", "I'm alive!");
    mqtt.subscribe("openhab/garage/relay1");
    }
       
  // publish Temperature reading every 10 seconds
  temp = sht1x.readTemperatureF();
  humidity = sht1x.readHumidity();
  if (millis() > (time + 10000)) {
    time = millis();
    // publish Temperature
    String pubString = String(temp);
    pubString.toCharArray(message_buff, pubString.length()+1);
    Serial.print(pubString + " F " );
    mqtt.publish("openhab/garage/temperature", message_buff);
    
    //publish switch1 status
    switch1State = digitalRead(switch1);
    Serial.println(switch1State);
    pubString = String(switch1State);
    pubString.toCharArray(message_buff, pubString.length()+1);
    mqtt.publish("openhab/garage/switch1", message_buff); 
    digitalWrite(led,switch1State);    // Light LED   
    }
  mqtt.loop();
}


void callback(char* topic, byte* payload, unsigned int length) {
  // MQTT inbound Messaging 
  int i = 0;
  for(i=0; i<length; i++) {
    message_buff[i] = payload[i];
  }
  message_buff[i] = '\0';
  String msgString = String(message_buff);
  Serial.println("Inbound: " + String(topic) +":"+ msgString);
  
  //Bounce relay
  if ( msgString == "GO" ) {
     digitalWrite(relay1,HIGH);
     delay(1000); 
     digitalWrite(relay1,LOW);
  }

  
  }

Python Programming for Arduino

posted 30 Apr 2015, 10:47 by Lê Duy Nhân   [ updated 30 Apr 2015, 23:58 ]


I am looking forward to receive a free copy of this book but can not find anywhere

MQTT testing on Pi (Send and Receive)

posted 30 Apr 2015, 09:12 by Lê Duy Nhân   [ updated 30 Apr 2015, 09:12 ]

Getting Started with MQTT

I wanted to play around with MQTT this evening so I put together a little tutorial on how to get started using Ubuntu and Mosquitto.

Installing Mosquitto

Enter the following into your terminal. Remember to replace YOUR_UBUNTU_VERSION_HERE with the version of ubuntu you’re using, I was using Maverick Meerkat at the time so I replaced it with just maverick. First add the following two lines to /etc/apt/sources.list

deb http://ppa.launchpad.net/mosquitto-dev/mosquitto-ppa/ubuntu YOUR_UBUNTU_VERSION_HERE main
deb-src http://ppa.launchpad.net/mosquitto-dev/mosquitto-ppa/ubuntu YOUR_UBUNTU_VERSION_HERE main

Then we need to verify the newly added packages:

$ sudo apt-key adv --keyserver keyserver.ubuntu.com --recv-keys 262C4500

Lets update Aptitude so we have the latest packages to choose from:

$ sudo aptitude update

And now lets install the Mosquitto server and clients:

$ sudo aptitude install mosquitto
$ sudo aptitude install mosquitto-clients

Subscribing to a Topic

$ mosquitto_sub -d -t hello/world

Publishing to a Topic

In another terminal window execute:

$ mosquitto_pub -d -t hello/world -m "Hello World"

You should see the text “Hello World” in the other window.

To get the full effect you can install Mosquitto on your Mac usingHomebrew and then connect to your Ubuntu machine…

$ mosquitto_sub -h YOUR_HOST_IP_ADDRESS -d -t hello/world

You should now see messages from your host sent to your local machine. You’ll probably need to open up port 1883 on your Ubuntu machine to make this actually work. I just used iptables to do so:

sudo iptables -A INPUT -p tcp -m tcp --dport 1883 -j ACCEPT

1-10 of 15