In this example, we will create a device based on an ESP8266 that will allow you to:
This is one of the simplest examples of using the VizIoT MQTT Client — an ideal starting point for smart home projects.
This data will be needed in the firmware.
#include <ESP8266WiFi.h>
#include <VizIoTMqttClient.h>
#include <ArduinoJson.h>
#include <Ticker.h>
// Wi-Fi settings
const char* WIFI_SSID = "your_wifi_ssid";
const char* WIFI_PASSWORD = "your_wifi_password";
// VizIoT device credentials
const char* VIZIOT_DEVICE_KEY = "your_16_char_device_key";
const char* VIZIOT_DEVICE_PASS = "your_20_char_device_pass";
// MQTT client
VizIoTMqttClient mqttClient(VIZIOT_DEVICE_KEY, VIZIOT_DEVICE_PASS);
// LED on D4 (built-in LED)
#define LED_ESP D4
bool ledState = false;
// Timer for periodic data sending
Ticker sender;
bool isSendDataToServer = false;
void SendDataToServer() {
isSendDataToServer = true;
}
#define INTERVAL_SEND_DATA 300 // every 5 minutes
// Form and send JSON packet to the server
void sendPacketToVizIoT() {
DynamicJsonDocument doc(256);
JsonObject obj = doc.to<JsonObject>();
obj["led"] = ledState ? 1 : 0;
obj["rssi"] = WiFi.RSSI();
String jsonStr;
serializeJson(doc, jsonStr);
if (mqttClient.publishJson(jsonStr.c_str())) {
Serial.println("Published JSON: " + jsonStr);
} else {
Serial.println("Failed to publish JSON");
}
}
// Handle incoming parameters
void onParameterReceived(const char* paramName, const char* value) {
Serial.print("Received: ");
Serial.print(paramName);
Serial.print(" = ");
Serial.println(value);
if (strcmp(paramName, "led") == 0) {
bool newState = (strcmp(value, "1") == 0);
ledState = newState;
digitalWrite(LED_ESP, ledState ? LOW : HIGH); // ON = LOW
Serial.print("LED state: ");
Serial.println(ledState ? "ON" : "OFF");
sendPacketToVizIoT();
}
}
// Connect to Wi-Fi
void setup_wifi() {
WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
Serial.print("Connecting to Wi-Fi");
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.print(".");
}
Serial.println("\nConnected to Wi-Fi");
}
// Main initialization
void setup() {
Serial.begin(115200);
pinMode(LED_ESP, OUTPUT);
digitalWrite(LED_ESP, HIGH); // Turn off LED initially
setup_wifi();
mqttClient.begin();
mqttClient.setParameterCallback(onParameterReceived);
sender.attach(INTERVAL_SEND_DATA, SendDataToServer);
SendDataToServer();
}
// Main loop
void loop() {
if (WiFi.status() != WL_CONNECTED) {
WiFi.reconnect();
delay(1000);
return;
}
mqttClient.poll();
if (!mqttClient.isConnected()) {
mqttClient.reconnect();
}
if (isSendDataToServer) {
isSendDataToServer = false;
sendPacketToVizIoT();
}
delay(100);
}
In Arduino IDE:
In the code, replace the values for:
WIFI_SSID — your Wi-Fi network nameWIFI_PASSWORD — passwordVIZIOT_DEVICE_KEY — device keyVIZIOT_DEVICE_PASS — device passwordAfter that, connect the ESP8266 to your PC and upload the sketch.
Create a dashboard: "Test Control Panel"
Add two widgets:
As soon as the device connects to the server, you will be able to: