在ESP32中查找PC本地IP以使用MQTT Node.js服务器,可以通过以下步骤进行:
#include <WiFi.h>
const char* ssid = "YourWiFiSSID";
const char* password = "YourWiFiPassword";
void setup() {
Serial.begin(115200);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.println("Connecting to WiFi...");
}
Serial.println("Connected to WiFi");
}
void loop() {
// Your code here
}
#include <WiFi.h>
#include <ESPmDNS.h>
const char* hostname = "esp32-device";
void setup() {
Serial.begin(115200);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.println("Connecting to WiFi...");
}
if (!MDNS.begin(hostname)) {
Serial.println("Error setting up MDNS responder");
while (1) {
delay(1000);
}
}
Serial.println("mDNS responder started");
}
void loop() {
// Your code here
}
const mqtt = require('mqtt');
const server = mqtt.createServer();
server.on('clientConnected', (client) => {
console.log('Client connected:', client.id);
});
server.on('published', (packet, client) => {
console.log('Message received:', packet.payload.toString());
});
server.listen(1883, () => {
console.log('MQTT server started');
});
const express = require('express');
const app = express();
app.get('/getLocalIP', (req, res) => {
const localIP = req.connection.remoteAddress;
res.send(localIP);
});
app.listen(3000, () => {
console.log('HTTP server started');
});
#include <WiFi.h>
#include <WiFiClient.h>
const char* serverIP = "192.168.1.100"; // PC的IP地址
const int serverPort = 3000; // PC的HTTP接口端口
void setup() {
Serial.begin(115200);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.println("Connecting to WiFi...");
}
Serial.println("Connected to WiFi");
WiFiClient client;
if (client.connect(serverIP, serverPort)) {
client.println("GET /getLocalIP HTTP/1.1");
client.println("Host: " + String(serverIP));
client.println("Connection: close");
client.println();
while (client.connected()) {
if (client.available()) {
String response = client.readStringUntil('\r');
Serial.println("Local IP: " + response);
break;
}
}
client.stop();
}
}
void loop() {
// Your code here
}
通过以上步骤,ESP32将能够连接到本地网络并获取PC的本地IP地址,以便与MQTT Node.js服务器进行通信。请注意,这只是一个简单的示例,实际应用中可能需要进行错误处理和安全性考虑。
领取专属 10元无门槛券
手把手带您无忧上云