valuemutex.c 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  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. valuemutex->mutex = osMutexNew(NULL);
  8. if(valuemutex->mutex == NULL) return false;
  9. valuemutex->value = value;
  10. valuemutex->size = size;
  11. return true;
  12. }
  13. bool delete_mutex(ValueMutex* valuemutex) {
  14. if(osMutexAcquire(valuemutex->mutex, osWaitForever) == osOK) {
  15. return osMutexDelete(valuemutex->mutex) == osOK;
  16. } else {
  17. return false;
  18. }
  19. }
  20. void* acquire_mutex(ValueMutex* valuemutex, uint32_t timeout) {
  21. if(osMutexAcquire(valuemutex->mutex, timeout) == osOK) {
  22. return valuemutex->value;
  23. } else {
  24. return NULL;
  25. }
  26. }
  27. bool release_mutex(ValueMutex* valuemutex, const void* value) {
  28. if(value != valuemutex->value) return false;
  29. if(osMutexRelease(valuemutex->mutex) != osOK) return false;
  30. return true;
  31. }
  32. bool read_mutex(ValueMutex* valuemutex, void* data, size_t len, uint32_t timeout) {
  33. void* value = acquire_mutex(valuemutex, timeout);
  34. if(value == NULL || len > valuemutex->size) return false;
  35. memcpy(data, value, len > 0 ? len : valuemutex->size);
  36. if(!release_mutex(valuemutex, value)) return false;
  37. return true;
  38. }
  39. bool write_mutex(ValueMutex* valuemutex, void* data, size_t len, uint32_t timeout) {
  40. void* value = acquire_mutex(valuemutex, timeout);
  41. if(value == NULL || len > valuemutex->size) return false;
  42. memcpy(value, data, len > 0 ? len : valuemutex->size);
  43. if(!release_mutex(valuemutex, value)) return false;
  44. return true;
  45. }