#include <ESP8266WiFi.h>
#include <MicroGear.h>
const char* ssid= "wifi_name";
const char* password = "wifi_password";
#define APPID "Application_ID"
#define KEY "Application_ KEY"
#define SECRET "Application_SECRET"
#define ALIAS "Board_name"
#define TARGET "Target_name"
#define LED D1
WiFiClient client;
int timer = 0;
MicroGear microgear(client);
void onMsghandler(char* topic, uint8_t* msg, unsigned int msglen){
Serial.print("Incoming message --> ");
Serial.print(topic);
Serial.print(" : ");
char strState[msglen];
for(int i= 0; i< msglen; i++){
strState[i]=(char)msg[i];
Serial.print((char)msg[i]);
}
Serial.println();
String stateStr = String(strState).substring(0, msglen);
if(stateStr == "CH1ON")
{
digitalWrite(LED,HIGH);
Serial.println("ON LED");
}
else if(stateStr == "CH1OFF")
{
digitalWrite(LED,LOW);
Serial.println("OFF LED");
}
}
void onFoundgear(char* attribute, uint8_t* msg, unsigned int msglen){
Serial.print("Found new member --> ");
for(int i=0; i<msglen; i++)
Serial.print((char)msg[i]);
Serial.println();
}
void onLostgear(char* attribute, uint8_t* msg, unsigned int msglen){
Serial.print("Lost member --> ");
for(int i=0; i<msglen; i++)
Serial.print((char)msg[i]);
Serial.println();
}
/*When a microgear is connected, dothis*/
void onConnected(char* attribute, uint8_t* msg, unsigned int msglen){
Serial.println("Connected to NETPIE...");
/* Set the alias of this microgearALIAS */
microgear.setAlias(ALIAS);
}
void setup()
{
microgear.on(MESSAGE,onMsghandler);
microgear.on(PRESENT,onFoundgear);
microgear.on(ABSENT,onLostgear);
microgear.on(CONNECTED,onConnected);
Serial.begin(115200);
Serial.println("Starting...");
pinMode(LED,OUTPUT);
digitalWrite(LED,LOW);
if(WiFi.begin(ssid, password))
{
while(WiFi.status() != WL_CONNECTED)
{
delay(500);
Serial.print(".");
}
}
Serial.println("WiFiconnected");
microgear.init(KEY,SECRET,ALIAS);
microgear.connect(APPID);
}
void loop()
{
if(microgear.connected()){
microgear.loop();
bool led = digitalRead(LED);
String status_LED;
if(led == HIGH){
status_LED="CH1ON,";
}
else{
status_LED="CH1OFF,";
}
String data2freeboard = status_LED ;
microgear.chat(TARGET,data2freeboard);
Serial.print("Send message to NetPie: ");
Serial.println(data2freeboard);
}
else{
Serial.println("connection lost, reconnect...");
if(timer >= 5000){
microgear.connect(APPID);
timer=0;
}
else timer += 100;
}
delay(1000);
}