MQTT Connection Guide

Everything you need to connect your devices to Virtuino Cloud via MQTT — from first connection to secure production setup.

Mosquitto Compatible — The Virtuino Cloud broker is 100% Mosquitto-compatible. Any MQTT client library or tool that supports standard MQTT works out of the box.

1How to Connect

Use the values below every time you configure an MQTT client (MQTTX, Arduino library, Python, Node-RED, etc.).

Parameter Value Notes
*Broker Host cloud.virtuino.com Same host for both plain and TLS connections
*Port (Plain) 1883 plain TCP No encryption — for development and testing only
*Port (TLS) 8883 TLS / SSL Encrypted — always use in production
*Username vr-abcd1234 Your Sub-account Key — found in Console → API & Connections
*Password your MQTT password Found in Console → API & Connections → MQTT Credentials
Client ID device_anything Any value you like — just make sure no other device on your account uses the same one. We recommend starting with device_ followed by something unique (e.g. the chip ID).
MQTT Version 3.1.1  or  5.0 Both supported; use 3.1.1 for maximum device compatibility
QoS 0, 1  or  2 All QoS levels (0, 1, 2) are supported
Keep Alive 60 seconds Increase to 120 s on slow or unstable networks
Clean Session true Recommended for most IoT devices
TLS Certificate CA Signed Server Certificate ISRG Root X1 (Let's Encrypt). No client certificate required

* Required field

2Tested Configuration (MQTTX)

The settings below have been tested and confirmed working with the MQTTX desktop client. Use them as a reference for any MQTT client application.

MQTTX Port 1883 — Plain
Name
virtuino
Host
mqtt:// cloud.virtuino.com
Port
1883
Client ID
device_abcdefgh123
Username
vr-abcd1234
Password
••••••••••••••••••••••
SSL/TLS

MQTT Version
3.1.1
Connect Timeout
10 (s)
Keep Alive
60 (s)
Auto Reconnect
Reconnect Period
4000 (ms)
Clean Session
MQTTX Port 8883 — TLS
Name
virtuino
Host
mqtts:// cloud.virtuino.com
Port
8883
Client ID
device_abcdefgh123
Username
vr-abcd1234
Password
••••••••••••••••••••••
SSL/TLS
SSL Secure
Certificate
● CA signed server certificate
ALPN
(empty)

MQTT Version
5.0
Connect Timeout
10 (s)
Keep Alive
60 (s)
Auto Reconnect
Reconnect Period
4000 (ms)
Clean Start
Session Expiry
0 (s)

3Topic Structure

Important — Devices & Fields must exist first:
Before publishing or subscribing to any topic, make sure you have already created the corresponding Device and Field in the Virtuino Cloud Console (Console → Devices). The device and field segments in the topic must exactly match the Device and Field names you defined on the platform — otherwise the broker will not recognise the topic and the data will be ignored.

The broker supports two bare-topic formats — choose the one that fits your project.

Format 1 — Simple Recommended for single-device projects

The simplest option. Use it for quick tests, prototypes, and single-device learning projects.

# Same topic used for both directions — the broker infers the
# direction from PUBLISH vs SUBSCRIBE, you never write it yourself.
field

# Examples — device publishes (data → cloud)
temperature
humidity

# Examples — device subscribes (commands ← cloud)
relay1
V1          # virtual-pin style

Format 2 — Device Path Recommended for multi-device projects

Organises topics by device, making it easy to manage multiple devices under the same account. The first topic segment is always the device name, the second is the field name.

# Same topic used for both directions
device/field

# Examples — device publishes (data → cloud)
esp32/temperature
arduino_uno/soil_moisture

# Examples — device subscribes (commands ← cloud)
esp32/relay
raspi/status

Publish & Subscribe

The same field's topic is used for both directions — what makes it "publish" or "subscribe" is simply which one your device code does with it:

Your device does this……using this topic…and it means
mqtt.publish(topic, value) temperature Send a reading to the cloud (e.g. "23.75")
mqtt.subscribe(topic) relay1 Receive a command from the cloud (e.g. "1" / "0")

A field can be used either way, or both — it depends on how you write your device code, not on the field's name. Dashboard widgets, rules, schedules and scripts talk to the same fields from the platform side automatically; they don't need any MQTT topic configured.

Wildcards

WildcardMeaningExampleMatches
+ Any single level +/status status of all devices, but not deeper levels (subscribe only)
# All levels from here down # everything the cloud sends to you (subscribe only)
# All levels from here down esp32/# all incoming topics for the esp32 device only (subscribe only)
Namespace isolation: Since you never write your Sub-account Key in a topic, there's nothing to accidentally leak — every topic your connection publishes or subscribes to is automatically scoped to your own account. It is not possible to reach another account's namespace.

4Client Settings Explained

These are the settings you configure in your MQTT client application (such as MQTTX, Node-RED, Home Assistant, etc.).

Connection Settings

SettingWhat it doesRecommended value
MQTT Version The protocol version used. 3.1.1 is universal and works with every Arduino/ESP library. 5.0 adds session expiry, message properties, and reason codes — useful in advanced setups but requires library support. 3.1.1 (devices)
5.0 (advanced)
Connect Timeout How many seconds the client waits for the broker to acknowledge the connection (CONNACK) before giving up and reporting an error. 10 s
Keep Alive The client sends a PINGREQ to the broker at this interval to keep the connection alive when no data is flowing. If the broker receives no ping or message within 1.5× this value, it considers the client disconnected and triggers the Last Will. 60 s
Auto Reconnect If the connection drops, the client automatically tries to reconnect without requiring a manual action or device restart. ON
Reconnect Period How many milliseconds to wait between reconnection attempts after a drop. 4000 ms
Clean Session
(MQTT 3.1.1)
When ON: the broker discards all previous subscriptions and queued messages when the client disconnects. The client starts fresh every time it connects. Recommended for most IoT devices.
When OFF: the broker remembers subscriptions and queues QoS 1 messages delivered while the device was offline.
ON
Clean Start
(MQTT 5.0 equivalent)
Same concept as Clean Session but in MQTT 5.0. When ON, the session state is cleared on connect. ON
Session Expiry Interval
(MQTT 5.0 only)
How many seconds the broker keeps a persistent session after the client disconnects. 0 means the session is deleted immediately on disconnect (equivalent to Clean Start ON). Only applies when Clean Start is OFF. 0

SSL / TLS Settings

SettingWhat it doesVirtuino Cloud
SSL/TLS Enables encrypted transport. When ON, all data between your device and the broker is encrypted — nobody can intercept or read your sensor values or credentials. Use port 8883 with SSL ON
SSL Secure When ON, the client verifies the broker's certificate against a trusted Certificate Authority. If the certificate is invalid or expired, the connection is refused — protecting against man-in-the-middle attacks. ON — always enable in production
Certificate:
CA Signed Server Certificate
The broker presents a certificate issued by a well-known public CA (Virtuino Cloud uses Let's Encrypt / ISRG Root X1). Your client trusts it automatically using the CA store built into your OS or library. You do not need to upload any certificate file. ✅ Supported & required
Certificate:
CA or Self-Signed
Certificates created by the operator themselves, not by a public CA. These require you to manually install the certificate on every client. Not used by Virtuino Cloud. ❌ Not applicable

5Last Will and Testament (LWT)

The Last Will is a message you pre-register with the broker at connect time. If your device disconnects unexpectedly (power loss, network dropout, crash), the broker publishes this message automatically. A clean disconnect (device calls DISCONNECT) does not trigger the LWT.

Use it to make dashboards show accurate online/offline status for every device.

FieldDescription & Usage
Last-Will Topic The topic the broker will publish to on your behalf when you disconnect unexpectedly. Should be a dedicated status topic for the device.

Recommended: esp32/LWT (bare — no Sub-account Key needed)
Use the reserved LWT field name (as the last segment) so Virtuino Cloud tracks the device state itself — see MQTT Confirmed. Any other topic still works for dashboard widgets that subscribe to it directly, but the platform will not track it.
Last-Will Payload The message content the broker will publish. Use a value that clearly signals that the device is down.

Common values: "offline", "0", "disconnected"
Pair with a regular publish of "online" on successful connect so the dashboard always reflects the true device state.
Last-Will QoS The QoS level for the LWT message itself.

QoS 0: broker sends the LWT once, no acknowledgement.
QoS 1: broker retries until all current subscribers acknowledge receipt — recommended so the dashboard always receives the disconnect event.

Recommended: QoS 1
Last-Will Retain When ON: the broker stores the LWT as the retained message for that topic. Any new subscriber (e.g. a dashboard widget that opens later) immediately receives "offline" as the current state — even if no new message has arrived. This is almost always the correct setting for status topics.

When OFF: only subscribers currently connected at the moment of disconnect will receive the LWT.

Recommended: Retain ON
Availability tracking and command confirmation
To have Virtuino Cloud track whether a device is online, and to be told when a command was not actually executed, see MQTT Confirmed — it covers the reserved LWT topic, the Device Monitor widget and ready-to-use device code.

6Code Examples

Start with the plain connection (port 1883) to verify your credentials and topic setup works. Once confirmed, switch to the secure connection (port 8883) for production.

Required library: All examples below use PubSubClient by Nick O'Leary. Install it via Arduino IDE → Sketch → Include Library → Manage Libraries → search PubSubClient.

ESP8266

Plain — Port 1883
Secure TLS — Port 8883
// ESP8266 — Plain MQTT connection (port 1883)
// For testing and development only — data is NOT encrypted.

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

// ── Wi-Fi ──────────────────────────────────────────
const char* ssid       = "YOUR_WIFI_SSID";
const char* wifiPass   = "YOUR_WIFI_PASSWORD";

// ── Virtuino Cloud MQTT ────────────────────────────
const char* mqttHost   = "cloud.virtuino.com";
const int   mqttPort   = 1883;
const char* mqttUser   = "vr-abcd1234";       // Sub-account Key
const char* mqttPass   = "YOUR_MQTT_PASSWORD";
String      clientId;                           // built in setup(): "device_" + chip ID

// ── Topics ─────────────────────────────────────────
// Built from mqttUser, so the account key is written only once
String deviceName  = "esp8266";
// Bare topics — no account key needed, the broker scopes them to your login automatically
String topicTemp   = deviceName + "/temperature";  // device publishes → cloud
String topicRelay  = deviceName + "/relay1";       // device subscribes ← cloud
String topicStatus = deviceName + "/LWT";          // reserved LWT topic (online / offline)

WiFiClient    wifiClient;
PubSubClient  mqtt(wifiClient);

// ── Incoming message handler ───────────────────────
void onMessage(char* topic, byte* payload, unsigned int len) {
  String msg = "";
  for (int i = 0; i < len; i++) msg += (char)payload[i];
  Serial.println("[" + String(topic) + "] " + msg);

  // Control relay from dashboard
  if (String(topic) == topicRelay) {
    bool relayOn = (msg == "1");
    digitalWrite(D1, relayOn ? HIGH : LOW);
  }
}

void connectMQTT() {
  while (!mqtt.connected()) {
    Serial.print("Connecting to MQTT...");
    if (mqtt.connect(clientId.c_str(), mqttUser, mqttPass,
                     topicStatus.c_str(), 1, true, "offline")) {
      Serial.println(" connected!");
      mqtt.subscribe(topicRelay.c_str());
      mqtt.publish(topicStatus.c_str(), "online", true);   // birth message clears the retained "offline"
    } else {
      Serial.print(" failed, rc="); Serial.println(mqtt.state());
      delay(5000);
    }
  }
}

void setup() {
  Serial.begin(115200);
  clientId = "device_" + String(ESP.getChipId(), HEX);  // unique per chip — no account key needed
  pinMode(D1, OUTPUT);

  WiFi.begin(ssid, wifiPass);
  while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); }
  Serial.println("\nWi-Fi connected: " + WiFi.localIP().toString());

  mqtt.setServer(mqttHost, mqttPort);
  mqtt.setCallback(onMessage);
}

void loop() {
  if (!mqtt.connected()) connectMQTT();
  mqtt.loop();

  // Publish temperature every 10 seconds
  static unsigned long lastPub = 0;
  if (millis() - lastPub > 10000) {
    lastPub = millis();
    float temp = random(200, 300) / 10.0;
    String payload = String(temp, 2);
    mqtt.publish(topicTemp.c_str(), payload.c_str());
    Serial.println("Published: " + payload);
  }
}
// ESP8266 — Secure MQTT connection (port 8883, TLS)
// Uses Let's Encrypt CA certificate — no file upload needed.
//
// ⚠ REQUIRES: ESP8266 Arduino Core ≥ 2.5.0 (BearSSL support)
// Arduino IDE → Tools → Board → Boards Manager → "esp8266 by ESP8266 Community" → update to 3.x

#include <ESP8266WiFi.h>
#include <WiFiClientSecure.h>
#include <BearSSLHelpers.h>
#include <PubSubClient.h>

// ── Wi-Fi ──────────────────────────────────────────
const char* ssid       = "YOUR_WIFI_SSID";
const char* wifiPass   = "YOUR_WIFI_PASSWORD";

// ── Virtuino Cloud MQTT ────────────────────────────
const char* mqttHost   = "cloud.virtuino.com";
const int   mqttPort   = 8883;
const char* mqttUser   = "vr-abcd1234";
const char* mqttPass   = "YOUR_MQTT_PASSWORD";
String      clientId;                           // built in setup(): "device_" + chip ID

// ── Topics ─────────────────────────────────────────
// Built from mqttUser, so the account key is written only once
String deviceName  = "esp8266";
// Bare topics — no account key needed, the broker scopes them to your login automatically
String topicTemp   = deviceName + "/temperature";  // device publishes → cloud
String topicRelay  = deviceName + "/relay1";       // device subscribes ← cloud
String topicStatus = deviceName + "/LWT";          // reserved LWT topic (online / offline)

// ── ISRG Root X1 — Let's Encrypt CA Certificate ───
const char caCert[] PROGMEM = R"EOF(
-----BEGIN CERTIFICATE-----
MIIFazCCA1OgAwIBAgIRAIIQz7DSQONZRGPgu2OCiwAwDQYJKoZIhvcNAQELBQAw
TzELMAkGA1UEBhMCVVMxKTAnBgNVBAoTIEludGVybmV0IFNlY3VyaXR5IFJlc2Vh
cmNoIEdyb3VwMRUwEwYDVQQDEwxJU1JHIFJvb3QgWDEwHhcNMTUwNjA0MTEwNDM4
WhcNMzUwNjA0MTEwNDM4WjBPMQswCQYDVQQGEwJVUzEpMCcGA1UEChMgSW50ZXJu
ZXQgU2VjdXJpdHkgUmVzZWFyY2ggR3JvdXAxFTATBgNVBAMTDElTUkcgUm9vdCBY
MTCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBAK3oJHP0FDfzm54rVygc
h77ct984kIxuPOZ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x4nLCgdNbOhdjsnvzqvHu7Ur
TkXWStAmzOVyyghqpZXjFaH3pO3JLF+l+/+sKAIuvtd7u+Nxe5AW0wdeRlN8NwdC
jNPElpzVmbUq4JUagEiuTDkHzsxHpFKVK7q4+63SM1N95R1NbdWhscdCb+ZAJzVc
oyi3B43njTOQ5yOf+1CceWxG1bQVs5ZufpsMljq4Ui0/1lvh+wjChP4kqKOJ2qxq
4RgqsahDYVvTH9w7jXbyLeiNdd8XM2w9U/t7y0Ff/9yi0GE44Za4rF2LN9d11TPA
mRGunUHBcnWEvgJBQl9nJEiU0Zsnvgc/ubhPgXRR4Xq37Z0j4r7g1SgEEzwxA57d
emyPxgcYxn/eR44/KJ4EBs+lVDR3veyJm+kXQ99b21/+jh5Xos1AnX5iItreGCc=
-----END CERTIFICATE-----
)EOF";

BearSSL::WiFiClientSecure  wifiClient;
BearSSL::X509List          trustedCA(caCert);
PubSubClient               mqtt(wifiClient);

void onMessage(char* topic, byte* payload, unsigned int len) {
  String msg = "";
  for (int i = 0; i < len; i++) msg += (char)payload[i];
  Serial.println("[" + String(topic) + "] " + msg);
}

void connectMQTT() {
  while (!mqtt.connected()) {
    Serial.print("Connecting (TLS)...");
    // Last Will: broker publishes "offline" to topicStatus if device drops unexpectedly
    if (mqtt.connect(clientId.c_str(), mqttUser, mqttPass,
                     topicStatus.c_str(), 1, true, "offline")) {
      Serial.println(" connected!");
      mqtt.publish(topicStatus.c_str(), "online", true);   // birth message clears the retained "offline"
      mqtt.subscribe(topicRelay.c_str());
    } else {
      Serial.print(" failed, rc="); Serial.println(mqtt.state());
      delay(5000);
    }
  }
}

void setup() {
  Serial.begin(115200);
  clientId = "device_" + String(ESP.getChipId(), HEX);  // unique per chip — no account key needed
  configTime(3 * 3600, 0, "pool.ntp.org");   // TLS needs correct time

  WiFi.begin(ssid, wifiPass);
  while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); }
  Serial.println("\nWi-Fi: " + WiFi.localIP().toString());

  wifiClient.setTrustAnchors(&trustedCA);   // verify broker cert against ISRG Root X1
  mqtt.setServer(mqttHost, mqttPort);
  mqtt.setCallback(onMessage);
  mqtt.setBufferSize(512);
}

void loop() {
  if (!mqtt.connected()) connectMQTT();
  mqtt.loop();

  static unsigned long lastPub = 0;
  if (millis() - lastPub > 10000) {
    lastPub = millis();
    float temp = analogRead(A0) * 0.1;
    mqtt.publish(topicTemp.c_str(), String(temp, 2).c_str());
  }
}

Without the String class

Why the examples above use String.
It reads naturally, concatenation is a single +, and there are no buffer sizes to get right — which is why we use it in the examples aimed at getting started quickly.

The cost is heap fragmentation. Every time a String grows or is reassigned, the old block is freed and a new one allocated. On an ESP8266, with only tens of kilobytes of heap, those gaps accumulate over days of uninterrupted operation: the total free memory still looks fine, but no single contiguous block is large enough, and the device eventually reboots. It is one of the most common causes of a sketch that “works for a week and then restarts on its own”.

The version below builds the topics once into fixed char buffers and never allocates again. Prefer it for anything meant to run permanently.
// ESP8266 — same sketch without the String class
// Topics are built once in setup(), so the account key is written only once

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

const char* ssid       = "YOUR_WIFI_SSID";
const char* wifiPass   = "YOUR_WIFI_PASSWORD";

const char* mqttHost   = "cloud.virtuino.com";
const int   mqttPort   = 1883;
const char* mqttUser   = "vr-abcd1234";       // Sub-account Key
const char* mqttPass   = "YOUR_MQTT_PASSWORD";
const char* deviceName = "esp8266";

char clientId[64];
char topicTemp[96];      // device publishes → cloud
char topicRelay[96];     // device subscribes ← cloud
char topicStatus[96];    // reserved LWT topic (online / offline)

WiFiClient    wifiClient;
PubSubClient  mqtt(wifiClient);

void onMessage(char* topic, byte* payload, unsigned int len) {
  // payload is NOT null-terminated — copy it first
  char msg[64];
  unsigned int n = (len < sizeof(msg) - 1) ? len : sizeof(msg) - 1;
  memcpy(msg, payload, n);
  msg[n] = '\0';

  Serial.printf("[%s] %s\n", topic, msg);

  // strcmp, not == : comparing char* with == compares addresses, not text
  if (strcmp(topic, topicRelay) == 0) {
    digitalWrite(D1, (strcmp(msg, "1") == 0) ? HIGH : LOW);
  }
}

void connectMQTT() {
  while (!mqtt.connected()) {
    Serial.print("Connecting to MQTT...");
    if (mqtt.connect(clientId, mqttUser, mqttPass,
                     topicStatus, 1, true, "offline")) {
      Serial.println(" connected!");
      mqtt.subscribe(topicRelay);
      mqtt.publish(topicStatus, "online", true);   // birth message
    } else {
      Serial.print(" failed, rc="); Serial.println(mqtt.state());
      delay(5000);
    }
  }
}

void setup() {
  Serial.begin(115200);
  pinMode(D1, OUTPUT);

  snprintf(clientId,    sizeof(clientId),    "device_%08x",             ESP.getChipId());  // unique per chip — no account key needed
  // Bare topics — no account key needed, the broker scopes them to your login automatically
  snprintf(topicTemp,   sizeof(topicTemp),   "%s/temperature", deviceName);
  snprintf(topicRelay,  sizeof(topicRelay),  "%s/relay1",     deviceName);
  snprintf(topicStatus, sizeof(topicStatus), "%s/LWT",         deviceName);

  WiFi.begin(ssid, wifiPass);
  while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); }
  Serial.print("\nWi-Fi connected: "); Serial.println(WiFi.localIP());

  mqtt.setServer(mqttHost, mqttPort);
  mqtt.setCallback(onMessage);
}

void loop() {
  if (!mqtt.connected()) connectMQTT();
  mqtt.loop();

  static unsigned long lastPub = 0;
  if (millis() - lastPub > 10000) {
    lastPub = millis();
    float temp = random(200, 300) / 10.0;
    char payload[16];
    snprintf(payload, sizeof(payload), "%.2f", temp);
    mqtt.publish(topicTemp, payload);
    Serial.printf("Published: %s\n", payload);
  }
}

ESP32

Plain — Port 1883
Secure TLS — Port 8883
// ESP32 — Plain MQTT connection (port 1883)

#include <WiFi.h>
#include <PubSubClient.h>

const char* ssid       = "YOUR_WIFI_SSID";
const char* wifiPass   = "YOUR_WIFI_PASSWORD";

const char* mqttHost   = "cloud.virtuino.com";
const int   mqttPort   = 1883;
const char* mqttUser   = "vr-abcd1234";
const char* mqttPass   = "YOUR_MQTT_PASSWORD";
String      clientId;                           // built in setup(): "device_" + chip ID

// Built from mqttUser, so the account key is written only once
String deviceName  = "esp32";
// Bare topics — no account key needed, the broker scopes them to your login automatically
String topicTemp   = deviceName + "/temperature";  // device publishes → cloud
String topicRelay  = deviceName + "/relay1";       // device subscribes ← cloud
String topicStatus = deviceName + "/LWT";          // reserved LWT topic (online / offline)

WiFiClient   wifiClient;
PubSubClient mqtt(wifiClient);

void onMessage(char* topic, byte* payload, unsigned int len) {
  String msg = "";
  for (int i = 0; i < len; i++) msg += (char)payload[i];
  Serial.println("[" + String(topic) + "] " + msg);

  if (String(topic) == topicRelay)
    digitalWrite(2, msg == "1" ? HIGH : LOW);   // GPIO 2 = built-in LED
}

void connectMQTT() {
  while (!mqtt.connected()) {
    Serial.print("Connecting...");
    if (mqtt.connect(clientId.c_str(), mqttUser, mqttPass,
                     topicStatus.c_str(), 1, true, "offline")) {
      Serial.println(" OK");
      mqtt.subscribe(topicRelay.c_str());
      mqtt.publish(topicStatus.c_str(), "online", true);   // birth message clears the retained "offline"
    } else {
      Serial.print(" rc="); Serial.println(mqtt.state());
      delay(5000);
    }
  }
}

void setup() {
  Serial.begin(115200);
  clientId = "device_" + String((uint32_t)ESP.getEfuseMac(), HEX);  // unique per chip — no account key needed
  pinMode(2, OUTPUT);

  WiFi.begin(ssid, wifiPass);
  while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); }
  Serial.println("\nIP: " + WiFi.localIP().toString());

  mqtt.setServer(mqttHost, mqttPort);
  mqtt.setCallback(onMessage);
}

void loop() {
  if (!mqtt.connected()) connectMQTT();
  mqtt.loop();

  static unsigned long last = 0;
  if (millis() - last > 10000) {
    last = millis();
    float temp = random(200, 300) / 10.0;         // replace with real sensor
    mqtt.publish(topicTemp.c_str(), String(temp, 1).c_str());
  }
}
// ESP32 — Secure MQTT connection (port 8883, TLS)
// WiFiClientSecure verifies the broker's Let's Encrypt certificate automatically.

#include <WiFi.h>
#include <WiFiClientSecure.h>
#include <PubSubClient.h>

const char* ssid       = "YOUR_WIFI_SSID";
const char* wifiPass   = "YOUR_WIFI_PASSWORD";

const char* mqttHost   = "cloud.virtuino.com";
const int   mqttPort   = 8883;
const char* mqttUser   = "vr-abcd1234";
const char* mqttPass   = "YOUR_MQTT_PASSWORD";
String      clientId;                           // built in setup(): "device_" + chip ID

// Built from mqttUser, so the account key is written only once
String deviceName  = "esp32";
// Bare topics — no account key needed, the broker scopes them to your login automatically
String topicTemp   = deviceName + "/temperature";  // device publishes → cloud
String topicRelay  = deviceName + "/relay1";       // device subscribes ← cloud
String topicStatus = deviceName + "/LWT";          // reserved LWT topic (online / offline)

// ── ISRG Root X1 — Let's Encrypt CA Certificate ───────────────────────────────
const char caCert[] = R"EOF(
-----BEGIN CERTIFICATE-----
MIIFazCCA1OgAwIBAgIRAIIQz7DSQONZRGPgu2OCiwAwDQYJKoZIhvcNAQELBQAw
TzELMAkGA1UEBhMCVVMxKTAnBgNVBAoTIEludGVybmV0IFNlY3VyaXR5IFJlc2Vh
cmNoIEdyb3VwMRUwEwYDVQQDEwxJU1JHIFJvb3QgWDEwHhcNMTUwNjA0MTEwNDM4
WhcNMzUwNjA0MTEwNDM4WjBPMQswCQYDVQQGEwJVUzEpMCcGA1UEChMgSW50ZXJu
ZXQgU2VjdXJpdHkgUmVzZWFyY2ggR3JvdXAxFTATBgNVBAMTDElTUkcgUm9vdCBY
MTCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBAK3oJHP0FDfzm54rVygc
h77ct984kIxuPOZXoHj3dcKi/vVqbvYATyjb3miGbESTtrFj/RQSa78f0uoxmyF+
0TM8ukj13Xnfs7j/EvEhmkvBioZxaUpmZmyPfjxwv60pIgbz5MDmgK7iS4+3mX6U
A5/TR5d8mUgjU+g4rk8Kb4Mu0UlXjIB0ttov0DiNewNwIRt18jA8+o+u3dpjq+sW
T8KOEUt+zwvo/7V3LvSye0rgTBIlDHCNAymg4VMk7BPZ7hm/ELNKjD+Jo2FR3qyH
B5T0Y3HsLuJvW5iB4YlcNHlsdu87kG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LN9d11TPA
mRGunUHBcnWEvgJBQl9nJEiU0Zsnvgc/ubhPgXRR4Xq37Z0j4r7g1SgEEzwxA57d
emyPxgcYxn/eR44/KJ4EBs+lVDR3veyJm+kXQ99b21/+jh5Xos1AnX5iItreGCc=
-----END CERTIFICATE-----
)EOF";

WiFiClientSecure wifiClient;
PubSubClient     mqtt(wifiClient);

void onMessage(char* topic, byte* payload, unsigned int len) {
  String msg = "";
  for (unsigned int i = 0; i < len; i++) msg += (char)payload[i];
  Serial.println("[" + String(topic) + "] " + msg);

  if (String(topic) == topicRelay)
    digitalWrite(2, msg == "1" ? HIGH : LOW);
}

void connectMQTT() {
  while (!mqtt.connected()) {
    Serial.print("Connecting (TLS)...");
    // connect() with Last Will arguments: (id, user, pass, willTopic, willQoS, willRetain, willMsg)
    if (mqtt.connect(clientId.c_str(), mqttUser, mqttPass,
                     topicStatus.c_str(), 1, true, "offline")) {
      Serial.println(" connected!");
      mqtt.publish(topicStatus.c_str(), "online", true);     // birth message clears the retained "offline"
      mqtt.subscribe(topicRelay.c_str());
    } else {
      Serial.print(" failed, rc="); Serial.println(mqtt.state());
      delay(5000);
    }
  }
}

void setup() {
  Serial.begin(115200);
  clientId = "device_" + String((uint32_t)ESP.getEfuseMac(), HEX);  // unique per chip — no account key needed
  pinMode(2, OUTPUT);

  WiFi.begin(ssid, wifiPass);
  while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); }
  Serial.println("\nIP: " + WiFi.localIP().toString());

  wifiClient.setCACert(caCert);        // verify broker against ISRG Root X1

  mqtt.setServer(mqttHost, mqttPort);
  mqtt.setCallback(onMessage);
  mqtt.setKeepAlive(60);
  mqtt.setBufferSize(512);
}

void loop() {
  if (!mqtt.connected()) connectMQTT();
  mqtt.loop();

  static unsigned long last = 0;
  if (millis() - last > 10000) {
    last = millis();
    float temp = random(200, 300) / 10.0;
    mqtt.publish(topicTemp.c_str(), String(temp, 1).c_str());
  }
}
CA Certificate note: The caCert in the examples above contains a truncated placeholder. Replace it with the complete ISRG Root X1 certificate from letsencrypt.org/certs/isrgrootx1.pem. Alternatively, call wifiClient.setInsecure() instead of setCACert() during development to skip certificate verification — but never in production.

7HTTP → MQTT Gateway & Device-to-Device

HTTP to MQTT Gateway

The Virtuino Cloud platform includes a built-in HTTP → MQTT gateway. Any source that can make an HTTP request can trigger an MQTT publish automatically — without running an MQTT client — simply by including "publish": true in the JSON body.

SourceHow to enableMQTT topic published
IoT Device (HTTP POST) Add "publish": true to the JSON body of the HTTP request sent to the platform API The corresponding bare field topic is published automatically — whatever your device is subscribed to
Dashboard Widget Enable the Publish toggle in the widget settings Published on every value change
Rule Enable the Publish option on the rule output Published whenever the rule fires
Schedule Enable the Publish option in the schedule action Published at each scheduled trigger
Script Enable the Publish option on the script output Published on every script execution that produces a value
Examples: Full HTTP POST request examples with "publish": true are available in the HTTP API documentation.
No MQTT client needed on the device. A plain HTTP POST with "publish": true is all it takes. The gateway handles the MQTT connection, credentials, and routing on the server side — ideal for devices with limited memory or libraries that only support HTTP.

Device-to-Device Communication

Because publish and subscribe share the same bare topic string (see Topic Structure), device-to-device messaging needs no special convention: whatever Device A publishes is automatically available to every other MQTT client subscribed to that same topic — other devices, Node-RED flows, or any external MQTT client authenticated on your account. (Dashboard widgets don't connect over MQTT themselves — the platform relays the value to them automatically, no topic to configure.)

Rule of thumb: One bare topic per value. Whoever publishes it is the sender; whoever subscribes to it is a receiver — the broker keeps everyone's publish and subscribe traffic on the correct real topic automatically, so the same name works for any number of receivers.
HTTP-to-MQTT Gateway diagram 📡 IoT Device ESP32, Arduino… HTTP POST HTTP POST "publish": true Virtuino Cloud HTTP → MQTT Gateway auto-publishes for you MQTT publish MQTT Broker cloud.virtuino.com SUBSCRIBERS USE THESE BARE TOPICS FORMAT 1 — SIMPLE field FORMAT 2 — DEVICE PATH device /field bare topic SUBSCRIBERS 📡 Other Devices 🔗 Node-RED 💻 Other MQTT apps