Using MQTT Binding on OpenHAB 2

Thanks for this gudie. It helped me get MQTT broker working after I also ha spent about two weeks without sucess following diffrent guides.

I have found it easiest to make sure Mosquito is running prior to loading Openhab. If you have the prompt window open you can see it connect client xxxxx on port xxxx.

Michael, maybe I am a bit off topic, but I shy-ed away from MQTT for a long time, because it looked complicated.
Then I got to use it, in a practical example by someone who could explain very well (wich was also my first use of openhab) and I was hooked. It is really extremely simple, once you get passed the programmers talk :wink:

Hi,

Can you specify the minimum version and give the reason, why using the newer one?

I have actually installed following version:

mosquitto version 1.3.4 (build date 2014-08-22 06:10:51+0000)

mosquitto is an MQTT v3.1 broker.

My problem is to send a command from a client over mqtt to openhab to control a rollershutter (thread: Sending command over Mqtt to OpenHAB)

Maybe this is something, where the newer version is required?

EDIT: I have test it with your sample with the mosquitto version 1.3.4:

Switch Switch1 {mqtt=">[mosquitto:myhome/bedroom/switch1:command:ON:1],>[mosquitto:myhome/bedroom/switch1:command:OFF:$
Switch Switch2 {mqtt=">[mosquitto:myhome/bedroom/switch2:command:ON:1],>[mosquitto:myhome/bedroom/switch2:command:OFF:$

and a sample sitemap:

sitemap demoswitch label="My MQTT Demo Switches" {
        Frame {
                Switch item=Switch1
                Switch item=Switch2
        }

        Frame {
                Default item=Rollladen_UG_links

        }
}

The demo switches are working as expected, but I don’t get it working with a rollershutter. I’m not sure, which concrete message I should send to change the percent value of the rollershutter.

Cheers!

Christian

UPDATE: Solved! See my solution in other thread (url above)

look, i love the promise of openHAB2 but im having the worst experience ever so far.
keep it simple right? this is what i was thinking when i decided to download the latest stable openhabian image… after the 4th try it still gave me errors that i could not sort(im no programmer)out.
3 more tries with the netInst version and i was away…
when i eventually got the thing to work(stable heartbeat with the leds),
i got a bit excited,but now im just frustrated.
i cannot get MQTT to work.
installed mosquitto on the pi3, it works, i can connect to it with devices etc.
can NOT get openhab2 to talk to the broker.
mqtt.cfg file
mqtt:mosquitto.url=tcp://localhost:1883
mqtt:mosquitto.clientId=openhab
mqtt:mosquitto.retain=true
mqtt:mosquitto.async=false

//sitemap
sitemap home label=“MyHouse”
{
Frame label=“Light Switch”
{
Switch item=STEVESW
}
Frame label=“Light Switch”
{
Switch item=LARRYSW
}
Frame label=“Light Switch”
{
Switch item=BRIANSW
}
Frame label=“MK-Room”
{
Switch item=Switch1
}
Frame label=“JK-Room”
{
Switch item=Switch2
}
Frame label=“Master Bedroom”
{
Switch item=DEMOSW
}
Frame label=“Living Room”
{
Switch item=DEMOSW
}
Frame label=“Garage”
{
Switch item=DEMOSW
}
Frame label=“Outside”
{
Switch item=DEMOSW
}
}

//switch items page

Switch STEVESW {mqtt=">[broker:home/lights/stevein:command:ON:1],>[broker:home/lights/stevein:command:OFF:0],<[broker:home/lights/stevein:state:ON:1],<[broker:home/lights/stevein:state:OFF:0]"}
Switch Switch1 {mqtt=">[broker:myhome/bedroom/switch1:command:ON:1],>[broker:myhome/bedroom/switch1:command:OFF:0],<[broker:myhome/bedroom/switch1:state:ON:1],<[broker:myhome/bedroom/switch1:state:OFF:0"}
Switch Switch2 {mqtt=">[mosquitto:myhome/bedroom/switch2:command:ON:1],>[mosquitto:myhome/bedroom/switch2:command:OFF:0],<[mosquitto:myhome/bedroom/switch2:state:ON:1],<[mosquitto:myhome/bedroom/switch2:state:OFF:0]"}

any help would be greatly appreciated as ive been at this for a week now and cannot get it to work.
i am probably overlooking something, and yes its gotten a little messy there…but for a start im just trying to get it to publish ANYTHING to the broker.

PLEASE HELP! :frowning:

1 Like

You shouldn’t use mqtt: infront of the config options since you are on OH2 and are using a dedicated mqtt.cfg file

mosquitto.url=tcp://localhost:1883
mosquitto.clientId=openhab
mosquitto.retain=true
mosquitto.async=false

Stop OH2, fix your mqtt.cfg, delete /var/lib/openhab2/config/org/openhab/mqtt.config (to remove stale configs) and start OH2

3 Likes

thanks for your Reply Dim, i seem to have got it working , more luck than good management…lol, but im still having some small issues so im going to to follow your suggestions, but how do i stop OH2 in openhabian?

it should be the same as in Debian Jessie:

sudo systemctl stop openhab2
1 Like

cool, ill try it now(thanks for your help btw)

1 Like

Dim! oh thats much better! thank you so much, now i can get on with the business of integrating everything!
Thanks again!

1 Like

I have installed MQTT binding 1.9.0 and configured it towards RabbitMQ

rabbitmq.url=tcp://192.168.1.30:1883
rabbitmq.clientId=openHAB
rabbitmq.user=openhab
rabbitmq.pwd=thepassword
rabbitmq.qos=1
rabbitmq.retain=true
rabbitmq.async=true

It refuse to connect, with error:

19:24:19.445 [ERROR] [penhab.io.transport.mqtt.MqttService] - Error starting broker connection
Unable to connect to server (32103) - java.net.ConnectException: Connection refused
        at org.eclipse.paho.client.mqttv3.internal.TCPNetworkModule.start(TCPNetworkModule.java:75)[217:org.openhab.io.transport.mqtt:1.9.0]
        at org.eclipse.paho.client.mqttv3.internal.ClientComms$ConnectBG.run(ClientComms.java:538)[217:org.openhab.io.transport.mqtt:1.9.0]
        at java.lang.Thread.run(Thread.java:745)[:1.8.0_65]
Caused by: java.net.ConnectException: Connection refused
        at java.net.PlainSocketImpl.socketConnect(Native Method)[:1.8.0_65]
        at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:350)[:1.8.0_65]
        at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206)[:1.8.0_65]
        at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188)[:1.8.0_65]
        at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)[:1.8.0_65]
        at java.net.Socket.connect(Socket.java:589)[:1.8.0_65]
        at org.eclipse.paho.client.mqttv3.internal.TCPNetworkModule.start(TCPNetworkModule.java:66)[217:org.openhab.io.transport.mqtt:1.9.0]
        ... 2 more

I have other MQTT clients connected with the same credentials.
Which MQTT protocol version is used in the binding?

Source:
http://www.eclipse.org/paho/files/javadoc/org/eclipse/paho/client/mqttv3/MqttConnectOptions.html
http://www.eclipse.org/paho/files/javadoc/index.html?overview-summary.html

Have you enabled the MQTT adapter on RabbitMQ?

Ps: It’s better to open up a new thread for this. Posting on a thread marked as solved will not get you too much attention :slight_smile:

Thanks, after RPi restart it works

I couldn’t connect to the MQTT over openHab please help

Home .items part is as follows:

//Jacksroom

Switch LEDTB “LED Tube” {mqtt=">[broker:Jacks-SmartHome/utilities/Jacksroom:command:ON:Z1ON],>[broker:Jacks-SmartHome/utilities/Jacksroom:command:OFF:Z1OFF]"}

Switch FAN “Room Fan” {mqtt=">[broker:Jacks-SmartHome/utilities/Jacksroom:command:ON:Z2ON],>[broker:Jacks-SmartHome/utilities/Jacksroom:command:OFF:Z2OFF]"}

Switch EXFAN “Exhaust Fan” {mqtt=">[broker:Jacks-SmartHome/utilities/Jacksroom:command:ON:Z3ON],>[broker:Jacks-SmartHome/utilities/Jacksroom:command:OFF:Z3OFF]"}

Switch PSRBSTR “Pressure Booster” {mqtt=">[broker:Jacks-SmartHome/utilities/Jacksroom:command:ON:Z4ON],>[broker:Jacks-SmartHome/utilities/Jacksroom:command:OFF:Z4OFF]"}

MQTT cofig file is as follows:

#
# Define your MQTT broker connections here for use in the MQTT Binding or MQTT
# Persistence bundles. Replace <broker> with an ID you choose.
#

# URL to the MQTT broker, e.g. tcp://localhost:1883 or ssl://localhost:8883
broker.url=tcp://192.168.137.13:1883

# Optional. Client id (max 23 chars) to use when connecting to the broker.
# If not provided a random default is generated.
broker.clientId=openhab

# Optional. True or false. If set to true, allows the use of clientId values
# up to 65535 characters long. Defaults to false.
# NOTE: clientId values longer than 23 characters may not be supported by all
# MQTT servers. Check the server documentation.
#<broker>.allowLongerClientIds=false

# Optional. User id to authenticate with the broker.
#<broker>.user=<user>

# Optional. Password to authenticate with the broker.
#<broker>.pwd=<password>

# Optional. 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.
#<broker>.qos=<qos>

# Optional. True or false. Defines if the broker should retain the messages sent to
# it. Defaults to false.
broker.retain=true

# Optional. True or false. Defines if messages are published asynchronously or
# synchronously. Defaults to true.
broker.async=false

# Optional. Defines the last will and testament that is sent when this client goes offline
# Format: topic:message:qos:retained <br/>
#<broker>.lwt=<last will definition>

Sitemap files is as follows:
sitemap home label=“Jacks-SmartHouse”
{
Frame label=“Jacks Room”
{
Switch item=LEDTB
Switch item=FAN
Switch item=EXFAN
Switch item=PSRBSTR
}
}

Please tell how to check the communication using MQQTFx

My ESP NodeMCU Firmware as Follows:

#include <ESP8266WiFi.h>
#include <MQTTClient.h>
#include <ESP8266WebServer.h>
#include <ESP8266mDNS.h>
#include <ESP8266HTTPUpdateServer.h>

//Only edit the settings in this section

/* WIFI Settings */
// Name of wifi network
const char* ssid = "Jacks_BSNL-3G";

// Password to wifi network
const char* password = "1m2f0m8m"; 

/* Web Updater Settings */
// Host Name of Device
const char* host = "Jacksroom";

// Path to access firmware update page (Not Neccessary to change)
const char* update_path = "/firmware";

// Username to access the web update page
const char* update_username = "admin1";

// Password to access the web update page
const char* update_password = "password1";

/* MQTT Settings */
// Topic which listens for commands
char* subscribeTopic = "Jacks-SmartHome/utilities/Jacksroom"; 

//MQTT Server IP Address
const char* server = "192.168.137.13";

//Unique device ID 
const char* mqttDeviceID = "Jacks-SmarthomeDevice1"; 

int channel1 = D0;
int channel2 = D1;
int channel3 = D2;
int channel4 = D3;

//webserver 
ESP8266WebServer httpServer(80);
ESP8266HTTPUpdateServer httpUpdater;

//MQTT
WiFiClient net;
MQTTClient client;

unsigned long lastMillis = 0;

//Connect to WiFI and MQTT
void connect();

//Setup pins, wifi, webserver and MQTT

void setup() 
{
  // set pin modes
  pinMode(channel1, OUTPUT);
  digitalWrite(channel1, LOW);

  pinMode(channel2, OUTPUT);
  digitalWrite(channel1, LOW);

  pinMode(channel3, OUTPUT);
  digitalWrite(channel3, LOW);

  pinMode(channel4, OUTPUT);
  digitalWrite(channel4, LOW);

  WiFi.mode(WIFI_STA);
  
  WiFi.begin(ssid, password);
  client.begin(server, net);

  connect();

  MDNS.begin(host);

  httpUpdater.setup(&httpServer, update_path, update_username, update_password);
  httpServer.begin();

  MDNS.addService("http", "tcp", 80);
}

//Connect to wifi and MQTT
void connect() 
{
  while (WiFi.status() != WL_CONNECTED) 
  {
    delay(1000);
  }

  while (!client.connect(mqttDeviceID)) 
  {
    delay(1000);
  }

  client.subscribe(subscribeTopic);
}

void loop() 
{
  // MQTT Loop
  client.loop();
  delay(10);

  // Make sure device is connected
  if(!client.connected()) 
  {
    connect();
  }

  httpServer.handleClient();

}

// Change the state of a relay based on the MQTT Message
void messageReceived(String topic, String payload, char * bytes, unsigned int length) 
{
    String msgString = payload;

  if (msgString == "Z1ON")
  {
    digitalWrite(channel1, HIGH);
    delay(250);
  }
  else if (msgString == "Z1OFF")
  {
    digitalWrite(channel1, LOW);
    delay(250);
  }
  else if (msgString == "Z2ON")
  {
    digitalWrite(channel2, HIGH);
    delay(250);
  }
  else if (msgString == "Z2OFF")
  {
    digitalWrite(channel2, LOW);
    delay(250);
  }
  else if (msgString == "Z3ON")
  {
    digitalWrite(channel3, HIGH);
    delay(250);
  }
  else if (msgString == "Z3OFF")
  {
    digitalWrite(channel3, LOW);
    delay(250);
  }
  else if (msgString == "Z4ON")
  {
    digitalWrite(channel4, HIGH);
    delay(250);
  }
  else if (msgString == "Z4OFF")
  {
    digitalWrite(channel4, LOW);
    delay(250);
  }
}

Would you please edit your message and put the .cfg file in a code block :slight_smile:

1 Like

I’m sorry for that I’m totally new to this… :smiley:

What is the name of your broker? My mqtt.cfg looks like this: broker=mosquitto


 
mqtt.cfg

mosquitto.url=tcp://localhost:1883
mosquitto.clientId=openhabian
mosquitto.qos=1
mosquitto.retain=true
mosquitto.async=false

Replace ‘broker’ with the name of your broker. Unless of course you named it “broker”.

2 Likes

broker name is same. Please check my esp firmware as its gives High Output through pins D0-D3 after uploading the firmware. I’m using nodemcu.

Hi
If you try to send the command on mosquitto_pub what happen on your nodemcu?

#MeToo,(lol) I am having some difficulties, getting MQTT up running.
I have a working broker, and MQTT bindings installed.
When I look at the payload in MQTTfx, I can see values are being published, but my Sitemap is not being populated.
Could anyone find the time to help me ?

My item(publish)

Number Netatmo_Indoor_Temperature    "Temperature [%.1f °C]"     <temperature>	{ channel = "netatmo:NAMain:d7a4c49c:70ee5019aa78:Temperature", mqtt=">[brokerOH2_2:netatmo_indoor/temp:state:*:default]"}

My item(subscribe)

Number Netatmo_Indoor_Temperature         	"Temperature [%.1f °C]"    	<temperature>	{mqtt="<[brokerOH2_2:netatmo_indoor/temp:state:*:default]"}

My sitemap:

Text		item=Netatmo_Indoor_Temperature 	icon="temperature"	label="Temperatur Alrum"		valuecolor=[>25="red",>20="green",>15="blue",<=15="purple"]

The installation is between 2 instances of OpenHAB2.