[Issue #8] - adding MQTT reconnect if the connection drops
ci/woodpecker/push/woodpecker Pipeline was successful
ci/woodpecker/tag/woodpecker Pipeline was successful

This commit is contained in:
2026-09-12 02:58:57 -04:00
parent 4e022d4e76
commit e5d78e8423
+31 -13
View File
@@ -36,8 +36,8 @@ func (m *SimpleMQTT) Connect(clientID, username, password string) error {
flags |= 0x40
}
// Variable header: MQTT (proto name), Level 4 (MQTT 3.1.1), flags, KeepAlive 60s
varHeader := []byte{0x00, 0x04, 'M', 'Q', 'T', 'T', 0x04, flags, 0x00, 0x3C}
// Variable header: MQTT (proto name), Level 4 (MQTT 3.1.1), flags, KeepAlive 0s (disabled)
varHeader := []byte{0x00, 0x04, 'M', 'Q', 'T', 'T', 0x04, flags, 0x00, 0x00}
payload := encodeString(clientID)
if username != "" {
@@ -145,7 +145,7 @@ func registerHADiscovery(mqtt *SimpleMQTT, sensor ClimateSensor) error {
}
// -------------------------------------------------------------
// Panic Handler & Entry Point
// Panic Handler & Helper Functions
// -------------------------------------------------------------
func panicErr(msg string, err error) {
if err != nil {
@@ -156,6 +156,22 @@ func panicErr(msg string, err error) {
}
}
func connectMQTT(netStack *NetworkStack, port uint16) (*SimpleMQTT, error) {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
conn, err := netStack.DialTCP(ctx, MQTTHost, port)
if err != nil {
return nil, err
}
mqtt := NewSimpleMQTT(conn)
if err := mqtt.Connect(ClientID, MQTTUser, MQTTPass); err != nil {
return nil, err
}
return mqtt, nil
}
func main() {
time.Sleep(2 * time.Second)
@@ -205,17 +221,10 @@ func main() {
}
portNum, _ := strconv.Atoi(MQTTPort)
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
conn, err := netStack.DialTCP(ctx, MQTTHost, uint16(portNum))
if err != nil {
panicErr("TCP dial", err)
}
mqtt := NewSimpleMQTT(conn)
println("Connecting MQTT session...")
if err := mqtt.Connect(ClientID, MQTTUser, MQTTPass); err != nil {
mqtt, err := connectMQTT(netStack, uint16(portNum))
if err != nil {
panicErr("MQTT connect", err)
}
println("MQTT connected.")
@@ -237,7 +246,16 @@ func main() {
}
if err := mqtt.Publish(StateTopic, []byte(stateJSON), false); err != nil {
println("MQTT publish error:", err.Error())
println("MQTT publish error:", err.Error(), "- attempting reconnect...")
newMqtt, recErr := connectMQTT(netStack, uint16(portNum))
if recErr != nil {
println("MQTT reconnect failed:", recErr.Error())
} else {
println("MQTT reconnected successfully.")
mqtt = newMqtt
_ = registerHADiscovery(mqtt, sensor)
_ = mqtt.Publish(StateTopic, []byte(stateJSON), false)
}
} else {
println(fmt.Sprintf("[%s] Published: %s", NodeName, stateJSON))
}