2024年10月17日 星期四

WOKWI MQTT&Node-Red (Hello & LED)2

 WOKWI MQTT&Node-Red (Hello & LED)2

使用broker.mqtt-dashboard.com:1883 Broker





Node-red程式

[{"id":"65c9291b678a7fe2","type":"ui_button","z":"b7407e6e7f998627","name":"","group":"5144f4dd267bd26c","order":2,"width":0,"height":0,"passthru":false,"label":"ON","tooltip":"","color":"","bgcolor":"","className":"","icon":"","payload":"on","payloadType":"str","topic":"topic","topicType":"msg","x":270,"y":140,"wires":[["942c6d647680c36c","a8005058e1f66d3a"]]},{"id":"a9165405803b4d06","type":"ui_button","z":"b7407e6e7f998627","name":"","group":"5144f4dd267bd26c","order":4,"width":0,"height":0,"passthru":false,"label":"OFF","tooltip":"","color":"","bgcolor":"","className":"","icon":"","payload":"off","payloadType":"str","topic":"topic","topicType":"msg","x":270,"y":200,"wires":[["942c6d647680c36c","a8005058e1f66d3a"]]},{"id":"942c6d647680c36c","type":"mqtt out","z":"b7407e6e7f998627","name":"LED_control","topic":"alex9ufo/led","qos":"1","retain":"true","respTopic":"","contentType":"","userProps":"","correl":"","expiry":"","broker":"81c048e3.19d648","x":470,"y":180,"wires":[]},{"id":"b93a4b5ca566c65b","type":"mqtt in","z":"b7407e6e7f998627","name":"Hello","topic":"alex9ufo/hello","qos":"0","datatype":"auto-detect","broker":"81c048e3.19d648","nl":false,"rap":true,"rh":0,"inputs":0,"x":270,"y":280,"wires":[["e855db5b2a1f5de2","6ca497bb7dc10aaa"]]},{"id":"e855db5b2a1f5de2","type":"ui_text","z":"b7407e6e7f998627","group":"8ee67a2c0d1061e6","order":1,"width":0,"height":0,"name":"訂閱的訊息","label":"訂閱的訊息","format":"{{msg.payload}}","layout":"row-spread","className":"","x":490,"y":280,"wires":[]},{"id":"a8005058e1f66d3a","type":"debug","z":"b7407e6e7f998627","name":"debug 303","active":true,"tosidebar":true,"console":false,"tostatus":false,"complete":"false","statusVal":"","statusType":"auto","x":470,"y":120,"wires":[]},{"id":"6ca497bb7dc10aaa","type":"debug","z":"b7407e6e7f998627","name":"debug 304","active":true,"tosidebar":true,"console":false,"tostatus":false,"complete":"false","statusVal":"","statusType":"auto","x":490,"y":320,"wires":[]},{"id":"5144f4dd267bd26c","type":"ui_group","name":"LED Control2","tab":"f304c5db6c1258cc","order":5,"disp":true,"width":"6","collapse":false,"className":""},{"id":"81c048e3.19d648","type":"mqtt-broker","broker":"broker.mqtt-dashboard.com","port":"1883","clientid":"","autoConnect":true,"usetls":false,"protocolVersion":4,"keepalive":15,"cleansession":true,"birthQos":"0","willQos":"0","credentials":{}},{"id":"8ee67a2c0d1061e6","type":"ui_group","name":"TEXT","tab":"f304c5db6c1258cc","order":4,"disp":true,"width":"6","collapse":false,"className":""},{"id":"f304c5db6c1258cc","type":"ui_tab","name":"WOKWI_DHT22","icon":"dashboard","order":127,"disabled":false,"hidden":false}]


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";
const char broker[] = "broker.mqtt-dashboard.com";
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 = 4000;
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();
  }
}

沒有留言:

張貼留言

2024_09 作業3 以Node-Red 為主

 2024_09 作業3  (以Node-Red 為主  Arduino 可能需要配合修改 ) Arduino 可能需要修改的部分 1)mqtt broker  2) 主題Topic (發行 接收) 3) WIFI ssid , password const char br...