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