DecentIoT Logo
DecentIoT Docs
Mqtt library

MQTT Library

Complete guide to DecentIoT MQTT Library for secure IoT device communication.

DecentIoT MQTT Library

The DecentIoT MQTT Library is a secure, easy-to-use Arduino library that enables your ESP8266/ESP32 devices to communicate with MQTT brokers using SSL/TLS encryption. It's designed specifically for the DecentIoT platform's virtual pin architecture.

Key Features

  • 🎯 Virtual Pin Architecture - P0, P1, P2, P3... represent virtual pins that map to your web dashboard widgets
  • 🔒 Your Own Cloud - Connect to your own MQTT broker (HiveMQ, AWS IoT, etc.)
  • 🌐 Professional Dashboard - Create beautiful, interactive dashboards with your own backend
  • Easy to Use - Simple macros and intuitive API design
  • 🔄 Real-time Communication - Bidirectional data flow between device and cloud
  • 🛠️ Production Ready - Robust, reliable, and well-tested
  • 💰 Cost Effective - No subscription fees, use your own MQTT infrastructure
  • 🔒 Secure by Default - Uses SSL/TLS for encrypted communication

Installation

  1. Open Arduino IDE
  2. Go to ToolsManage Libraries
  3. Search for "DecentIoT"
  4. Click Install

The library will automatically install required dependencies:

  • PubSubClient by Nick O'Leary (MIT License)
  • ArduinoJson by Benoit Blanchon (MIT License)

Manual Installation

  1. Download the library ZIP file from GitHub
  2. Go to SketchInclude LibraryAdd .ZIP Library
  3. Select the downloaded ZIP file
  4. Install dependencies manually:
    • PubSubClient library
    • ArduinoJson library

Quick Start

1. Basic Setup

#include <DecentIoT.h>

// WiFi credentials
#define WIFI_SSID "your-wifi-ssid"
#define WIFI_PASS "your-wifi-password"

// MQTT broker credentials
#define MQTT_BROKER "your-broker.hivemq.cloud"
#define MQTT_PORT 8883
#define MQTT_USERNAME "your-username"
#define MQTT_PASSWORD "your-password"

// DecentIoT credentials
#define PROJECT_ID "your-project-id"
#define USER_ID "your-user-id"
#define DEVICE_ID "your-device-id"

void setup() {
  Serial.begin(115200);
  
  // Connect to WiFi
  WiFi.begin(WIFI_SSID, WIFI_PASS);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("WiFi connected!");
  
  // Initialize DecentIoT
  DecentIoT.begin(MQTT_BROKER, MQTT_PORT, MQTT_USERNAME, MQTT_PASSWORD, PROJECT_ID, USER_ID, DEVICE_ID);
}

void loop() {
  DecentIoT.run();
  delay(10);
}

2. Virtual Pin System

Virtual pins (P0, P1, P2, etc.) are the core of DecentIoT's architecture. They represent flexible data channels that map to your web dashboard widgets.

// Send data to virtual pin P1 (maps to dashboard widget)
DecentIoT.write(P1, 25.5);  // Temperature reading

// Send data to virtual pin P2 (maps to dashboard widget)
DecentIoT.write(P2, true);  // LED status

3. Receiving Commands

// Handle incoming commands on virtual pin P0
DECENTIOT_RECEIVE(P0) {
  digitalWrite(LED_PIN, value);
  Serial.printf("LED: %s\n", value ? "ON" : "OFF");
}

Core Concepts

Virtual Pin Architecture

Virtual pins are completely flexible! You design them based on your project needs:

Example Project 1 - Smart Home:
P0  → Living Room Light (bool) - Maps to Switch widget
P1  → Bedroom Temperature (float) - Maps to Gauge widget
P2  → Kitchen Humidity (float) - Maps to Chart widget
P3  → Garage Door (bool) - Maps to Button widget
P4  → Security Status (string) - Maps to Label widget

Example Project 2 - Weather Station:
P0  → Temperature (float) - Maps to Gauge widget
P1  → Humidity (float) - Maps to Gauge widget
P2  → Pressure (float) - Maps to Value Display widget
P3  → Wind Speed (int) - Maps to Graph widget
P4  → Weather Status (string) - Maps to Label widget

Data Types Supported

  • Boolean (bool) - For switches, buttons, status indicators
  • Integer (int) - For counters, discrete values
  • Float (float) - For sensors, measurements
  • String (String) - For text, status messages

Advanced Features

Scheduling System

The library includes a powerful scheduling system for automated tasks:

// Schedule recurring task (every 10 seconds)
DECENTIOT_SEND(P1, 10000) {
  float temp = readTemperature();
  DecentIoT.write(P1, temp);
  Serial.printf("Temperature: %.1f°C\n", temp);
}

// Schedule one-time task (after 5 seconds)
DecentIoT.scheduleOnce("sensor_reading", 5000, []() {
  float humidity = readHumidity();
  DecentIoT.write(P2, humidity);
});

// Cancel scheduled task
DecentIoT.cancel("sensor_reading");
DecentIoT.cancelSend("P1");

Error Handling

// Check connection status
if (DecentIoT.connected()) {
  Serial.println("Connected to MQTT broker");
} else {
  Serial.println("Connection failed");
  Serial.println(DecentIoT.getLastError());
}

API Reference

Core Methods

MethodDescriptionParameters
begin()Initialize connectionbroker, port, username, password, projectId, userId, deviceId
run()Process messagesNone
write()Send data to virtual pinpin, value
connected()Check connection statusNone
disconnect()Disconnect from brokerNone

Scheduling Methods

MethodDescriptionParameters
schedule()Schedule recurring tasktaskId, interval, callback
scheduleOnce()Schedule one-time tasktaskId, delay, callback
cancel()Cancel scheduled tasktaskId
cancelSend()Cancel send task for pinpin

Macros

MacroDescriptionUsage
DECENTIOT_SENDSchedule recurring send taskDECENTIOT_SEND(P1, 10000) { ... }
DECENTIOT_RECEIVEHandle incoming commandsDECENTIOT_RECEIVE(P0) { ... }

Troubleshooting

Common Issues

Connection Failed

  • Check WiFi credentials
  • Verify MQTT broker settings
  • Ensure SSL/TLS port (8883) is used

Messages Not Received

  • Check virtual pin names (P0, P1, P2, etc.)
  • Verify dashboard widget mapping
  • Check MQTT topic structure

Memory Issues

  • Reduce JSON payload size
  • Use shorter virtual pin names
  • Optimize scheduling intervals

Debug Mode

Enable debug output by adding to your setup:

void setup() {
  Serial.begin(115200);
  // ... other setup code
  Serial.setDebugOutput(true);  // Enable debug output
}

Next Steps

Support


Built with ❤️ by MD Jannatul Nayem