1 /*
2  * Copyright (c) 2024 BayLibre SAS
3  *
4  * SPDX-License-Identifier: Apache-2.0
5  */
6 
7 #include <zephyr/logging/log.h>
8 LOG_MODULE_REGISTER(net_ptp_sample, LOG_LEVEL_DBG);
9 
10 #include <zephyr/kernel.h>
11 
12 #include <errno.h>
13 #include <stdlib.h>
14 
15 #include "ptp/clock.h"
16 #include "ptp/port.h"
17 
18 static int run_duration = CONFIG_NET_SAMPLE_RUN_DURATION;
19 static struct k_work_delayable stop_sample;
20 static struct k_sem quit_lock;
21 
stop_handler(struct k_work * work)22 static void stop_handler(struct k_work *work)
23 {
24 	ARG_UNUSED(work);
25 
26 	k_sem_give(&quit_lock);
27 }
28 
get_current_status(void)29 static int get_current_status(void)
30 {
31 	struct ptp_port *port;
32 	sys_slist_t *ports_list = ptp_clock_ports_list();
33 
34 	if (!ports_list || sys_slist_len(ports_list) == 0) {
35 		return -EINVAL;
36 	}
37 
38 	port = CONTAINER_OF(sys_slist_peek_head(ports_list), struct ptp_port, node);
39 
40 	if (!port) {
41 		return -EINVAL;
42 	}
43 
44 	switch (ptp_port_state(port)) {
45 	case PTP_PS_INITIALIZING:
46 	case PTP_PS_FAULTY:
47 	case PTP_PS_DISABLED:
48 	case PTP_PS_LISTENING:
49 	case PTP_PS_PRE_TIME_TRANSMITTER:
50 	case PTP_PS_PASSIVE:
51 	case PTP_PS_UNCALIBRATED:
52 		printk("FAIL\n");
53 		return 0;
54 	case PTP_PS_TIME_RECEIVER:
55 		printk("TIME RECEIVER\n");
56 		return 2;
57 	case PTP_PS_TIME_TRANSMITTER:
58 	case PTP_PS_GRAND_MASTER:
59 		printk("TIME TRANSMITTER\n");
60 		return 1;
61 	}
62 
63 	return -1;
64 }
65 
init_testing(void)66 void init_testing(void)
67 {
68 	uint32_t uptime = k_uptime_get_32();
69 	int ret;
70 
71 	if (run_duration == 0) {
72 		return;
73 	}
74 
75 	k_sem_init(&quit_lock, 0, K_SEM_MAX_LIMIT);
76 
77 	k_work_init_delayable(&stop_sample, stop_handler);
78 	k_work_reschedule(&stop_sample, K_SECONDS(run_duration));
79 
80 	k_sem_take(&quit_lock, K_FOREVER);
81 
82 	LOG_INF("Stopping after %u seconds",
83 		(k_uptime_get_32() - uptime) / 1000);
84 
85 	/* Try to figure out what is the sync state.
86 	 * Return:
87 	 *  <0 - configuration error
88 	 *   0 - not time sync
89 	 *   1 - we are TimeTransmitter
90 	 *   2 - we are TimeReceiver
91 	 */
92 	ret = get_current_status();
93 
94 	exit(ret);
95 }
96 
main(void)97 int main(void)
98 {
99 	init_testing();
100 	return 0;
101 }
102