1 /*
2  * Copyright (c) 2024 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 "bs_pc_backchannel.h"
14 
15 #include <zephyr/logging/log.h>
16 LOG_MODULE_REGISTER(sync, CONFIG_LOG_DEFAULT_LEVEL);
17 
18 #define CHANNEL_ID 0
19 #define MSG_SIZE 1
20 
bk_sync_init(void)21 int bk_sync_init(void)
22 {
23 	uint device_number = get_device_nbr();
24 	uint peer_number = device_number ^ 1;
25 	uint device_numbers[] = { peer_number };
26 	uint channel_numbers[] = { CHANNEL_ID };
27 	uint *ch;
28 
29 	ch = bs_open_back_channel(device_number, device_numbers, channel_numbers,
30 				  ARRAY_SIZE(channel_numbers));
31 	if (!ch) {
32 		return -1;
33 	}
34 
35 	LOG_DBG("Sync initialized");
36 
37 	return 0;
38 }
39 
bk_sync_send(void)40 void bk_sync_send(void)
41 {
42 	uint8_t sync_msg[MSG_SIZE] = { get_device_nbr() };
43 
44 	LOG_DBG("Sending sync");
45 	bs_bc_send_msg(CHANNEL_ID, sync_msg, ARRAY_SIZE(sync_msg));
46 }
47 
bk_sync_wait(void)48 void bk_sync_wait(void)
49 {
50 	uint8_t sync_msg[MSG_SIZE];
51 
52 	LOG_DBG("Waiting for sync");
53 
54 	while (true) {
55 		if (bs_bc_is_msg_received(CHANNEL_ID) > 0) {
56 			bs_bc_receive_msg(CHANNEL_ID, sync_msg, ARRAY_SIZE(sync_msg));
57 			if (sync_msg[0] != get_device_nbr()) {
58 				/* Received a message from another device, exit */
59 				break;
60 			}
61 		}
62 
63 		k_sleep(K_MSEC(1));
64 	}
65 
66 	LOG_DBG("Sync received");
67 }
68