2021-03-09 21:25:22 +01:00
|
|
|
#ifndef FRAMEWORK_IPC_MUTEXGUARD_H_
|
|
|
|
#define FRAMEWORK_IPC_MUTEXGUARD_H_
|
2018-07-13 18:28:26 +02:00
|
|
|
|
2022-05-08 21:45:51 +02:00
|
|
|
#include <fmt/core.h>
|
|
|
|
|
|
|
|
#include "fsfw/ipc/MutexIF.h"
|
|
|
|
#include "fsfw/serviceinterface.h"
|
2018-07-13 18:28:26 +02:00
|
|
|
|
2021-03-09 11:25:13 +01:00
|
|
|
class MutexGuard {
|
2022-02-02 10:29:30 +01:00
|
|
|
public:
|
|
|
|
MutexGuard(MutexIF* mutex, MutexIF::TimeoutType timeoutType = MutexIF::TimeoutType::BLOCKING,
|
|
|
|
uint32_t timeoutMs = 0)
|
|
|
|
: internalMutex(mutex) {
|
|
|
|
if (mutex == nullptr) {
|
2022-05-08 21:45:51 +02:00
|
|
|
// It's tricky to use the error functions defined in the service interface
|
|
|
|
// because those functions require the mutex guard themselves
|
|
|
|
fmt::print("ERROR | Passed mutex is invalid\n");
|
2022-02-02 10:29:30 +01:00
|
|
|
return;
|
|
|
|
}
|
|
|
|
result = mutex->lockMutex(timeoutType, timeoutMs);
|
|
|
|
if (result == MutexIF::MUTEX_TIMEOUT) {
|
2022-05-08 21:45:51 +02:00
|
|
|
fmt::print("ERROR | Lock of mutex failed with timeout of {} milliseconds\n", timeoutMs);
|
2022-02-02 10:29:30 +01:00
|
|
|
} else if (result != HasReturnvaluesIF::RETURN_OK) {
|
2022-05-08 21:45:51 +02:00
|
|
|
fmt::print("ERROR | Lock of Mutex failed with code {}\n", result);
|
2022-02-02 10:29:30 +01:00
|
|
|
}
|
|
|
|
}
|
2021-02-23 14:40:08 +01:00
|
|
|
|
2022-02-02 10:29:30 +01:00
|
|
|
ReturnValue_t getLockResult() const { return result; }
|
2021-03-09 11:25:13 +01:00
|
|
|
|
2022-02-02 10:29:30 +01:00
|
|
|
~MutexGuard() {
|
|
|
|
if (internalMutex != nullptr) {
|
|
|
|
internalMutex->unlockMutex();
|
2021-02-23 14:40:08 +01:00
|
|
|
}
|
2022-02-02 10:29:30 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
private:
|
|
|
|
MutexIF* internalMutex;
|
|
|
|
ReturnValue_t result = HasReturnvaluesIF::RETURN_FAILED;
|
2018-07-13 18:28:26 +02:00
|
|
|
};
|
2021-02-23 14:40:08 +01:00
|
|
|
|
2021-03-09 21:25:22 +01:00
|
|
|
#endif /* FRAMEWORK_IPC_MUTEXGUARD_H_ */
|