Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

IS it possible to connect mqtt broker in node-red with esp8266? #216

Open
coldbook01 opened this issue Apr 16, 2024 · 0 comments
Open

IS it possible to connect mqtt broker in node-red with esp8266? #216

coldbook01 opened this issue Apr 16, 2024 · 0 comments

Comments

@coldbook01
Copy link

I want to use different from mqtt's network to accomplish different domains access mqtt broker on node-red, but it need enter localhost as password.
The test is now unsuccessful, I want to know the feasibility of this function.
`#include <ESP8266WiFi.h>
#include <PubSubClient.h>

// WiFi 設定
const char* ssid = "";
const char* password = "";

// MQTT 伺服器資訊
const char* mqttServer = "https://easy-wasps-spend.loca.lt"; // 您的 LocalTunnel 公佈的 URL
const int mqttPort = ;

// MQTT 用戶名和密碼
const char* mqttUser = "";
const char* mqttPassword = "";

WiFiClient espClient;
PubSubClient client(espClient);

void setup() {
Serial.begin(115200);
setup_wifi();
client.setServer(mqttServer, mqttPort);
client.setCallback(callback);
}

void setup_wifi() {
delay(10);
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, password); // 包含路由器登錄密碼
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
}

void callback(char* topic, byte* payload, unsigned int length) {
Serial.print("Message arrived [");
Serial.print(topic);
Serial.print("] ");
for (int i = 0; i < length; i++) {
Serial.print((char)payload[i]);
}
Serial.println();
}

void reconnect() {
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
if (client.connect("ESP8266Client", mqttUser, mqttPassword)) {
Serial.println("connected");
client.subscribe(""); // 訂閱 room/light 節點
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
delay(5000);
}
}
}

void loop() {
if (!client.connected()) {
reconnect();
}
client.loop();
// 在這裡可以添加您的代碼,發送或處理 MQTT 消息
}
`
this is the code i trying with.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant