1 /*
2  * Copyright (c) 2019 Vestas Wind Systems A/S
3  *
4  * SPDX-License-Identifier: Apache-2.0
5  */
6 
7 #include <CANopen.h>
8 
9 /**
10  * @brief CANopen sync thread.
11  *
12  * The CANopen real-time sync thread processes SYNC RPDOs and TPDOs
13  * through the CANopenNode stack with an interval of 1 millisecond.
14  *
15  * @param p1 Unused
16  * @param p2 Unused
17  * @param p3 Unused
18  */
canopen_sync_thread(void * p1,void * p2,void * p3)19 static void canopen_sync_thread(void *p1, void *p2, void *p3)
20 {
21 	uint32_t start; /* cycles */
22 	uint32_t stop;  /* cycles */
23 	uint32_t delta; /* cycles */
24 	uint32_t elapsed = 0; /* microseconds */
25 	bool sync;
26 
27 	ARG_UNUSED(p1);
28 	ARG_UNUSED(p2);
29 	ARG_UNUSED(p3);
30 
31 	while (true) {
32 		start = k_cycle_get_32();
33 		if (CO && CO->CANmodule[0] && CO->CANmodule[0]->CANnormal) {
34 			CO_LOCK_OD();
35 			sync = CO_process_SYNC(CO, elapsed);
36 			CO_process_RPDO(CO, sync);
37 			CO_process_TPDO(CO, sync, elapsed);
38 			CO_UNLOCK_OD();
39 		}
40 
41 		k_sleep(K_MSEC(1));
42 		stop = k_cycle_get_32();
43 		delta = stop - start;
44 		elapsed = (uint32_t)k_cyc_to_ns_floor64(delta) / NSEC_PER_USEC;
45 	}
46 }
47 
48 K_THREAD_DEFINE(canopen_sync, CONFIG_CANOPENNODE_SYNC_THREAD_STACK_SIZE,
49 		canopen_sync_thread, NULL, NULL, NULL,
50 		CONFIG_CANOPENNODE_SYNC_THREAD_PRIORITY, 0, 1);
51