Http request is async and I want to wait for the response (promise)

Hi all,
I have a rule in which I make API call, that API call takes time and since sendHttpGetRequest is async I don’t know how to solve the problem.

var Data = sendHttpGetRequest(“url”)

This Data is ofc empty because of async sendHttpGetRequest.
How to make a promise in openhab2 rules ?

Thanks!

It isn’t async. The server is taking too long to respond or is responding with an empty response. That action does block until it gets a response.

The server needs around 30-90 seconds because I am doing object detection algorithm.

What do you think, how can I solve this?

You have two choices.

  1. HTTP Binding Cache config which lets you specify how often to call the URL and the maximum amount of time to wait. However, this only works for a polling periodic check of the URL. You haven’t provided enough information for me to know if that is sufficient for what you are trying to do.

  2. executeCommandLine in a Rule which makes a call to curl. You can specify the maximum amount of time to wait. Note that this can be dangerous in Rules because there are only five execution threads available. If you trigger this rule too fast or you have other rules that take a long time to execute you can run out of execution threads. There are ways around that but I don’t want to write the code for it here if option 1 will work for you.

Or another option: have a script always running in the background (outside openHAB) which waits for a trigger from openHAB to start the object detection, and then pushes the result to an openHAB Item.

You then simply have one openHAB rule which triggers the script, and another triggered by the resultant change to the openHAB item. In the meantime, no threads get locked up.

1 Like

Thanks, I did it with curl and it is working :grinning:

To give context, my project has motion detector and when somebody is in front of the doors, image is sent from camera to that object detection api which does detection and it return a message to my Telegram app on the phone.

It’s the first time I hear about the 5 threads…
I’d be interested in the worlaround if that’s the case…

At a high level the work around is to not have Thread::sleep longer than half a second or long running calls (e.g. executeCommandLine for a long running command) in your rules. So use the HTTP binding or Exec binding instead.

If you can’t do that then you need to restructure what you are doing to:

  • use Timers
  • split the logic into multiple rules and instead of waiting in the one rule, generate an event that can trigger a second rule to do the rest of the work
  • find a different approach entirely that doesn’t require the wait (e.g. move the call to the command line to a script that runs independent of OH and publishes the results to OH through the REST API or MQTT

Really, the correct solution depends heavily on what you are trying to accomplish. There is no one workaround.