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

MQTT 连接失败: status can only transition to connecting from disconnected #670

Open
erroot opened this issue Mar 12, 2024 · 1 comment

Comments

@erroot
Copy link

erroot commented Mar 12, 2024

opts.SetConnectionLostHandler(func(client mqtt.Client, err error) {
	fmt.Println("连接丢失,尝试重新连接...:", err)
	s.isDisconnect = true
})
   //自动重连线程
   go func() {
	s.connect()
	time.Sleep(15 * time.Second)

	for {
		if !s.client.IsConnected() || !s.client.IsConnectionOpen() || s.isDisconnect {
			log.Printf("连接断开,尝试重新连接.IsConnected:%v,IsConnectionOpen:%v isDisconnect:%v\n",
				s.client.IsConnected(),
				s.client.IsConnectionOpen(),
				s.isDisconnect)

			s.client.Disconnect(100)
			time.Sleep(15000 * time.Millisecond)

			s.connect()
		}
		time.Sleep(15 * time.Second)
	}
}()
    
    func (s *MqttClientSverice) connect() {
        if token := s.client.Connect(); token.Wait() && token.Error() != nil {
	        log.Println("MQTT 连接失败:", token.Error())
	        return
        }
        s.isDisconnect = false
        log.Println("MQTT broker connected...")
        for _, topic := range s.config.Topics {
	        if token := s.client.Subscribe(topic, 0, s.onMessageReceived); token.Wait() && token.Error() != nil {
		        log.Println("Error subscribing to topic:", token.Error())
	        } else {
		        log.Println("MQTT broker Subscribed  topic:", topic)
	        }
        }
    }

这样写的重连机制有问题:MQTT 连接失败: status can only transition to connecting from disconnected 库内部认为状态不对,但是进程重启是可以重连的

@MattBrittan
Copy link
Contributor

Sorry - I only understand English.

Only moving from disconnected to connecting was a deliberate choice (if the status is not disconnected then something is still running so connecting is not a valid operation). However it's possible there is a bug/logic error somewhere, unfortunately I'll need more information (ideally an example that replicates the issue) in order to understand the issue you are facing. Note that with AutoReconnect operational (the default) there is no need for you to call Connect again.

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

2 participants