1 /*
2  * Copyright (c) 2023 Nordic Semiconductor ASA
3  *
4  * SPDX-License-Identifier: Apache-2.0
5  */
6 
7 #include <zephyr/kernel.h>
8 #include <zephyr/sys/util.h>
9 #include "argparse.h"
10 #include "bs_types.h"
11 #include "bs_tracing.h"
12 #include "time_machine.h"
13 #include "bstests.h"
14 #include "bs_pc_backchannel.h"
15 
16 #include <zephyr/logging/log.h>
17 LOG_MODULE_REGISTER(sync, LOG_LEVEL_INF);
18 
19 #define CHANNEL_ID 0
20 #define MSG_SIZE 1
21 
backchannel_init(void)22 int backchannel_init(void)
23 {
24 	uint device_number = get_device_nbr();
25 	uint peer_number = device_number ^ 1;
26 	uint device_numbers[] = { peer_number };
27 	uint channel_numbers[] = { CHANNEL_ID };
28 	uint *ch;
29 
30 	ch = bs_open_back_channel(device_number, device_numbers, channel_numbers,
31 				  ARRAY_SIZE(channel_numbers));
32 
33 	if (!ch) {
34 		return -1;
35 	}
36 
37 	return 0;
38 }
39 
backchannel_sync_send(void)40 void backchannel_sync_send(void)
41 {
42 	uint8_t sync_msg[MSG_SIZE] = { get_device_nbr() };
43 
44 	LOG_INF("Sending sync");
45 	bs_bc_send_msg(CHANNEL_ID, sync_msg, ARRAY_SIZE(sync_msg));
46 }
47 
backchannel_sync_wait(void)48 void backchannel_sync_wait(void)
49 {
50 	uint8_t sync_msg[MSG_SIZE];
51 
52 	while (true) {
53 		if (bs_bc_is_msg_received(CHANNEL_ID) > 0) {
54 			bs_bc_receive_msg(CHANNEL_ID, sync_msg, ARRAY_SIZE(sync_msg));
55 			if (sync_msg[0] != get_device_nbr()) {
56 				/* Received a message from another device, exit */
57 				break;
58 			}
59 		}
60 
61 		k_sleep(K_MSEC(1));
62 	}
63 
64 	LOG_INF("Sync received");
65 }
66