/*
  MQTT 遠端控制RGB LED
*/
#include <WiFi.h>
#include <PubSubClient.h> //PubSubClient程式庫MQTT必用
//-------------------------
const byte r = 22;     //紅色接腳  
const byte g = 18;     //綠色
const byte b = 2;      //藍色
//-----------------------------------------------------------------------------
char* ssid = "Wokwi-GUEST"; //請修改為您連線的網路名稱
char* password = ""; //請修改為您連線的網路密碼
// ------ 以下修改成你MQTT設定 ------
char* MQTTServer = "mqttgo.io";//免註冊MQTT伺服器
int MQTTPort = 1883;          //MQTT Port 除非加密,否則不用更改port
char* MQTTUser = "";          //不須帳密
char* MQTTPassword = "";      //不須帳密

//訂閱主題1:改變LED燈號(記得改Topic)
char* MQTTSubTopic1 = "lankuo/led/power";
char* MQTTSubTopic2 = "lankuo/led/color";
//建立MQTT與聯網物件
WiFiClient WifiClient;
PubSubClient MQTTClient(WifiClient);

int valr=255,valg=50,valb=10;

void setup() {
  pinMode(r, OUTPUT);       // 設定為輸出模式
  pinMode(b, OUTPUT);       // 設定為輸出模式
  pinMode(g, OUTPUT);       // 設定為輸出模式
  //--------------------
  Serial.begin(9600);
  Serial.print("Connecting to WiFi");
  WiFi.begin(ssid, password,6);
  while (WiFi.status() != WL_CONNECTED) {
    delay(100);
    Serial.print(".");
  }
  Serial.println("WiFi連線成功");
  Serial.print("IP Address:");
  Serial.println(WiFi.localIP());
  //開始MQTT連線
  MQTTConnecte();
}
//-----------------------------------------------------------------------------
void loop() { 
  //如果WiFi連線中斷,則重啟WiFi連線
  if (WiFi.status() != WL_CONNECTED) { WifiConnecte(); }

  //如果MQTT連線中斷,則重啟MQTT連線
  if (!MQTTClient.connected()) {  MQTTConnecte(); }

  MQTTClient.loop();//更新訂閱狀態
  
  //setColor(valr,valg,valb);   //初始狀態255.50.10
  delay(50);
  
}

void setColor(int ValueR, int ValueG, int ValueB){
  analogWrite(r, ValueR);
  analogWrite(g, ValueG);
  analogWrite(b, ValueB);
}
//開始WiFi連線---------------------------------------
void WifiConnecte() {
 Serial.print("Connecting to WiFi");
  //WiFi.begin("Wokwi-GUEST", "", 6);
   WiFi.begin(ssid, password,6);
  while (WiFi.status() != WL_CONNECTED) {
    delay(100);
    Serial.print(".");
  }
  Serial.println("WiFi連線成功");
  Serial.print("IP Address:");
  Serial.println(WiFi.localIP());
}

//開始MQTT連線----------------------------------------
void MQTTConnecte() {
  MQTTClient.setServer(MQTTServer, MQTTPort);

  //以下開始處理訂閱主題
  MQTTClient.setCallback(MQTTCallback); //收到訂閱資料時,要處理MQTTCALLBACK
  while (!MQTTClient.connected()) {
    //以亂數為ClietID
    String  MQTTClientid = "esp32-" + String(random(1000000, 9999999));//建立一個郵差,為了要不一樣,所以使用亂數
    if (MQTTClient.connect(MQTTClientid.c_str(), MQTTUser, MQTTPassword)) {
      Serial.println("MQTT已連線");
      
      MQTTClient.subscribe(MQTTSubTopic1); //訂閱SubTopic1主題
      MQTTClient.subscribe(MQTTSubTopic2); //訂閱SubTopic2主題
    } else {
      Serial.print("MQTT連線失敗,狀態碼=");
      Serial.println(MQTTClient.state());
      Serial.println("五秒後重新連線");
      delay(5000);
    }
  }
}

//接收到訂閱時---------------------------------------------------------------
void MQTTCallback(char* topic, byte* payload, unsigned int length) {
  Serial.print(topic); Serial.print("訂閱通知:");
  String payloadString;//將接收的payload轉成字串
  
  for (int i = 0; i < length; i++) {
    payloadString = payloadString + (char)payload[i];
  }
  Serial.println(payloadString);//顯示訂閱內容
  if (strcmp(topic, MQTTSubTopic1) == 0) {   //比對主題是否為訂閱主題1,
    Serial.println("改變燈號:" + payloadString);
    valr=payloadString.substring(0,3).toInt();
    valg=payloadString.substring(3,6).toInt();
    valb=payloadString.substring(6,9).toInt();
      Serial.println("開啟燈號:");
      Serial.print("valr=");Serial.println(valr);
      Serial.print("valg=");Serial.println(valg);
      Serial.print("valb=");Serial.println(valb);
    setColor(valr,valg,valb);
    if (payloadString == "off") {
      Serial.print("關閉燈號");
      setColor(0,0,0);
    }
  }
  if (strcmp(topic, MQTTSubTopic2) == 0) {
   
    valr=payloadString.substring(0,3).toInt();
    valg=payloadString.substring(3,6).toInt();
    valb=payloadString.substring(6,9).toInt();
    Serial.println("開啟燈號:");
      Serial.print("valr=");Serial.println(255-valr);
      Serial.print("valg=");Serial.println(255-valg);
      Serial.print("valb=");Serial.println(255-valb);
    setColor(255-valr,255-valg,255-valb);
    if (payloadString == "off") {
      Serial.print("關閉燈號");
      setColor(0,0,0);
    }
  }
}