2024年8月16日 星期五

MQTT Basic (WOKWI ESP32 + MQTT Box )

 MQTT Basic (WOKWI  ESP32 + MQTT Box )












WOKWI程式


/*
 Basic ESP32 MQTT example
*/

#include <WiFi.h>
#include <PubSubClient.h>

// Update these with values suitable for your network.

const char* ssid = "Wokwi-GUEST";
const char* password = "";
//const char* mqtt_server = "broker.mqtt-dashboard.com";
const char* mqtt_server = "test.mosquitto.org";

WiFiClient espClient;
PubSubClient client(espClient);

#define LED 2

long lastMsg = 0;
char msg[50];
int value = 0;


//================================
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, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }

  randomSeed(micros());

  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
}
//============================================================
void callback(char* topic, byte* message, unsigned int length) {
  printPayload(topic, message, length);  
}

void printPayload(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];
  }
  if(String(topic) == "alex9ufo/esp32/led"){
      if(messageTemp=="ON"){
        Serial.println("Led ON");
        digitalWrite(LED,LOW);
      }  
      if(messageTemp=="OFF"){
        Serial.println("Led OFF");
        digitalWrite(LED,HIGH);
      }
  }
  Serial.println(messageTemp);
}
//============================================================
void reconnect() {
  // Loop until we're reconnected
  while (!client.connected()) {
    Serial.print("Attempting MQTT connection...");
    // Create a random client ID
    String clientId = "ESP32Client-";
    clientId += String(random(0xffff), HEX);
    // Attempt to connect
    if (client.connect(clientId.c_str())) {
      Serial.println("connected");
      // Once connected, publish an announcement...
      client.publish("alex9ufo/esp32/hello", "hello world");
      // ... and resubscribe
      client.subscribe("alex9ufo/esp32/led");
    } else {
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println(" try again in 5 seconds");
      // Wait 5 seconds before retrying
      delay(5000);
    }
  }
}
//============================================================
void setup() {
  pinMode(LED, OUTPUT);     // Initialize the BUILTIN_LED pin as an output
  digitalWrite(LED,HIGH);

  Serial.begin(115200);
  setup_wifi();
  client.setServer(mqtt_server, 1883);
  client.setCallback(callback);
}
//============================================================
void loop() {

  if (!client.connected()) {
    reconnect();
  }
  client.loop();

  long now = millis();
  if (now - lastMsg > 8000) {
    lastMsg = now;
    ++value;
    snprintf (msg, 75, "hello world #%ld", value);
    Serial.print("Publish message: ");
    Serial.println(msg);
    client.publish("alex9ufo/esp32/hello", msg);
  }
}
//============================================================

沒有留言:

張貼留言

Arduino 物聯網應用 - 上課教材

Arduino 物聯網應用 - 上課教材 https://dic.vbird.tw/arduino/list.php Arduino 物聯網應用 - 課程列表 我們會從 Arduino 的認識、IDE 環境的熟悉、與操作電腦的序列埠連動的功能、Arduino 開發語言的熟悉、 簡...