While Connecting esp8266 with OR using MQTT Broker fails with State 2

Hi all,
I am new to the plaltform, but i am trying to connect esp8266 with OR using mqtt broker.

To verify the connection I followed this tutorial from OR github wiki:
Tutorial: Connect your MQTT Client

I was able to connect MQTTX with localhost and GET and POST data using MQTTX software:

Now when I am trying to connect my ESP8266 with OR using the same credentials and code as provided in the github wiki(User Guide: Connect ESP32 or ESP8266 using MQTT)

I am getting below output in serial monitor.

Below is my ESP8266 Code and secret.h file:
ESP8266 :

> #include "secret.h"
> #include <ESP8266WiFi.h> // remove comment for ESP8266, and add comment at #include <WiFi.h> 
> //#include <WiFi.h>          
> #include <PubSubClient.h>
> 
> //Objects
> WiFiClientSecure askClient; //SSL Client
> //WiFiClient askClient; //Non-SSL Client, also remove the comments for askClient.setCACert(local_root_ca);
> 
> PubSubClient client(askClient);
> 
> void setup() {
>   Serial.begin(9600);
>   Serial.println(ssid);
> 
>   WiFi.begin(ssid, password);
> 
>   while (WiFi.status() != WL_CONNECTED) {
>     delay(500);
>   
>   }
> 
>   Serial.println(WiFi.localIP());
>   //askClient.setCACert(local_root_ca); //If you use non SSL then comment out
>   askClient.setCertificate_P(reinterpret_cast<const uint8_t*>(local_root_ca), strlen_P(local_root_ca));
>   client.setServer(mqtt_server, mqtt_port);
>   reconnect();
>   client.setCallback(callback);
>   reconnect();
>   Serial.println(WiFi.localIP());
>   
> }
> 
> void loop() {
>   //Publish Boolean format:
>   client.publish("master/client123/writeattributevalue/writeAttribute/4q0u7wZVXGRMaewy2yRkhp", "1");
>   //To publish Strings:
>   //client.publish("yourrealm/ClientID/writeattributevalue/AttributeName/AssetID", String("Hello").c_str());
>   delay(100);
> 
> }
> 
> //MQTT callback
> void callback(char* topic, byte * payload, unsigned int length) {
>   
> 
>   for (int i = 0; i < length; i++) {
> 
>     Serial.println(topic);
>     Serial.print(" has send ");
>     Serial.print((char)payload[i]);
>   }
> 
> }
> 
> //MQTT reconnect
> void reconnect() {
>   // Loop until we're reconnected
>   while (!client.connected()) {
>     Serial.print("********** Attempting MQTT connection...");
>     // Attempt to connect
>     if (client.connect(ClientID, username, mqttpass, lastwill, 1, 1, lastwillmsg)) {
>       Serial.println("-> MQTT client connected");
>       client.subscribe(topic);
>       Serial.print("Subscribed to: ");
>       Serial.println(topic);
>     } else {
>       Serial.print("failed, rc=");
>       Serial.print(client.state());
>       Serial.println("-> try again in 5 seconds");
>       // Wait 5 seconds before retrying
>       delay(5000);
>     }
>   }
> }

secret.h

> // Wifi 
> const char* ssid = "403"; // Wifi SSID
> const char* password = "12345678"; // Wifi Password
> 
> //MQTT Broker
> const char* mqtt_server = "localhost";
> unsigned int mqtt_port = 1883; //SSL 8883 NoneSSL 1883
> const char* username = "master:mqttuser"; // Service User Realm:Serviceuser
> const char* mqttpass = "yvIudfWHC4R4dfzJbsa4l2nwWRkhasBr"; // Service User Secret
> const char* ClientID = "client123";
> //LastWill
> const char* lastwill = "master/client123/writeattributevalue/writeAttribute/4q0u7wZVXGRMaewy2yRkhp";
> const char* lastwillmsg = "0";
> 
> 
> //subscribing Topic
> const char *topic = "master/client123/attribute/writeAttribute/4q0u7wZVXGRMaewy2yRkhp"; //see Subscribing Topics in Documentation https://github.com/openremote/openremote/wiki/User-Guide%3A-Manager-APIs#mqtt-api-mqtt-broker
> 
> 
> //Local CA
> 
> const char* local_root_ca = \
>                             "-----BEGIN CERTIFICATE-----\n" \
>                             "MIIDnzCCAoegAwIBAgIUE3jYzxKpepVM0CSLZd9GNv6BHj8wDQYJKoZIhvcNAQEL\n" \
>                             "BQAwUDELMAkGA1UEBhMCR0IxHTAbBgNVBAMMFE9wZW5SZW1vdGUgRGVtbyBDZXJ0\n" \
>                             "MRMwEQYDVQQKDApPcGVuUmVtb3RlMQ0wCwYDVQQLDAREZW1vMCAXDTIwMDYwODE5\n" \
>                             "MTc1MVoYDzIwNTAwNjAxMTkxNzUxWjBQMQswCQYDVQQGEwJHQjEdMBsGA1UEAwwU\n" \
>                             "T3BlblJlbW90ZSBEZW1vIENlcnQxEzARBgNVBAoMCk9wZW5SZW1vdGUxDTALBgNV\n" \
>                             "BAsMBERlbW8wggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCrKEk77HcJ\n" \
>                             "B5SqvoN2UbRsDh9d0ECN8tOU5hC2poih+6XBJgikQ8gdy7ptt477KRh3ZIiw3ZTX\n" \
>                             "Hg0//Ju71D/4EDBYwHxoSK9WehP5Kz/LrBHhtArXK3RYH8pFS13CDOPjXnm6LMN5\n" \
>                             "2mRGwm2gCwKwRTbfm+D9hjpVuwt0sfHaXVETlUc4JystlfYVurMcfsox9tsbRuzl\n" \
>                             "EakyK9Cr1V7bgaLMosHDX3NSuEyzb9DQZ3PBK3JjJhSeYkGNuP/NocMrWy/JHd2v\n" \
>                             "2Wev9W+D1Pv46Sqfrvd6K7oP00FL0CdODkMRBVTlb1wq/6uJdRbnVUM0PGA9enrQ\n" \
>                             "vMB11fFglHa3AgMBAAGjbzBtMB0GA1UdDgQWBBT0ixs03BOrns+E2+xSU+nfP9KX\n" \
>                             "iTAfBgNVHSMEGDAWgBT0ixs03BOrns+E2+xSU+nfP9KXiTAPBgNVHRMBAf8EBTAD\n" \
>                             "AQH/MBoGA1UdEQQTMBGCCWxvY2FsaG9zdIcEfwAAATANBgkqhkiG9w0BAQsFAAOC\n" \
>                             "AQEAawmLoD7bzFTM0Z58PR6jQR3ypD6IAyei6xiBI7wvxbjyxqQrk1i0rK2Aexjk\n" \
>                             "v2ZsAUmtrm5k5pWpBsokNuRddPV1K2OZjTj9HPc9AxqjyHKyqRXmVKWkzbWQDLVS\n" \
>                             "lGRk7yviUFS8nRuY0vLfqZzF7e2HeasThILJibY8rUVLuq+iMS35RDwQ9usIOiYz\n" \
>                             "dF4CO3HFZ6NtDheM1mPAy4Q76H1P1fINuA8mp/by9J8heexqjgpBKYexiQhjb1A7\n" \
>                             "NBdWbJPXoNJplGXjGIbj8KxW61ih1wDRE2ZseOflRstO9/Txm7+Cuqo+WBOK39cU\n" \
>                             "CXPKre2pqmkIu65wJ6VcTKeSqw==" \
>                             "-----END CERTIFICATE-----";

Can someone please help me to find out what is the root cause of the problem that I am facing.
Is it related to arduino code? Is it related to docker file? it is issue with mqtt port.
I am okay to connect to OR using non SSL that is port 1883.
kindly help

Hi and welcome to the forum,

could you provide your docker-compose.yml?

Also based on your secret.h

 const char* mqtt_server = "localhost";

won’t work, unless you have a mqtt broker running on the ESP :slight_smile:

# OpenRemote v3
#
# Profile that runs the stack by default on https://localhost using a self-signed SSL certificate,
# but optionally on https://$OR_HOSTNAME with an auto generated SSL certificate from Letsencrypt.
#
# It is configured to use the AWS logging driver.
#
version: '2.4'

volumes:
  proxy-data:
  temp-data:
  postgresql-data:
#  btmesh-data:

services:

  proxy:
    image: openremote/proxy:${PROXY_VERSION:-latest}
    restart: always
    depends_on:
      manager:
        condition: service_healthy
    ports:
      - "80:80"
      - "${OR_SSL_PORT:-443}:443"
      - "8883:8883"
    volumes:
      - proxy-data:/deployment
    environment:
      LE_EMAIL: ${OR_EMAIL_ADMIN:-}
      DOMAINNAME: ${OR_HOSTNAME:-localhost}
      DOMAINNAMES: ${OR_ADDITIONAL_HOSTNAMES:-}
      # USE A CUSTOM PROXY CONFIG - COPY FROM https://raw.githubusercontent.com/openremote/proxy/main/haproxy.cfg
      #HAPROXY_CONFIG: '/data/proxy/haproxy.cfg'

  postgresql:
    restart: always
    image: openremote/postgresql:${POSTGRESQL_VERSION:-latest}
    volumes:
      - postgresql-data:/var/lib/postgresql/data
      - temp-data:/tmp

  keycloak:
    restart: always
    image: openremote/keycloak:${KEYCLOAK_VERSION:-latest}
    depends_on:
      postgresql:
        condition: service_healthy
    volumes:
      - ./deployment:/deployment
    environment:
      KEYCLOAK_ADMIN_PASSWORD: ${OR_ADMIN_PASSWORD:-secret}
      KC_HOSTNAME: ${OR_HOSTNAME:-localhost}
      KC_HOSTNAME_PORT: ${OR_SSL_PORT:--1}


  manager:
#    privileged: true
    restart: always
    #image: openremote/manager:${MANAGER_VERSION:-latest}
    image: openremote/manager:${MANAGER_VERSION:-develop}
    depends_on:
      keycloak:
        condition: service_healthy
    ports:
        - "1883:1883"
        
    environment:
      OR_SETUP_TYPE:
      OR_ADMIN_PASSWORD:
      OR_SETUP_RUN_ON_RESTART:
      OR_EMAIL_HOST:
      OR_EMAIL_USER:
      OR_EMAIL_PASSWORD:
      OR_EMAIL_X_HEADERS:
      OR_EMAIL_FROM:
      OR_EMAIL_ADMIN:
      OR_HOSTNAME: ${OR_HOSTNAME:-localhost}
      OR_ADDITIONAL_HOSTNAMES: ${OR_ADDITIONAL_HOSTNAMES:-}
      OR_SSL_PORT: ${OR_SSL_PORT:--1}
      OR_DEV_MODE: ${OR_DEV_MODE:-false}

      # The following variables will configure the demo
      OR_FORECAST_SOLAR_API_KEY:
      OR_OPEN_WEATHER_API_APP_ID:
      OR_SETUP_IMPORT_DEMO_AGENT_KNX:
      OR_SETUP_IMPORT_DEMO_AGENT_VELBUS:
    volumes:
      - ./deployment:/deployment 
#      - /var/run/dbus:/var/run/dbus
#      # Bluetooth mesh volume
#      - btmesh-data:/btmesh
#   devices:
#     - /dev/ttyACM0:/dev/ttyS0

type or paste code here

Here is my docker-compose.yml and I am running this under my localhost.

I am trying to connect my esp8266 to the OR mqtt broker which is somehow returning -2. I have tried connecting my esp8266 with public MQTT broker to get and post data.

Please help and let m know where I am going wrong.

ok, multiple issues:
At first: don’t run the docker-compose as localhost, use your network ip: “i.e. 192.168.1.20”
It is in the Quickstart Guide explained, but just start your docker with:

OR_HOSTNAME=192.168.1.20  docker-compose -p openremote up -d

or you add it directly to the docker-compose.yml

but before you do this, add the 1883 port to your docker-compose.yml:

   ports:
      - "80:80"
      - "${OR_SSL_PORT:-443}:443"
      - "8883:8883"
      - "1883:1883"

like i already said, in your secret.h file there should stand:

const char* mqtt_server = "IP OF YOUR MACHINE";

Thanks @Denis, really appreciated your help:
I tried modifying the docker-compose.yml file as instructed. Below is the updated .yml file.

docker-compose.yml.txt (2.6 KB)

# OpenRemote v3
#
# Profile that runs the stack by default on https://localhost using a self-signed SSL certificate,
# but optionally on https://$OR_HOSTNAME with an auto generated SSL certificate from Letsencrypt.
#
# It is configured to use the AWS logging driver.
#
version: '2.4'

volumes:
  proxy-data:
  temp-data:
  postgresql-data:
#  btmesh-data:

services:

  proxy:
    image: openremote/proxy:${PROXY_VERSION:-latest}
    restart: always
    depends_on:
      manager:
        condition: service_healthy
    ports:
      - "80:80"
      - "${OR_SSL_PORT:-443}:443"
      - "8883:8883"
      - "1883:1883"
    volumes:
      - proxy-data:/deployment
    environment:
      LE_EMAIL: ${OR_EMAIL_ADMIN:-}
      DOMAINNAME: ${OR_HOSTNAME:-localhost}
      DOMAINNAMES: ${OR_ADDITIONAL_HOSTNAMES:-}
      # USE A CUSTOM PROXY CONFIG - COPY FROM https://raw.githubusercontent.com/openremote/proxy/main/haproxy.cfg
      #HAPROXY_CONFIG: '/data/proxy/haproxy.cfg'

  postgresql:
    restart: always
    image: openremote/postgresql:${POSTGRESQL_VERSION:-latest}
    volumes:
      - postgresql-data:/var/lib/postgresql/data
      - temp-data:/tmp

  keycloak:
    restart: always
    image: openremote/keycloak:${KEYCLOAK_VERSION:-latest}
    depends_on:
      postgresql:
        condition: service_healthy
    volumes:
      - ./deployment:/deployment
    environment:
      KEYCLOAK_ADMIN_PASSWORD: ${OR_ADMIN_PASSWORD:-secret}
      KC_HOSTNAME: ${OR_HOSTNAME:-localhost}
      KC_HOSTNAME_PORT: ${OR_SSL_PORT:--1}


  manager:
#    privileged: true
    restart: always
    #image: openremote/manager:${MANAGER_VERSION:-latest}
    image: openremote/manager:${MANAGER_VERSION:-develop}
    depends_on:
      keycloak:
        condition: service_healthy
    ports:
        - "1883:1883"
        
    environment:
      OR_SETUP_TYPE:
      OR_ADMIN_PASSWORD:
      OR_SETUP_RUN_ON_RESTART:
      OR_EMAIL_HOST:
      OR_EMAIL_USER:
      OR_EMAIL_PASSWORD:
      OR_EMAIL_X_HEADERS:
      OR_EMAIL_FROM:
      OR_EMAIL_ADMIN:
      OR_HOSTNAME: ${OR_HOSTNAME:-localhost}
      OR_ADDITIONAL_HOSTNAMES: ${OR_ADDITIONAL_HOSTNAMES:-}
      OR_SSL_PORT: ${OR_SSL_PORT:--1}
      OR_DEV_MODE: ${OR_DEV_MODE:-false}

      # The following variables will configure the demo
      OR_FORECAST_SOLAR_API_KEY:
      OR_OPEN_WEATHER_API_APP_ID:
      OR_SETUP_IMPORT_DEMO_AGENT_KNX:
      OR_SETUP_IMPORT_DEMO_AGENT_VELBUS:
    volumes:
      - ./deployment:/deployment 
#      - /var/run/dbus:/var/run/dbus
#      # Bluetooth mesh volume
#      - btmesh-data:/btmesh
#   devices:
#     - /dev/ttyACM0:/dev/ttyS0

I am using below command to run the docker file.
cmd /C "set OR_HOSTNAME=192.168.159.248 && docker-compose -p openremote up -d"

I am getting below error message.

Kindly help and let me know what is that I am doing wrong here.

If you are using last version of Openremote i think you are missing

at the beginning in volumes:

manager-data:

in postgresql volumes:

- manager-data:/storage

in the manager volumes at the end:

- manager-data:/storage

reference:

@pcr and @Denis i was able to run my docker file using IP and also i was able to connect MQTTX to OR using 192.168.0.105:8883 below is my docker file.
docker-compose.yml.txt (2.7 KB)

but i was not able to connect my esp8266 with OR MQTT broker. my connection was again failing with rc=-2.
below is my secre.h

// Wifi 
const char* ssid = "403"; // Wifi SSID
const char* password = "12345678"; // Wifi Password

//MQTT Broker
const char* mqtt_server = "192.168.0.105";
unsigned int mqtt_port = 8883; //SSL 8883 NoneSSL 1883
const char* username = "master:mqttuser"; // Service User Realm:Serviceuser
const char* mqttpass = "yvIudfWHC4R4dfzJbsa4l2nwWRkhasBr"; // Service User Secret
const char* ClientID = "client123";
//LastWill
const char* lastwill = "master/client123/writeattributevalue/writeAttribute/4q0u7wZVXGRMaewy2yRkhp";
const char* lastwillmsg = "0";


//subscribing Topic
const char *topic = "master/client123/attribute/writeAttribute/4q0u7wZVXGRMaewy2yRkhp"; //see Subscribing Topics in Documentation https://github.com/openremote/openremote/wiki/User-Guide%3A-Manager-APIs#mqtt-api-mqtt-broker


//Local CA

const char* local_root_ca = \
                            "-----BEGIN CERTIFICATE-----\n" \
                            "MIIDnzCCAoegAwIBAgIUE3jYzxKpepVM0CSLZd9GNv6BHj8wDQYJKoZIhvcNAQEL\n" \
                            "BQAwUDELMAkGA1UEBhMCR0IxHTAbBgNVBAMMFE9wZW5SZW1vdGUgRGVtbyBDZXJ0\n" \
                            "MRMwEQYDVQQKDApPcGVuUmVtb3RlMQ0wCwYDVQQLDAREZW1vMCAXDTIwMDYwODE5\n" \
                            "MTc1MVoYDzIwNTAwNjAxMTkxNzUxWjBQMQswCQYDVQQGEwJHQjEdMBsGA1UEAwwU\n" \
                            "T3BlblJlbW90ZSBEZW1vIENlcnQxEzARBgNVBAoMCk9wZW5SZW1vdGUxDTALBgNV\n" \
                            "BAsMBERlbW8wggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCrKEk77HcJ\n" \
                            "B5SqvoN2UbRsDh9d0ECN8tOU5hC2poih+6XBJgikQ8gdy7ptt477KRh3ZIiw3ZTX\n" \
                            "Hg0//Ju71D/4EDBYwHxoSK9WehP5Kz/LrBHhtArXK3RYH8pFS13CDOPjXnm6LMN5\n" \
                            "2mRGwm2gCwKwRTbfm+D9hjpVuwt0sfHaXVETlUc4JystlfYVurMcfsox9tsbRuzl\n" \
                            "EakyK9Cr1V7bgaLMosHDX3NSuEyzb9DQZ3PBK3JjJhSeYkGNuP/NocMrWy/JHd2v\n" \
                            "2Wev9W+D1Pv46Sqfrvd6K7oP00FL0CdODkMRBVTlb1wq/6uJdRbnVUM0PGA9enrQ\n" \
                            "vMB11fFglHa3AgMBAAGjbzBtMB0GA1UdDgQWBBT0ixs03BOrns+E2+xSU+nfP9KX\n" \
                            "iTAfBgNVHSMEGDAWgBT0ixs03BOrns+E2+xSU+nfP9KXiTAPBgNVHRMBAf8EBTAD\n" \
                            "AQH/MBoGA1UdEQQTMBGCCWxvY2FsaG9zdIcEfwAAATANBgkqhkiG9w0BAQsFAAOC\n" \
                            "AQEAawmLoD7bzFTM0Z58PR6jQR3ypD6IAyei6xiBI7wvxbjyxqQrk1i0rK2Aexjk\n" \
                            "v2ZsAUmtrm5k5pWpBsokNuRddPV1K2OZjTj9HPc9AxqjyHKyqRXmVKWkzbWQDLVS\n" \
                            "lGRk7yviUFS8nRuY0vLfqZzF7e2HeasThILJibY8rUVLuq+iMS35RDwQ9usIOiYz\n" \
                            "dF4CO3HFZ6NtDheM1mPAy4Q76H1P1fINuA8mp/by9J8heexqjgpBKYexiQhjb1A7\n" \
                            "NBdWbJPXoNJplGXjGIbj8KxW61ih1wDRE2ZseOflRstO9/Txm7+Cuqo+WBOK39cU\n" \
                            "CXPKre2pqmkIu65wJ6VcTKeSqw==" \
                            "-----END CERTIFICATE-----";

and below is my main.ino file:

#include "secret.h"
#include <ESP8266WiFi.h> // remove comment for ESP8266, and add comment at #include <WiFi.h> 
//#include <WiFi.h>          
#include <PubSubClient.h>

//Objects
WiFiClientSecure askClient; //SSL Client
//WiFiClient askClient; //Non-SSL Client, also remove the comments for askClient.setCACert(local_root_ca);

PubSubClient client(askClient);

void setup() {
  Serial.begin(9600);
  Serial.println(ssid);

  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
  
  }

  Serial.println(WiFi.localIP());
  //askClient.setCACert(local_root_ca); //If you use non SSL then comment out
  askClient.setCertificate_P(reinterpret_cast<const uint8_t*>(local_root_ca), strlen_P(local_root_ca));
  client.setServer(mqtt_server, mqtt_port);
  reconnect();
  client.setCallback(callback);
  reconnect();
  Serial.println(WiFi.localIP());
  
}

void loop() {
  //Publish Boolean format:
  client.publish("master/client123/writeattributevalue/writeAttribute/4q0u7wZVXGRMaewy2yRkhp", "1");
  //To publish Strings:
  //client.publish("yourrealm/ClientID/writeattributevalue/AttributeName/AssetID", String("Hello").c_str());
  delay(100);

}

//MQTT callback
void callback(char* topic, byte * payload, unsigned int length) {
  

  for (int i = 0; i < length; i++) {

    Serial.println(topic);
    Serial.print(" has send ");
    Serial.print((char)payload[i]);
  }

}

//MQTT reconnect
void reconnect() {
  // Loop until we're reconnected
  while (!client.connected()) {
    Serial.print("********** Attempting MQTT connection...");
    // Attempt to connect
    if (client.connect(ClientID, username, mqttpass, lastwill, 1, 1, lastwillmsg)) {
      Serial.println("-> MQTT client connected");
      client.subscribe(topic);
      Serial.print("Subscribed to: ");
      Serial.println(topic);
    } else {
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println("-> try again in 5 seconds");
      // Wait 5 seconds before retrying
      delay(5000);
    }
  }
}

Can @pcr , @Denis or someone help me!!

Try 1883, the ESP8266 can‘t use cert, you need a fingerprint.

hi,
try it

ESP32_Mqtt_SSL-1.txt (7.4 KB)

Hi @apurba
Please read carefully, he is using an ESP8266 not ESP32.

There are some significant difference.

Hi @Denis,yeah right, i was posted it because he might get some idea that’s the reason from this post.

1 Like

How can i find out fingerprint of server certificate.

Sorry, i’m not ChatGPT, you can google this by yourself.
If you got further question related to openremote, you are welcome to ask.
Otherweise feel free to use the Contact of openremote to recieve an offer.