2025年5月23日 星期五

WOKWI RFID(亂數模擬) + 4 Relay 控制 (1)

WOKWI RFID(亂數模擬) + 4 Relay 控制 (1)






int LED1 = 23;
int LED2 = 22;
int LED3 = 21;
int LED4 = 19;

int inPin = 12;  












#define BOTtoken "802139062815:AAE0KApbm5Ng00VCv2O57JWA_XKtbx6a4IXM"  

#define CHAT_ID "791652128469"

以上 需修改成自己的  BOTtoken   CHAT_ID


WOKWI程式

#include <WiFi.h>
#include <WiFiClientSecure.h>
#include <UniversalTelegramBot.h>   // Universal Telegram Bot Library
#include <ArduinoMqttClient.h>

//MFRC522 程式庫  模擬mfrc522 送出卡號 PB可以控制
int LED1 = 23;
int LED2 = 22;
int LED3 = 21;
int LED4 = 19;

char ssid[]="Wokwi-GUEST";
char pass[]="";

WiFiClient wifiClient;
MqttClient mqttClient(wifiClient);
// Initialize Telegram BOT
#define BOTtoken "802139062815:AAE0KApbm5Ng00VCv2O57JWA_XKtbx6a4IXM"  
// your Bot Token (Get from Botfather)
// Use @myidbot to find out the chat ID of an individual or a group
// Also note that you need to click "start" on a bot before it can
// message you
#define CHAT_ID "791652128469"

WiFiClientSecure client1;
UniversalTelegramBot bot(BOTtoken, client1);

// Checks for new messages every 1 second.
int botRequestDelay = 1000;
unsigned long lastTimeBotRan;

//const char broker[] = "test.mosquitto.org";
const char broker[] = "broker.mqttgo.io";
//const char broker[] = "broker.mqtt-dashboard.com";
int        port     = 1883;

const char *SubTopic1 = "alex9ufo/esp32/led";
const char *PubTopic2 = "alex9ufo/esp32/led_status";
const char *PubTopic3 = "alex9ufo/esp32/RFID";
const char willTopic[] = "alex9ufo/esp32/Starting";

int inPin = 12;    // pushbutton connected to digital pin
bool Send = false;  //true
bool RFID = false;  //true
bool ledState= false;
String LEDjson = "";
String RFIDjson = "";
//===========================================================
//判斷 旗號Flash , Timer 是否為真
void LED_Message() {
  //判斷 旗號 Flash / timer  是否為真 ? 閃爍 定時
 
  ////判斷 旗號 Send 是否為真 回傳MQTT訊息到MQTT Broker 
  if (Send) {
    // Convert JSON string to character array
    Serial.print("Publish message: ");
    Serial.println(LEDjson);
    LEDjson.trim();
    bool retained = false;
    int qos = 1;
    bool dup = false;
   
    // Publish JSON character array to MQTT topic
    mqttClient.beginMessage(PubTopic2,  LEDjson.length(), retained, qos, dup);  //LED Status
    mqttClient.print(LEDjson);
    mqttClient.endMessage();
    Send = false;    //處理過後 旗號 Send為假
  }

}
//===========================================================
// Handle what happens when you receive new messages
void handleNewMessages(int numNewMessages) {
  Serial.println("handleNewMessages");
  Serial.println(String(numNewMessages));

  for (int i=0; i<numNewMessages; i++) {
    // Chat id of the requester
    String chat_id = String(bot.messages[i].chat_id);
    if (chat_id != CHAT_ID){
      bot.sendMessage(chat_id, "Unauthorized user", "");
      continue;
    }
   
    // Print the received message
    String text = bot.messages[i].text;
    Serial.println(text);

    String from_name = bot.messages[i].from_name;

    if (text == "/start") {
      String welcome = "Welcome, " + from_name + ".\n";
      welcome += "Use the following commands to control your outputs.\n\n";
      welcome += "/led1on to turn ON LED1 \n";
      welcome += "/led1off to turn OFF LED1 \n";

      welcome += "/led2on to turn ON LED2 \n";
      welcome += "/led2off to turn OFF LED2 \n";

      welcome += "/led3on to turn ON LED3 \n";
      welcome += "/led3off to turn OFF LED3 \n";

      welcome += "/led4on to turn ON LED4 \n";
      welcome += "/led4off to turn OFF LED4 \n";

      welcome += "/ledalloff  to turn OFF all LED \n";
      welcome += "/ledallon to turn ON all LED \n";

      welcome += "/state to request current LED state \n";
      bot.sendMessage(chat_id, welcome, "");
    }

    if (text == "/led1on") {
      bot.sendMessage(chat_id, "LED1 state set to ON", "");
      ledState = HIGH;
      digitalWrite(LED1, ledState);
      Send = true ;
      LEDjson ="LED1ON";
    }
   
    if (text == "/led1off") {
      bot.sendMessage(chat_id, "LED1 state set to OFF", "");
      ledState = LOW;
      digitalWrite(LED1, ledState);
      Send = true ;
      LEDjson ="LED1OFF";    
    }

 

    if (text == "/led2on") {
      bot.sendMessage(chat_id, "LED2 state set to ON", "");
      ledState = HIGH;
      digitalWrite(LED2, ledState);
      Send = true ;
      LEDjson ="LED2ON";
    }
   
    if (text == "/led2off") {
      bot.sendMessage(chat_id, "LED2 state set to OFF", "");
      ledState = LOW;
      digitalWrite(LED2, ledState);
      Send = true ;
      LEDjson ="LED2OFF";    
    }

 

    if (text == "/led3on") {
      bot.sendMessage(chat_id, "LED3 state set to ON", "");
      ledState = HIGH;
      digitalWrite(LED3, ledState);
      Send = true ;
      LEDjson ="LED3ON";
    }
   
    if (text == "/led3off") {
      bot.sendMessage(chat_id, "LED3 state set to OFF", "");
      ledState = LOW;
      digitalWrite(LED3, ledState);
      Send = true ;
      LEDjson ="LED3OFF";    
    }

    if (text == "/led4on") {
      bot.sendMessage(chat_id, "LED4 state set to ON", "");
      ledState = HIGH;
      digitalWrite(LED4, ledState);
      Send = true ;
      LEDjson ="LED4ON";
    }
   
    if (text == "/led4off") {
      bot.sendMessage(chat_id, "LED4 state set to OFF", "");
      ledState = LOW;
      digitalWrite(LED4, ledState);
      Send = true ;
      LEDjson ="LED4OFF";    
    }
 

    if (text == "/ledallon") {
      bot.sendMessage(chat_id, "all LED state set to ON", "");
      ledState = HIGH;
      digitalWrite(LED1, ledState);
      digitalWrite(LED2, ledState);
      digitalWrite(LED3, ledState);
      digitalWrite(LED4, ledState);
     
      Send = true ;
      LEDjson ="LEDALLON";
    }
   
    if (text == "/ledalloff") {
      bot.sendMessage(chat_id, "all LED state set to OFF", "");
      ledState = LOW;
      digitalWrite(LED1, ledState);
      digitalWrite(LED2, ledState);
      digitalWrite(LED3, ledState);
      digitalWrite(LED4, ledState);
      Send = true ;
      LEDjson ="LEDALLOFF";    
    }

    if (text == "/state") {
      if (digitalRead(LED1))
        {
          bot.sendMessage(chat_id, "LED1 is ON", "");
        }
        else
        {
         bot.sendMessage(chat_id, "LED1 is OFF", "");
        }


      if (digitalRead(LED2))
        {
          bot.sendMessage(chat_id, "LED2 is ON", "");
        }
        else
        {
        bot.sendMessage(chat_id, "LED2 is OFF", "");
        }
     

      if (digitalRead(LED3))
        {
          bot.sendMessage(chat_id, "LED3 is ON", "");
        }
        else
        {
          bot.sendMessage(chat_id, "LED3 is OFF", "");
        }
     

      if (digitalRead(LED4))
        {
          bot.sendMessage(chat_id, "LED4 is ON", "");
        }
        else
        {
          bot.sendMessage(chat_id, "LED4 is OFF", "");
        }
     

    }

  }
}

//===========================================================
//副程式  setup wifi
void setup_wifi() {
  delay(10);
  // We start by connecting to a WiFi network
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);     //print ssid
  WiFi.begin(ssid, pass);  //初始化WiFi 函式庫並回傳目前的網路狀態
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }   //假設 wifi 未連接 show ………

  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
}
//==================================================================
void setup() {
  Serial.begin(115200); // 初始化序列埠
  pinMode(LED1, OUTPUT);
  digitalWrite(LED1, LOW);  // Turn off the LED initially
  pinMode(LED2, OUTPUT);
  digitalWrite(LED2, LOW);  // Turn off the LED initially
  pinMode(LED3, OUTPUT);
  digitalWrite(LED3, LOW);  // Turn off the LED initially
  pinMode(LED4, OUTPUT);
  digitalWrite(LED4, LOW);  // Turn off the LED initially

  pinMode(inPin, INPUT);    // sets the digital pin 12 as input
  randomSeed(analogRead(0)); // 設定亂數種子,增加亂數的隨機性  

  //Initialize serial and wait for port to open:
  Serial.begin(115200);   // Initialize serial communications with the PC
  while (!Serial);    // Do nothing if no serial port is opened (added for Arduinos based on ATMEGA32U4)
 
  setup_wifi();
  Serial.println("\nWiFi 已連線");

  // 啟用不安全連線(略過 SSL 憑證驗證)
  client1.setInsecure();

  // 初始訊息
  bot.sendMessage(CHAT_ID, "ESP32 啟動完成,", "");
  bot.sendMessage(CHAT_ID, "輸入 /start" , "");

  Serial.println("You're connected to the network");
  Serial.println();
 
  Serial.print("Attempting to connect to the MQTT broker: ");
  Serial.println(broker);

  if (!mqttClient.connect(broker, port)) {
    Serial.print("MQTT connection failed! Error code = ");
    Serial.println(mqttClient.connectError());

    while (1);
  }
  Serial.println("You're connected to the MQTT broker!");
  Serial.println();  
}
//==================================================================
void loop() {
  // call poll() regularly to allow the library to receive MQTT messages and
  // send MQTT keep alives which avoids being disconnected by the broker
  mqttClient.poll();
 
  LED_Message();

  //===============================================================
  if (millis() > lastTimeBotRan + botRequestDelay)  {
    int numNewMessages = bot.getUpdates(bot.last_message_received + 1);

    while(numNewMessages) {
      Serial.println("got response");
      handleNewMessages(numNewMessages);
      numNewMessages = bot.getUpdates(bot.last_message_received + 1);
    }
    lastTimeBotRan = millis();
  }
  //===============================================================
  if ( digitalRead(inPin)==HIGH) {
    // 模擬 RFID UID 結構
    struct RFID_UID {
      uint8_t uidByte[10]; // UID 位元組陣列,最大長度為 10
      uint8_t size;        // UID 長度
    };
    // 建立一個 RFID UID 物件
    RFID_UID uid;
    // 設定 UID 資料
    uid.size = 4;
   
    for (int i = 0; i < uid.size; i++) {
      uid.uidByte[i] = random(256); // 生成 0-255 的亂數
    }

    // 顯示 UID
    Serial.print("UID: ");
    for (int i = 0; i < uid.size; i++) {
      Serial.print(uid.uidByte[i] < 0x10 ? " 0" : " "); // 補零
      Serial.print(uid.uidByte[i], HEX);             // 以十六進位格式輸出
    }
    Serial.println();

    RFIDjson = "{ \"uid\": \"";
    for (int i = 0; i < uid.size; i++) {
        RFIDjson += String(uid.uidByte[i], HEX);
      }
    RFIDjson += "\" }";

    RFIDjson.trim();

    bool retained = false;
    int qos = 1;
    bool dup = false;
    mqttClient.beginMessage(PubTopic3,  RFIDjson.length(), retained, qos, dup);
    mqttClient.print(RFIDjson);
    mqttClient.endMessage();
    Serial.println(RFIDjson);
    Serial.println();
    bot.sendMessage(CHAT_ID, RFIDjson, "");  
    delay(500);
  }
 
}

沒有留言:

張貼留言

ESP32 (ESP-IDF in VS Code) MFRC522 + MQTT + PYTHON TKinter +SQLite

 ESP32 (ESP-IDF in VS Code) MFRC522 + MQTT + PYTHON TKinter +SQLite  ESP32 VS Code 程式 ; PlatformIO Project Configuration File ; ;   Build op...