2020-10-13 08:22:43 +00:00
|
|
|
#pragma once
|
|
|
|
|
2020-10-26 09:26:15 +00:00
|
|
|
#include "cmsis_os.h"
|
2020-10-15 18:23:18 +00:00
|
|
|
#include "m-list.h"
|
2020-10-13 08:22:43 +00:00
|
|
|
|
|
|
|
/*
|
|
|
|
== PubSub ==
|
|
|
|
|
|
|
|
PubSub allows users to subscribe on notifies and notify subscribers.
|
|
|
|
Notifier side can pass `void*` arg to subscriber callback,
|
|
|
|
and also subscriber can set `void*` context pointer that pass into
|
|
|
|
callback (you can see callback signature below).
|
|
|
|
*/
|
|
|
|
|
2020-10-15 18:23:18 +00:00
|
|
|
typedef void (*PubSubCallback)(void*, void*);
|
|
|
|
typedef struct PubSubType PubSub;
|
2020-10-13 08:22:43 +00:00
|
|
|
|
|
|
|
typedef struct {
|
|
|
|
PubSubCallback cb;
|
|
|
|
void* ctx;
|
2020-10-15 18:23:18 +00:00
|
|
|
PubSub* self;
|
2020-10-13 08:22:43 +00:00
|
|
|
} PubSubItem;
|
|
|
|
|
2020-10-15 18:23:18 +00:00
|
|
|
LIST_DEF(list_pubsub_cb, PubSubItem, M_POD_OPLIST);
|
2020-10-13 08:22:43 +00:00
|
|
|
|
2020-10-15 18:23:18 +00:00
|
|
|
struct PubSubType {
|
|
|
|
list_pubsub_cb_t items;
|
|
|
|
osMutexId_t mutex;
|
|
|
|
};
|
2020-10-13 08:22:43 +00:00
|
|
|
|
|
|
|
/*
|
|
|
|
To create PubSub you should create PubSub instance and call `init_pubsub`.
|
|
|
|
*/
|
2020-10-15 18:23:18 +00:00
|
|
|
bool init_pubsub(PubSub* pubsub);
|
|
|
|
|
|
|
|
/*
|
|
|
|
Since we use dynamic memory - we must explicity delete pubsub
|
|
|
|
*/
|
|
|
|
bool delete_pubsub(PubSub* pubsub);
|
2020-10-13 08:22:43 +00:00
|
|
|
|
|
|
|
/*
|
|
|
|
Use `subscribe_pubsub` to register your callback.
|
|
|
|
*/
|
2020-10-15 18:23:18 +00:00
|
|
|
PubSubItem* subscribe_pubsub(PubSub* pubsub, PubSubCallback cb, void* ctx);
|
2020-10-13 08:22:43 +00:00
|
|
|
|
|
|
|
/*
|
|
|
|
Use `unsubscribe_pubsub` to unregister callback.
|
|
|
|
*/
|
2020-10-15 18:23:18 +00:00
|
|
|
bool unsubscribe_pubsub(PubSubItem* pubsub_id);
|
2020-10-13 08:22:43 +00:00
|
|
|
|
|
|
|
/*
|
|
|
|
Use `notify_pubsub` to notify subscribers.
|
|
|
|
*/
|
2020-10-15 18:23:18 +00:00
|
|
|
bool notify_pubsub(PubSub* pubsub, void* arg);
|
2020-10-13 08:22:43 +00:00
|
|
|
|
|
|
|
/*
|
|
|
|
|
|
|
|
```C
|
|
|
|
// MANIFEST
|
|
|
|
// name="test"
|
|
|
|
// stack=128
|
|
|
|
|
|
|
|
void example_pubsub_handler(void* arg, void* ctx) {
|
|
|
|
printf("get %d from %s\n", *(uint32_t*)arg, (const char*)ctx);
|
|
|
|
}
|
|
|
|
|
|
|
|
void pubsub_test() {
|
|
|
|
const char* app_name = "test app";
|
|
|
|
|
|
|
|
PubSub example_pubsub;
|
|
|
|
init_pubsub(&example_pubsub);
|
|
|
|
|
|
|
|
if(!subscribe_pubsub(&example_pubsub, example_pubsub_handler, (void*)app_name)) {
|
|
|
|
printf("critical error\n");
|
|
|
|
flapp_exit(NULL);
|
|
|
|
}
|
|
|
|
|
|
|
|
uint32_t counter = 0;
|
|
|
|
while(1) {
|
|
|
|
notify_pubsub(&example_pubsub, (void*)&counter);
|
|
|
|
counter++;
|
|
|
|
|
|
|
|
osDelay(100);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
```
|
|
|
|
*/
|