Spivey
Published © MIT

Control an ESP8266 via Wia's MQTT API

Go through setting up an ESP8266 board, and subscribing to a Wia Command via MQTT. This will allow you to control your Device with Wia!

BeginnerFull instructions provided1 hour3,088
Control an ESP8266 via Wia's MQTT API

Things used in this project

Hardware components

ESP8266 ESP-01
Espressif ESP8266 ESP-01
×1

Software apps and online services

Wia
Wia

Story

Read more

Code

Wia Command

Arduino
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
#include <string.h>
#include <ArduinoJson.h>

const char* ssid = "Your Wifi ssid";   // Your Wifi ssid
const char* password =  "password";   // Your Wifi password

const char* mqttServer = "api.wia.io" // mqtt://api.wia.io
const int mqttPort = 1883;  // Default MQTT port

const String deviceId = "Device Id";   // starts with dev_, found in Wia Dashboard
const String deviceSecretKey = "Device Secret Key";  // Starts with d_sk_, found in Wia Dashboard

const String commandName = "check-temperature";  // Configured in Wia Dashboard

String topic = "devices/" + deviceId + "/commands/" + commandName + "/run";

// Instantiating a WiFiClient and  
passing it into the PubSubClient
WiFiClient espClient;
PubSubClient client(espClient);


// The function that handles the response from the Command
void callback(char* topic, byte* payload, unsigned int length) {

  Serial.print("Command initiated: ");
  Serial.println(topic);
   
  // Add functionality for command here i.e (Check the temperature)

}

void reconnect() {
  while (!client.connected()) {
    Serial.println("Connecting to MQTT...");

    if (client.connect("ESP8266Client", deviceSecretKey, " ")) {

      Serial.println("connected");

    } else {
      Serial.print("failed with state ");
      Serial.print(client.state());
      delay(2000);
    }
  }

  // Converts to String to char array to pass to PubSubClient
  char topicChar[100];
  topic.toCharArray(topicChar, topic.length() + 1);
  Serial.print("Subscribed to: ");
  Serial.println(topic);

  // Subscribe to the command topic
  client.subscribe(topicChar);
}

void setup() {
  Serial.begin(115200);

  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.println("Connecting to WiFi..");
  }
  Serial.println("Connected to the WiFi network");

  client.setServer(mqttServer, mqttPort);
  client.setCallback(callback);
}


void loop() {
  if (!client.connected()) {
    reconnect();
  }
  // Continiously loop to check if a command has been initiated
  client.loop();
}

Credits

Spivey

Spivey

82 projects • 59 followers
Tourist in a Tutu || US Born || Melbourne/Mexico/California Raised || New Yorker at ❤️ || SF to Dublin to be COO of Wia the best IoT startup
Thanks to Alan Donoghue.

Comments