How to use Zephyr zbus to Communicate Between Threads

Originally published at: How to use Zephyr zbus to Communicate Between Threads - The Golioth Developer Blog

If you’re not using zbus, you probably should be. As the name indicates, this is the Zephyr bus, a built-in system for publishing, reading, subscribing to, and observing messages in a thread-safe way. It delivers peace of mind with minimal effort. Think of zbus as a collection of data producers and data consumers. One thread might be periodically taking sensor readings (producer). When that thread publishes to a zbus channel, all listeners (consumers) have a callback that runs to process the new message. You could make Golioth Stream service one of your consumers, pushing sensor data to the cloud each time a new zbus message is received. At the same time, another consumer could update your device’s screen with data from each new message. This example may seem trivial, but as your project grows in complexity you’ll be glad you used zbus. Zbus overview Your Zbus experience begins by defining a channel. Each channel has a set message type (a struct), a starting message value, and a list of observers. Optionally each channel may specify a function to validate each message before publishing, and a pointer to user data. In addition to the observers that were set up when the channel was defined, a zbus channel may be read from at any time, making the most recently published message data available. Zbus breaks down “observers” in a few different categories. Listeners receive a callback with data from each new message. Subscribers may choose to receive a notification of new message. The subscriber is responsible for choosing when to read the message after receiving the notification. There is also an option for subscribers to receive a copy of each message via…