1 /*
2  * Copyright (c) 2022 Rodrigo Peixoto <rodrigopex@gmail.com>
3  * SPDX-License-Identifier: Apache-2.0
4  */
5 #include "messages.h"
6 
7 #include <stdint.h>
8 
9 #include <zephyr/kernel.h>
10 #include <zephyr/logging/log.h>
11 #include <zephyr/zbus/zbus.h>
12 
13 LOG_MODULE_DECLARE(zbus, CONFIG_ZBUS_LOG_LEVEL);
14 
15 ZBUS_CHAN_DEFINE(pkt_chan,		   /* Name */
16 		 struct external_data_msg, /* Message type */
17 
18 		 NULL,			     /* Validator */
19 		 NULL,			     /* User data */
20 		 ZBUS_OBSERVERS(filter_lis), /* observers */
21 		 ZBUS_MSG_INIT(0)	     /* Initial value {0} */
22 );
23 
24 ZBUS_CHAN_DEFINE(version_chan,	     /* Name */
25 		 struct version_msg, /* Message type */
26 
27 		 NULL,						   /* Validator */
28 		 NULL,						   /* User data */
29 		 ZBUS_OBSERVERS_EMPTY,				   /* observers */
30 		 ZBUS_MSG_INIT(.major = 0, .minor = 1, .build = 1) /* Initial value {0} */
31 );
32 
33 ZBUS_CHAN_DEFINE(data_ready_chan, /* Name */
34 		 struct ack_msg,  /* Message type */
35 
36 		 NULL,			       /* Validator */
37 		 NULL,			       /* User data */
38 		 ZBUS_OBSERVERS(consumer_sub), /* observers */
39 		 ZBUS_MSG_INIT(0)	       /* Initial value {0} */
40 );
41 
42 ZBUS_CHAN_DEFINE(ack,		 /* Name */
43 		 struct ack_msg, /* Message type */
44 
45 		 NULL,			       /* Validator */
46 		 NULL,			       /* User data */
47 		 ZBUS_OBSERVERS(producer_sub), /* observers */
48 		 ZBUS_MSG_INIT(0)	       /* Initial value {0} */
49 );
50 
filter_cb(const struct zbus_channel * chan)51 static void filter_cb(const struct zbus_channel *chan)
52 {
53 	/* Note that the listener does not change the actual message.
54 	 * It changes the external dynamic memory area but not the reference and size of the
55 	 * channel's message struct. Use that with care.
56 	 */
57 
58 	const struct external_data_msg *chan_message;
59 
60 	__ASSERT_NO_MSG(chan == &pkt_chan);
61 
62 	chan_message = zbus_chan_const_msg(chan);
63 
64 	if (chan_message->size % 2) {
65 		memset(chan_message->reference, 0, chan_message->size);
66 	}
67 
68 	struct ack_msg dr = {1};
69 
70 	zbus_chan_pub(&data_ready_chan, &dr, K_NO_WAIT);
71 }
72 
73 ZBUS_LISTENER_DEFINE(filter_lis, filter_cb);
74 
main(void)75 int main(void)
76 {
77 	const struct version_msg *v = zbus_chan_const_msg(&version_chan);
78 
79 	LOG_DBG(" -> Dynamic channel sample version %u.%u-%u\n\n", v->major, v->minor, v->build);
80 	return 0;
81 }
82