pubsub.h 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. #pragma once
  2. #include "flipper.h"
  3. /*
  4. == PubSub ==
  5. PubSub allows users to subscribe on notifies and notify subscribers.
  6. Notifier side can pass `void*` arg to subscriber callback,
  7. and also subscriber can set `void*` context pointer that pass into
  8. callback (you can see callback signature below).
  9. */
  10. typedef void(PubSubCallback*)(void*, void*);
  11. typedef struct {
  12. PubSubCallback cb;
  13. void* ctx;
  14. } PubSubItem;
  15. typedef struct {
  16. PubSub* self;
  17. PubSubItem* item;
  18. } PubSubId;
  19. typedef struct {
  20. PubSubItem items[NUM_OF_CALLBACKS];
  21. PubSubId ids[NUM_OF_CALLBACKS]; ///< permanent links to item
  22. size_t count; ///< count of callbacks
  23. } PubSub;
  24. /*
  25. To create PubSub you should create PubSub instance and call `init_pubsub`.
  26. */
  27. void init_pubsub(PubSub* pubsub);
  28. /*
  29. Use `subscribe_pubsub` to register your callback.
  30. */
  31. PubSubId* subscribe_pubsub(PubSub* pubsub, PubSubCallback cb, void* ctx);
  32. /*
  33. Use `unsubscribe_pubsub` to unregister callback.
  34. */
  35. void unsubscribe_pubsub(PubSubId* pubsub_id);
  36. /*
  37. Use `notify_pubsub` to notify subscribers.
  38. */
  39. void notify_pubsub(PubSub* pubsub, void* arg);
  40. /*
  41. ```C
  42. // MANIFEST
  43. // name="test"
  44. // stack=128
  45. void example_pubsub_handler(void* arg, void* ctx) {
  46. printf("get %d from %s\n", *(uint32_t*)arg, (const char*)ctx);
  47. }
  48. void pubsub_test() {
  49. const char* app_name = "test app";
  50. PubSub example_pubsub;
  51. init_pubsub(&example_pubsub);
  52. if(!subscribe_pubsub(&example_pubsub, example_pubsub_handler, (void*)app_name)) {
  53. printf("critical error\n");
  54. flapp_exit(NULL);
  55. }
  56. uint32_t counter = 0;
  57. while(1) {
  58. notify_pubsub(&example_pubsub, (void*)&counter);
  59. counter++;
  60. osDelay(100);
  61. }
  62. }
  63. ```
  64. */