1 /*
2 * Copyright (c) 2020 Intel Corporation.
3 *
4 * SPDX-License-Identifier: Apache-2.0
5 */
6
7 #include <zephyr/logging/log.h>
8 LOG_MODULE_DECLARE(net_gptp_sample);
9
10 #include <zephyr/kernel.h>
11 #include <errno.h>
12 #include <stdlib.h>
13
14 #include <zephyr/net/net_core.h>
15 #include <zephyr/net/gptp.h>
16
17 #include "ethernet/gptp/gptp_messages.h"
18 #include "ethernet/gptp/gptp_data_set.h"
19
20 static int run_duration = CONFIG_NET_SAMPLE_RUN_DURATION;
21 static struct k_work_delayable stop_sample;
22 static struct k_sem quit_lock;
23
stop_handler(struct k_work * work)24 static void stop_handler(struct k_work *work)
25 {
26 ARG_UNUSED(work);
27
28 k_sem_give(&quit_lock);
29 }
30
get_current_status(void)31 static int get_current_status(void)
32 {
33 struct gptp_domain *domain;
34 struct gptp_port_ds *port_ds;
35 int ret, port;
36
37 port = 1;
38
39 domain = gptp_get_domain();
40
41 ret = gptp_get_port_data(domain, port, &port_ds,
42 NULL, NULL, NULL, NULL);
43 if (ret < 0) {
44 LOG_WRN("Cannot get gPTP information for port %d (%d)",
45 port, ret);
46 return ret;
47 }
48
49 if (port != port_ds->port_id.port_number) {
50 return -EINVAL;
51 }
52
53 switch (GPTP_GLOBAL_DS()->selected_role[port]) {
54 case GPTP_PORT_INITIALIZING:
55 case GPTP_PORT_FAULTY:
56 case GPTP_PORT_DISABLED:
57 case GPTP_PORT_LISTENING:
58 case GPTP_PORT_PRE_MASTER:
59 case GPTP_PORT_PASSIVE:
60 case GPTP_PORT_UNCALIBRATED:
61 printk("FAIL\n");
62 return 0;
63 case GPTP_PORT_MASTER:
64 printk("MASTER\n");
65 return 1;
66 case GPTP_PORT_SLAVE:
67 printk("SLAVE\n");
68 return 2;
69 }
70
71 return -1;
72 }
73
init_testing(void)74 void init_testing(void)
75 {
76 uint32_t uptime = k_uptime_get_32();
77 int ret;
78
79 if (run_duration == 0) {
80 return;
81 }
82
83 k_sem_init(&quit_lock, 0, K_SEM_MAX_LIMIT);
84
85 k_work_init_delayable(&stop_sample, stop_handler);
86 k_work_reschedule(&stop_sample, K_SECONDS(run_duration));
87
88 k_sem_take(&quit_lock, K_FOREVER);
89
90 LOG_INF("Stopping after %u seconds",
91 (k_uptime_get_32() - uptime) / 1000);
92
93 /* Try to figure out what is the sync state.
94 * Return:
95 * <0 - configuration error
96 * 0 - not time sync
97 * 1 - we are MASTER
98 * 2 - we are SLAVE
99 */
100 ret = get_current_status();
101
102 exit(ret);
103 }
104