Im trying to handle a http response with data with data that I first need to get from a device. Im failing missearbly. It seems that Im not getting the hang of how to send variables back and forth between device and agent.
Below youll find a cropped version of the code.
Any good advice?
Br, Ragnar
###AGENT CODE (CROPPED)###
`// Log the URLs we can use
server.log("Get temperature: " + http.agenturl() + “?readtemp”);
function respond_temp(datapoint, response){
response.send(200, “ID " + datapoint.id + " has " + datapoint.temp + " degrees”);
}
function requestHandler(request, response) {
if ("readtemp" in request.query) {
device.on("data", function(datapoint){
respond_temp(datapoint, response);
});
}
}
// the HTTP handler
http.onrequest(requestHandler);`
There’s a couple things to realize… the .on functions (agent.on and device.on) register a callback. What this basically means is that it tells the program to do something (run the callback) when a particular message is received (the first callback).
Right now you’re calling device.on each time you get a new HTTP request, which isn’t necessary. In order to do what you are trying to do, there are a couple steps:
When the HTTP request comes in, send a message to the device
When the device gets the message from (1), take a reading and send a message back to the agent
When the agent gets the message from (2), respond to the http request (this means we need to have stored our http request somewhere).
Here’s a thread from a while ago that has code for what you are trying to do: