-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmqtt_bridge.ino
More file actions
110 lines (88 loc) · 2.56 KB
/
Copy pathmqtt_bridge.ino
File metadata and controls
110 lines (88 loc) · 2.56 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
// --- Wi-Fi credentials ---
const char* ssid = "<SSID>";
const char* password = "<Password>";
// --- HiveMQ Cloud MQTT broker details ---
const char* mqtt_server = "<MQTT Server IP>"; // Replace with your Windows PC IP (from ipconfig)
const int mqtt_port = "<MQTT Port>"; // Use 1883 for unencrypted
const char* mqtt_user = "<MQTT Username>"; // REPLACE with YOUR HiveMQ username
const char* mqtt_password = "<MQTT Password>"; // REPLACE with YOUR HiveMQ password
const char* mqtt_topic = "<MQTT Topic>";
// --- MQTT setup with TLS ---
WiFiClientSecure espClient;
PubSubClient client(espClient);
unsigned long lastReconnectAttempt = 0;
void setup_wifi() {
delay(10);
Serial.println();
Serial.print("Connecting to WiFi: ");
Serial.println(ssid);
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("✓ WiFi connected!");
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
}
boolean reconnect() {
Serial.print("Attempting MQTT connection (TLS)...");
String clientId = "NodeMCU-";
clientId += String(ESP.getChipId(), HEX);
if (client.connect(clientId.c_str(), mqtt_user, mqtt_password)) {
Serial.println(" ✓ CONNECTED!");
return true;
} else {
Serial.print(" ✗ FAILED, rc=");
Serial.println(client.state());
return false;
}
}
void setup() {
Serial.begin(9600);
delay(1000);
Serial.println("NodeMCU Bridge with HiveMQ Cloud (TLS)");
setup_wifi();
// Use insecure mode (doesn't verify certificate)
// This is simpler but less secure
espClient.setInsecure();
client.setServer(mqtt_server, mqtt_port);
client.setKeepAlive(60);
delay(1000);
}
void loop() {
if (WiFi.status() != WL_CONNECTED) {
Serial.println("WiFi lost! Reconnecting...");
setup_wifi();
delay(5000);
return;
}
if (!client.connected()) {
unsigned long now = millis();
if (now - lastReconnectAttempt > 5000) {
lastReconnectAttempt = now;
if (reconnect()) {
lastReconnectAttempt = 0;
}
}
} else {
client.loop();
}
if (Serial.available()) {
String data = Serial.readStringUntil('\n');
data.trim();
if (data.length() > 0 && client.connected()) {
Serial.print("Publishing: ");
Serial.println(data);
if (client.publish(mqtt_topic, data.c_str())) {
Serial.println("✓ Published!");
} else {
Serial.println("✗ Publish failed!");
}
}
}
}