1 /*
2  * Copyright (c) 2019 Manivannan Sadhasivam
3  *
4  * SPDX-License-Identifier: Apache-2.0
5  */
6 
7 #include <zephyr.h>
8 
9 #include <timer.h>
10 
11 static void timer_work_handler(struct k_work *work);
12 K_WORK_DEFINE(timer_work, timer_work_handler);
13 
14 static uint32_t saved_time;
15 /* TODO: Use Non-volatile memory for backup */
16 static volatile uint32_t backup_reg[2];
17 
timer_work_handler(struct k_work * work)18 static void timer_work_handler(struct k_work *work)
19 {
20 	TimerIrqHandler();
21 }
22 
timer_callback(struct k_timer * _timer)23 static void timer_callback(struct k_timer *_timer)
24 {
25 	ARG_UNUSED(_timer);
26 
27 	k_work_submit(&timer_work);
28 }
29 
30 K_TIMER_DEFINE(lora_timer, timer_callback, NULL);
31 
RtcBkupWrite(uint32_t data0,uint32_t data1)32 void RtcBkupWrite(uint32_t data0, uint32_t data1)
33 {
34 	backup_reg[0] = data0;
35 	backup_reg[1] = data1;
36 }
37 
RtcBkupRead(uint32_t * data0,uint32_t * data1)38 void RtcBkupRead(uint32_t *data0, uint32_t *data1)
39 {
40 	*data0 = backup_reg[0];
41 	*data1 = backup_reg[1];
42 }
43 
RtcGetCalendarTime(uint16_t * milliseconds)44 uint32_t RtcGetCalendarTime(uint16_t *milliseconds)
45 {
46 	uint32_t now = k_uptime_get_32();
47 
48 	*milliseconds = now;
49 
50 	/* Return in seconds */
51 	return now / MSEC_PER_SEC;
52 }
53 
RtcGetTimerValue(void)54 uint32_t RtcGetTimerValue(void)
55 {
56 	return k_uptime_get_32();
57 }
58 
RtcGetTimerElapsedTime(void)59 uint32_t RtcGetTimerElapsedTime(void)
60 {
61 	return (k_uptime_get_32() - saved_time);
62 }
63 
RtcGetMinimumTimeout(void)64 uint32_t RtcGetMinimumTimeout(void)
65 {
66 	return 1;
67 }
68 
RtcStopAlarm(void)69 void RtcStopAlarm(void)
70 {
71 	k_timer_stop(&lora_timer);
72 }
73 
RtcSetAlarm(uint32_t timeout)74 void RtcSetAlarm(uint32_t timeout)
75 {
76 	k_timer_start(&lora_timer, K_MSEC(timeout), K_NO_WAIT);
77 }
78 
RtcSetTimerContext(void)79 uint32_t RtcSetTimerContext(void)
80 {
81 	saved_time = k_uptime_get_32();
82 
83 	return saved_time;
84 }
85 
86 /* For us, 1 tick = 1 milli second. So no need to do any conversion here */
RtcGetTimerContext(void)87 uint32_t RtcGetTimerContext(void)
88 {
89 	return saved_time;
90 }
91 
DelayMsMcu(uint32_t ms)92 void DelayMsMcu(uint32_t ms)
93 {
94 	k_sleep(K_MSEC(ms));
95 }
96 
RtcMs2Tick(uint32_t milliseconds)97 uint32_t RtcMs2Tick(uint32_t milliseconds)
98 {
99 	return milliseconds;
100 }
101 
RtcTick2Ms(uint32_t tick)102 uint32_t RtcTick2Ms(uint32_t tick)
103 {
104 	return tick;
105 }
106 
BoardCriticalSectionBegin(uint32_t * mask)107 void BoardCriticalSectionBegin(uint32_t *mask)
108 {
109 	*mask = irq_lock();
110 }
111 
BoardCriticalSectionEnd(uint32_t * mask)112 void BoardCriticalSectionEnd(uint32_t *mask)
113 {
114 	irq_unlock(*mask);
115 }
116