Hello everyone,
I am learning javascript and nodejs, im currently making an nodejs app to
manage my philips hue lamps.
And i am struggling with the asynchronous and callbacks.
First let me explain what i want to achieve.
I have a function that get the id of all my lights, named getLightsId :
function getLightsId(callback){
args ={
path:{"username":"username"}
};
client.registerMethod("getLightState",
"bridge_adress/api/${username}/lights/", "GET");
client.methods.getLightState(args, function(data,response){
var id = [];
for(key in data){
id.push(key);
}
callback(id);
});}
Then i have a function getLightState that get the state of a specific lamp
determined by its id
function getLightState(id, callback){
args ={
path:{"username":"username", "id":id}
};
client.registerMethod("getLightState",
"http://bridge_address/api/${username}/lights/${id}", "GET");
client.methods.getLightState(args, function(data,response){
callback(data);
});}
And finally i have a function initLightsState that send the state of all
the lights in an object to my client. be prepared to see ugly shit :p, its
pretty dirty, but hey, it works (kinda).
function initLightsState(callback){
getLightsId(function(idArray) {
var lightsState = new Object();
idArray.forEach(function(id) {
setInterval(function(){getLightState(id, function(state) {
lightsState[id] = state;
});},500);
});
callback(lightsState);
io.sockets.on('connection', function (socket) {
setInterval(function(){
socket.emit('updateLightsState', lightsState);
},500);
});
});}
I had to put a setInterval() to my getLightState function because otherwise
it was always sending me the same object with the same data, i know its
dirty but i couldnt find another way.
then i emit also with a setInterval() my object to my client.
The problem is that its obviously spamming my client with the state of my
lights.. it works, but its very far from being the cleanest way to do this.
What i want to do, is to compare server-side the previous state of my light
with the current one, and only if its different send it to the client.
But im stuck with the callback and everything and cant get it work.
Could someone please show me the simplest way to do this ?
Thanks a lot.
--
--
Job Board: http://jobs.nodejs.org/
Posting guidelines:
https://github.com/joyent/node/wiki/Mailing-List-Posting-Guidelines
You received this message because you are subscribed to the Google
Groups "nodejs" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to
[email protected]
For more options, visit this group at
http://groups.google.com/group/nodejs?hl=en?hl=en
---
You received this message because you are subscribed to the Google Groups
"nodejs" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
For more options, visit https://groups.google.com/d/optout.