2024年8月17日 星期六

MQTT Basic2 (WOKWI ESP32 + MQTT Box )

 MQTT Basic2  (WOKWI  ESP32 + MQTT Box )

使用 <ArduinoMqttClient.h> library


主題有修正如下
const char broker[] = "test.mosquitto.org";
int        port     = 1883;
const char Pubtopic1[]  = "alex9ufo/hello";
const char Subtopic2[]  = "alex9ufo/led";
message == "on" 亮 message == "off" 熄






WOKWI程式

#include <ArduinoMqttClient.h>
#include <WiFi.h>

///////please enter your sensitive data in the Secret tab/arduino_secrets.h
char ssid[] =  "Wokwi-GUEST"; // your network SSID (name)
char pass[] =  "" ;           // your network password (use for WPA, or use as key for WEP)

WiFiClient wifiClient;
MqttClient mqttClient(wifiClient);

const char broker[] = "test.mosquitto.org";
int        port     = 1883;
const char Pubtopic1[]  = "alex9ufo/hello";
const char Subtopic2[]  = "alex9ufo/led";
const char willTopic[] = "alex9ufo/Starting";

//set interval for sending messages (milliseconds)

const long interval = 8000;
unsigned long previousMillis = 0;

int count = 0;
const int LED = 2;
char msg[50];
int value = 0;

//=======================================================================
void onMqttMessage(int messageSize) {
  // we received a message, print out the topic and contents
  Serial.println("Received a message with topic '");
  Serial.print(mqttClient.messageTopic());
  Serial.print("', length ");
  Serial.print(messageSize);
  Serial.println(" bytes:");
  String Topic= mqttClient.messageTopic();

  String message="";
  // use the Stream interface to print the contents
  while (mqttClient.available()) {
    //Serial.print((char)mqttClient.read());
    message += (char)mqttClient.read();
  }
  Serial.println(message);
  message.trim();
  Topic.trim();

  if (Topic=="alex9ufo/led") {
    if (message == "on") {
      digitalWrite(LED, LOW);  // Turn on the LED
      Serial.print("LED = on ");
    }

    if (message == "off" ) {
      digitalWrite(LED, HIGH); // Turn off the LED
      Serial.print("LED = off ");
    }
  }
  Serial.println();
  Serial.println();
}

//=======================================================================
//副程式  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() {
  //Initialize serial and wait for port to open:
  Serial.begin(115200);
  pinMode(LED, OUTPUT);     // Initialize the BUILTIN_LED pin as an output

  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("You're connected to the network");
  Serial.println();
 
  String willPayload = "ESP32 Start working....!";
  bool willRetain = true;
  int willQos = 1;

  mqttClient.beginWill(willTopic, willPayload.length(), willRetain, willQos);
  mqttClient.print(willPayload);
  mqttClient.endWill();

  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();

  // set the message receive callback
  mqttClient.onMessage(onMqttMessage);
  Serial.print("Subscribing to topic: ");
  Serial.println(Subtopic2);
  // subscribe to a topic
  // the second parameter sets the QoS of the subscription,
  // the the library supports subscribing at QoS 0, 1, or 2
  int subscribeQos = 1;
  mqttClient.subscribe(Subtopic2, subscribeQos);

}

//=======================================================================
void loop() {
  // call poll() regularly to allow the library to send MQTT keep alive which
  // avoids being disconnected by the broker
  mqttClient.poll();

  unsigned long currentMillis = millis();

  if (currentMillis - previousMillis >= interval) {
    // save the last time a message was sent
    previousMillis = currentMillis;

    //record random value from A0, A1 and A2
    ++value;
    snprintf (msg, 75, "hello world #%ld", value);
    Serial.print("Publish message: ");
    Serial.println(msg);

    Serial.print("Sending message to topic: ");
    Serial.println(Pubtopic1);
    Serial.println(msg);

    // send message, the Print interface can be used to set the message contents
    mqttClient.beginMessage(Pubtopic1);
    mqttClient.print(msg);
    mqttClient.endMessage();

    Serial.println();
  }
}

沒有留言:

張貼留言

113 學年度第 1 學期 RFID應用課程 Arduino程式

113 學年度第 1 學期 RFID應用課程 Arduino程式 https://www.mediafire.com/file/zr0h0p3iosq12jw/MFRC522+(2).7z/file 內含修改過後的 MFRC522 程式庫 (原程式有錯誤) //定義MFRC522...