|
| 1 | +// Copyright 2025 Shift Crypto AG |
| 2 | +// |
| 3 | +// Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +// you may not use this file except in compliance with the License. |
| 5 | +// You may obtain a copy of the License at |
| 6 | +// |
| 7 | +// http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +// |
| 9 | +// Unless required by applicable law or agreed to in writing, software |
| 10 | +// distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +// See the License for the specific language governing permissions and |
| 13 | +// limitations under the License. |
| 14 | + |
| 15 | +#include <delay.h> |
| 16 | +#include <hal_timer.h> |
| 17 | +#include <platform/driver_init.h> |
| 18 | +#include <stdbool.h> |
| 19 | +#include <stdint.h> |
| 20 | +#include <string.h> |
| 21 | +#include <util.h> |
| 22 | +#include <utils_assert.h> |
| 23 | + |
| 24 | +struct task { |
| 25 | + struct timer_task timer; |
| 26 | + volatile bool done; |
| 27 | +}; |
| 28 | + |
| 29 | +static struct task _tasks[10] = {0}; |
| 30 | + |
| 31 | +static void _hal_timer_cb(const struct timer_task* const timer) |
| 32 | +{ |
| 33 | + for (size_t i = 0; i < COUNT_OF(_tasks); i++) { |
| 34 | + if (&_tasks[i].timer == timer) { |
| 35 | + _tasks[i].done = true; |
| 36 | + } |
| 37 | + } |
| 38 | +} |
| 39 | + |
| 40 | +bool delay_init_ms(delay_t* self, uint32_t ms) |
| 41 | +{ |
| 42 | + // find an unused slot in tasks |
| 43 | + size_t i; |
| 44 | + CRITICAL_SECTION_ENTER(); |
| 45 | + for (i = 0; i < COUNT_OF(_tasks); i++) { |
| 46 | + if (_tasks[i].timer.cb == NULL) { |
| 47 | + break; |
| 48 | + } |
| 49 | + } |
| 50 | + CRITICAL_SECTION_LEAVE(); |
| 51 | + if (i == COUNT_OF(_tasks)) { |
| 52 | + return false; |
| 53 | + } |
| 54 | + _tasks[i].done = false; |
| 55 | + memset(&_tasks[i], 0, sizeof(struct task)); |
| 56 | + _tasks[i].timer.interval = ms; |
| 57 | + _tasks[i].timer.cb = _hal_timer_cb; |
| 58 | + _tasks[i].timer.mode = TIMER_TASK_ONE_SHOT; |
| 59 | + self->id = i; |
| 60 | + return true; |
| 61 | +} |
| 62 | + |
| 63 | +void delay_start(const delay_t* self) |
| 64 | +{ |
| 65 | + ASSERT(self->id < COUNT_OF(_tasks)); |
| 66 | + ASSERT(!_tasks[self->id].done); |
| 67 | + timer_add_task(&TIMER_0, &_tasks[self->id].timer); |
| 68 | +} |
| 69 | + |
| 70 | +bool delay_poll(const delay_t* self) |
| 71 | +{ |
| 72 | + ASSERT(self->id < COUNT_OF(_tasks)); |
| 73 | + if (_tasks[self->id].done) { |
| 74 | + memset(&_tasks[self->id], 0, sizeof(struct task)); |
| 75 | + return true; |
| 76 | + } |
| 77 | + return false; |
| 78 | +} |
0 commit comments