Long Poll with SimpleApiPlugin

I made a Plugin with a Tab and the SimpleApiPlugin
All works fine so far.

Now i want to do a long poll and send a request 'observe_view_model' to the server.
The server returns only when data changes.
The problem is now that the server seems to accept only one request at a time. No request
makes it to 'on_api_command()' as long as 'observe_view_model' is pending.

My guess is that my approach is conceptually wrong in this context.
Any help or hints are highly appreciated.

Thanks reading

It sounds like you want to send data from Python (server) to JS (client) when something triggers it from the server (python) such as a GCODE or other event...

You could create your own event, and then fire it from the Python side of your plugin. Then in your viewmodel you can setup a method to handle that event. Then you aren't polling, just waiting for your event to come through.

You could still use the simple API to signal if the event should be sent or not, or you may just want to send it no matter what.

I do this in the Camera Settings plugin to get the list of available cameras:

  1. The client side of the plugin sends a SimpleAPI request signaling the server side that it wants the list.
  2. This causes the server side of the plugin to go out and build the actual camera list and then fire off a custom event back to the client with the actual list.
  3. The client handles this event and uses the data appropriately.
1 Like

Also note the reason you are not seeing any further requests come through while the other one is pending is because OctoPrint's API handling is single threaded (or near enough, iirc).

To send push data, the websocket is a much better option.

1 Like

Thats the information i needed.
Octoprint API is single threaded and despite of that events or websocket are better anyway.
Still learning....

I try it out, thanks

1 Like

Events work as expected, great

Two more questions raised:
Are these events based on Websockets or are they Octoprint specific ?

What is the earliest time to send an event ? I triggered the server to send an event
in $(document).ready on client side, but it didnt work. (Later on in response to a
button click it works...)

The events do come in over the websocket, the same way the data for things like the terminal & temperature graph does.

In terms of when to make an API request, the only thing I can think of is after the initial login state check, I recall some issues if requests were sent before that because the cookies/sessions would not line up.

You could try using it in self.onStartup callback (list of frontend callbacks maybe?

1 Like

Thanks.
I tried out several callbacks, neither worked. I dont know what i did wrong.
As i didnt want to spend more time on this issue i did the initial update by simply responding
directly to the request now.