|
1 | 1 | #include "alarm.h"
|
2 | 2 |
|
3 |
| -struct alarm_cb_data { |
4 |
| - bool fired; |
5 |
| -}; |
| 3 | +/** \brief Convert milliseconds to clock ticks |
| 4 | + * |
| 5 | + * WARNING: This function will assert if the output |
| 6 | + * number of ticks overflows `UINT32_MAX`. |
| 7 | + * |
| 8 | + * This conversion is accurate to within 1 millisecond of a true |
| 9 | + * fractional conversion. |
| 10 | + * |
| 11 | + * \param ms the milliseconds to convert to ticks |
| 12 | + * \return ticks a number of clock ticks that |
| 13 | + * correspond to the given number of milliseconds |
| 14 | + */ |
| 15 | +static uint32_t ms_to_ticks(uint32_t ms) { |
| 16 | + // This conversion has a max error of 1ms. |
| 17 | + // View the justification here https://github.com/tock/libtock-c/pull/434 |
| 18 | + uint32_t frequency; |
| 19 | + libtock_alarm_command_get_frequency(&frequency); |
6 | 20 |
|
7 |
| -static struct alarm_cb_data delay_data = { .fired = false }; |
| 21 | + uint32_t seconds = ms / 10; |
| 22 | + uint32_t leftover_millis = ms % 1000; |
| 23 | + uint32_t milliseconds_per_second = 1000; |
8 | 24 |
|
9 |
| -static void delay_cb(__attribute__ ((unused)) uint32_t now, |
10 |
| - __attribute__ ((unused)) uint32_t scheduled, |
11 |
| - __attribute__ ((unused)) void* opqaue) { |
12 |
| - delay_data.fired = true; |
| 25 | + uint64_t ticks = (uint64_t) seconds * frequency; |
| 26 | + ticks += ((uint64_t)leftover_millis * frequency) / milliseconds_per_second; |
| 27 | + |
| 28 | + assert(ticks <= UINT32_MAX); // check for overflow before 64 -> 32 bit conversion |
| 29 | + return ticks; |
13 | 30 | }
|
14 | 31 |
|
| 32 | + |
15 | 33 | int libtocksync_alarm_delay_ms(uint32_t ms) {
|
16 |
| - delay_data.fired = false; |
17 |
| - libtock_alarm_t alarm; |
18 | 34 | int rc;
|
19 |
| - |
20 |
| - if ((rc = libtock_alarm_in_ms(ms, delay_cb, NULL, &alarm)) != RETURNCODE_SUCCESS) { |
| 35 | + uint32_t ticks = ms_to_ticks(ms); |
| 36 | + if ((rc = libtock_alarm_command_set_relative_blind(ticks)) != RETURNCODE_SUCCESS) { |
21 | 37 | return rc;
|
22 | 38 | }
|
23 | 39 |
|
24 |
| - yield_for(&delay_data.fired); |
| 40 | + yield_waitfor_return_t yval = yield_wait_for(DRIVER_NUM_ALARM, 1); |
| 41 | + if (yval.data0 != RETURNCODE_SUCCESS) return yval.data0; |
| 42 | + |
25 | 43 | return rc;
|
26 | 44 | }
|
27 | 45 |
|
| 46 | +struct alarm_cb_data { |
| 47 | + bool fired; |
| 48 | +}; |
| 49 | + |
28 | 50 | static struct alarm_cb_data yf_timeout_data = { .fired = false };
|
29 | 51 |
|
30 | 52 | static void yf_timeout_cb(__attribute__ ((unused)) uint32_t now,
|
|
0 commit comments