2024年12月13日 星期五

My HiveMQ Cloud Wokwi LED Control

 My HiveMQ Cloud  Wokwi  LED Control





#include <Arduino.h>

#include <WiFi.h>
#include <WiFiClientSecure.h>
#include <PubSubClient.h>
#define BUILTIN_LED 13

//const char *ssid =  "yourSSID";     // change according to your Network - cannot be longer than 32 characters!
//const char *pass =  "yourPASSWORD"; // change according to your Network
const char* ssid =    "Wokwi-GUEST";    // your network SSID (name)
const char* pass =    "";             // your network password (use for WPA, or use as key for WEP)


const char* mqtt_broker =   "62f166feaf034496b2fc16b53e7da20c.s1.eu.hivemq.cloud";  //ip address or hostname of the mqtt broker
const int   mqtt_port =     8883 ;                        //port of the mqtt broker
const char* mqtt_username = "xxxxxxxx";                   //username of this mqtt client
const char* mqtt_password = "xxxxxxxxxxxxxx";            //password of this mqtt client

// MQTT topic for IR sensor
const char* topic_publish1 = "alex9ufo/led/led_status";
const char* topic_subscribe1 = "alex9ufo/led/led_event";

//Variables
long lastMsg = 0;
char jsonChar[50];

//String json = "";
bool Flash = false;  //true
bool Timer = false;  //true
//bool Send = false;  //true
bool Send = true;  //true
String json = "Test";
int Count= 0;

//=============================================================================
// Create instances
WiFiClientSecure wifiClient;
PubSubClient mqttClient(wifiClient);

//=============================================================================
// Variables for timing
long previous_time = 0;

void setupMQTT() {
  mqttClient.setServer(mqtt_broker, mqtt_port);
}
//============================================================
void callback(char* topic, byte* message, unsigned int length) {
  // Printing Received Message
  Serial.print("Message received on topic: ");
  Serial.println(topic);

  String messageTemp;
  for(int i=0; i<length; i+=1) {
    messageTemp += (char)message[i];
  }

  Serial.print(messageTemp);
  if(String(topic) == "alex9ufo/led/led_event"){
      if(messageTemp=="ON"){
        digitalWrite(BUILTIN_LED, LOW);   // Turn the LED off (Note that HIGH is the voltage level
        // but actually the LED is on; this is because
        Serial.println("Received ON , Send HIGH TO BuildIn_LED");
        Flash = false;
        Timer = false;
        json ="ON";
        Send = true ;
      }

      if(messageTemp=="OFF"){
        digitalWrite(BUILTIN_LED, HIGH);   // Turn the LED on (Note that LOW is the voltage level
        // but actually the LED is on; this is because
        Serial.println("Received OFF , Send LOW TO BuildIn_LED");
        Flash = false;
        Timer = false;
        json ="OFF";
        Send = true ;
      }
     
      if(messageTemp=="TOGGLE"){
        digitalWrite(BUILTIN_LED, !digitalRead(BUILTIN_LED));   // Turn the LED toggle
        // but actually the LED is on; this is because
        Serial.println("Received TOGGLE , Send Toggle(H->L , L->H) TO BuildIn_LED");
        Flash = false;
        Timer = false;
        json ="TOGGLE";
        Send = true ;  
      }
     
      if(messageTemp=="FLASH"){      
        digitalWrite(BUILTIN_LED, HIGH);   // Turn the LED off (Note that HIGH is the voltage level
        // but actually the LED is on; this is because
        Serial.println("Received FLASH , Flashing BuildIn_LED ");
        Flash = true;
        Timer = false;
        json ="FLASH";
        Send = true ;  
      }
     
      if(messageTemp=="TIMER"){    
        digitalWrite(BUILTIN_LED, LOW);   // Turn the LED off (Note that HIGH is the voltage level
        // but actually the LED is on; this is because
        Serial.println("Received TIMER ,  BuildIn_LED ON 5 SEC");
        Flash = false;
        Timer = true;
        Count= 10;
        json ="TIMER";
        Send = true ;
      }
  }
  Serial.println(messageTemp);
}
//=============================================================================
void reconnect() {
  Serial.println("Connecting to MQTT Broker...");
  while (!mqttClient.connected()) {
    Serial.println("Reconnecting to MQTT Broker...");
    String clientId = "ESP32Client-";
    clientId += String(random(0xffff), HEX);
   
    if (mqttClient.connect(clientId.c_str(), mqtt_username, mqtt_password)) {
      Serial.println("Connected to MQTT Broker.");
      mqttClient.subscribe(topic_subscribe1);
    } else {
      Serial.print("Failed, rc=");
      Serial.print(mqttClient.state());
      Serial.println(" try again in 5 seconds");
      delay(5000);
    }
  }
}
//======================================================
void setup_wifi() {
  delay(10);
  // We start by connecting to a WiFi network
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);
  WiFi.begin(ssid, pass);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
}

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

  pinMode(BUILTIN_LED, OUTPUT);
  digitalWrite(BUILTIN_LED, HIGH);
  setup_wifi();
  Serial.println(F("Booting...."));
  Serial.println(F("Control Build LED ON,OFF,FLASH,TOGGLE,TIMER...."));
 
  // Initialize secure WiFiClient
  wifiClient.setInsecure(); // Use this only for testing, it allows connecting without a root certificate
 
  setupMQTT();
  mqttClient.setCallback(callback);

  mqttClient.subscribe(topic_subscribe1);
}

//======================================================
void loop() {
  if (!mqttClient.connected()) {
    reconnect();
  }
  mqttClient.loop();

  if (Flash)
  {
    digitalWrite(BUILTIN_LED, !digitalRead(BUILTIN_LED));
    delay(500);
  }

  if (Timer)
  {

    digitalWrite(BUILTIN_LED, LOW);
    delay(500);
    Count=Count-1;
    if (Count == 0 ){
       Timer=false;
       digitalWrite(BUILTIN_LED, HIGH);
    }
  }

  if (Send) {
    // Convert JSON string to character array
    json.toCharArray(jsonChar, json.length()+1);

    if  (mqttClient.connected()) {
        Serial.print("Publish message: ");
        Serial.println(json);
        // Publish JSON character array to MQTT topic
        mqttClient.publish(topic_publish1,jsonChar);
    }
     Send = false;    
  }

}   //Loop
//======================================================

沒有留言:

張貼留言

Node-Red LINE Notify + LINE Developers

 Node-Red  <<LINE Notify + LINE Developers [{"id":"e3c78b4eb9b36766","type":"function","z...