Apollon77 / hap-controller-node

Node.js library to implement a HAP (HomeKit) controller
Mozilla Public License 2.0
54 stars 16 forks source link

When to unsubscribe from characteristics ? #85

Closed NebzHB closed 2 years ago

NebzHB commented 2 years ago

Hi,

I have a question, when do i need to unsubscribeCharacteristics ?

cause for Aqara M1S by example, one of my user receive serviceDown event during the night without any change to the mdns... and followed by 2 serviceUp events, on serviceUp event, i reconnect to the accessory and subscribeCharacteristics based on props ev in getAccessory. but i get double subscriptions and thus 2 events for the same characteristic :( i've tried to check if subscribedCharacteristics is not empty before to re-subscribe but it's empty :( so i cannot unsubscribe ...

image

should i unsubscribeCharacteristics when receiving serviceDown ?

thank for your help :)

Apollon77 commented 2 years ago

Hey,

next please post log and not screenshots :-)) Reading this is pain

Honestly I have no real idea when an HTTP device is considered "down" by the resolver, so I personally do not really use "down" beside logging.

Just use "serviceUp" and in case of connection issues/timeouts use "retry timeouts" :-)

But for the concrete question: In fact when using subscriptions you should listen to the "event-disconnect" event (see also example) because this is emitted when the persistent subscription connection dies - and you get the list of "before subscribed characteristics" as parameter so you can directly try to resubscribe.

So it seems that the service resolver (that one works on UDP/MDNS package stuff) just thought that the device is "offline", but in my world this means nothing if the connection is still established

NebzHB commented 2 years ago

ok, sorry for the logs.

that Aqara M1S is quite a pain in the ...

when you add a device to the hub, you receive a serviceDown and then a serviceUp with a new port... that port change make it mandatory to reconnect :(

thank you for your explanations

Apollon77 commented 2 years ago

Ahh very interesting ... puuhh .... then you can call "client.close()" to make sure to kill all connections correctly and then reestablish ... with "close()" you also kill the subscription connection

Apollon77 commented 2 years ago

PS: I checked. I my iobroker adapter I reconnect on "Up" in any case too ... and yes I issue an unsubscribe there ... but you can also use close()

NebzHB commented 2 years ago

i have ensured i don't have 2 event listener that way :

if(conf.pairings[p].client.listeners('event').length == 0) {
conf.pairings[p].client.on('event', eventReceived);
}
NebzHB commented 2 years ago

because even if i was unsubscribed, i was still receiving the events

Apollon77 commented 2 years ago

Yes, right if you reuse the client object. I deceided to remive the event listeners on unsubscribe because it's getting intransparent