1# Messaging 2 3Messaging (`lv_msg`) is a classic []publisher subscriber](https://en.wikipedia.org/wiki/Publish%E2%80%93subscribe_pattern) implementation for LVGL. 4 5## IDs 6Both the publishers and the subscribers needs to know the message identifiers. 7In `lv_msg` these are simple `uint32_t` integers. For example: 8```c 9#define MSG_DOOR_OPENED 1 10#define MSG_DOOR_CLOSED 2 11#define MSG_USER_NAME_CHANGED 100 12#define MSG_USER_AVATAR_CHANGED 101 13``` 14 15You can orgnaize the message IDs as you wish. 16 17Both parties also need to know about the format of teh payload. E.g. in the above example 18`MSG_DOOR_OPENED` and `MSG_DOOR_CLOSED` has no payload but `MSG_USER_NAME_CHANGED` can have a `const char *` payload containing the user name, and `MSG_USER_AVATAR_CHANGED` a `const void *` image source with the new avatar image. 19 20 21## Send message 22 23Messages can be sent with `lv_msg_send(msg_id, payload)`. E.g. 24```c 25lv_msg_send(MSG_USER_DOOR_OPENED, NULL); 26lv_msg_send(MSG_USER_NAME_CHANGED, "John Smith"); 27``` 28 29## Subscribe to a message 30 31`lv_msg_subscribe(msg_id, callback, user_data)` can be used to subscribe to message. 32 33The callback should look like this: 34```c 35 36static void user_name_subscriber_cb(void * s, lv_msg_t * m) 37{ 38 /*s: a subscriber obeject, can be used to unscubscribe*/ 39 /*m: a message object with the msg_id, payload, and user_data (set durung subscription)*/ 40 41 ...do something... 42} 43``` 44 45From `lv_msg_t` the followings can be used to get some data: 46- `lv_msg_get_id(m)` 47- `lv_msg_get_payload(m)` 48- `lv_msg_get_user_data(m)` 49 50## Subscribe with an lv_obj 51It's quite typical that an LVGL widget is interested in some messages. 52To make it simpler `lv_msg_subsribe_obj(msg_id, obj, user_data)` can be used. 53If a new message is published with `msg_id` an `LV_EVENT_MSG_RECEIVED` event will be sent to the object. 54 55For example: 56```c 57lv_obj_add_event_cb(user_name_label, user_name_label_event_cb, LV_EVENT_MSG_RECEIVED, NULL); 58lv_msg_subsribe_obj(MSG_USER_NAME_CHANGED, user_name_label, NULL); 59 60... 61 62void user_name_label_event_cb(lv_event_t * e) 63{ 64 lv_obj_t * label = lv_event_get_target(e); 65 lv_msg_t * m = lv_event_get_msg(e); 66 lv_label_set_text(label, lv_msg_get_payload(m)); 67} 68 69``` 70 71### Unsubscribe 72`lv_msg_subscribe` returns a pointer which can be used to unsubscribe: 73```c 74void * s1; 75s1 = lv_msg_subscribe(MSG_USER_DOOR_OPENED, some_callback, NULL); 76 77... 78 79lv_msg_unsubscribe(s1); 80``` 81 82## Example 83 84```eval_rst 85 86.. include:: ../../examples/others/msg/index.rst 87 88``` 89## API 90 91 92```eval_rst 93 94.. doxygenfile:: lv_msg.h 95 :project: lvgl 96 97``` 98