Consider an example that will allow you to control the microcontroller LED through the «Switches» widget and plot the Wi-Fi signal level.
Required materials:
Device adding and setting:
Firmware ESP8266:
#include <ESP8266WiFi.h> #include <Ticker.h> #include <VizIoTMqttClient.h> //Pin address with LED #define LED_ESP 2 //ssid and access password for connection to WI-FI const char* ssid = "........."; const char* password = "..........."; //VizIoT access key and password Devices (can be found in device settings) String VizIoT_Device_key = ".............."; String VizIoT_Device_pass = ".................."; WiFiClient espClient; PubSubClient clientMQTT(espClient); VizIoTMqttClient clientVizIoT(clientMQTT); long lastMsg = 0; char msg[100]; byte statusLed = 0; /*----------Sending data Ticker----------------*/ Ticker sender; bool isSendDataToServer; void SendDataToServer() {isSendDataToServer = true;} #define INTERVAL_SEND_DATA 60 void setup() { //allow to control the LED pinMode(LED_ESP, OUTPUT); digitalWrite(LED_ESP, HIGH); //Turn on the output of information in the Serial Monitor Serial.begin(9600); //We connect to WI-FI setup_wifi(); //Set the address of the MQTT broker clientVizIoT.config(VizIoT_Device_key, VizIoT_Device_pass); //set callbeck function clientVizIoT.listenCommand(callback); sender.attach(INTERVAL_SEND_DATA, SendDataToServer); // Create an event for sending data every INTERVAL_SEND_DATA sec } //Handling the Data Received Event void callback(String parameter, byte value) { Serial.print("Posting a message: parameter"); Serial.print(parameter); Serial.print("value "); Serial.println(value); if (parameter.compareTo("led") == 0) { if (value == 1) { statusLed = 1; digitalWrite(LED_ESP, LOW); } else { statusLed = 0; digitalWrite(LED_ESP, HIGH); } snprintf(msg, sizeof(msg), "{\"led\":\"%c\"}", (statusLed) ? '1' : '0'); Serial.print("Posting a message: "); Serial.println(msg); clientVizIoT.sendJsonString(String(msg)); } } //Wi-Fi connection function void setup_wifi() { WiFi.begin(ssid, password); while (WiFi.status() != WL_CONNECTED) { //To be connected to WI-FI delay(500); Serial.print("."); } Serial.println(""); Serial.println("WiFi connected"); } void loop() { //required to process incoming messages and maintain connection to the Broker clientVizIoT.loop(); //Sending the WI-FI signal level and LED status to the server every minute if (isSendDataToServer) { isSendDataToServer = false; snprintf (msg, sizeof(msg), "{\"rssi\":\"%i\",\"led\":\"%c\"}", WiFi.RSSI(), (statusLed) ? '1' : '0'); Serial.print("Posting a message: "); Serial.println(msg); clientVizIoT.sendJsonString(String(msg)); } }
#define MQTT_MAX_PACKET_SIZE 1024in the «PubSubClient» library, which is usually located in «C:\Users\{Username}\Documents\arduino\libraries\PubSubClient\src\PubSubClient.h»
Adding widgets:
Now you have everything configured and it remains to wait for your device to connect to the server and you can control the LED by clicking on the switch in the Dashboard.