Agent http response with a device.on() "variable request"

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

`// Log the URLs we can use
server.log("Get temperature: " + http.agenturl() + “?readtemp”);

function respond_temp(datapoint, response){
response.send(200, “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


`myThermistor <- thermistor(temp_sns, b_therm, t0_therm, r_therm, 10, true);

// Case of getting temp to agent
local id = hardware.getdeviceid();
local datapoint = {
“id” : id,
“temp” : format("%.2f", myThermistor.read_c())

agent.send(“data”, datapoint); `

What I do is to send the readings from my device to the agent every second. The readings are then stored on the agent, and used in the response.

@Ragnar - you may want to read this article (this one may be of use too).

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:

  1. When the HTTP request comes in, send a message to the device
  2. When the device gets the message from (1), take a reading and send a message back to the agent
  3. 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:

@beardedinventor - This was cleard up a lott! Thanks!