|
| 1 | +// Package freertos provides a compatibility layer on top of the TinyGo |
| 2 | +// scheduler for C code that wants to call FreeRTOS functions. One example is |
| 3 | +// the ESP-IDF, which expects there to be a FreeRTOS-like RTOS. |
| 4 | +package freertos |
| 5 | + |
| 6 | +// #include <freertos/FreeRTOS.h> |
| 7 | +// #include <freertos/semphr.h> |
| 8 | +import "C" |
| 9 | +import ( |
| 10 | + "sync" |
| 11 | + "unsafe" |
| 12 | + |
| 13 | + "internal/task" |
| 14 | +) |
| 15 | + |
| 16 | +type Semaphore struct { |
| 17 | + lock sync.Mutex // the lock itself |
| 18 | + task *task.Task // the task currently locking this semaphore |
| 19 | + count uint32 // how many times this semaphore is locked |
| 20 | +} |
| 21 | + |
| 22 | +//export xSemaphoreCreateRecursiveMutex |
| 23 | +func xSemaphoreCreateRecursiveMutex() C.SemaphoreHandle_t { |
| 24 | + var mutex Semaphore |
| 25 | + return (C.SemaphoreHandle_t)(unsafe.Pointer(&mutex)) |
| 26 | +} |
| 27 | + |
| 28 | +//export vSemaphoreDelete |
| 29 | +func vSemaphoreDelete(xSemaphore C.SemaphoreHandle_t) { |
| 30 | + mutex := (*Semaphore)(unsafe.Pointer(xSemaphore)) |
| 31 | + if mutex.task != nil { |
| 32 | + panic("vSemaphoreDelete: still locked") |
| 33 | + } |
| 34 | +} |
| 35 | + |
| 36 | +//export xSemaphoreTakeRecursive |
| 37 | +func xSemaphoreTakeRecursive(xMutex C.SemaphoreHandle_t, xTicksToWait C.TickType_t) C.BaseType_t { |
| 38 | + // TODO: implement xTickToWait, or at least when xTicksToWait equals 0. |
| 39 | + mutex := (*Semaphore)(unsafe.Pointer(xMutex)) |
| 40 | + if mutex.task == task.Current() { |
| 41 | + // Already locked. |
| 42 | + mutex.count++ |
| 43 | + return 1 // pdTRUE |
| 44 | + } |
| 45 | + // Not yet locked. |
| 46 | + mutex.lock.Lock() |
| 47 | + mutex.task = task.Current() |
| 48 | + return 1 // pdTRUE |
| 49 | +} |
| 50 | + |
| 51 | +//export xSemaphoreGiveRecursive |
| 52 | +func xSemaphoreGiveRecursive(xMutex C.SemaphoreHandle_t) C.BaseType_t { |
| 53 | + mutex := (*Semaphore)(unsafe.Pointer(xMutex)) |
| 54 | + if mutex.task == task.Current() { |
| 55 | + // Already locked. |
| 56 | + mutex.count-- |
| 57 | + if mutex.count == 0 { |
| 58 | + mutex.lock.Unlock() |
| 59 | + } |
| 60 | + return 1 // pdTRUE |
| 61 | + } |
| 62 | + panic("xSemaphoreGiveRecursive: not locked by this task") |
| 63 | +} |
0 commit comments