Fix: re-subscribe after mqtt connection lost
This commit is contained in:
		
							
								
								
									
										15
									
								
								sauna.go
									
									
									
									
									
								
							
							
						
						
									
										15
									
								
								sauna.go
									
									
									
									
									
								
							@@ -33,7 +33,7 @@ var messagePubHandler mqtt.MessageHandler = func(client mqtt.Client, msg mqtt.Me
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
var saunaHandler mqtt.MessageHandler = func(client mqtt.Client, msg mqtt.Message) {
 | 
			
		||||
	log.Printf("Received message: %s from topic: %s\n", msg.Payload(), msg.Topic())
 | 
			
		||||
	logger.Printf("Received message: %s from topic: %s\n", msg.Payload(), msg.Topic())
 | 
			
		||||
	sauna_mutex.Lock()
 | 
			
		||||
	err := json.Unmarshal(msg.Payload(), &sauna_temperature)
 | 
			
		||||
	sauna_temperature.Time = time.Now()
 | 
			
		||||
@@ -49,6 +49,7 @@ var saunaHandler mqtt.MessageHandler = func(client mqtt.Client, msg mqtt.Message
 | 
			
		||||
 | 
			
		||||
var connectHandler mqtt.OnConnectHandler = func(client mqtt.Client) {
 | 
			
		||||
	logger.Println("Connected")
 | 
			
		||||
	subscribe(client)
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
var connectLostHandler mqtt.ConnectionLostHandler = func(client mqtt.Client, err error) {
 | 
			
		||||
@@ -77,7 +78,7 @@ func http_endpoint_sauna(w http.ResponseWriter, r *http.Request) {
 | 
			
		||||
	}
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
func Start() {
 | 
			
		||||
func connect() mqtt.Client {
 | 
			
		||||
	// MQTT connection
 | 
			
		||||
	opts := mqtt.NewClientOptions()
 | 
			
		||||
	opts.AddBroker("tcp://nuc:1883")
 | 
			
		||||
@@ -87,14 +88,22 @@ func Start() {
 | 
			
		||||
	opts.OnConnectionLost = connectLostHandler
 | 
			
		||||
	client := mqtt.NewClient(opts)
 | 
			
		||||
	if token := client.Connect(); token.Wait() && token.Error() != nil {
 | 
			
		||||
		panic(token.Error())
 | 
			
		||||
		logger.Panic(token.Error())
 | 
			
		||||
	}
 | 
			
		||||
	return client
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
func subscribe(client mqtt.Client) {
 | 
			
		||||
	// MQTT subscribtion
 | 
			
		||||
	topic := "sauna/temperature"
 | 
			
		||||
	token := client.Subscribe(topic, 1, saunaHandler)
 | 
			
		||||
	token.Wait()
 | 
			
		||||
	logger.Printf("Subscribed to topic %s", topic)
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
func Start() {
 | 
			
		||||
	client := connect()
 | 
			
		||||
	subscribe(client)
 | 
			
		||||
 | 
			
		||||
	http.HandleFunc("/api/sauna", http_endpoint_sauna)
 | 
			
		||||
}
 | 
			
		||||
 
 | 
			
		||||
		Reference in New Issue
	
	Block a user