Web app access Imp synchronously?

Hi All

I’m creating a web app, and I want to poll the status of some variables on the Imp. Something along the lines of:

  1. web app requests data from agent
  2. agent checks imp
  3. imp repsonds to agent with data
  4. agent responds to web app (responding to original http request)

I might be looking in the wrong place, or thinking about this the wrong way, but it doesn’t look like this can be done with the [agent|device].[on|send] combinations. Are there other functions for this that I’m just missing?

Many thanks

No, your flow is correct. @beardedinventors non blocking code example probably the best for using http.onrequest.


It might be easier to understand if you look at blocking code first… the non-blocking code is a bit more complex.

Thanks for that, looks to be just what I need.

So just to check I’ve got this right…

  • Request comes in.
  • Agent puts the response to one side, using the timestamp as a key, while it checks the device.
  • Communicates with the device, sending the timestamp and receiving it back again from the device, using it a a kind of rudimentary session key.
  • response from device, agent looks up the http response it saved using the timestamp value, and “completes” the request, able to use data it has received form the device.

Is that about right?

Spot on!

There’s also some extra code in there to make sure that if the imp doesn’t respond in a given amount of time, it sends a timeout response.

Thanks for the help. Got this working quite nicely with an iOS app for turning my central heating on and off :slight_smile:

Another quick question - is the response.send function equivalent to a “return” statement? ie, will the function finish at the point the response is sent, or should I break out manually?


No - response.send simply sends a response back to whoever made the request. If you want the function to return immediately, you’ll need to return after it.

http.onrequest(function(req, resp) { if ("state" in req.query) { device.send("http", req.query.state); resp.send(200, "OK"); return; } resp.send(406, "Required query parameter 'state' missing."); });

That’s great, thanks :slight_smile: