Skip to content

Instantly share code, notes, and snippets.

@ubi-gists
Created March 15, 2017 22:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ubi-gists/1f5518770650b37fdb41ee24ed6ab49a to your computer and use it in GitHub Desktop.
Save ubi-gists/1f5518770650b37fdb41ee24ed6ab49a to your computer and use it in GitHub Desktop.
/****************************************
* Include Libraries
****************************************/
#include "UbidotsESPMQTT.h"
/****************************************
* Define Constants
****************************************/
#define TOKEN "...." // Your Ubidots TOKEN
#define WIFINAME "...." //Your SSID
#define WIFIPASS "...." // Your Wifi Pass
#define MQTTCLIENTNAME "sonoff15345" // Your MQTT Client Name, it must be unique so we recommend to choose a random ASCCI name
Ubidots client(TOKEN, MQTTCLIENTNAME);
/****************************************
* Auxiliar Functions
****************************************/
void relays_on() {
Serial.write(0xA0);
Serial.write(0x04);
Serial.write(0x03);
Serial.write(0xA1);
Serial.flush();
}
void relays_off(){
Serial.write(0xA0);
Serial.write(0x04);
Serial.write(0x00);
Serial.write(0xA1);
Serial.flush();
}
void callback(char* topic, byte* payload, unsigned int length) {
Serial.print("Message arrived [");
Serial.print(topic);
Serial.print("] ");
for (int i=0;i<length;i++) {
Serial.print((char)payload[i]);
}
if ((char)payload[0]=='1'){
relays_on();
}
else{
relays_off();
}
Serial.println();
}
/****************************************
* Main Functions
****************************************/
void setup() {
// put your setup code here, to run once:
Serial.begin(19200);
Serial.println("Connecting to WiFi...");
client.wifiConnection(WIFINAME, WIFIPASS);
client.begin(callback);
Serial.println("Connected!");
pinMode(16, OUTPUT);
client.ubidotsSubscribe("sonoff-dual","relays"); // Ubidots device and Variable's API Labels
Serial.println("Subscribed!");
}
void loop() {
// put your main code here, to run repeatedly:
if(!client.connected()){
client.reconnect();
client.ubidotsSubscribe("sonoff-dual","relays"); //Insert the dataSource and Variable's Labels
}
client.loop();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment