Connecting ESP8266 to OpenRemote MQTT Broker

Hi all,

Has anyone actually ever successfully connected an ESP8266 to Open Remote? All the posts I’ve read on this forum are about people facing challenges but never actually getting it to work the way it’s supposed to.

I am new to open remote but have a decent background in electronics. I have been trying to connect my ESP8266 device to the OpenRemote mqtt broker with no success. I have followed the wiki guide and made some adjustments as per the posts on this forum but I keep getting the Error/return code -4.

// Wifi 
char* ssid = "Finfoot";  //"Muchira Portal";  //      Wifi SSID
const char* password =  "H(g{Cw8trahV";// "nobaconhere5"; //      Wifi Password

//MQTT Broker
const char* mqtt_server = "192.168.100.173";  //
unsigned int mqtt_port = 1883; //SSL 8883 NoneSSL 1883
const char* username = "master:mqttuser"; // Service User Realm:Serviceuser
const char* mqttpass = "68q0WccufHszcJoJc94dDEYy5MIR5K7U"; // Service User Secret
const char* ClientID = "client123";
//LastWill
const char* lastwill = "master/client123/writeattributevalue/AttributeName/7JiY3cLJTO14FE2GoowKGP";
const char* lastwillmsg = "0";


//subscribing Topic
const char *topic = "master/client123/attribute/subscribeAttribute/7JiY3cLJTO14FE2GoowKGP"; //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" \
                            "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\n" \
                            "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\n" \
                            "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\n" \
                            "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\n" \
                            "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\n" \
                            "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\n" \
                            "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\n" \
                            "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\n" \
                            "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\n" \
                            "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\n" \
                            "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\n" \
                            "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\n" \
                            "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\n" \
                            "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\n" \
                            "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\n" \
                            "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\n" \
                            "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\n" \
                            "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\n" \
                            "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\n" \
                            "xxxxxxxxxxxxxxxxxxxxxxxxxxxxx" \
                            "-----END CERTIFICATE-----";

                           
                            
#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(115200);
  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
  client.setServer(mqtt_server, mqtt_port);
  //reconnect();
  client.setCallback(callback);
  reconnect();

}

void loop() {
  //Publish Boolean format:
  client.publish("master/client123/writeattributevalue/writeAttribute/7JiY3cLJTO14FE2GoowKGP", "23");
  //To publish Strings:
  client.publish("master/client123/writeattributevalue/msg/7JiY3cLJTO14FE2GoowKGP", String("Hello").c_str());
  delay(10000);

}

//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);
    }
  }
}

I also observed that when I change the hostname from localhost to my computer’s IP address I am sometimes unable to access the open remote manager from my browser as the openremote/proxy container keeps restarting on it’s own. I am beginning to think this may be a windows issue. Does anyone have a solution?

The only changes I made to the docker compos.yml was to add the 1883 port as shown below:

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

@Denis @Rich @Don

Hi,

Can you please share your docker-compose.yml?

Hi Denis,

Here’s my docker-compose.yml:

# 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:
  manager-data:
  postgresql-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
      - manager-data:/storage

  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}
    depends_on:
      keycloak:
        condition: service_healthy
    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:
      - manager-data:/storage

# 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:
  manager-data:
  postgresql-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: 192.168.100.173
      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
      - manager-data:/storage

  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: 192.168.100.173
      KC_HOSTNAME_PORT: ${OR_SSL_PORT:--1}


  manager:
#    privileged: true
    restart: always
    image: openremote/manager:${MANAGER_VERSION:-latest}
    depends_on:
      keycloak:
        condition: service_healthy
    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: 192.168.100.173
      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:
      - manager-data:/storage

try this and just start with: docker-compose -p openremote up

Hi Denis, thank you for taking time to respond. I have tried the docker-compose.yml you have sent with no success. I am still getting rc=-4. However, I have noticed that the rc changes from -4 to -2 when I turn off the docker engine. I have attached the output from the serial monitor for reference.

I’m not too familiar with docker but logic would tell me that if the rc on ESP8266 is changing in response to events happening on my computer (i.e turning on and off the docker engine) then surely there must be some link between the two even though I am not making a successful connection.

What are your thoughts on this?

Could you please try to connect to the broker with a client like mqtt explorer?

Btw these are the client.states

#define MQTT_CONNECTION_TIMEOUT     -4
#define MQTT_CONNECTION_LOST        -3
#define MQTT_CONNECT_FAILED         -2
#define MQTT_DISCONNECTED           -1
#define MQTT_CONNECTED               0
#define MQTT_CONNECT_BAD_PROTOCOL    1
#define MQTT_CONNECT_BAD_CLIENT_ID   2
#define MQTT_CONNECT_UNAVAILABLE     3
#define MQTT_CONNECT_BAD_CREDENTIALS 4
#define MQTT_CONNECT_UNAUTHORIZED    5

Not read everything above but I see your code is trying to connect to the broker using port 1883 and you have exposed port 1883 on the proxy service but the proxy service by default does not route 1883 to the manager container (see default proxy haproxy.cfg).

You will need to map port 1883 on the manager service as that where the broker is actually running but then you have no TLS encryption (fine on a private network).

Hi Denis, I installed mqtt explorer and managed to connect but only on port 8883. Thanks to @Rich I now know why I couldn’t connect on 1883. It also explains why my ESP8266 was failing to connect.

Hi Rich, thanks for this valuable insight. Any chance you can walk me through or point me to a tutorial that shows me how to map port 1883 on the manager service?

Hi Rich, thanks for this valuable insight. Any chance you can walk me through or point me to a tutorial that shows me how to map port 1883 on the manager service?

Please bare with me. I’m not to familiar with this environment.

Hi,

If you really want to not use TLS then add this to your manager service in your docker compose file:

  manager:
    ports:
      - "1883:1883"

Then remove the 1883 port mapping from the proxy service

Hi Rich,

I have made the changes you suggested to my docker-compose.yml however, I am still failing to establish a connection between MQTT explorer and the OR mqtt broker on port 1883. I assume it’ll be the same with my ESP8266.

# 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:
  manager-data:
  postgresql-data:

services:

  proxy:
    image: openremote/proxy:${PROXY_VERSION:-latest}
    restart: always
    depends_on:
      manager:
        condition: service_healthy
    ports:
      - "80:80" # Needed for SSL generation using letsencrypt
      - "${OR_SSL_PORT:-443}:443"
      - "8883:8883"
      #- "127.0.0.1:8404:8404" # Localhost metrics access
    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
      - manager-data:/storage

  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}
    depends_on:
      keycloak:
        condition: service_healthy
    ports:
      - "1883:1883"
    #  - "127.0.0.1:8405:8404" # Localhost metrics access
    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:
      - manager-data:/storage

On another note, earlier I had managed to connect Mqtt explorer using port 8883 with TLS switched on as in the image below. I assumed that this meant if I got an esp32 and tried to connect on port 8883 that would solve my problem. Unfortunately not. It keeps failing with state -2. I am not quite sure where I’m getting it wrong here.


Hi @Denis , @Rich . Thank you very much for your patience with me. I have finally got it to work. I was frustrated because I had followed the instructions you gave me to the letter and it was still not working. After tracing all the steps from the start I realise where I made the mistake. I had downloaded a second docker-compose.yml which was consequently named docker-compose(1).yml . So in making all the changes to the compose file that were recommended here, they were not reflecting on the OR instance because I was starting the wrong compose file.

I will attach my code for the ESP8266 here for the next guy who will face similar challenges

#include <ESP8266WiFi.h>
#include <NTPClient.h>
#include <WiFiUdp.h>
#include <PubSubClient.h>


// WiFi Setup
const char *ssid = "*******";
const char *password = "*******";

//MQTT Setup
const char* mqtt_server = "192.168.100.176";  //
unsigned int mqtt_port = 1883;
const char* username = "master:mqttuser"; // 
const char* mqttpass = "68q0WccufHszcJoJc94dDEYy5MIR5K7U"; // Service User Secret
const char* ClientID = "ESP_02";
//LastWill
const char* lastwill = "master/ESP_02/writeattributevalue/msg/7McfOJJUQuncwGs58Hcluv";
const char* lastwillmsg = "0";
//subscribing Topic
const char *topic = "master/ESP_02/attribute/subscribeAttribute/7McfOJJUQuncwGs58Hcluv";


//Sensor setup
int sensorPin = D2;
int pulse;
unsigned long previous_time;
unsigned long elapsed_time;
const long sampling_period = 10000;
const long utcOffsetInSeconds = 7200;
volatile int cummulative_count;
int previous_count;
volatile int overflow_count;


WiFiUDP ntpUDP;
NTPClient timeClient(ntpUDP, "pool.ntp.org", utcOffsetInSeconds);
WiFiClient askClient; //Non-SSL Client, also remove the comments for askClient.setCACert(local_root_ca);
PubSubClient client(askClient);


void setup() {
  pinMode(LED_BUILTIN, OUTPUT);     // Initialize the LED_BUILTIN pin as an output
  pinMode(sensorPin, INPUT);
  Serial.begin(115200);
  WiFi.mode(WIFI_AP); 
  timeClient.begin();
  client.setServer(mqtt_server, mqtt_port);
  client.setCallback(callback);
  attachInterrupt(digitalPinToInterrupt(sensorPin), increase, RISING);
}

void loop() {
  
  // Connect or reconnect to WiFi  
    if(WiFi.status() != WL_CONNECTED){
      Serial.print("Attempting to connect");
      while(WiFi.status() != WL_CONNECTED){
        WiFi.begin(ssid, password); 
        Serial.print(".");
        delay(5000);     
      } 
      Serial.println("\nConnected.");
      Serial.println(WiFi.localIP());
      reconnect();
      
    }


  if (isSampleTime()) {
    pulse = abs(cummulative_count - previous_count);
    previous_count = cummulative_count;
    Serial.print("Overflow Count: ");Serial.print(overflow_count);Serial.print("  ");Serial.print("Total: ");Serial.print(cummulative_count); Serial.print("  ");Serial.print("Flowrate: "); Serial.println(pulse);
    String pulse_str = String(pulse);
    String total_str = String(cummulative_count);
    const char* pulse_char = pulse_str.c_str();
    const char* total_char = total_str.c_str();
    client.publish("master/ESP_02/writeattributevalue/pulseCount/7McfOJJUQuncwGs58Hcluv", pulse_char);
    client.publish("master/ESP_02/writeattributevalue/totalizer/7McfOJJUQuncwGs58Hcluv", total_char);
     
    digitalWrite(LED_BUILTIN, LOW);   // Turn the LED on
    wait(500);                      
    digitalWrite(LED_BUILTIN, HIGH); // Turn LED off 
  }

  
}

ICACHE_RAM_ATTR void increase() {
  cummulative_count++;
  if(cummulative_count<0){
    cummulative_count = 0;
    overflow_count++;
  }
}

void wait(int period){
  unsigned long epoch = millis();
  while((period+epoch)> millis()){
  }
}

bool isSampleTime(){
  bool sample_state;
  timeClient.update();
  if((sampling_period/1000)==60){
    sample_state = (timeClient.getSeconds()==0);
  }
  else if((sampling_period/1000)<60){
    sample_state = (timeClient.getSeconds()%(sampling_period/1000)==0);
  }
  else if((sampling_period/1000)>60 && (sampling_period/1000)%60==0){
    sample_state = (timeClient.getMinutes()%(sampling_period/(1000*60))==0);
  }
  else{
    sample_state = false;
  }
  return sample_state;
}

void blink_LED() {
  digitalWrite(LED_BUILTIN, LOW);   // Turn the LED on (Note that LOW is the voltage level
  wait(200);                      // Wait for a second
  digitalWrite(LED_BUILTIN, HIGH);  // Turn the LED off by making the voltage HIGH
  wait(400);                      // Wait for two seconds (to demonstrate the active low LED)
  digitalWrite(LED_BUILTIN, LOW);   // Turn the LED on (Note that LOW is the voltage level
  wait(200);                      // Wait for a second
  digitalWrite(LED_BUILTIN, HIGH);  // Turn the LED off by making the voltage HIGH
  wait(400);
  digitalWrite(LED_BUILTIN, LOW);   // Turn the LED on (Note that LOW is the voltage level
  wait(200);                      // Wait for a second
  digitalWrite(LED_BUILTIN, HIGH);  // Turn the LED off by making the voltage HIGH
  wait(400);
  digitalWrite(LED_BUILTIN, LOW);   // Turn the LED on (Note that LOW is the voltage level
  wait(200);                      // Wait for a second
  digitalWrite(LED_BUILTIN, HIGH);  // Turn the LED off by making the voltage HIGH
  wait(400);
}

//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);
    }
  }
}

Some images:


I will note however, that I never manged to successfully connect to SSL port 8883 through the proxy using the ESP32 or ESP8266. I’ll look more into it at a later stage but for now this will suit my needs. Thanks again for all the help. I’m happy to be a part of this forum. :smiley:

1 Like

Well done for persevering and getting it working

Well done.

What kind of problem you are facing with connecting via secured port?

Here for me everything works fine.