Skip to content

Instantly share code, notes, and snippets.

@cat-haines
Last active December 20, 2015 23:58
Show Gist options
  • Select an option

  • Save cat-haines/6216204 to your computer and use it in GitHub Desktop.

Select an option

Save cat-haines/6216204 to your computer and use it in GitHub Desktop.
Here's some code I wrote in my mail editor to demonstrate how you can use ping-pong messages to only respond to an HTTP request after receiving confirmation that your imp got the message. It also uses a watched function to return timeouts if a specific timeout is exceeded.
responseQueue <- [];
timeout <- 5; // timeout (in seconds) for roundtrip from agent -> device -> agent.
// function that triggers responses if timeout expires
function checkResponses() {
local newQueue = [];
// loop through http response queue
local t = time();
for (local i = 0; i < responseQueue.len(); i++) {
// if it's been sitting for more than allowed timeout
if ((t - r.timestamp) > timeout) {
// send a timeout error
r.response.send(408, "Device timed out");
server.log("Request " + r.timestamp + " timed-out.");
} else {
// otherwise, keep it around
newQueue.push(r);
}
}
// get rid of all the expired responses
// (note: this is a really lazy way of doing this)
responseQueue = newQueue;
// call this function again in a second
imp.wakeup(checkResponses, 1.0);
}
// when we get an HTTP request
http.onrequest(function(req, resp) {
// create object for queue and push it onto it
local queueObject = { timestamp = time(), response = resp };
responseQueue.push(queueObject);
// send message to see if device is online
device.send("ping", queueObject.timestamp);
});
// when we get a message saying the device is online
device.on("pong", function(timestamp) {
// check to see if the originating request is still in the queue
foreach(r in responseQueue) {
// if it is, send a 200 response
if (r.timestamp == timestamp) {
r.resp.send(200, "OK");
return;
}
}
server.log("Request " + timestamp + " already timed out");
});
// when we get a ping message
agent.on("ping", function(timestamp) {
// do something
// send a pong
server.send("pong", timestamp);
}
@ozzieg

ozzieg commented Aug 20, 2013

Copy link
Copy Markdown

Nothing is triggering the "checkReponses()" method. Am I missing something? Also, shouldn't the request body be parsed or stored away as well?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment