Created
October 27, 2012 17:44
-
-
Save jchris/3965476 to your computer and use it in GitHub Desktop.
sync with coap
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var setup, outbox = [], relay = [], syncServers = [], | |
relayCap = 4, copyFactor = 1, defaultLeisure = 5000/*ms*/, | |
outboxInterval, relaysInterval, initInterval; | |
exports.log = function (json) { | |
if (!setup) {doInit();} | |
outbox.push([0, json]); | |
}; | |
function setupTimers() { | |
outboxInterval = outboxInterval || | |
setInterval(sendOutbox, defaultLeisure*(1+Math.random())); | |
relaysInterval = relaysInterval || | |
setInterval(sendRelays, defaultLeisure*10*(1+Math.random())) | |
initInterval = initInterval || | |
setInterval(doInit, defaultLeisure*defaultLeisure*(1+Math.random())); | |
}; | |
function doInit() { | |
setup = true; | |
coap.on("PUT", function(id, json) { | |
relay.push([0, json]); | |
}) | |
// additionally one could use telehash discovery | |
coap.multicastConfirmable('GET', '/.well-known/core', function(err, message) { | |
if (err) throw(err); | |
setupTimers(); | |
// todo implement this API | |
message.on("ack", function(endpoint, _reply) { | |
syncServers.push(endpoint) | |
}) | |
}); | |
}; | |
function incrementItem(queue, id) { | |
for (var i = queue.length - 1; i >= 0; i--) { | |
if (queue[i][2] == id) { | |
queue[i][0]++; | |
if (queue[i][0] >= copyFactor) { | |
// trim from the outbox when reaches copyFactor | |
queue = queue.splice(i, 1); | |
} | |
} | |
}; | |
}; | |
function sendMessage(queue) { | |
return function (entry) { | |
var json = entry[1], id = coap.newId(); | |
entry[2] = id; | |
// todo implement this API | |
coap.confirmable('PUT', syncServers, id, json, function(err, message) { | |
message.on("ack", function(endpoint) { | |
incrementItem(queue, id); | |
}) | |
}); | |
}; | |
} | |
function sendRelays() { | |
if (relay.length > relayCap) { | |
sendMessage(relay)(relay[0]); | |
} | |
}; | |
function sendOutbox() { | |
outbox.forEach(sendMessage(outbox)); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment