#include "WiFi.h"
#include "Adafruit_MQTT.h"
#include "Adafruit_MQTT_Client.h"

#define RED 17
#define GREEN 16
#define BLUE 4

#define MQTT_SERVER     "io.adafruit.com"
#define MQTT_PORT        1883
#define MQTT_USERNAME   "narahari4919n"
#define MQTT_KEY        "aio_beRb27jO3XE8fDy8ozxjk4UAXQut"
#define SUBSCRIBE_TOPIC "narahari4919n/f/RGB control"

void wifi_connect();
void mqtt_setup();
void RGB_callback(char* value, short unsigned int len);

WiFiClient client;

Adafruit_MQTT_Client mqtt(&client, MQTT_SERVER, MQTT_PORT, MQTT_USERNAME, MQTT_KEY);
Adafruit_MQTT_Subscribe RGB_control = Adafruit_MQTT_Subscribe(&mqtt, SUBSCRIBE_TOPIC, MQTT_QOS_1);


void setup() {
  pinMode(RED, OUTPUT);
  pinMode(GREEN,OUTPUT);
  pinMode(BLUE, OUTPUT);
  Serial.begin(9600);
  wifi_connect();

  RGB_control.setCallback(RGB_callback);
  mqtt.subscribe(&RGB_control); 
}
  

void loop() {
 mqtt_connect();
 mqtt.processPackets(5000);
}


void wifi_connect(){
  WiFi.mode(WIFI_STA);
  Serial.println("Scanning for networks......");
  char n = WiFi.scanNetworks();
  Serial.println("Scan done");

  if(n==0)
  Serial.println("No networks found");

  else{
    for(int i=0; i<n; i++){
    char buffer[30];
    sprintf(buffer, "%d: %S (%d)", i+1, WiFi.SSID(i), WiFi.RSSI(i));
    Serial.println(buffer);
    } 
  WiFi.begin(WiFi.SSID(0), "");
  Serial.println("Connecting");
  while(WiFi.status() != WL_CONNECTED){
    Serial.print(".");
    delay(6000);
    } 
  Serial.println("WiFi connected");
  Serial.println(WiFi.localIP());
  }
}

void mqtt_connect(){
  uint8_t ret;

  if(mqtt.connected())
  return;

  else {
    uint8_t tries = 3;
    Serial.println("Connecting to MQTT server........");
    while(tries!=0){
      if((ret=mqtt.connect())!=0){
        Serial.println(mqtt.connectErrorString(ret));
        Serial.println("Retrying to connect");
        tries--;
        delay(3000);
      }
      else{
        Serial.println("Connected to MQTT server");
        break;
      }    
    }
  }
}

void RGB_callback(char* command, short unsigned int len){
  digitalWrite(RED,0);
  digitalWrite(GREEN,0);
  digitalWrite(BLUE,0);

  char value = char(command[0]);  

  switch(value){
    case '1': digitalWrite(RED,1);
            break;
    case '2': digitalWrite(GREEN,1);
            break;
    case '3': digitalWrite(BLUE,1);
            break;
  }
}