valuemutex.c 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. #include "valuemutex.h"
  2. #include <string.h>
  3. bool init_mutex(ValueMutex* valuemutex, void* value, size_t size) {
  4. // mutex without name,
  5. // no attributes (unfortunatly robust mutex is not supported by FreeRTOS),
  6. // with dynamic memory allocation
  7. const osMutexAttr_t value_mutext_attr = {
  8. .name = NULL, .attr_bits = 0, .cb_mem = NULL, .cb_size = 0U};
  9. valuemutex->mutex = osMutexNew(&value_mutext_attr);
  10. if(valuemutex->mutex == NULL) return false;
  11. valuemutex->value = value;
  12. valuemutex->size = size;
  13. return true;
  14. }
  15. void* acquire_mutex(ValueMutex* valuemutex, uint32_t timeout) {
  16. if(osMutexAcquire(valuemutex->mutex, timeout) == osOK) {
  17. return valuemutex->value;
  18. } else {
  19. return NULL;
  20. }
  21. }
  22. bool release_mutex(ValueMutex* valuemutex, void* value) {
  23. if(value != valuemutex->value) return false;
  24. if(osMutexRelease(valuemutex->mutex) != osOK) return false;
  25. return true;
  26. }
  27. bool read_mutex(ValueMutex* valuemutex, void* data, size_t len, uint32_t timeout) {
  28. void* value = acquire_mutex(valuemutex, timeout);
  29. if(value == NULL || len > valuemutex->size) return false;
  30. memcpy(data, value, len > 0 ? len : valuemutex->size);
  31. if(!release_mutex(valuemutex, value)) return false;
  32. return true;
  33. }
  34. bool write_mutex(ValueMutex* valuemutex, void* data, size_t len, uint32_t timeout) {
  35. void* value = acquire_mutex(valuemutex, timeout);
  36. if(value == NULL || len > valuemutex->size) return false;
  37. memcpy(value, data, len > 0 ? len : valuemutex->size);
  38. if(!release_mutex(valuemutex, value)) return false;
  39. return true;
  40. }