espressif / esp-homekit-sdk

566 stars 107 forks source link

Document concurrency model #28

Open lukehoersten opened 3 years ago

lukehoersten commented 3 years ago

I'm looking for more information on the concurrency model of the ESP HomeKit SDK HAP implementation. Does the HAP Core run it's own thread and then the App gets its own thread, etc? Thread safety considerations would be helpful as well.

shahpiyushv commented 3 years ago

Since entire HomeKit communication happens over HTTP, all the read/write callbacks are invoked in the context of the esp_http_server. The various events (like HAP_EVENT_CTRL_PAIRED) are invoked using the esp_event_loop. Whenever application calls hap_char_update_val(), the value change event is queued and notification sent to controllers, again in the esp_http_server task's context. There is also another hap-loop task for some internal operations and state machine.

The app_main() function itself is invoked in the context of the main task, about which, you can read here.

Ideally, the hap_char_update_val() API would need some protection, since it can get invoked from multiple task contexts, but currently it is missing. Other APIs can also have protection, but a lot of those aren't really required to be invoked from different tasks .

I hope this answers your question.

lukehoersten commented 3 years ago

Yes this is super helpful - thank you.

Is it safe for me to call hap_ functions from multiple tasks?