catgiggle / OctoPrint-GpioControl

GNU Affero General Public License v3.0
25 stars 13 forks source link

Fix plugin API endpoint to report status of all GPIOs #7

Closed sqozz closed 3 years ago

sqozz commented 3 years ago

Hey. First of all, thanks for the nice plugin! While migrating away from PSUControl and LEDControl for this plugin I realized that I struggle to integrate it into my home automation system. For this I need a generic API endpoint which reports the state of the GPIOs. Optimally it would be possible to request each GPIOs state by a unique endpoint like /api/plugin/gpiocontrol/{id} but I realized that doesn't seem possible with OctoPrints plugin architecture. Therefore I went with the next best thing and fixed the on_api_get endpoint (which was broken since it supplied an empty list as data argument to on_api_command). It now returns a list with all configured GPIOs with their current status:

sqozz@workstation ~ » curl -s -H "Content-Type: application/json" -H "X-Api-Key: [redacted]" http://octoprint/api/plugin/gpiocontrol
{"0":"on"}

It uses the data from on_api_command to produce a consistent result in case you decide to change the output of it. Let me know if there are some improvements I should implement :)

catgiggle commented 3 years ago

I think, that this is currently implemented. Please see code below. It does exactly what you need - it takes state for specific GPIO. Please note that id is not GPIO number, but number from 0 to something.

curl 'https://xxx/api/plugin/gpiocontrol' -H 'Content-Type: application/json' --data '{"id":1,"command":"getGpioState"}'
sqozz commented 3 years ago

Yes, however it requires a POST request to be made. Strictly speaking this is not following the REST specification (see https://tools.ietf.org/html/rfc7231#section-4.3.1):

The GET method requests transfer of a current selected representation for the target resource.

So there is currently no way to get things like e.g. https://www.home-assistant.io/integrations/switch.rest/ to work because (quote): "The switch can get the state via GET and set the state via POST on a given REST resource.".

Also on_api_get currently produces HTTP 500.

catgiggle commented 3 years ago

Please take a look at version 1.0.4. I already released it. I think you will be satisfied :)

I improved a way of updating button states. Previously it called API for each button. Now one request is sent for all buttons. This is much better solution. Thanks for drawing my attention to this!