astrorafael / twisted-mqtt

MQTT Client protocol for Twisted.
MIT License
30 stars 11 forks source link

Demo Code ceases working on MQTT server restart #3

Closed vk2tds closed 8 years ago

vk2tds commented 8 years ago

The demo code (publisher, pubsubs) stops working when the MQTT server is restarted, due to 'Unexpected publish() operation' for IdleState'. Restarting the code fixes the issue until the next time the connection is dropped.

One of the examples should probably show how to deal with the connection to the server going down. I would update this, but I am only starting to get my head around MQTT and this library

yombo commented 8 years ago

My take on this is that this isn't a server (service), but a client. My fork gets around this issue with just a couple of tweaks.

Fork: https://github.com/yombo/twisted-mqtt

Implementation using protocol and factory instead of as a service. This also handles pub/sub with a queue and doesn't make the client micromanage the connection; Eg: your code doesn't have to wait for the connack to finish, it can just start publishing and subscribing right away.

https://github.com/yombo/yombo-gateway/blob/6e612747e8a8a76a7d7a3f09b85b06ad0c50a150/yombo/lib/mqtt.py#L255

On another note, I will be updating this soon to re-subscribe on reconnect. This will handle connection interruptions / server restarts, etc.

vk2tds commented 8 years ago

My take on this is that it is a client issue too. Thanks... I will check this out

astrorafael commented 8 years ago

For Twisted, a Service is simply something that can be started and stopped and this certainly does include client side connections. However, up to Twisted 16.3.0, there was no good support to persistent services - those that can be reconnected automatically. See chapter 2.1.20 Getting Connected with Endpoints for a good explanation on this.

Anyway, I'll try to improve the demo code to support automatic reconnections.

I have yet to have an in depth look to changes and bug fixes proposed by yombo. I designed this library to be used by services, but if someone finds it better to subclass it, this should be possible too.

Please, have into account that this library is in alpha state yet. This means, it works in my use case :-) but sure there will be bugs for other uses that I have not thought about.