1 /*
2  * Copyright 2024 NXP
3  *
4  * SPDX-License-Identifier: Apache-2.0
5  */
6 
7 #include <stdio.h>
8 #include <stdlib.h>
9 #include <string.h>
10 #include <zephyr/kernel.h>
11 #include <zephyr/drivers/mbox.h>
12 
13 static K_SEM_DEFINE(g_mbox_data_rx_sem, 0, 1);
14 
15 static mbox_channel_id_t g_mbox_received_data;
16 static mbox_channel_id_t g_mbox_received_channel;
17 
callback(const struct device * dev,mbox_channel_id_t channel_id,void * user_data,struct mbox_msg * data)18 static void callback(const struct device *dev, mbox_channel_id_t channel_id, void *user_data,
19 		     struct mbox_msg *data)
20 {
21 	memcpy(&g_mbox_received_data, data->data, data->size);
22 	g_mbox_received_channel = channel_id;
23 
24 	k_sem_give(&g_mbox_data_rx_sem);
25 }
26 
main(void)27 int main(void)
28 {
29 	const struct mbox_dt_spec tx_channel = MBOX_DT_SPEC_GET(DT_PATH(mbox_consumer), tx);
30 	const struct mbox_dt_spec rx_channel = MBOX_DT_SPEC_GET(DT_PATH(mbox_consumer), rx);
31 	struct mbox_msg msg = {0};
32 	uint32_t message = 0;
33 
34 	printk("mbox_data Server demo started\n");
35 
36 	const int max_transfer_size_bytes = mbox_mtu_get_dt(&tx_channel);
37 	/* Sample currently supports only transfer size up to 4 bytes */
38 	if ((max_transfer_size_bytes <= 0) || (max_transfer_size_bytes > 4)) {
39 		printk("mbox_mtu_get() error\n");
40 		return 0;
41 	}
42 
43 	if (mbox_register_callback_dt(&rx_channel, callback, NULL)) {
44 		printk("mbox_register_callback() error\n");
45 		return 0;
46 	}
47 
48 	if (mbox_set_enabled_dt(&rx_channel, 1)) {
49 		printk("mbox_set_enable() error\n");
50 		return 0;
51 	}
52 
53 	while (message < 99) {
54 		k_sem_take(&g_mbox_data_rx_sem, K_FOREVER);
55 		message = g_mbox_received_data;
56 
57 		printk("Server receive (on channel %d) value: %d\n", g_mbox_received_channel,
58 		       g_mbox_received_data);
59 
60 		message++;
61 
62 		msg.data = &message;
63 		msg.size = max_transfer_size_bytes;
64 
65 		printk("Server send (on channel %d) value: %d\n", tx_channel.channel_id, message);
66 		if (mbox_send_dt(&tx_channel, &msg) < 0) {
67 			printk("mbox_send() error\n");
68 			return 0;
69 		}
70 	}
71 
72 	printk("mbox_data Server demo ended.\n");
73 	return 0;
74 }
75