jeatheak / Mitsubishi-WF-RAC-Integration

WF-RAC homeassistant integration
MIT License
101 stars 19 forks source link

add mutex to stop multiple threads confusing the airco #20

Closed theawesomestrob closed 1 year ago

theawesomestrob commented 1 year ago

I noticed if I mash the buttons in home assistant to turn an aircon unit on+off/set temp/etc very quickly, the device will get confused and reject a lot of the requests.

I added some more debug logging to see what was going on, and it seems that home assistant was running the POSTs from multiple threads at the ~same time, and the aircon was replying with status 501 and the text "Not supported this command"

eg here you can see two threads POSTing to the same device, causing one of the threads to receive a 501 response

2022-09-06 18:52:23.208 DEBUG (SyncWorker_8) [custom_components.mitsubishi-wf-rac.wfrac.repository] (thread 140148970076976) POSTing to http://10.8.4.118:51443/beaver/command/setAirconStat: [...]
2022-09-06 18:52:23.637 DEBUG (SyncWorker_0) [custom_components.mitsubishi-wf-rac.wfrac.repository] (thread 140149305355056) POSTing to http://10.8.4.118:51443/beaver/command/setAirconStat: [...]
2022-09-06 18:52:23.912 DEBUG (SyncWorker_5) [custom_components.mitsubishi-wf-rac.wfrac.repository] (thread 140149198629680) Got response (200): '{"command":"setAirconStat",[...]
2022-09-06 18:52:24.069 DEBUG (SyncWorker_8) [custom_components.mitsubishi-wf-rac.wfrac.repository] (thread 140148970076976) Got response (501): 'Not supported this command'

To solve that I've added a lock to the Repository instance, so the threads access the aircon device one at a time.

I also refactored Repository slightly so it's easy to control all the POSTs from one place, and added a minimum time between requests (currently 1s) to try to ensure we won't overwhelm the unit's http server.

For now the waiting is done via a simple time.sleep() but I don't think it will be too difficult to make the Repository code async so we can wait without wasting a thread…