swissmanu / harmonyhubjs-client

A Node.JS library which allows you to interact with your Logitech Harmony Hub.
https://github.com/swissmanu/harmonyhubjs-client
MIT License
155 stars 42 forks source link

listen for activities #6

Closed Pmant closed 8 years ago

Pmant commented 8 years ago

Is it possible to listen for activity changes and do something when an activity starts / ends? I know I just could repeatedly check the current activity but maybe there is a better way.

swissmanu commented 8 years ago

the hub publishes state digest messages as soon as an activity is started, in progress or stopped. harmonyhubjs has already a mechanism to listen for these digest messages (see harmonyclient.js#L55). you can register to harmonyhubjs' stateDigest event with:

client.on('stateDigest', function(digest) { /* ... */ });

please refer to the protocol documents for further information about the state digest message: State Digest.

if you're interested into a higher abstraction of harmonhubjs-client/harmonyhubjs-discover, have a look at orchestra-jsapi. it encapsulates both libraries and uses the event subscription mechanism above in the exact same way. (see index.js#L40)

Pmant commented 8 years ago

Thank you, this helped me a lot! With the code below I'm able to log activity starts/ends, but after about 60 seconds the script exits, the client seems to time out.

var harmony = require('harmonyhubjs-client');

harmony('192.168.0.58').then(function(harmonyClient) {
    console.log('hub client started');
    harmonyClient.on('stateDigest', function(digest) {
        console.log('stateDigest: ' + JSON.stringify(digest));
    });
}).catch(function(e){
    console.log('error');
});
Pmant commented 8 years ago
harmonyClient._xmppClient.connection.reconnect = true;

this helps but still disconnects every minute as I can see with

harmonyClient._xmppClient.connection.socket.on('close', function(e) {
    console.log('socket closed');
});
harmonyClient._xmppClient.on('online', function(jid) {
    console.log('xmpp online');
});

I also tried

harmonyClient._xmppClient.connection.socket.setTimeout(0);
harmonyClient._xmppClient.connection.socket.setKeepAlive(true,10000);
swissmanu commented 8 years ago

I came across the same problem when implementing orchestra once. Though, I was not able to find the actual cause of it. I worked around by implementing a reconnect mechanism on myself (see https://github.com/swissmanu/orchestra-jsapi/blob/master/index.js#L34)

Don't know if this disconnect happens upon Logitechs intention :-/

Pmant commented 8 years ago

I was able to prevent the disconnect by periodically sending a command to the server:

! function keepAlive(){
    harmonyClient.request('getCurrentActivity').timeout(5000).then(function(response) {
        setTimeout(keepAlive, 10000);
    }).catch(function(e){
        //disconnected from hub
    });
}();