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 uint32_t g_mbox_received_data;
16 static uint32_t g_mbox_received_channel;
17 
18 #define CHANNELS_TO_TEST 4
19 #define TX_CHANNEL_INDEX 0
20 #define RX_CHANNEL_INDEX 1
21 
22 static const struct mbox_dt_spec channels[CHANNELS_TO_TEST][2] = {
23 	{
24 		MBOX_DT_SPEC_GET(DT_PATH(mbox_consumer), tx0),
25 		MBOX_DT_SPEC_GET(DT_PATH(mbox_consumer), rx0),
26 	},
27 	{
28 		MBOX_DT_SPEC_GET(DT_PATH(mbox_consumer), tx1),
29 		MBOX_DT_SPEC_GET(DT_PATH(mbox_consumer), rx1),
30 	},
31 	{
32 		MBOX_DT_SPEC_GET(DT_PATH(mbox_consumer), tx2),
33 		MBOX_DT_SPEC_GET(DT_PATH(mbox_consumer), rx2),
34 	},
35 	{
36 		MBOX_DT_SPEC_GET(DT_PATH(mbox_consumer), tx3),
37 		MBOX_DT_SPEC_GET(DT_PATH(mbox_consumer), rx3),
38 	},
39 };
40 
callback(const struct device * dev,uint32_t channel,void * user_data,struct mbox_msg * data)41 static void callback(const struct device *dev, uint32_t channel, void *user_data,
42 		     struct mbox_msg *data)
43 {
44 	if (data != NULL) {
45 		memcpy(&g_mbox_received_data, data->data, data->size);
46 		g_mbox_received_channel = channel;
47 	}
48 
49 	k_sem_give(&g_mbox_data_rx_sem);
50 }
51 
main(void)52 int main(void)
53 {
54 	struct mbox_msg msg = {0};
55 	uint32_t message = 0;
56 
57 	for (int i = 0; i < ARRAY_SIZE(channels); i++) {
58 		const struct mbox_dt_spec *tx_channel = &channels[i][TX_CHANNEL_INDEX];
59 		const struct mbox_dt_spec *rx_channel = &channels[i][RX_CHANNEL_INDEX];
60 
61 		const int max_transfer_size_bytes = mbox_mtu_get_dt(tx_channel);
62 		/* Sample currently supports only transfer size up to 4 bytes */
63 		if ((max_transfer_size_bytes <= 0) || (max_transfer_size_bytes > 4)) {
64 			printk("mbox_mtu_get() error\n");
65 			return 0;
66 		}
67 
68 		if (mbox_register_callback_dt(rx_channel, callback, NULL)) {
69 			printk("mbox_register_callback() error\n");
70 			return 0;
71 		}
72 
73 		if (mbox_set_enabled_dt(rx_channel, 1)) {
74 			printk("mbox_set_enable() error\n");
75 			return 0;
76 		}
77 
78 		int test_count = 0;
79 
80 		while (test_count < 100) {
81 			test_count++;
82 
83 			k_sem_take(&g_mbox_data_rx_sem, K_FOREVER);
84 			message = g_mbox_received_data;
85 
86 			message++;
87 
88 			msg.data = &message;
89 			msg.size = max_transfer_size_bytes;
90 
91 			if (mbox_send_dt(tx_channel, &msg) < 0) {
92 				printk("mbox_send() error\n");
93 				return 0;
94 			}
95 		}
96 
97 		/* Disable current rx channel after channel loop */
98 		mbox_set_enabled_dt(rx_channel, 0);
99 	}
100 }
101