Using Sonoff Power Switches with Tasmota firmware and openHAB2 MQTT2 binding

Hi guys,

after hours of working on my openHAB2 configuration for my Sonoff Smart Switches, using the Tasmota firmware, I got that running, using the new MQTT2 binding. As for now I have 7 Sonoff Power Switches and didn’t want to configure them through PaperUI. After a hint from @Dim I got my configuration completely in files, providing me with the ability to do some slight changes on all channels at the same time.

This is just meant as an example and I would be more than happy, get more hints and ideas of how to use them in a better way - especially to avoid duplicate configurations. Currently there is no documentation for that thing, that I’m aware of. That’s why I choosed to share my findings and hope, that they may be useful for anyone of you.

In the configuration I have put all of the available options. If I don’t make use of them for now, they are commented out, but I’m already aware of their existence.

/etc/openhab2/things/mqtt.things

Bridge mqtt:broker:MosquittoMqttBroker "Mosquitto MQTT Broker" @ "MQTT" [ 
  host="x.x.x.x",
  secure=false,
  port=1883,
  qos=0,
  retain=false,
  clientid="Oh2Mqtt2Thing",
  //certificate="",
  //certificatepin=false,
  //publickey="",
  //publickeypin=false,
  keep_alive_time=30000,
  reconnect_time=60000,
  //lastwill_message="",
  //lastwill_qos=1,
  //lastwill_topic="",
  username="mymqttuser",
  password="mymqttpass"
]
{
    // Sonoff Power Switch 01
    Thing mqtt:topic:SonoffPs01 "Sonoff Power Switch 01" @ "MQTT"  {
      Channels:
          Type switch : switch "Power Switch" [ 
            stateTopic="tasmota/sonoff-ps01/POWER", 
            commandTopic="tasmota/sonoff-ps01/cmnd/POWER",
            //retained=false,
            //postCommand="",
            //transformationPattern="JSONPATH:$.POWER", 
            //formatBeforePublish="%s",
            on="ON",
            off="OFF"          
          ]
          Type string : state01 "Switch State 01" [ 
            stateTopic="tasmota/sonoff-ps01/STATE",
            transformationPattern="JSONPATH:$.POWER",
            on="ON",
            off="OFF"
          ]
          Type string : state02 "Switch State 02" [ 
            stateTopic="stat/sonoff-ps01/POWER",
            on="ON",
            off="OFF"
          ]
          Type string : state03 "Switch State 03" [ 
            stateTopic="stat/sonoff-ps01/RESULT",
            transformationPattern="JSONPATH:$.POWER",
            on="ON",
            off="OFF"
          ]
          Type number : vcc "VCC" [ 
            stateTopic="tasmota/sonoff-ps01/STATE",
            transformationPattern="JSONPATH:$.Vcc"
          ]
          Type string : wifi-ap "Wifi AP" [ 
            stateTopic="tasmota/sonoff-ps01/STATE",
            transformationPattern="JSONPATH:$.Wifi.AP"
          ]
          Type string : wifi-ssid "Wifi SSID" [ 
            stateTopic="tasmota/sonoff-ps01/STATE",
            transformationPattern="JSONPATH:$.Wifi.SSId"
          ]
          Type string : wifi-channel "Wifi Channel" [ 
            stateTopic="tasmota/sonoff-ps01/STATE",
            transformationPattern="JSONPATH:$.Wifi.Channel"
          ]
          Type string : wifi-rssi "Wifi RSSI" [ 
            stateTopic="tasmota/sonoff-ps01/STATE",
            transformationPattern="JSONPATH:$.Wifi.RSSI"
          ]
          Type string : uptime "Uptime" [ 
            stateTopic="tasmota/sonoff-ps01/STATE",
            transformationPattern="JSONPATH:$.Uptime"
          ]
          Type string : time "Time" [ 
            stateTopic="tasmota/sonoff-ps01/STATE",
            transformationPattern="JSONPATH:$.Time"
          ]
          Type string : devicestate "Device State" [ 
            stateTopic="tasmota/sonoff-ps01/LWT"
          ]
    }
    
    // Sonoff Power Switch 02
    Thing mqtt:topic:SonoffPs02 "Sonoff Power Switch 02" @ "MQTT"  {
      Channels:
          Type switch : switch "Power Switch" [ 
            stateTopic="tasmota/sonoff-ps02/POWER", 
            commandTopic="tasmota/sonoff-ps02/cmnd/POWER",
            //retained=false,
            //postCommand="",
            //transformationPattern="JSONPATH:$.POWER", 
            //formatBeforePublish="%s",
            on="ON",
            off="OFF"          
          ]
          Type string : state02 "Switch State 02" [ 
            stateTopic="tasmota/sonoff-ps02/STATE",
            transformationPattern="JSONPATH:$.POWER",
            on="ON",
            off="OFF"
          ]
          Type string : state02 "Switch State 02" [ 
            stateTopic="stat/sonoff-ps02/POWER",
            on="ON",
            off="OFF"
          ]
          Type string : state03 "Switch State 03" [ 
            stateTopic="stat/sonoff-ps02/RESULT",
            transformationPattern="JSONPATH:$.POWER",
            on="ON",
            off="OFF"
          ]
          Type number : vcc "VCC" [ 
            stateTopic="tasmota/sonoff-ps02/STATE",
            transformationPattern="JSONPATH:$.Vcc"
          ]
          Type string : wifi-ap "Wifi AP" [ 
            stateTopic="tasmota/sonoff-ps02/STATE",
            transformationPattern="JSONPATH:$.Wifi.AP"
          ]
          Type string : wifi-ssid "Wifi SSID" [ 
            stateTopic="tasmota/sonoff-ps02/STATE",
            transformationPattern="JSONPATH:$.Wifi.SSId"
          ]
          Type string : wifi-channel "Wifi Channel" [ 
            stateTopic="tasmota/sonoff-ps02/STATE",
            transformationPattern="JSONPATH:$.Wifi.Channel"
          ]
          Type string : wifi-rssi "Wifi RSSI" [ 
            stateTopic="tasmota/sonoff-ps02/STATE",
            transformationPattern="JSONPATH:$.Wifi.RSSI"
          ]
          Type string : uptime "Uptime" [ 
            stateTopic="tasmota/sonoff-ps02/STATE",
            transformationPattern="JSONPATH:$.Uptime"
          ]
          Type string : time "Time" [ 
            stateTopic="tasmota/sonoff-ps02/STATE",
            transformationPattern="JSONPATH:$.Time"
          ]
          Type string : devicestate "Device State" [ 
            stateTopic="tasmota/sonoff-ps02/LWT"
          ]
    }
}

This will create 3 things for you:

  1. The Broker Connection to (in my case) Mosquitto Broker
  2. Thing Sonoff Power Switch 01
  3. Thing Sonoff Power Switch 02

My items are configured in /etc/openhab2/items/sonoff-power-switches.items

/*
  Lighting Room1
*/
Switch SonoffPs01Switch_Switch "SPS01 Switch" (SonoffPowerSwitches_Basic,ChristmasLivingrooms) { channel="mqtt:topic:SonoffPs01:switch" }
String SonoffPs01Switch_State "SPS01 State" (SonoffPowerSwitches_Basic) { channel="mqtt:topic:SonoffPs01:state01", channel="mqtt:topic:SonoffPs01:state02", channel="mqtt:topic:SonoffPs01:state03", channel="mqtt:topic:SonoffPs01:switch" }
Number SonoffPs01Switch_Vcc "SPS01 VCC" (SonoffPowerSwitches_Basic) { channel="mqtt:topic:SonoffPs01:vcc" }
String SonoffPs01Switch_WifiAp "SPS01 Wifi AP" (SonoffPowerSwitches_Basic) { channel="mqtt:topic:SonoffPs01:wifi-ap" }
String SonoffPs01Switch_WifiSsid "SPS01 Wifi SSID" (SonoffPowerSwitches_Basic) { channel="mqtt:topic:SonoffPs01:wifi-ssid" }
String SonoffPs01Switch_WifiChannel "SPS01 Wifi Channel" (SonoffPowerSwitches_Basic) { channel="mqtt:topic:SonoffPs01:wifi-channel" }
String SonoffPs01Switch_WifiRssi "SPS01 Wifi RSSI" (SonoffPowerSwitches_Basic) { channel="mqtt:topic:SonoffPs01:wifi-rssi" }
String SonoffPs01Switch_Uptime "SPS01 Uptime" (SonoffPowerSwitches_Basic) { channel="mqtt:topic:SonoffPs01:uptime" }
String SonoffPs01Switch_Time "SPS01 Time" (SonoffPowerSwitches_Basic) { channel="mqtt:topic:SonoffPs01:time" }
String SonoffPs01Switch_DeviceState "SPS01 Device State" (SonoffPowerSwitches_Basic) { channel="mqtt:topic:SonoffPs01:devicestate" }

/*
  Lighting Room2
*/
Switch SonoffPs02Switch_Switch "SPS02 Switch" (SonoffPowerSwitches_S20,ChristmasNightLights) { channel="mqtt:topic:SonoffPs02:switch" }
String SonoffPs02Switch_State "SPS02 State" (SonoffPowerSwitches_S20) { channel="mqtt:topic:SonoffPs02:state01", channel="mqtt:topic:SonoffPs02:state02", channel="mqtt:topic:SonoffPs02:state03", channel="mqtt:topic:SonoffPs02:switch" }
Number SonoffPs02Switch_Vcc "SPS02 VCC" (SonoffPowerSwitches_S20) { channel="mqtt:topic:SonoffPs02:vcc" }
String SonoffPs02Switch_WifiAp "SPS02 Wifi AP" (SonoffPowerSwitches_S20) { channel="mqtt:topic:SonoffPs02:wifi-ap" }
String SonoffPs02Switch_WifiSsid "SPS02 Wifi SSID" (SonoffPowerSwitches_S20) { channel="mqtt:topic:SonoffPs02:wifi-ssid" }
String SonoffPs02Switch_WifiChannel "SPS02 Wifi Channel" (SonoffPowerSwitches_S20) { channel="mqtt:topic:SonoffPs02:wifi-channel" }
String SonoffPs02Switch_WifiRssi "SPS02 Wifi RSSI" (SonoffPowerSwitches_S20) { channel="mqtt:topic:SonoffPs02:wifi-rssi" }
String SonoffPs02Switch_Uptime "SPS02 Uptime" (SonoffPowerSwitches_S20) { channel="mqtt:topic:SonoffPs02:uptime" }
String SonoffPs02Switch_Time "SPS02 Time" (SonoffPowerSwitches_S20) { channel="mqtt:topic:SonoffPs02:time" }
String SonoffPs02Switch_DeviceState "SPS02 Device State" (SonoffPowerSwitches_S20) { channel="mqtt:topic:SonoffPs02:devicestate" }

I’m currently using Sonoff Basis and S20 switches. There is not difference in channels or items that I’m aware of.

They are configured using the HTTP API and Postman. If of interest, I could share my collection as well.

Happy automation!

Cheers,
Sven

Edit 1
During the creation of this topic @David_Graeff has created a great blog post, giving more information on how to use the MQTTv2 binding in several ways: https://www.openhab.org/blog/2018-12-16-mqtt-arrives-in-the-modern-openhab-2-x-architecture.html

28 Likes

Hi Sven
I have some Sonoff basic switches with Tasmota and trying to get them to work on openHAB , pls can you let me know how to do it . What change I Tasmota and how do I install MQTT 2, thanks

I can try. What exactly is your problem?

You need to install the MQTT2 add-on via PaperUI. Based on the version of openHAB you’re using, there should be two MQTT bindings: 1.13 and 2.4. After installing the add-on 2.4 you should be able to use my configuration from above.
I didn’t use the built-in MQTT broker, because I installed Mosquitto previously. There are some descriptions, on how to do that when you follow https://www.openhab.org/addons/bindings/mqtt1/. My mosquitto.conf looks like this:

pid_file /var/run/mosquitto.pid

listener 1883 x.x.x.x

persistence true
persistence_location /var/lib/mosquitto/
persistence_file mosquitto.db

log_dest syslog
log_dest stdout
log_dest topic
log_type error
log_type warning
log_type notice
log_type information
log_type subscribe
log_type websockets

log_dest file /var/log/mosquitto/mosquitto.log
connection_messages true
log_timestamp true
allow_anonymous false
password_file /etc/mosquitto/pwfile

include_dir /etc/mosquitto/conf.d

You need to configure a user for authentication. This is described in the documentation of the Mosquitto project (I cannot remeber this for now).

As stated before I’m using the HTTP API to configure Tasmota, except for the MQTT host. This is still a todo, but is very easy.


I’ve changed the Full Topic from %prefix%/%topic%/ to tasmota/%topic%/ for no reason. That was just done by inexperience. So you can leave it as it is. However the WebUI of Tasmota does not allow you to configure most of the options. For that you need to use the API or possibly MQTT as well - I doubt that, but I don’t know it. The available commands are documented in the Wiki

Hope that helps.

Thanks for sharing.was interested in the new binding but couldn’t find a lot of documentation on it. Will have a look at it.

What is for you the advantage of using the v2 binding versus the ‘old’ one?

There were problems when you wanted to use both the mqtt1 binding and the mqtt actions.

For me, being able to send commands to my tasmotas was the main selling point.

The old one is … old :slight_smile:

But seriously: If you don’t use any new concepts like PaperUI, Automation rules, JavaScripts, Jython etc you can use the mqtt1 one. Just be careful with the pitfalls, because there are many.

I had issues getting the mqtt1 binding working stable (see https://community.openhab.org/t/reliability-of-binding-mqtt/). Currently I’m testing the stability of the mqtt2 binding. As you stated before, because of the lack of documentation, I’ve created this.

1 Like

I managed to make the “Maintenance actions” part working with MQTT2.

If you followed the above wiki for your setup of the maintenance here are my changes for the files:

sonoff.rules:

// Work with a list of selected Sonoff modules
val sonoff_device_ids = newArrayList(
“sonoff-A00EEA”,
//… add all your modules here!
“sonoff-E8A6E4”
)
// OR
// Work with the grouptopic, addressing ALL modules at once
//val sonoff_device_ids = newArrayList(“sonoffs”)

rule “Sonoff Maintenance”
when
Item Sonoff_Action received command
then
logInfo(“sonoff.rules”, “Sonoff Maintenance on all devices: " + receivedCommand)
val actionsBroker = getActions(“mqtt”,“mqtt:broker:MyMQTTBroker”) // change to your broker name!
for (String device_id : sonoff_device_ids) {
switch (receivedCommand) {
case “restart” :
actionsBroker.publishMQTT( “cmnd/” + device_id + “/restart”, “1”)
case “queryFW” :
actionsBroker.publishMQTT( “cmnd/” + device_id + “/status”, “2”)
case “upgrade” : {
actionsBroker.publishMQTT( “cmnd/” + device_id +”/otaurl", “http://sonoff.maddox.co.uk/tasmota/sonoff-DE.bin”)
actionsBroker.publishMQTT( “cmnd/” + device_id + “/upgrade”, “1”)
}
}
}
Sonoff_Action.postUpdate(NULL)
end

sonoff.items:

String Sonoff_Version “Sonoff Version: [%s]” <sonoff_basic> { channel=“mqtt:topic:MyMQTTBroker:MySonoff_DeviceThing:Version”} // change to your broker and thing name!

The definition of the thing used in that item:

 Thing topic MySonoff_DeviceThing "Light_Switch" {
Channels:
    Type switch : PowerSwitch  [ stateTopic="stat/MySonoff_Device/POWER" , transformationPattern="JSONPATH:$.POWER" , commandTopic="cmnd/MySonoff_Device/POWER", on="ON", off="OFF" ]
    Type string : Version [stateTopic="stat/MySonoff_Device/STATUS2", transformationPattern="JSONPATH:$.StatusFWR.Version"]
  }   

Note: My sonoff devices do react/switch on “cmnd” topics. The MQTT full topic is set to “%prefix%/%topic%/”

[Edit] Removed a syntax error in the items file which prevented the automatic linking!
[Edit2] Changed false stateTopic for switch.

4 Likes

Would you be so kind and provide those changes to the tasmota wiki?

Sure, have to look on the correct/best way.
[Edit:]
Done!!

Great improvement of my configuration, which uses duplication of config lines - was very annoying but I’m still not very familiar with the language construct.

I will update my configuration within the next days, maybe during the holidays, and update the first post on success.

@opus Thanks for this hint! I wasn’t even aware of those maintenance buttons.

hey,

thank you for the write down. Unfortunately for me, I can’t get it to work, although I made my config like yours.

If I want to turn the switch on, I should be able to do so by just sending ON to the switch item?
For example:
curl -X PUT --header “Content-Type: text/plain” --header “Accept: application/json” -d “ON” “http://myIP:8080/rest/items/SonoffPs01Switch_Switch/state

In my log:

2018-12-20 14:20:55.664 [vent.ItemStateChangedEvent] - SonoffPs01Switch_Switch changed from UNDEF to ON

2018-12-20 14:20:59.098 [vent.ItemStateChangedEvent] - SonoffPs01Switch_Switch changed from ON to OFF

2018-12-20 14:21:02.445 [vent.ItemStateChangedEvent] - SonoffPs01Switch_Switch changed from OFF to ON

In Paper UI everything seems to be Online:

I can’t say what this curl command will do and why you are using it at all. You are trying to control your switch via MQTT, don’t you?
If you configured the Broker , mqtt thing and item according my example and switching doesn’t work although the thing reports online, I would unlink the item on PaperUI and link it again.
If you haven’t linked it via PaperUI in the first place, do so now. ( I reported that behaviour in another thread, and I think that it isn"t working as it should).
Monitoring the mqtt traffic with something like mqtt-spy did show me in such cases no message was sent from openhab.

Ok, will try to set up everything via paper ui.
The curl was just for switching the switch. I was expecting that I am seeing some kind of MQTT message emitted after turning the switch on and off.

In my log i am currently seeing following messages:

2018-12-20 15:09:56.378 [WARN ] [moquette.spi.impl.SessionsRepository] - Session does not exist. CId=d0253800_144815178

That is for example my mqtt-spy ID. I am also seeing similar messages for my sonoffs. Do they have any relevance?

No. If you use the internal broker, it will warn each time a new session is established with an already known client id. Of no relevance though.

I did all the setup with files, the actual linking was the only part that didn’t work. So use the files and manually link the item on PaperUI.
@David_Graeff: Is this the intended behaviour? IMHO the file created by item should automatically do the linking.

Ok, thank you.
At least it means that there is a connection between the broker and the client?

Too bad :smiley: already started from scratch.

At least it works now for me. Thank you for your help!

The mqtt binding is not doing any extra magic. The framework should create the links automatically.

Correct, and I’m stupid!
I used a false syntax in the items file! Will correct it in all my statements (including the Tasmota Wiki).

1 Like