Merge remote-tracking branch 'upstream/source/master' into mueller/prototyping

This commit is contained in:
Robin Müller 2020-08-04 14:28:48 +02:00
commit e03007bd72
286 changed files with 11088 additions and 4604 deletions

View File

@ -16,7 +16,7 @@ ReturnValue_t ActionHelper::handleActionMessage(CommandMessage* command) {
ActionMessage::getStoreId(command));
return HasReturnvaluesIF::RETURN_OK;
} else {
return CommandMessage::UNKNOW_COMMAND;
return CommandMessage::UNKNOWN_COMMAND;
}
}
@ -85,7 +85,7 @@ ReturnValue_t ActionHelper::reportData(MessageQueueId_t reportTo,
if (result != HasReturnvaluesIF::RETURN_OK) {
return result;
}
result = data->serialize(&dataPtr, &size, maxSize, true);
result = data->serialize(&dataPtr, &size, maxSize, SerializeIF::Endianness::BIG);
if (result != HasReturnvaluesIF::RETURN_OK) {
ipcStore->deleteData(storeAddress);
return result;

View File

@ -10,7 +10,7 @@ class ActionMessage {
private:
ActionMessage();
public:
static const uint8_t MESSAGE_ID = MESSAGE_TYPE::ACTION;
static const uint8_t MESSAGE_ID = messagetypes::ACTION;
static const Command_t EXECUTE_ACTION = MAKE_COMMAND_ID(1);
static const Command_t STEP_SUCCESS = MAKE_COMMAND_ID(2);
static const Command_t STEP_FAILED = MAKE_COMMAND_ID(3);

View File

@ -4,22 +4,22 @@
#include <framework/action/HasActionsIF.h>
#include <framework/objectmanager/ObjectManagerIF.h>
CommandActionHelper::CommandActionHelper(CommandsActionsIF* setOwner) :
CommandActionHelper::CommandActionHelper(CommandsActionsIF *setOwner) :
owner(setOwner), queueToUse(NULL), ipcStore(
NULL), commandCount(0), lastTarget(0) {
NULL), commandCount(0), lastTarget(0) {
}
CommandActionHelper::~CommandActionHelper() {
}
ReturnValue_t CommandActionHelper::commandAction(object_id_t commandTo,
ActionId_t actionId, SerializeIF* data) {
HasActionsIF* receiver = objectManager->get<HasActionsIF>(commandTo);
ActionId_t actionId, SerializeIF *data) {
HasActionsIF *receiver = objectManager->get<HasActionsIF>(commandTo);
if (receiver == NULL) {
return CommandsActionsIF::OBJECT_HAS_NO_FUNCTIONS;
}
store_address_t storeId;
uint8_t* storePointer;
uint8_t *storePointer;
size_t maxSize = data->getSerializedSize();
ReturnValue_t result = ipcStore->getFreeElement(&storeId, maxSize,
&storePointer);
@ -27,7 +27,8 @@ ReturnValue_t CommandActionHelper::commandAction(object_id_t commandTo,
return result;
}
size_t size = 0;
result = data->serialize(&storePointer, &size, maxSize, true);
result = data->serialize(&storePointer, &size, maxSize,
SerializeIF::Endianness::BIG);
if (result != HasReturnvaluesIF::RETURN_OK) {
return result;
}
@ -35,11 +36,11 @@ ReturnValue_t CommandActionHelper::commandAction(object_id_t commandTo,
}
ReturnValue_t CommandActionHelper::commandAction(object_id_t commandTo,
ActionId_t actionId, const uint8_t* data, uint32_t size) {
ActionId_t actionId, const uint8_t *data, uint32_t size) {
// if (commandCount != 0) {
// return CommandsFunctionsIF::ALREADY_COMMANDING;
// }
HasActionsIF* receiver = objectManager->get<HasActionsIF>(commandTo);
HasActionsIF *receiver = objectManager->get<HasActionsIF>(commandTo);
if (receiver == NULL) {
return CommandsActionsIF::OBJECT_HAS_NO_FUNCTIONS;
}
@ -71,13 +72,13 @@ ReturnValue_t CommandActionHelper::initialize() {
}
queueToUse = owner->getCommandQueuePtr();
if(queueToUse == NULL){
if (queueToUse == NULL) {
return HasReturnvaluesIF::RETURN_FAILED;
}
return HasReturnvaluesIF::RETURN_OK;
}
ReturnValue_t CommandActionHelper::handleReply(CommandMessage* reply) {
ReturnValue_t CommandActionHelper::handleReply(CommandMessage *reply) {
if (reply->getSender() != lastTarget) {
return HasReturnvaluesIF::RETURN_FAILED;
}
@ -88,7 +89,8 @@ ReturnValue_t CommandActionHelper::handleReply(CommandMessage* reply) {
return HasReturnvaluesIF::RETURN_OK;
case ActionMessage::COMPLETION_FAILED:
commandCount--;
owner->completionFailedReceived(ActionMessage::getActionId(reply), ActionMessage::getReturnCode(reply));
owner->completionFailedReceived(ActionMessage::getActionId(reply),
ActionMessage::getReturnCode(reply));
return HasReturnvaluesIF::RETURN_OK;
case ActionMessage::STEP_SUCCESS:
owner->stepSuccessfulReceived(ActionMessage::getActionId(reply),
@ -96,11 +98,13 @@ ReturnValue_t CommandActionHelper::handleReply(CommandMessage* reply) {
return HasReturnvaluesIF::RETURN_OK;
case ActionMessage::STEP_FAILED:
commandCount--;
owner->stepFailedReceived(ActionMessage::getActionId(reply), ActionMessage::getStep(reply),
owner->stepFailedReceived(ActionMessage::getActionId(reply),
ActionMessage::getStep(reply),
ActionMessage::getReturnCode(reply));
return HasReturnvaluesIF::RETURN_OK;
case ActionMessage::DATA_REPLY:
extractDataForOwner(ActionMessage::getActionId(reply), ActionMessage::getStoreId(reply));
extractDataForOwner(ActionMessage::getActionId(reply),
ActionMessage::getStoreId(reply));
return HasReturnvaluesIF::RETURN_OK;
default:
return HasReturnvaluesIF::RETURN_FAILED;

View File

@ -1,5 +1,5 @@
#ifndef HASACTIONSIF_H_
#define HASACTIONSIF_H_
#ifndef FRAMEWORK_ACTION_HASACTIONSIF_H_
#define FRAMEWORK_ACTION_HASACTIONSIF_H_
#include <framework/action/ActionHelper.h>
#include <framework/action/ActionMessage.h>
@ -11,27 +11,31 @@
* Interface for component which uses actions
*
* @details
* This interface is used to execute actions in the component. Actions, in the sense of this interface, are activities with a well-defined beginning and
* end in time. They may adjust sub-states of components, but are not supposed to change
* the main mode of operation, which is handled with the HasModesIF described below.
* This interface is used to execute actions in the component. Actions, in the
* sense of this interface, are activities with a well-defined beginning and
* end in time. They may adjust sub-states of components, but are not supposed
* to change the main mode of operation, which is handled with the HasModesIF
* described below.
*
* The HasActionsIF allows components to define such actions and make them available
* for other components to use. Implementing the interface is straightforward: Theres a
* single executeAction call, which provides an identifier for the action to execute, as well
* as arbitrary parameters for input. Aside from direct, software-based
* actions, it is used in device handler components as an interface to forward commands to
* devices.
* Implementing components of the interface are supposed to check identifier (ID) and
* parameters and immediately start execution of the action. It is, however, not required to
* immediately finish execution. Instead, this may be deferred to a later point in time, at
* which the component needs to inform the caller about finished or failed execution.
* The HasActionsIF allows components to define such actions and make them
* available for other components to use. Implementing the interface is
* straightforward: Theres a single executeAction call, which provides an
* identifier for the action to execute, as well as arbitrary parameters for
* input.
* Aside from direct, software-based actions, it is used in device handler
* components as an interface to forward commands to devices.
* Implementing components of the interface are supposed to check identifier
* (ID) and parameters and immediately start execution of the action.
* It is, however, not required to immediately finish execution.
* Instead, this may be deferred to a later point in time, at which the
* component needs to inform the caller about finished or failed execution.
*
* \ingroup interfaces
* @ingroup interfaces
*/
class HasActionsIF {
public:
static const uint8_t INTERFACE_ID = CLASS_ID::HAS_ACTIONS_IF;
static const ReturnValue_t IS_BUSY = MAKE_RETURN_CODE(1);//!<
static const ReturnValue_t IS_BUSY = MAKE_RETURN_CODE(1);
static const ReturnValue_t INVALID_PARAMETERS = MAKE_RETURN_CODE(2);
static const ReturnValue_t EXECUTION_FINISHED = MAKE_RETURN_CODE(3);
static const ReturnValue_t INVALID_ACTION_ID = MAKE_RETURN_CODE(4);
@ -43,13 +47,14 @@ public:
virtual MessageQueueId_t getCommandQueue() const = 0;
/**
* Execute or initialize the execution of a certain function.
* Returning #EXECUTION_FINISHED or a failure code, nothing else needs to be done.
* When needing more steps, return RETURN_OK and issue steps and completion manually.
* Returning #EXECUTION_FINISHED or a failure code, nothing else needs to
* be done. When needing more steps, return RETURN_OK and issue steps and
* completion manually.
* One "step failed" or completion report must be issued!
*/
virtual ReturnValue_t executeAction(ActionId_t actionId, MessageQueueId_t commandedBy,
const uint8_t* data, size_t size) = 0;
virtual ReturnValue_t executeAction(ActionId_t actionId,
MessageQueueId_t commandedBy, const uint8_t* data, size_t size) = 0;
};
#endif /* HASACTIONSIF_H_ */
#endif /* FRAMEWORK_ACTION_HASACTIONSIF_H_ */

View File

@ -1,5 +1,5 @@
#ifndef ARRAYLIST_H_
#define ARRAYLIST_H_
#ifndef FRAMEWORK_CONTAINER_ARRAYLIST_H_
#define FRAMEWORK_CONTAINER_ARRAYLIST_H_
#include <framework/returnvalues/HasReturnvaluesIF.h>
#include <framework/serialize/SerializeAdapter.h>
@ -7,8 +7,9 @@
/**
* @brief A List that stores its values in an array.
* @details The backend is an array that can be allocated
* by the class itself or supplied via ctor.
* @details
* The underlying storage is an array that can be allocated by the class
* itself or supplied via ctor.
*
* @ingroup container
*/
@ -19,81 +20,13 @@ public:
static const uint8_t INTERFACE_ID = CLASS_ID::ARRAY_LIST;
static const ReturnValue_t FULL = MAKE_RETURN_CODE(0x01);
/**
* An Iterator to go trough an ArrayList
*
* It stores a pointer to an element and increments the
* pointer when incremented itself.
*/
class Iterator {
public:
/**
* Empty ctor, points to NULL
*/
Iterator() :
value(0) {
}
/**
* Initializes the Iterator to point to an element
*
* @param initialize
*/
Iterator(T *initialize) {
value = initialize;
}
/**
* The current element the iterator points to
*/
T *value;
Iterator& operator++() {
value++;
return *this;
}
Iterator operator++(int) {
Iterator tmp(*this);
operator++();
return tmp;
}
Iterator& operator--() {
value--;
return *this;
}
Iterator operator--(int) {
Iterator tmp(*this);
operator--();
return tmp;
}
T operator*() {
return *value;
}
T *operator->() {
return value;
}
const T *operator->() const{
return value;
}
//SHOULDDO this should be implemented as non-member
bool operator==(const typename ArrayList<T, count_t>::Iterator& other) const{
return (value == other.value);
}
//SHOULDDO this should be implemented as non-member
bool operator!=(const typename ArrayList<T, count_t>::Iterator& other) const {
return !(*this == other);
}
}
;
/**
* Copying is forbiden by declaring copy ctor and copy assignment deleted
* It is too ambigous in this case.
* (Allocate a new backend? Use the same? What to do in an modifying call?)
*/
ArrayList(const ArrayList& other) = delete;
const ArrayList& operator=(const ArrayList& other) = delete;
/**
* Number of Elements stored in this List
@ -134,6 +67,78 @@ public:
}
}
/**
* An Iterator to go trough an ArrayList
*
* It stores a pointer to an element and increments the
* pointer when incremented itself.
*/
class Iterator {
public:
/**
* Empty ctor, points to NULL
*/
Iterator(): value(0) {}
/**
* Initializes the Iterator to point to an element
*
* @param initialize
*/
Iterator(T *initialize) {
value = initialize;
}
/**
* The current element the iterator points to
*/
T *value;
Iterator& operator++() {
value++;
return *this;
}
Iterator operator++(int) {
Iterator tmp(*this);
operator++();
return tmp;
}
Iterator& operator--() {
value--;
return *this;
}
Iterator operator--(int) {
Iterator tmp(*this);
operator--();
return tmp;
}
T operator*() {
return *value;
}
T *operator->() {
return value;
}
const T *operator->() const{
return value;
}
//SHOULDDO this should be implemented as non-member
bool operator==(const typename ArrayList<T, count_t>::Iterator& other) const{
return (value == other.value);
}
//SHOULDDO this should be implemented as non-member
bool operator!=(const typename ArrayList<T, count_t>::Iterator& other) const {
return !(*this == other);
}
};
/**
* Iterator pointing to the first stored elmement
*
@ -223,19 +228,6 @@ public:
return (maxSize_ - size);
}
private:
/**
* This is the copy constructor
*
* It is private, as copying is too ambigous in this case. (Allocate a new backend? Use the same?
* What to do in an modifying call?)
*
* @param other
*/
ArrayList(const ArrayList& other) :
size(other.size), entries(other.entries), maxSize_(other.maxSize_),
allocated(false) {}
protected:
/**
* pointer to the array in which the entries are stored

42
container/DynamicFIFO.h Normal file
View File

@ -0,0 +1,42 @@
#ifndef FRAMEWORK_CONTAINER_DYNAMICFIFO_H_
#define FRAMEWORK_CONTAINER_DYNAMICFIFO_H_
#include <framework/container/FIFOBase.h>
#include <vector>
/**
* @brief Simple First-In-First-Out data structure. The maximum size
* can be set in the constructor.
* @details
* The maximum capacity can be determined at run-time, so this container
* performs dynamic memory allocation!
* The public interface of FIFOBase exposes the user interface for the FIFO.
* @tparam T Entry Type
* @tparam capacity Maximum capacity
*/
template<typename T>
class DynamicFIFO: public FIFOBase<T> {
public:
DynamicFIFO(size_t maxCapacity): FIFOBase<T>(nullptr, maxCapacity),
fifoVector(maxCapacity) {
// trying to pass the pointer of the uninitialized vector
// to the FIFOBase constructor directly lead to a super evil bug.
// So we do it like this now.
this->setData(fifoVector.data());
};
/**
* @brief Custom copy constructor which prevents setting the
* underlying pointer wrong.
*/
DynamicFIFO(const DynamicFIFO& other): FIFOBase<T>(other),
fifoVector(other.maxCapacity) {
this->setData(fifoVector.data());
}
private:
std::vector<T> fifoVector;
};
#endif /* FRAMEWORK_CONTAINER_DYNAMICFIFO_H_ */

View File

@ -1,82 +1,34 @@
#ifndef FIFO_H_
#define FIFO_H_
#ifndef FRAMEWORK_CONTAINER_FIFO_H_
#define FRAMEWORK_CONTAINER_FIFO_H_
#include <framework/returnvalues/HasReturnvaluesIF.h>
#include <framework/container/FIFOBase.h>
#include <array>
/**
* @brief Simple First-In-First-Out data structure
* @brief Simple First-In-First-Out data structure with size fixed at
* compile time
* @details
* Performs no dynamic memory allocation.
* The public interface of FIFOBase exposes the user interface for the FIFO.
* @tparam T Entry Type
* @tparam capacity Maximum capacity
*/
template<typename T, uint8_t capacity>
class FIFO {
private:
uint8_t readIndex, writeIndex, currentSize;
T data[capacity];
uint8_t next(uint8_t current) {
++current;
if (current == capacity) {
current = 0;
}
return current;
}
template<typename T, size_t capacity>
class FIFO: public FIFOBase<T> {
public:
FIFO() :
readIndex(0), writeIndex(0), currentSize(0) {
FIFO(): FIFOBase<T>(fifoArray.data(), capacity) {};
/**
* @brief Custom copy constructor to set pointer correctly.
* @param other
*/
FIFO(const FIFO& other): FIFOBase<T>(other) {
this->setData(fifoArray.data());
}
bool empty() {
return (currentSize == 0);
}
bool full() {
return (currentSize == capacity);
}
uint8_t size(){
return currentSize;
}
ReturnValue_t insert(T value) {
if (full()) {
return FULL;
} else {
data[writeIndex] = value;
writeIndex = next(writeIndex);
++currentSize;
return HasReturnvaluesIF::RETURN_OK;
}
}
ReturnValue_t retrieve(T *value) {
if (empty()) {
return EMPTY;
} else {
*value = data[readIndex];
readIndex = next(readIndex);
--currentSize;
return HasReturnvaluesIF::RETURN_OK;
}
}
ReturnValue_t peek(T * value) {
if(empty()) {
return EMPTY;
} else {
*value = data[readIndex];
return HasReturnvaluesIF::RETURN_OK;
}
}
ReturnValue_t pop() {
T value;
return this->retrieve(&value);
}
static const uint8_t INTERFACE_ID = CLASS_ID::FIFO_CLASS;
static const ReturnValue_t FULL = MAKE_RETURN_CODE(1);
static const ReturnValue_t EMPTY = MAKE_RETURN_CODE(2);
private:
std::array<T, capacity> fifoArray;
};
#endif /* FIFO_H_ */
#endif /* FRAMEWORK_CONTAINERS_STATICFIFO_H_ */

65
container/FIFOBase.h Normal file
View File

@ -0,0 +1,65 @@
#ifndef FRAMEWORK_CONTAINER_FIFOBASE_H_
#define FRAMEWORK_CONTAINER_FIFOBASE_H_
#include <framework/returnvalues/HasReturnvaluesIF.h>
#include <cstddef>
#include <cstring>
template <typename T>
class FIFOBase {
public:
static const uint8_t INTERFACE_ID = CLASS_ID::FIFO_CLASS;
static const ReturnValue_t FULL = MAKE_RETURN_CODE(1);
static const ReturnValue_t EMPTY = MAKE_RETURN_CODE(2);
/** Default ctor, takes pointer to first entry of underlying container
* and maximum capacity */
FIFOBase(T* values, const size_t maxCapacity);
/**
* Insert value into FIFO
* @param value
* @return
*/
ReturnValue_t insert(T value);
/**
* Retrieve item from FIFO. This removes the item from the FIFO.
* @param value
* @return
*/
ReturnValue_t retrieve(T *value);
/**
* Retrieve item from FIFO without removing it from FIFO.
* @param value
* @return
*/
ReturnValue_t peek(T * value);
/**
* Remove item from FIFO.
* @return
*/
ReturnValue_t pop();
bool empty();
bool full();
size_t size();
size_t getMaxCapacity() const;
protected:
void setData(T* data);
size_t maxCapacity = 0;
T* values;
size_t readIndex = 0;
size_t writeIndex = 0;
size_t currentSize = 0;
size_t next(size_t current);
};
#include <framework/container/FIFOBase.tpp>
#endif /* FRAMEWORK_CONTAINER_FIFOBASE_H_ */

87
container/FIFOBase.tpp Normal file
View File

@ -0,0 +1,87 @@
#ifndef FRAMEWORK_CONTAINER_FIFOBASE_TPP_
#define FRAMEWORK_CONTAINER_FIFOBASE_TPP_
#ifndef FRAMEWORK_CONTAINER_FIFOBASE_H_
#error Include FIFOBase.h before FIFOBase.tpp!
#endif
template<typename T>
inline FIFOBase<T>::FIFOBase(T* values, const size_t maxCapacity):
maxCapacity(maxCapacity), values(values){};
template<typename T>
inline ReturnValue_t FIFOBase<T>::insert(T value) {
if (full()) {
return FULL;
} else {
values[writeIndex] = value;
writeIndex = next(writeIndex);
++currentSize;
return HasReturnvaluesIF::RETURN_OK;
}
};
template<typename T>
inline ReturnValue_t FIFOBase<T>::retrieve(T* value) {
if (empty()) {
return EMPTY;
} else {
*value = values[readIndex];
readIndex = next(readIndex);
--currentSize;
return HasReturnvaluesIF::RETURN_OK;
}
};
template<typename T>
inline ReturnValue_t FIFOBase<T>::peek(T* value) {
if(empty()) {
return EMPTY;
} else {
*value = values[readIndex];
return HasReturnvaluesIF::RETURN_OK;
}
};
template<typename T>
inline ReturnValue_t FIFOBase<T>::pop() {
T value;
return this->retrieve(&value);
};
template<typename T>
inline bool FIFOBase<T>::empty() {
return (currentSize == 0);
};
template<typename T>
inline bool FIFOBase<T>::full() {
return (currentSize == maxCapacity);
}
template<typename T>
inline size_t FIFOBase<T>::size() {
return currentSize;
}
template<typename T>
inline size_t FIFOBase<T>::next(size_t current) {
++current;
if (current == maxCapacity) {
current = 0;
}
return current;
}
template<typename T>
inline size_t FIFOBase<T>::getMaxCapacity() const {
return maxCapacity;
}
template<typename T>
inline void FIFOBase<T>::setData(T *data) {
this->values = data;
}
#endif

View File

@ -164,6 +164,7 @@ public:
return theMap.maxSize();
}
bool full() {
if(_size == theMap.maxSize()) {
return true;
@ -174,15 +175,15 @@ public:
}
virtual ReturnValue_t serialize(uint8_t** buffer, size_t* size,
const size_t max_size, bool bigEndian) const {
ReturnValue_t result = SerializeAdapter<uint32_t>::serialize(&this->_size,
buffer, size, max_size, bigEndian);
size_t maxSize, Endianness streamEndianness) const {
ReturnValue_t result = SerializeAdapter::serialize(&this->_size,
buffer, size, maxSize, streamEndianness);
uint32_t i = 0;
while ((result == HasReturnvaluesIF::RETURN_OK) && (i < this->_size)) {
result = SerializeAdapter<key_t>::serialize(&theMap[i].first, buffer,
size, max_size, bigEndian);
result = SerializeAdapter<T>::serialize(&theMap[i].second, buffer, size,
max_size, bigEndian);
result = SerializeAdapter::serialize(&theMap[i].first, buffer,
size, maxSize, streamEndianness);
result = SerializeAdapter::serialize(&theMap[i].second, buffer, size,
maxSize, streamEndianness);
++i;
}
return result;
@ -193,27 +194,27 @@ public:
uint32_t i = 0;
for (i = 0; i < _size; ++i) {
printSize += SerializeAdapter<key_t>::getSerializedSize(
printSize += SerializeAdapter::getSerializedSize(
&theMap[i].first);
printSize += SerializeAdapter<T>::getSerializedSize(&theMap[i].second);
printSize += SerializeAdapter::getSerializedSize(&theMap[i].second);
}
return printSize;
}
virtual ReturnValue_t deSerialize(const uint8_t** buffer, size_t* size,
bool bigEndian) {
ReturnValue_t result = SerializeAdapter<uint32_t>::deSerialize(&this->_size,
buffer, size, bigEndian);
Endianness streamEndianness) {
ReturnValue_t result = SerializeAdapter::deSerialize(&this->_size,
buffer, size, streamEndianness);
if (this->_size > theMap.maxSize()) {
return SerializeIF::TOO_MANY_ELEMENTS;
}
uint32_t i = 0;
while ((result == HasReturnvaluesIF::RETURN_OK) && (i < this->_size)) {
result = SerializeAdapter<key_t>::deSerialize(&theMap[i].first, buffer,
size, bigEndian);
result = SerializeAdapter<T>::deSerialize(&theMap[i].second, buffer, size,
bigEndian);
result = SerializeAdapter::deSerialize(&theMap[i].first, buffer,
size, streamEndianness);
result = SerializeAdapter::deSerialize(&theMap[i].second, buffer, size,
streamEndianness);
++i;
}
return result;

View File

@ -1,5 +1,5 @@
#ifndef HYBRIDITERATOR_H_
#define HYBRIDITERATOR_H_
#ifndef FRAMEWORK_CONTAINER_HYBRIDITERATOR_H_
#define FRAMEWORK_CONTAINER_HYBRIDITERATOR_H_
#include <framework/container/ArrayList.h>
#include <framework/container/SinglyLinkedList.h>
@ -8,34 +8,32 @@ template<typename T, typename count_t = uint8_t>
class HybridIterator: public LinkedElement<T>::Iterator,
public ArrayList<T, count_t>::Iterator {
public:
HybridIterator() :
value(NULL), linked(NULL), end(NULL) {
}
HybridIterator() {}
HybridIterator(typename LinkedElement<T>::Iterator *iter) :
LinkedElement<T>::Iterator(*iter), value(
iter->value), linked(true), end(NULL) {
LinkedElement<T>::Iterator(*iter), value(iter->value),
linked(true) {
}
HybridIterator(LinkedElement<T> *start) :
LinkedElement<T>::Iterator(start), value(
start->value), linked(true), end(NULL) {
LinkedElement<T>::Iterator(start), value(start->value),
linked(true) {
}
HybridIterator(typename ArrayList<T, count_t>::Iterator start,
typename ArrayList<T, count_t>::Iterator end) :
ArrayList<T, count_t>::Iterator(start), value(start.value), linked(
false), end(end.value) {
ArrayList<T, count_t>::Iterator(start), value(start.value),
linked(false), end(end.value) {
if (value == this->end) {
value = NULL;
}
}
HybridIterator(T *firstElement, T *lastElement) :
ArrayList<T, count_t>::Iterator(firstElement), value(firstElement), linked(
false), end(++lastElement) {
ArrayList<T, count_t>::Iterator(firstElement), value(firstElement),
linked(false), end(++lastElement) {
if (value == end) {
value = NULL;
}
@ -44,17 +42,17 @@ public:
HybridIterator& operator++() {
if (linked) {
LinkedElement<T>::Iterator::operator++();
if (LinkedElement<T>::Iterator::value != NULL) {
if (LinkedElement<T>::Iterator::value != nullptr) {
value = LinkedElement<T>::Iterator::value->value;
} else {
value = NULL;
value = nullptr;
}
} else {
ArrayList<T, count_t>::Iterator::operator++();
value = ArrayList<T, count_t>::Iterator::value;
if (value == end) {
value = NULL;
value = nullptr;
}
}
return *this;
@ -66,11 +64,11 @@ public:
return tmp;
}
bool operator==(HybridIterator other) {
bool operator==(const HybridIterator& other) const {
return value == other.value;
}
bool operator!=(HybridIterator other) {
bool operator!=(const HybridIterator& other) const {
return !(*this == other);
}
@ -82,11 +80,11 @@ public:
return value;
}
T* value;
T* value = nullptr;
private:
bool linked;
T *end;
bool linked = false;
T *end = nullptr;
};
#endif /* HYBRIDITERATOR_H_ */
#endif /* FRAMEWORK_CONTAINER_HYBRIDITERATOR_H_ */

View File

@ -75,50 +75,50 @@ public:
return this->storedPackets;
}
ReturnValue_t serialize(uint8_t** buffer, uint32_t* size,
const uint32_t max_size, bool bigEndian) const {
ReturnValue_t result = AutoSerializeAdapter::serialize(&blockStartAddress,buffer,size,max_size,bigEndian);
ReturnValue_t serialize(uint8_t** buffer, size_t* size,
size_t maxSize, Endianness streamEndianness) const {
ReturnValue_t result = SerializeAdapter::serialize(&blockStartAddress,buffer,size,maxSize,streamEndianness);
if(result != HasReturnvaluesIF::RETURN_OK){
return result;
}
result = indexType.serialize(buffer,size,max_size,bigEndian);
result = indexType.serialize(buffer,size,maxSize,streamEndianness);
if(result != HasReturnvaluesIF::RETURN_OK){
return result;
}
result = AutoSerializeAdapter::serialize(&this->size,buffer,size,max_size,bigEndian);
result = SerializeAdapter::serialize(&this->size,buffer,size,maxSize,streamEndianness);
if(result != HasReturnvaluesIF::RETURN_OK){
return result;
}
result = AutoSerializeAdapter::serialize(&this->storedPackets,buffer,size,max_size,bigEndian);
result = SerializeAdapter::serialize(&this->storedPackets,buffer,size,maxSize,streamEndianness);
return result;
}
ReturnValue_t deSerialize(const uint8_t** buffer, int32_t* size,
bool bigEndian){
ReturnValue_t result = AutoSerializeAdapter::deSerialize(&blockStartAddress,buffer,size,bigEndian);
ReturnValue_t deSerialize(const uint8_t** buffer, size_t* size,
Endianness streamEndianness){
ReturnValue_t result = SerializeAdapter::deSerialize(&blockStartAddress,buffer,size,streamEndianness);
if(result != HasReturnvaluesIF::RETURN_OK){
return result;
}
result = indexType.deSerialize(buffer,size,bigEndian);
result = indexType.deSerialize(buffer,size,streamEndianness);
if(result != HasReturnvaluesIF::RETURN_OK){
return result;
}
result = AutoSerializeAdapter::deSerialize(&this->size,buffer,size,bigEndian);
result = SerializeAdapter::deSerialize(&this->size,buffer,size,streamEndianness);
if(result != HasReturnvaluesIF::RETURN_OK){
return result;
}
result = AutoSerializeAdapter::deSerialize(&this->storedPackets,buffer,size,bigEndian);
result = SerializeAdapter::deSerialize(&this->storedPackets,buffer,size,streamEndianness);
if(result != HasReturnvaluesIF::RETURN_OK){
return result;
}
return result;
}
uint32_t getSerializedSize() const {
uint32_t size = AutoSerializeAdapter::getSerializedSize(&blockStartAddress);
size_t getSerializedSize() const {
uint32_t size = SerializeAdapter::getSerializedSize(&blockStartAddress);
size += indexType.getSerializedSize();
size += AutoSerializeAdapter::getSerializedSize(&this->size);
size += AutoSerializeAdapter::getSerializedSize(&this->storedPackets);
size += SerializeAdapter::getSerializedSize(&this->size);
size += SerializeAdapter::getSerializedSize(&this->storedPackets);
return size;
}
@ -509,37 +509,37 @@ public:
* Parameters according to HasSerializeIF
* @param buffer
* @param size
* @param max_size
* @param bigEndian
* @param maxSize
* @param streamEndianness
* @return
*/
ReturnValue_t serialize(uint8_t** buffer, uint32_t* size,
const uint32_t max_size, bool bigEndian) const{
ReturnValue_t serialize(uint8_t** buffer, size_t* size,
size_t maxSize, Endianness streamEndianness) const{
uint8_t* crcBuffer = *buffer;
uint32_t oldSize = *size;
if(additionalInfo!=NULL){
additionalInfo->serialize(buffer,size,max_size,bigEndian);
additionalInfo->serialize(buffer,size,maxSize,streamEndianness);
}
ReturnValue_t result = currentWriteBlock->serialize(buffer,size,max_size,bigEndian);
ReturnValue_t result = currentWriteBlock->serialize(buffer,size,maxSize,streamEndianness);
if(result != HasReturnvaluesIF::RETURN_OK){
return result;
}
result = AutoSerializeAdapter::serialize(&this->size,buffer,size,max_size,bigEndian);
result = SerializeAdapter::serialize(&this->size,buffer,size,maxSize,streamEndianness);
if(result != HasReturnvaluesIF::RETURN_OK){
return result;
}
uint32_t i = 0;
while ((result == HasReturnvaluesIF::RETURN_OK) && (i < this->size)) {
result = SerializeAdapter<Index<T> >::serialize(&this->entries[i], buffer, size,
max_size, bigEndian);
result = SerializeAdapter::serialize(&this->entries[i], buffer, size,
maxSize, streamEndianness);
++i;
}
if(result != HasReturnvaluesIF::RETURN_OK){
return result;
}
uint16_t crc = Calculate_CRC(crcBuffer,(*size-oldSize));
result = AutoSerializeAdapter::serialize(&crc,buffer,size,max_size,bigEndian);
result = SerializeAdapter::serialize(&crc,buffer,size,maxSize,streamEndianness);
return result;
}
@ -555,10 +555,10 @@ public:
size += additionalInfo->getSerializedSize();
}
size += currentWriteBlock->getSerializedSize();
size += AutoSerializeAdapter::getSerializedSize(&this->size);
size += SerializeAdapter::getSerializedSize(&this->size);
size += (this->entries[0].getSerializedSize()) * this->size;
uint16_t crc = 0;
size += AutoSerializeAdapter::getSerializedSize(&crc);
size += SerializeAdapter::getSerializedSize(&crc);
return size;
}
/**
@ -566,28 +566,28 @@ public:
* CRC Has to be checked before!
* @param buffer
* @param size
* @param bigEndian
* @param streamEndianness
* @return
*/
ReturnValue_t deSerialize(const uint8_t** buffer, int32_t* size,
bool bigEndian){
ReturnValue_t deSerialize(const uint8_t** buffer, size_t* size,
Endianness streamEndianness){
ReturnValue_t result = HasReturnvaluesIF::RETURN_OK;
if(additionalInfo!=NULL){
result = additionalInfo->deSerialize(buffer,size,bigEndian);
result = additionalInfo->deSerialize(buffer,size,streamEndianness);
}
if(result != HasReturnvaluesIF::RETURN_OK){
return result;
}
Index<T> tempIndex;
result = tempIndex.deSerialize(buffer,size,bigEndian);
result = tempIndex.deSerialize(buffer,size,streamEndianness);
if(result != HasReturnvaluesIF::RETURN_OK){
return result;
}
uint32_t tempSize = 0;
result = AutoSerializeAdapter::deSerialize(&tempSize,buffer,size,bigEndian);
result = SerializeAdapter::deSerialize(&tempSize,buffer,size,streamEndianness);
if(result != HasReturnvaluesIF::RETURN_OK){
return result;
}
@ -596,9 +596,9 @@ public:
}
uint32_t i = 0;
while ((result == HasReturnvaluesIF::RETURN_OK) && (i < this->size)) {
result = SerializeAdapter<Index<T> >::deSerialize(
result = SerializeAdapter::deSerialize(
&this->entries[i], buffer, size,
bigEndian);
streamEndianness);
++i;
}
if(result != HasReturnvaluesIF::RETURN_OK){

View File

@ -2,16 +2,76 @@
#define FRAMEWORK_CONTAINER_RINGBUFFERBASE_H_
#include <framework/returnvalues/HasReturnvaluesIF.h>
#include <cstddef>
template<uint8_t N_READ_PTRS = 1>
class RingBufferBase {
public:
RingBufferBase(uint32_t startAddress, uint32_t size, bool overwriteOld) :
start(startAddress), write(startAddress), size(size), overwriteOld(overwriteOld) {
RingBufferBase(size_t startAddress, const size_t size, bool overwriteOld) :
start(startAddress), write(startAddress), size(size),
overwriteOld(overwriteOld) {
for (uint8_t count = 0; count < N_READ_PTRS; count++) {
read[count] = startAddress;
}
}
virtual ~RingBufferBase() {}
bool isFull(uint8_t n = 0) {
return (availableWriteSpace(n) == 0);
}
bool isEmpty(uint8_t n = 0) {
return (availableReadData(n) == 0);
}
size_t availableReadData(uint8_t n = 0) const {
return ((write + size) - read[n]) % size;
}
size_t availableWriteSpace(uint8_t n = 0) const {
//One less to avoid ambiguous full/empty problem.
return (((read[n] + size) - write - 1) % size);
}
bool overwritesOld() const {
return overwriteOld;
}
size_t maxSize() const {
return size - 1;
}
void clear() {
write = start;
for (uint8_t count = 0; count < N_READ_PTRS; count++) {
read[count] = start;
}
}
size_t writeTillWrap() {
return (start + size) - write;
}
size_t readTillWrap(uint8_t n = 0) {
return (start + size) - read[n];
}
size_t getStart() const {
return start;
}
protected:
const size_t start;
size_t write;
size_t read[N_READ_PTRS];
const size_t size;
const bool overwriteOld;
void incrementWrite(uint32_t amount) {
write = ((write + amount - start) % size) + start;
}
void incrementRead(uint32_t amount, uint8_t n = 0) {
read[n] = ((read[n] + amount - start) % size) + start;
}
ReturnValue_t readData(uint32_t amount, uint8_t n = 0) {
if (availableReadData(n) >= amount) {
incrementRead(amount, n);
@ -20,77 +80,34 @@ public:
return HasReturnvaluesIF::RETURN_FAILED;
}
}
ReturnValue_t writeData(uint32_t amount) {
if (availableWriteSpace() >= amount || overwriteOld) {
if (availableWriteSpace() >= amount or overwriteOld) {
incrementWrite(amount);
return HasReturnvaluesIF::RETURN_OK;
} else {
return HasReturnvaluesIF::RETURN_FAILED;
}
}
uint32_t availableReadData(uint8_t n = 0) const {
return ((write + size) - read[n]) % size;
}
uint32_t availableWriteSpace(uint8_t n = 0) const {
//One less to avoid ambiguous full/empty problem.
return (((read[n] + size) - write - 1) % size);
}
bool isFull(uint8_t n = 0) {
return (availableWriteSpace(n) == 0);
}
bool isEmpty(uint8_t n = 0) {
return (availableReadData(n) == 0);
}
virtual ~RingBufferBase() {
}
uint32_t getRead(uint8_t n = 0) const {
size_t getRead(uint8_t n = 0) const {
return read[n];
}
void setRead(uint32_t read, uint8_t n = 0) {
if (read >= start && read < (start+size)) {
this->read[n] = read;
}
}
uint32_t getWrite() const {
return write;
}
void setWrite(uint32_t write) {
this->write = write;
}
void clear() {
write = start;
for (uint8_t count = 0; count < N_READ_PTRS; count++) {
read[count] = start;
}
}
uint32_t writeTillWrap() {
return (start + size) - write;
}
uint32_t readTillWrap(uint8_t n = 0) {
return (start + size) - read[n];
}
uint32_t getStart() const {
return start;
}
bool overwritesOld() const {
return overwriteOld;
}
uint32_t maxSize() const {
return size - 1;
}
protected:
const uint32_t start;
uint32_t write;
uint32_t read[N_READ_PTRS];
const uint32_t size;
const bool overwriteOld;
void incrementWrite(uint32_t amount) {
write = ((write + amount - start) % size) + start;
}
void incrementRead(uint32_t amount, uint8_t n = 0) {
read[n] = ((read[n] + amount - start) % size) + start;
}
};
#endif /* FRAMEWORK_CONTAINER_RINGBUFFERBASE_H_ */

View File

@ -0,0 +1,59 @@
#include <framework/container/SharedRingBuffer.h>
#include <framework/ipc/MutexFactory.h>
#include <framework/ipc/MutexHelper.h>
SharedRingBuffer::SharedRingBuffer(object_id_t objectId, const size_t size,
bool overwriteOld, size_t maxExcessBytes, dur_millis_t mutexTimeout):
SystemObject(objectId), SimpleRingBuffer(size, overwriteOld,
maxExcessBytes), mutexTimeout(mutexTimeout) {
mutex = MutexFactory::instance()->createMutex();
}
SharedRingBuffer::SharedRingBuffer(object_id_t objectId, uint8_t *buffer,
const size_t size, bool overwriteOld, size_t maxExcessBytes,
dur_millis_t mutexTimeout):
SystemObject(objectId), SimpleRingBuffer(buffer, size, overwriteOld,
maxExcessBytes), mutexTimeout(mutexTimeout) {
mutex = MutexFactory::instance()->createMutex();
}
ReturnValue_t SharedRingBuffer::getFreeElementProtected(uint8_t** writePtr,
size_t amount) {
MutexHelper(mutex, mutexTimeout);
return SimpleRingBuffer::getFreeElement(writePtr,amount);
}
ReturnValue_t SharedRingBuffer::writeDataProtected(const uint8_t *data,
size_t amount) {
MutexHelper(mutex, mutexTimeout);
return SimpleRingBuffer::writeData(data,amount);
}
ReturnValue_t SharedRingBuffer::readDataProtected(uint8_t *data, size_t amount,
bool incrementReadPtr, bool readRemaining,
size_t *trueAmount) {
MutexHelper(mutex, mutexTimeout);
return SimpleRingBuffer::readData(data,amount, incrementReadPtr,
readRemaining, trueAmount);
}
ReturnValue_t SharedRingBuffer::deleteDataProtected(size_t amount,
bool deleteRemaining, size_t *trueAmount) {
MutexHelper(mutex, mutexTimeout);
return SimpleRingBuffer::deleteData(amount, deleteRemaining, trueAmount);
}
size_t SharedRingBuffer::getExcessBytes() const {
MutexHelper(mutex, mutexTimeout);
return SimpleRingBuffer::getExcessBytes();
}
void SharedRingBuffer::moveExcessBytesToStart() {
MutexHelper(mutex, mutexTimeout);
return SimpleRingBuffer::moveExcessBytesToStart();
}
size_t SharedRingBuffer::getAvailableReadDataProtected(uint8_t n) const {
MutexHelper(mutex, mutexTimeout);
return ((write + size) - read[n]) % size;
}

View File

@ -0,0 +1,68 @@
#ifndef FRAMEWORK_CONTAINER_SHAREDRINGBUFFER_H_
#define FRAMEWORK_CONTAINER_SHAREDRINGBUFFER_H_
#include <framework/container/SimpleRingBuffer.h>
#include <framework/ipc/MutexIF.h>
#include <framework/objectmanager/SystemObject.h>
#include <framework/timemanager/Clock.h>
class SharedRingBuffer: public SystemObject,
public SimpleRingBuffer {
public:
/**
* This constructor allocates a new internal buffer with the supplied size.
* @param size
* @param overwriteOld
* If the ring buffer is overflowing at a write operartion, the oldest data
* will be overwritten.
*/
SharedRingBuffer(object_id_t objectId, const size_t size,
bool overwriteOld, size_t maxExcessBytes,
dur_millis_t mutexTimeout = 10);
/**
* This constructor takes an external buffer with the specified size.
* @param buffer
* @param size
* @param overwriteOld
* If the ring buffer is overflowing at a write operartion, the oldest data
* will be overwritten.
*/
SharedRingBuffer(object_id_t objectId, uint8_t* buffer, const size_t size,
bool overwriteOld, size_t maxExcessBytes,
dur_millis_t mutexTimeout = 10);
void setMutexTimeout(dur_millis_t newTimeout);
virtual size_t getExcessBytes() const override;
/**
* Helper functions which moves any excess bytes to the start
* of the ring buffer.
* @return
*/
virtual void moveExcessBytesToStart() override;
/** Performs mutex protected SimpleRingBuffer::getFreeElement call */
ReturnValue_t getFreeElementProtected(uint8_t** writePtr, size_t amount);
/** Performs mutex protected SimpleRingBuffer::writeData call */
ReturnValue_t writeDataProtected(const uint8_t* data, size_t amount);
/** Performs mutex protected SimpleRingBuffer::readData call */
ReturnValue_t readDataProtected(uint8_t *data, size_t amount,
bool incrementReadPtr = false,
bool readRemaining = false, size_t *trueAmount = nullptr);
/** Performs mutex protected SimpleRingBuffer::deleteData call */
ReturnValue_t deleteDataProtected(size_t amount,
bool deleteRemaining = false, size_t* trueAmount = nullptr);
size_t getAvailableReadDataProtected (uint8_t n = 0) const;
private:
dur_millis_t mutexTimeout;
MutexIF* mutex = nullptr;
};
#endif /* FRAMEWORK_CONTAINER_SHAREDRINGBUFFER_H_ */

View File

@ -1,22 +1,64 @@
#include <framework/container/SimpleRingBuffer.h>
#include <string.h>
#include <cstring>
SimpleRingBuffer::SimpleRingBuffer(uint32_t size, bool overwriteOld) :
RingBufferBase<>(0, size, overwriteOld), buffer(NULL) {
buffer = new uint8_t[size];
SimpleRingBuffer::SimpleRingBuffer(const size_t size, bool overwriteOld,
size_t maxExcessBytes) :
RingBufferBase<>(0, size, overwriteOld),
maxExcessBytes(maxExcessBytes) {
if(maxExcessBytes > size) {
this->maxExcessBytes = size;
}
else {
this->maxExcessBytes = maxExcessBytes;
}
buffer = new uint8_t[size + maxExcessBytes];
}
SimpleRingBuffer::SimpleRingBuffer(uint8_t *buffer, const size_t size,
bool overwriteOld, size_t maxExcessBytes):
RingBufferBase<>(0, size, overwriteOld), buffer(buffer) {
if(maxExcessBytes > size) {
this->maxExcessBytes = size;
}
else {
this->maxExcessBytes = maxExcessBytes;
}
}
SimpleRingBuffer::~SimpleRingBuffer() {
delete[] buffer;
}
ReturnValue_t SimpleRingBuffer::getFreeElement(uint8_t **writePointer,
size_t amount) {
if (availableWriteSpace() >= amount or overwriteOld) {
size_t amountTillWrap = writeTillWrap();
if (amountTillWrap < amount) {
if((amount - amountTillWrap + excessBytes) > maxExcessBytes) {
return HasReturnvaluesIF::RETURN_FAILED;
}
excessBytes = amount - amountTillWrap;
}
*writePointer = &buffer[write];
incrementWrite(amount);
return HasReturnvaluesIF::RETURN_OK;
}
else {
return HasReturnvaluesIF::RETURN_FAILED;
}
}
ReturnValue_t SimpleRingBuffer::writeData(const uint8_t* data,
uint32_t amount) {
if (availableWriteSpace() >= amount || overwriteOld) {
uint32_t amountTillWrap = writeTillWrap();
size_t amount) {
if (availableWriteSpace() >= amount or overwriteOld) {
size_t amountTillWrap = writeTillWrap();
if (amountTillWrap >= amount) {
// remaining size in buffer is sufficient to fit full amount.
memcpy(&buffer[write], data, amount);
} else {
}
else {
memcpy(&buffer[write], data, amountTillWrap);
memcpy(buffer, data + amountTillWrap, amount - amountTillWrap);
}
@ -27,18 +69,19 @@ ReturnValue_t SimpleRingBuffer::writeData(const uint8_t* data,
}
}
ReturnValue_t SimpleRingBuffer::readData(uint8_t* data, uint32_t amount,
bool readRemaining, uint32_t* trueAmount) {
uint32_t availableData = availableReadData(READ_PTR);
uint32_t amountTillWrap = readTillWrap(READ_PTR);
ReturnValue_t SimpleRingBuffer::readData(uint8_t* data, size_t amount,
bool incrementReadPtr, bool readRemaining, size_t* trueAmount) {
size_t availableData = availableReadData(READ_PTR);
size_t amountTillWrap = readTillWrap(READ_PTR);
if (availableData < amount) {
if (readRemaining) {
// more data available than amount specified.
amount = availableData;
} else {
return HasReturnvaluesIF::RETURN_FAILED;
}
}
if (trueAmount != NULL) {
if (trueAmount != nullptr) {
*trueAmount = amount;
}
if (amountTillWrap >= amount) {
@ -47,12 +90,27 @@ ReturnValue_t SimpleRingBuffer::readData(uint8_t* data, uint32_t amount,
memcpy(data, &buffer[read[READ_PTR]], amountTillWrap);
memcpy(data + amountTillWrap, buffer, amount - amountTillWrap);
}
if(incrementReadPtr) {
deleteData(amount, readRemaining);
}
return HasReturnvaluesIF::RETURN_OK;
}
ReturnValue_t SimpleRingBuffer::deleteData(uint32_t amount,
bool deleteRemaining, uint32_t* trueAmount) {
uint32_t availableData = availableReadData(READ_PTR);
size_t SimpleRingBuffer::getExcessBytes() const {
return excessBytes;
}
void SimpleRingBuffer::moveExcessBytesToStart() {
if(excessBytes > 0) {
std::memcpy(buffer, &buffer[size], excessBytes);
excessBytes = 0;
}
}
ReturnValue_t SimpleRingBuffer::deleteData(size_t amount,
bool deleteRemaining, size_t* trueAmount) {
size_t availableData = availableReadData(READ_PTR);
if (availableData < amount) {
if (deleteRemaining) {
amount = availableData;
@ -60,9 +118,10 @@ ReturnValue_t SimpleRingBuffer::deleteData(uint32_t amount,
return HasReturnvaluesIF::RETURN_FAILED;
}
}
if (trueAmount != NULL) {
if (trueAmount != nullptr) {
*trueAmount = amount;
}
incrementRead(amount, READ_PTR);
return HasReturnvaluesIF::RETURN_OK;
}

View File

@ -2,48 +2,117 @@
#define FRAMEWORK_CONTAINER_SIMPLERINGBUFFER_H_
#include <framework/container/RingBufferBase.h>
#include <stddef.h>
#include <cstddef>
/**
* @brief Circular buffer implementation, useful for buffering into data streams.
* @details Note that the deleteData() has to be called to increment the read pointer
* @brief Circular buffer implementation, useful for buffering
* into data streams.
* @details
* Note that the deleteData() has to be called to increment the read pointer.
* This class allocated dynamically, so
* @ingroup containers
*/
class SimpleRingBuffer: public RingBufferBase<> {
public:
SimpleRingBuffer(uint32_t size, bool overwriteOld);
/**
* This constructor allocates a new internal buffer with the supplied size.
*
* @param size
* @param overwriteOld If the ring buffer is overflowing at a write
* operation, the oldest data will be overwritten.
* @param maxExcessBytes These additional bytes will be allocated in addtion
* to the specified size to accomodate contiguous write operations
* with getFreeElement.
*
*/
SimpleRingBuffer(const size_t size, bool overwriteOld,
size_t maxExcessBytes = 0);
/**
* This constructor takes an external buffer with the specified size.
* @param buffer
* @param size
* @param overwriteOld
* If the ring buffer is overflowing at a write operartion, the oldest data
* will be overwritten.
* @param maxExcessBytes
* If the buffer can accomodate additional bytes for contigous write
* operations with getFreeElement, this is the maximum allowed additional
* size
*/
SimpleRingBuffer(uint8_t* buffer, const size_t size, bool overwriteOld,
size_t maxExcessBytes = 0);
virtual ~SimpleRingBuffer();
/**
* Write to circular buffer and increment write pointer by amount
* Write to circular buffer and increment write pointer by amount.
* @param data
* @param amount
* @return -@c RETURN_OK if write operation was successfull
* -@c RETURN_FAILED if
*/
ReturnValue_t writeData(const uint8_t* data, size_t amount);
/**
* Returns a pointer to a free element. If the remaining buffer is
* not large enough, the data will be written past the actual size
* and the amount of excess bytes will be cached.
* @param writePointer Pointer to a pointer which can be used to write
* contiguous blocks into the ring buffer
* @param amount
* @return
*/
ReturnValue_t writeData(const uint8_t* data, uint32_t amount);
ReturnValue_t getFreeElement(uint8_t** writePointer, size_t amount);
virtual size_t getExcessBytes() const;
/**
* Helper functions which moves any excess bytes to the start
* of the ring buffer.
* @return
*/
virtual void moveExcessBytesToStart();
/**
* Read from circular buffer at read pointer
* Read from circular buffer at read pointer.
* @param data
* @param amount
* @param incrementReadPtr
* If this is set to true, the read pointer will be incremented.
* If readRemaining is set to true, the read pointer will be incremented
* accordingly.
* @param readRemaining
* @param trueAmount
* If this is set to true, the data will be read even if the amount
* specified exceeds the read data available.
* @param trueAmount [out]
* If readRemaining was set to true, the true amount read will be assigned
* to the passed value.
* @return
* - @c RETURN_OK if data was read successfully
* - @c RETURN_FAILED if not enough data was available and readRemaining
* was set to false.
*/
ReturnValue_t readData(uint8_t* data, uint32_t amount, bool readRemaining = false, uint32_t* trueAmount = NULL);
ReturnValue_t readData(uint8_t* data, size_t amount,
bool incrementReadPtr = false, bool readRemaining = false,
size_t* trueAmount = nullptr);
/**
* Delete data starting by incrementing read pointer
* Delete data by incrementing read pointer.
* @param amount
* @param deleteRemaining
* @param trueAmount
* If the amount specified is larger than the remaing size to read and this
* is set to true, the remaining amount will be deleted as well
* @param trueAmount [out]
* If deleteRemaining was set to true, the amount deleted will be assigned
* to the passed value.
* @return
*/
ReturnValue_t deleteData(uint32_t amount, bool deleteRemaining = false, uint32_t* trueAmount = NULL);
ReturnValue_t deleteData(size_t amount, bool deleteRemaining = false,
size_t* trueAmount = nullptr);
private:
// static const uint8_t TEMP_READ_PTR = 1;
static const uint8_t READ_PTR = 0;
uint8_t* buffer;
uint8_t* buffer = nullptr;
size_t maxExcessBytes;
size_t excessBytes = 0;
};
#endif /* FRAMEWORK_CONTAINER_SIMPLERINGBUFFER_H_ */

View File

@ -1,8 +1,9 @@
#ifndef SINGLYLINKEDLIST_H_
#define SINGLYLINKEDLIST_H_
#ifndef FRAMEWORK_CONTAINER_SINGLYLINKEDLIST_H_
#define FRAMEWORK_CONTAINER_SINGLYLINKEDLIST_H_
#include <cstddef>
#include <cstdint>
#include <stddef.h>
#include <stdint.h>
/**
* @brief Linked list data structure,
* each entry has a pointer to the next entry (singly)
@ -14,11 +15,8 @@ public:
T *value;
class Iterator {
public:
LinkedElement<T> *value;
Iterator() :
value(NULL) {
}
LinkedElement<T> *value = nullptr;
Iterator() {}
Iterator(LinkedElement<T> *element) :
value(element) {
@ -47,12 +45,11 @@ public:
}
};
LinkedElement(T* setElement, LinkedElement<T>* setNext = NULL) : value(setElement),
next(setNext) {
}
virtual ~LinkedElement(){
LinkedElement(T* setElement, LinkedElement<T>* setNext = nullptr):
value(setElement), next(setNext) {}
virtual ~LinkedElement(){}
}
virtual LinkedElement* getNext() const {
return next;
}
@ -61,15 +58,15 @@ public:
this->next = next;
}
void setEnd() {
this->next = nullptr;
virtual void setEnd() {
this->next = nullptr;
}
LinkedElement* begin() {
return this;
}
LinkedElement* end() {
return NULL;
return nullptr;
}
private:
LinkedElement *next;
@ -78,37 +75,80 @@ private:
template<typename T>
class SinglyLinkedList {
public:
SinglyLinkedList() :
start(NULL) {
}
using ElementIterator = typename LinkedElement<T>::Iterator;
SinglyLinkedList() {}
SinglyLinkedList(ElementIterator start) :
start(start.value) {}
SinglyLinkedList(typename LinkedElement<T>::Iterator start) :
start(start.value) {
}
SinglyLinkedList(LinkedElement<T>* startElement) :
start(startElement) {
}
typename LinkedElement<T>::Iterator begin() const {
return LinkedElement<T>::Iterator::Iterator(start);
}
typename LinkedElement<T>::Iterator::Iterator end() const {
return LinkedElement<T>::Iterator::Iterator();
start(startElement) {}
ElementIterator begin() const {
return ElementIterator::Iterator(start);
}
uint32_t getSize() const {
uint32_t size = 0;
/** Returns iterator to nulltr */
ElementIterator end() const {
return ElementIterator::Iterator();
}
/**
* Returns last element in singly linked list.
* @return
*/
ElementIterator back() const {
LinkedElement<T> *element = start;
while (element != nullptr) {
element = element->getNext();
}
return ElementIterator::Iterator(element);
}
size_t getSize() const {
size_t size = 0;
LinkedElement<T> *element = start;
while (element != NULL) {
while (element != nullptr) {
size++;
element = element->getNext();
}
return size;
}
void setStart(LinkedElement<T>* setStart) {
start = setStart;
void setStart(LinkedElement<T>* firstElement) {
start = firstElement;
}
void setNext(LinkedElement<T>* currentElement,
LinkedElement<T>* nextElement) {
currentElement->setNext(nextElement);
}
void setLast(LinkedElement<T>* lastElement) {
lastElement->setEnd();
}
void insertElement(LinkedElement<T>* element, size_t position) {
LinkedElement<T> *currentElement = start;
for(size_t count = 0; count < position; count++) {
if(currentElement == nullptr) {
return;
}
currentElement = currentElement->getNext();
}
LinkedElement<T>* elementAfterCurrent = currentElement->next;
currentElement->setNext(element);
if(elementAfterCurrent != nullptr) {
element->setNext(elementAfterCurrent);
}
}
void insertBack(LinkedElement<T>* lastElement) {
back().value->setNext(lastElement);
}
protected:
LinkedElement<T> *start;
LinkedElement<T> *start = nullptr;
};
#endif /* SINGLYLINKEDLIST_H_ */

View File

@ -56,26 +56,26 @@ MessageQueueId_t ControllerBase::getCommandQueue() const {
}
void ControllerBase::handleQueue() {
CommandMessage message;
CommandMessage command;
ReturnValue_t result;
for (result = commandQueue->receiveMessage(&message); result == RETURN_OK;
result = commandQueue->receiveMessage(&message)) {
for (result = commandQueue->receiveMessage(&command); result == RETURN_OK;
result = commandQueue->receiveMessage(&command)) {
result = modeHelper.handleModeCommand(&message);
result = modeHelper.handleModeCommand(&command);
if (result == RETURN_OK) {
continue;
}
result = healthHelper.handleHealthCommand(&message);
result = healthHelper.handleHealthCommand(&command);
if (result == RETURN_OK) {
continue;
}
result = handleCommandMessage(&message);
result = handleCommandMessage(&command);
if (result == RETURN_OK) {
continue;
}
message.setToUnknownCommand();
commandQueue->reply(&message);
command.setToUnknownCommand();
commandQueue->reply(&command);
}
}

View File

@ -16,9 +16,9 @@
MapPacketExtraction::MapPacketExtraction(uint8_t setMapId,
object_id_t setPacketDestination) :
lastSegmentationFlag(NO_SEGMENTATION), mapId(setMapId), packetLength(0), bufferPosition(
packetBuffer), packetDestination(setPacketDestination), packetStore(
NULL), tcQueueId(MessageQueueSenderIF::NO_QUEUE) {
lastSegmentationFlag(NO_SEGMENTATION), mapId(setMapId), packetLength(0),
bufferPosition(packetBuffer), packetDestination(setPacketDestination),
packetStore(nullptr), tcQueueId(MessageQueueMessageIF::NO_QUEUE) {
memset(packetBuffer, 0, sizeof(packetBuffer));
}

View File

@ -1,8 +1,11 @@
#include <framework/datapool/DataSetBase.h>
#include <framework/serviceinterface/ServiceInterfaceStream.h>
DataSetBase::DataSetBase() {
for (uint8_t count = 0; count < DATA_SET_MAX_SIZE; count++) {
DataSetBase::DataSetBase(PoolVariableIF** registeredVariablesArray,
const size_t maxFillCount):
registeredVariables(registeredVariablesArray),
maxFillCount(maxFillCount) {
for (uint8_t count = 0; count < maxFillCount; count++) {
registeredVariables[count] = nullptr;
}
}
@ -21,7 +24,7 @@ ReturnValue_t DataSetBase::registerVariable(
"Pool variable is nullptr." << std::endl;
return DataSetIF::POOL_VAR_NULL;
}
if (fillCount >= DATA_SET_MAX_SIZE) {
if (fillCount >= maxFillCount) {
sif::error << "DataSet::registerVariable: "
"DataSet is full." << std::endl;
return DataSetIF::DATA_SET_FULL;
@ -31,20 +34,14 @@ ReturnValue_t DataSetBase::registerVariable(
return HasReturnvaluesIF::RETURN_OK;
}
ReturnValue_t DataSetBase::read() {
ReturnValue_t DataSetBase::read(uint32_t lockTimeout) {
ReturnValue_t result = HasReturnvaluesIF::RETURN_OK;
if (state == States::DATA_SET_UNINITIALISED) {
lockDataPool();
lockDataPool(lockTimeout);
for (uint16_t count = 0; count < fillCount; count++) {
if (registeredVariables[count]->getReadWriteMode()
!= PoolVariableIF::VAR_WRITE
&& registeredVariables[count]->getDataPoolId()
!= PoolVariableIF::NO_PARAMETER) {
ReturnValue_t status = registeredVariables[count]->read();
if (status != HasReturnvaluesIF::RETURN_OK) {
result = INVALID_PARAMETER_DEFINITION;
break;
}
result = readVariable(count);
if(result != RETURN_OK) {
break;
}
}
state = States::DATA_SET_WAS_READ;
@ -52,53 +49,67 @@ ReturnValue_t DataSetBase::read() {
}
else {
sif::error << "DataSet::read(): "
"Call made in wrong position." << std::endl;
"Call made in wrong position. Don't forget to commit"
" member datasets!" << std::endl;
result = SET_WAS_ALREADY_READ;
}
return result;
}
ReturnValue_t DataSetBase::commit() {
uint16_t DataSetBase::getFillCount() const {
return fillCount;
}
ReturnValue_t DataSetBase::readVariable(uint16_t count) {
ReturnValue_t result = HasReturnvaluesIF::RETURN_OK;
// These checks are often performed by the respective
// variable implementation too, but I guess a double check does not hurt.
if (registeredVariables[count]->getReadWriteMode() !=
PoolVariableIF::VAR_WRITE and
registeredVariables[count]->getDataPoolId()
!= PoolVariableIF::NO_PARAMETER)
{
result = registeredVariables[count]->readWithoutLock();
if(result != HasReturnvaluesIF::RETURN_OK) {
result = INVALID_PARAMETER_DEFINITION;
}
}
return result;
}
ReturnValue_t DataSetBase::commit(uint32_t lockTimeout) {
if (state == States::DATA_SET_WAS_READ) {
handleAlreadyReadDatasetCommit();
handleAlreadyReadDatasetCommit(lockTimeout);
return HasReturnvaluesIF::RETURN_OK;
}
else {
return handleUnreadDatasetCommit();
return handleUnreadDatasetCommit(lockTimeout);
}
}
ReturnValue_t DataSetBase::lockDataPool() {
return HasReturnvaluesIF::RETURN_OK;
}
ReturnValue_t DataSetBase::unlockDataPool() {
return HasReturnvaluesIF::RETURN_FAILED;
}
void DataSetBase::handleAlreadyReadDatasetCommit() {
lockDataPool();
void DataSetBase::handleAlreadyReadDatasetCommit(uint32_t lockTimeout) {
lockDataPool(lockTimeout);
for (uint16_t count = 0; count < fillCount; count++) {
if (registeredVariables[count]->getReadWriteMode()
!= PoolVariableIF::VAR_READ
&& registeredVariables[count]->getDataPoolId()
!= PoolVariableIF::NO_PARAMETER) {
registeredVariables[count]->commit();
registeredVariables[count]->commitWithoutLock();
}
}
state = States::DATA_SET_UNINITIALISED;
unlockDataPool();
}
ReturnValue_t DataSetBase::handleUnreadDatasetCommit() {
ReturnValue_t DataSetBase::handleUnreadDatasetCommit(uint32_t lockTimeout) {
ReturnValue_t result = HasReturnvaluesIF::RETURN_OK;
lockDataPool();
lockDataPool(lockTimeout);
for (uint16_t count = 0; count < fillCount; count++) {
if (registeredVariables[count]->getReadWriteMode()
== PoolVariableIF::VAR_WRITE
&& registeredVariables[count]->getDataPoolId()
!= PoolVariableIF::NO_PARAMETER) {
registeredVariables[count]->commit();
registeredVariables[count]->commitWithoutLock();
} else if (registeredVariables[count]->getDataPoolId()
!= PoolVariableIF::NO_PARAMETER) {
if (result != COMMITING_WITHOUT_READING) {
@ -113,12 +124,21 @@ ReturnValue_t DataSetBase::handleUnreadDatasetCommit() {
return result;
}
ReturnValue_t DataSetBase::lockDataPool(uint32_t timeoutMs) {
return HasReturnvaluesIF::RETURN_OK;
}
ReturnValue_t DataSetBase::unlockDataPool() {
return HasReturnvaluesIF::RETURN_OK;
}
ReturnValue_t DataSetBase::serialize(uint8_t** buffer, size_t* size,
const size_t maxSize, bool bigEndian) const {
const size_t maxSize, SerializeIF::Endianness streamEndianness) const {
ReturnValue_t result = HasReturnvaluesIF::RETURN_FAILED;
for (uint16_t count = 0; count < fillCount; count++) {
result = registeredVariables[count]->serialize(buffer, size, maxSize,
bigEndian);
streamEndianness);
if (result != HasReturnvaluesIF::RETURN_OK) {
return result;
}
@ -127,11 +147,11 @@ ReturnValue_t DataSetBase::serialize(uint8_t** buffer, size_t* size,
}
ReturnValue_t DataSetBase::deSerialize(const uint8_t** buffer, size_t* size,
bool bigEndian) {
SerializeIF::Endianness streamEndianness) {
ReturnValue_t result = HasReturnvaluesIF::RETURN_FAILED;
for (uint16_t count = 0; count < fillCount; count++) {
result = registeredVariables[count]->deSerialize(buffer, size,
bigEndian);
streamEndianness);
if (result != HasReturnvaluesIF::RETURN_OK) {
return result;
}

View File

@ -2,6 +2,7 @@
#define FRAMEWORK_DATAPOOL_DATASETBASE_H_
#include <framework/datapool/DataSetIF.h>
#include <framework/datapool/PoolVariableIF.h>
#include <framework/ipc/MutexIF.h>
/**
* @brief The DataSetBase class manages a set of locally checked out variables.
@ -21,7 +22,8 @@
* of the set, the DataSet class automatically sets the valid flag in the
* data pool to invalid (without) changing the variable's value.
*
* The base class lockDataPo
* The base class lockDataPool und unlockDataPool implementation are empty
* and should be implemented to protect the underlying pool type.
* @author Bastian Baetz
* @ingroup data_pool
*/
@ -35,7 +37,8 @@ public:
* supply a pointer to this dataset to PoolVariable
* initializations to register pool variables.
*/
DataSetBase();
DataSetBase(PoolVariableIF** registeredVariablesArray,
const size_t maxFillCount);
virtual~ DataSetBase();
/**
@ -49,14 +52,15 @@ public:
*
* The data pool is locked during the whole read operation and
* freed afterwards.The state changes to "was written" after this operation.
* @return - @c RETURN_OK if all variables were read successfully.
* - @c INVALID_PARAMETER_DEFINITION if PID, size or type of the
* requested variable is invalid.
* - @c SET_WAS_ALREADY_READ if read() is called twice without calling
* commit() in between
* @return
* - @c RETURN_OK if all variables were read successfully.
* - @c INVALID_PARAMETER_DEFINITION if PID, size or type of the
* requested variable is invalid.
* - @c SET_WAS_ALREADY_READ if read() is called twice without calling
* commit() in between
*/
virtual ReturnValue_t read();
virtual ReturnValue_t read(uint32_t lockTimeout =
MutexIF::BLOCKING) override;
/**
* @brief The commit call initializes writing back the registered variables.
* @details
@ -67,23 +71,30 @@ public:
* The data pool is locked during the whole commit operation and
* freed afterwards. The state changes to "was committed" after this operation.
*
* If the set does contain at least one variable which is not write-only commit()
* can only be called after read(). If the set only contains variables which are
* write only, commit() can be called without a preceding read() call.
* If the set does contain at least one variable which is not write-only
* commit() can only be called after read(). If the set only contains
* variables which are write only, commit() can be called without a
* preceding read() call.
* @return - @c RETURN_OK if all variables were read successfully.
* - @c COMMITING_WITHOUT_READING if set was not read yet and
* contains non write-only variables
*/
virtual ReturnValue_t commit();
virtual ReturnValue_t commit(uint32_t lockTimeout =
MutexIF::BLOCKING) override;
/* DataSetIF implementation */
/**
* Register the passed pool variable instance into the data set.
* @param variable
* @return
*/
virtual ReturnValue_t registerVariable( PoolVariableIF* variable) override;
/**
* Provides the means to lock the underlying data structure to ensure
* thread-safety. Default implementation is empty
* @return Always returns -@c RETURN_OK
*/
virtual ReturnValue_t lockDataPool() override;
virtual ReturnValue_t lockDataPool(uint32_t timeoutMs =
MutexIF::BLOCKING) override;
/**
* Provides the means to unlock the underlying data structure to ensure
* thread-safety. Default implementation is empty
@ -91,19 +102,17 @@ public:
*/
virtual ReturnValue_t unlockDataPool() override;
virtual uint16_t getFillCount() const;
/* SerializeIF implementations */
ReturnValue_t serialize(uint8_t** buffer, size_t* size,
const size_t maxSize, bool bigEndian) const override;
virtual ReturnValue_t serialize(uint8_t** buffer, size_t* size,
const size_t maxSize,
SerializeIF::Endianness streamEndianness) const override;
virtual size_t getSerializedSize() const override;
virtual ReturnValue_t deSerialize(const uint8_t** buffer, size_t* size,
bool bigEndian) override;
SerializeIF::Endianness streamEndianness) override;
//SHOULDDO we could use a linked list of datapool variables
//!< This definition sets the maximum number of variables to
//! register in one DataSet.
static const uint8_t DATA_SET_MAX_SIZE = 63;
protected:
/**
* @brief The fill_count attribute ensures that the variables
* register in the correct array position and that the maximum
@ -125,11 +134,16 @@ protected:
/**
* @brief This array represents all pool variables registered in this set.
* Child classes can use a static or dynamic container to create
* an array of registered variables and assign the first entry here.
*/
PoolVariableIF* registeredVariables[DATA_SET_MAX_SIZE] = { };
PoolVariableIF** registeredVariables = nullptr;
const size_t maxFillCount = 0;
void handleAlreadyReadDatasetCommit();
ReturnValue_t handleUnreadDatasetCommit();
private:
ReturnValue_t readVariable(uint16_t count);
void handleAlreadyReadDatasetCommit(uint32_t lockTimeout);
ReturnValue_t handleUnreadDatasetCommit(uint32_t lockTimeout);
};
#endif /* FRAMEWORK_DATAPOOL_DATASETBASE_H_ */

View File

@ -2,6 +2,7 @@
#define DATASETIF_H_
#include <framework/returnvalues/HasReturnvaluesIF.h>
#include <framework/timemanager/Clock.h>
class PoolVariableIF;
/**
@ -33,20 +34,24 @@ public:
*/
virtual ~DataSetIF() {}
virtual ReturnValue_t read(uint32_t lockTimeout) = 0;
virtual ReturnValue_t commit(uint32_t lockTimeout) = 0;
/**
* @brief This operation provides a method to register local data pool
* variables to register in a data set by passing itself
* to this DataSet operation.
*/
virtual ReturnValue_t registerVariable( PoolVariableIF* variable ) = 0;
virtual ReturnValue_t registerVariable(PoolVariableIF* variable) = 0;
virtual uint16_t getFillCount() const = 0;
private:
/**
* @brief Most underlying data structures will have a pool like structure
* and will require a lock and unlock mechanism to ensure
* thread-safety
* @return Lock operation result
*/
virtual ReturnValue_t lockDataPool() = 0;
virtual ReturnValue_t lockDataPool(uint32_t timeoutMs) = 0;
/**
* @brief Unlock call corresponding to the lock call.
* @return Unlock operation result

View File

@ -21,14 +21,14 @@ ReturnValue_t HkSwitchHelper::initialize() {
}
ReturnValue_t HkSwitchHelper::performOperation(uint8_t operationCode) {
CommandMessage message;
while (actionQueue->receiveMessage(&message) == HasReturnvaluesIF::RETURN_OK) {
ReturnValue_t result = commandActionHelper.handleReply(&message);
CommandMessage command;
while (actionQueue->receiveMessage(&command) == HasReturnvaluesIF::RETURN_OK) {
ReturnValue_t result = commandActionHelper.handleReply(&command);
if (result == HasReturnvaluesIF::RETURN_OK) {
continue;
}
message.setToUnknownCommand();
actionQueue->reply(&message);
command.setToUnknownCommand();
actionQueue->reply(&command);
}
return HasReturnvaluesIF::RETURN_OK;

View File

@ -1,30 +1,37 @@
#include <framework/datapool/PoolEntry.h>
#include <framework/serviceinterface/ServiceInterfaceStream.h>
#include <framework/globalfunctions/arrayprinter.h>
#include <cstring>
template <typename T>
PoolEntry<T>::PoolEntry(std::initializer_list<T> initValue, uint8_t set_length,
uint8_t set_valid ) : length(set_length), valid(set_valid) {
PoolEntry<T>::PoolEntry(std::initializer_list<T> initValue, uint8_t setLength,
bool setValid ) : length(setLength), valid(setValid) {
this->address = new T[this->length];
if(initValue.size() == 0) {
memset(this->address, 0, this->getByteSize());
std::memset(this->address, 0, this->getByteSize());
}
else if (initValue.size() != setLength){
sif::warning << "PoolEntry: setLength is not equal to initializer list"
"length! Performing zero initialization with given setLength"
<< std::endl;
std::memset(this->address, 0, this->getByteSize());
}
else {
memcpy(this->address, initValue.begin(), this->getByteSize());
std::copy(initValue.begin(), initValue.end(), this->address);
}
}
template <typename T>
PoolEntry<T>::PoolEntry( T* initValue, uint8_t set_length, uint8_t set_valid ) :
length(set_length), valid(set_valid) {
PoolEntry<T>::PoolEntry( T* initValue, uint8_t setLength, bool setValid ) :
length(setLength), valid(setValid) {
this->address = new T[this->length];
if (initValue != NULL) {
memcpy(this->address, initValue, this->getByteSize() );
if (initValue != nullptr) {
std::memcpy(this->address, initValue, this->getByteSize() );
} else {
memset(this->address, 0, this->getByteSize() );
std::memset(this->address, 0, this->getByteSize() );
}
}
//As the data pool is global, this dtor is only be called on program exit.
//Warning! Never copy pool entries!
template <typename T>
@ -48,21 +55,20 @@ void* PoolEntry<T>::getRawData() {
}
template <typename T>
void PoolEntry<T>::setValid( uint8_t isValid ) {
void PoolEntry<T>::setValid(bool isValid) {
this->valid = isValid;
}
template <typename T>
uint8_t PoolEntry<T>::getValid() {
bool PoolEntry<T>::getValid() {
return valid;
}
template <typename T>
void PoolEntry<T>::print() {
for (uint8_t size = 0; size < this->length; size++ ) {
sif::debug << "| " << std::hex << (double)this->address[size]
<< (this->valid? " (valid) " : " (invalid) ");
}
sif::debug << "Pool Entry Validity: " <<
(this->valid? " (valid) " : " (invalid) ") << std::endl;
arrayprinter::print(reinterpret_cast<uint8_t*>(address), length);
sif::debug << std::dec << std::endl;
}

View File

@ -1,95 +1,126 @@
#ifndef POOLENTRY_H_
#define POOLENTRY_H_
#ifndef FRAMEWORK_DATAPOOL_POOLENTRY_H_
#define FRAMEWORK_DATAPOOL_POOLENTRY_H_
#include <framework/datapool/PoolEntryIF.h>
#include <stddef.h>
#include <cstring>
#include <initializer_list>
#include <type_traits>
#include <cstddef>
/**
* @brief This is a small helper class that defines a single data pool entry.
* @details
* The helper is used to store all information together with the data as a
* single data pool entry.The content's type is defined by the template argument.
* It is prepared for use with plain old data types, but may be extended to
* complex types if necessary. It can be initialized with a certain value,
* size and validity flag. It holds a pointer to the real data and offers
* methods to access this data and to acquire additional information
* (such as validity and array/byte size). It is NOT intended to be used
* outside the DataPool class.
* @author Bastian Baetz
* @ingroup data_pool
* single data pool entry. The content's type is defined by the template
* argument.
*
* It is prepared for use with plain old data types, but may be
* extended to complex types if necessary. It can be initialized with a
* certain value, size and validity flag.
*
* It holds a pointer to the real data and offers methods to access this data
* and to acquire additional information (such as validity and array/byte size).
* It is NOT intended to be used outside DataPool implementations as it performs
* dynamic memory allocation.
*
* @ingroup data_pool
*/
template <typename T>
class PoolEntry : public PoolEntryIF {
public:
static_assert(not std::is_same<T, bool>::value,
"Do not use boolean for the PoolEntry type, use uint8_t instead!"
"Warum? Darum :-)");
"Do not use boolean for the PoolEntry type, use uint8_t "
"instead! The ECSS standard defines a boolean as a one bit "
"field. Therefore it is preferred to store a boolean as an "
"uint8_t");
/**
* @brief In the classe's constructor, space is allocated on the heap and
* potential init values are copied to that space.
* @param initValue Initializer list with values to initialize with
* @param set_length Defines the array length of this entry.
* @param set_valid Sets the initialization flag. It is invalid (0) by default.
* @details
* Not passing any arguments will initialize an non-array pool entry
* (setLength = 1) with an initial invalid state.
* Please note that if an initializer list is passed, the correct
* corresponding length should be passed too, otherwise a zero
* initialization will be performed with the given setLength.
* @param initValue
* Initializer list with values to initialize with, for example {0,0} to
* initialize the two entries to zero.
* @param setLength
* Defines the array length of this entry. Should be equal to the
* intializer list length.
* @param setValid
* Sets the initialization flag. It is invalid by default.
*/
PoolEntry( std::initializer_list<T> initValue = {}, uint8_t set_length = 1, uint8_t set_valid = 0 );
PoolEntry(std::initializer_list<T> initValue = {}, uint8_t setLength = 1,
bool setValid = false);
/**
* @brief In the classe's constructor, space is allocated on the heap and
* potential init values are copied to that space.
* @param initValue A pointer to the single value or array that holds the init value.
* With the default value (NULL), the entry is initalized with all 0.
* @param set_length Defines the array length of this entry.
* @param set_valid Sets the initialization flag. It is invalid (0) by default.
* @param initValue
* A pointer to the single value or array that holds the init value.
* With the default value (nullptr), the entry is initalized with all 0.
* @param setLength
* Defines the array length of this entry.
* @param setValid
* Sets the initialization flag. It is invalid by default.
*/
PoolEntry( T* initValue = NULL, uint8_t set_length = 1, uint8_t set_valid = 0 );
PoolEntry(T* initValue, uint8_t setLength = 1, bool setValid = false);
//! Explicitely deleted copy ctor, copying is not allowed!
PoolEntry(const PoolEntry&) = delete;
//! Explicitely deleted copy assignment, copying is not allowed!
PoolEntry& operator=(const PoolEntry&) = delete;
/**
* \brief The allocated memory for the variable is freed in the destructor.
* \details As the data pool is global, this dtor is only called on program exit.
* PoolEntries shall never be copied, as a copy might delete the variable on the heap.
* @brief The allocated memory for the variable is freed
* in the destructor.
* @details
* As the data pool is global, this dtor is only called on program exit.
* PoolEntries shall never be copied, as a copy might delete the variable
* on the heap.
*/
~PoolEntry();
/**
* \brief This is the address pointing to the allocated memory.
* @brief This is the address pointing to the allocated memory.
*/
T* address;
/**
* \brief This attribute stores the length information.
* @brief This attribute stores the length information.
*/
uint8_t length;
/**
* \brief Here, the validity information for a variable is stored.
* @brief Here, the validity information for a variable is stored.
* Every entry (single variable or vector) has one valid flag.
*/
uint8_t valid;
/**
* \brief getSize returns the array size of the entry.
* \details A single parameter has size 1.
* @brief getSize returns the array size of the entry.
* @details A single parameter has size 1.
*/
uint8_t getSize();
/**
* \brief This operation returns the size in bytes.
* \details The size is calculated by sizeof(type) * array_size.
* @brief This operation returns the size in bytes.
* @details The size is calculated by sizeof(type) * array_size.
*/
uint16_t getByteSize();
/**
* \brief This operation returns a the address pointer casted to void*.
* @brief This operation returns a the address pointer casted to void*.
*/
void* getRawData();
/**
* \brief This method allows to set the valid information of the pool entry.
* @brief This method allows to set the valid information
* of the pool entry.
*/
void setValid( uint8_t isValid );
void setValid( bool isValid );
/**
* \brief This method allows to get the valid information of the pool entry.
* @brief This method allows to get the valid information
* of the pool entry.
*/
uint8_t getValid();
bool getValid();
/**
* \brief This is a debug method that prints all values and the valid information to the screen.
* It prints all array entries in a row.
* @brief This is a debug method that prints all values and the valid
* information to the screen. It prints all array entries in a row.
*/
void print();

View File

@ -1,5 +1,5 @@
#ifndef POOLENTRYIF_H_
#define POOLENTRYIF_H_
#ifndef FRAMEWORK_DATAPOOL_POOLENTRYIF_H_
#define FRAMEWORK_DATAPOOL_POOLENTRYIF_H_
#include <framework/globalfunctions/Type.h>
#include <cstdint>
@ -9,55 +9,53 @@
* single data pool entry.
* @details
* The interface provides methods to determine the size and the validity
* information of a value. It also defines a method to receive a pointer to
* the raw data content. It is mainly used by DataPool itself, but also as a
* information of a value. It also defines a method to receive a pointer to the
* raw data content. It is mainly used by DataPool itself, but also as a
* return pointer.
* @author Bastian Baetz
*
* @author Bastian Baetz
* @ingroup data_pool
*
*/
class PoolEntryIF {
public:
/**
* @brief This is an empty virtual destructor,
* as it is proposed for C++ interfaces.
* as it is required for C++ interfaces.
*/
virtual ~PoolEntryIF() {}
virtual ~PoolEntryIF() {
}
/**
* @brief getSize returns the array size of the entry.
* A single variable parameter has size 1.
*/
virtual uint8_t getSize() = 0;
/**
* @brief This operation returns the size in bytes, which is calculated by
* sizeof(type) * array_size.
*/
virtual uint16_t getByteSize() = 0;
/**
* @brief This operation returns a the address pointer casted to void*.
*/
virtual void* getRawData() = 0;
/**
* @brief This method allows to set the valid information of the pool entry.
*/
virtual void setValid(uint8_t isValid) = 0;
virtual void setValid(bool isValid) = 0;
/**
* @brief This method allows to set the valid information of the pool entry.
*/
virtual uint8_t getValid() = 0;
virtual bool getValid() = 0;
/**
* @brief This is a debug method that prints all values and the valid
* information to the screen. It prints all array entries in a row.
* @details
* Also displays whether the pool entry is valid or invalid.
*/
virtual void print() = 0;
/**
* @brief Returns the type of the entry.
* Returns the type of the entry.
*/
virtual Type getType() = 0;
};

View File

@ -24,8 +24,9 @@ PoolRawAccessHelper::~PoolRawAccessHelper() {
}
ReturnValue_t PoolRawAccessHelper::serialize(uint8_t **buffer, size_t *size,
const size_t max_size, bool bigEndian) {
SerializationArgs serializationArgs = {buffer, size, max_size, bigEndian};
const size_t max_size, SerializeIF::Endianness streamEndianness) {
SerializationArgs serializationArgs = {buffer, size, max_size,
streamEndianness};
ReturnValue_t result = RETURN_OK;
size_t remainingParametersSize = numberOfParameters * 4;
for(uint8_t count=0; count < numberOfParameters; count++) {
@ -44,9 +45,10 @@ ReturnValue_t PoolRawAccessHelper::serialize(uint8_t **buffer, size_t *size,
}
ReturnValue_t PoolRawAccessHelper::serializeWithValidityMask(uint8_t ** buffer,
size_t * size, const size_t max_size, bool bigEndian) {
size_t * size, const size_t max_size,
SerializeIF::Endianness streamEndianness) {
ReturnValue_t result = RETURN_OK;
SerializationArgs argStruct = {buffer, size, max_size, bigEndian};
SerializationArgs argStruct = {buffer, size, max_size, streamEndianness};
size_t remainingParametersSize = numberOfParameters * 4;
uint8_t validityMaskSize = ceil((float)numberOfParameters/8.0);
uint8_t validityMask[validityMaskSize];
@ -76,8 +78,8 @@ ReturnValue_t PoolRawAccessHelper::serializeCurrentPoolEntryIntoBuffer(
bool withValidMask, uint8_t * validityMask) {
uint32_t currentPoolId;
// Deserialize current pool ID from pool ID buffer
ReturnValue_t result = AutoSerializeAdapter::deSerialize(&currentPoolId,
&poolIdBuffer,remainingParameters, false);
ReturnValue_t result = SerializeAdapter::deSerialize(&currentPoolId,
&poolIdBuffer,remainingParameters, SerializeIF::Endianness::MACHINE);
if(result != RETURN_OK) {
sif::debug << std::hex << "PoolRawAccessHelper: Error deSeralizing "
"pool IDs" << std::dec << std::endl;
@ -109,8 +111,8 @@ ReturnValue_t PoolRawAccessHelper::handlePoolEntrySerialization(
GlobDataSet currentDataSet;
//debug << "Current array position: " << (int)arrayPosition << std::endl;
PoolRawAccess currentPoolRawAccess(currentPoolId,arrayPosition,
&currentDataSet,PoolVariableIF::VAR_READ);
PoolRawAccess currentPoolRawAccess(currentPoolId, arrayPosition,
&currentDataSet, PoolVariableIF::VAR_READ);
result = currentDataSet.read();
if (result != RETURN_OK) {
@ -137,7 +139,7 @@ ReturnValue_t PoolRawAccessHelper::handlePoolEntrySerialization(
}
result = currentDataSet.serialize(argStruct.buffer, argStruct.size,
argStruct.max_size, argStruct.bigEndian);
argStruct.max_size, argStruct.streamEndianness);
if (result != RETURN_OK) {
sif::debug << "Pool Raw Access Helper: Error serializing pool data with "
"ID 0x" << std::hex << currentPoolId << " into send buffer "

View File

@ -43,7 +43,7 @@ public:
* @c RETURN_FAILED on failure
*/
ReturnValue_t serialize(uint8_t ** buffer, size_t * size,
const size_t max_size, bool bigEndian);
const size_t max_size, SerializeIF::Endianness streamEndianness);
/**
* Serializes data pool entries into provided buffer with the validity mask buffer
@ -56,7 +56,7 @@ public:
* @c RETURN_FAILED on failure
*/
ReturnValue_t serializeWithValidityMask(uint8_t ** buffer, size_t * size,
const size_t max_size, bool bigEndian);
const size_t max_size, SerializeIF::Endianness streamEndianness);
private:
@ -71,7 +71,7 @@ private:
uint8_t ** buffer;
size_t * size;
const size_t max_size;
bool bigEndian;
SerializeIF::Endianness streamEndianness;
};
/**
* Helper function to serialize single pool entries

View File

@ -1,12 +1,12 @@
#ifndef POOLVARIABLEIF_H_
#define POOLVARIABLEIF_H_
#ifndef FRAMEWORK_DATAPOOL_POOLVARIABLEIF_H_
#define FRAMEWORK_DATAPOOL_POOLVARIABLEIF_H_
#include <framework/returnvalues/HasReturnvaluesIF.h>
#include <framework/serialize/SerializeIF.h>
/**
* @brief This interface is used to control data pool variable representations.
* @brief This interface is used to control data pool
* variable representations.
* @details
* To securely handle data pool variables, all pool entries are locally
* managed by data pool variable access classes, which are called pool
@ -21,21 +21,13 @@ class PoolVariableIF : public SerializeIF {
friend class DataSetBase;
friend class GlobDataSet;
friend class LocalDataSet;
protected:
/**
* @brief The commit call shall write back a newly calculated local
* value to the data pool.
*/
virtual ReturnValue_t commit() = 0;
/**
* @brief The read call shall read the value of this parameter from
* the data pool and store the content locally.
*/
virtual ReturnValue_t read() = 0;
public:
static constexpr uint8_t INTERFACE_ID = CLASS_ID::POOL_VARIABLE_IF;
static constexpr ReturnValue_t INVALID_READ_WRITE_MODE = MAKE_RETURN_CODE(0xA0);
static constexpr bool VALID = 1;
static constexpr bool INVALID = 0;
static constexpr uint32_t NO_PARAMETER = 0;
static constexpr uint32_t NO_PARAMETER = 0xffffffff;
enum ReadWriteMode_t {
VAR_READ, VAR_WRITE, VAR_READ_WRITE
@ -47,7 +39,8 @@ public:
*/
virtual ~PoolVariableIF() {}
/**
* @brief This method returns if the variable is write-only, read-write or read-only.
* @brief This method returns if the variable is write-only,
* read-write or read-only.
*/
virtual ReadWriteMode_t getReadWriteMode() const = 0;
/**
@ -55,15 +48,50 @@ public:
*/
virtual uint32_t getDataPoolId() const = 0;
/**
* @brief With this call, the valid information of the variable is returned.
* @brief With this call, the valid information of the
* variable is returned.
*/
virtual bool isValid() const = 0;
/**
* @brief With this call, the valid information of the variable is set.
*/
// why not just use a boolean here?
virtual void setValid(uint8_t validity) = 0;
virtual void setValid(bool validity) = 0;
/**
* @brief The commit call shall write back a newly calculated local
* value to the data pool.
* @details
* It is assumed that these calls are implemented in a thread-safe manner!
*/
virtual ReturnValue_t commit(uint32_t lockTimeout) = 0;
/**
* @brief The read call shall read the value of this parameter from
* the data pool and store the content locally.
* @details
* It is assumbed that these calls are implemented in a thread-safe manner!
*/
virtual ReturnValue_t read(uint32_t lockTimeout) = 0;
protected:
/**
* @brief Same as commit with the difference that comitting will be
* performed without a lock
* @return
* This can be used if the lock protection is handled externally
* to avoid the overhead of locking and unlocking consecutively.
* Declared protected to avoid free public usage.
*/
virtual ReturnValue_t readWithoutLock() = 0;
/**
* @brief Same as commit with the difference that comitting will be
* performed without a lock
* @return
* This can be used if the lock protection is handled externally
* to avoid the overhead of locking and unlocking consecutively.
* Declared protected to avoid free public usage.
*/
virtual ReturnValue_t commitWithoutLock() = 0;
};
using pool_rwm_t = PoolVariableIF::ReadWriteMode_t;

View File

@ -26,7 +26,7 @@ MessageQueueId_t DataPoolAdmin::getCommandQueue() const {
}
ReturnValue_t DataPoolAdmin::executeAction(ActionId_t actionId,
MessageQueueId_t commandedBy, const uint8_t* data, uint32_t size) {
MessageQueueId_t commandedBy, const uint8_t* data, size_t size) {
if (actionId != SET_VALIDITY) {
return INVALID_ACTION_ID;
}
@ -91,7 +91,7 @@ void DataPoolAdmin::handleCommand() {
}
ReturnValue_t DataPoolAdmin::handleMemoryLoad(uint32_t address,
const uint8_t* data, uint32_t size, uint8_t** dataPointer) {
const uint8_t* data, size_t size, uint8_t** dataPointer) {
uint32_t poolId = glob::dataPool.PIDToDataPoolId(address);
uint8_t arrayIndex = glob::dataPool.PIDToArrayIndex(address);
GlobDataSet testSet;
@ -129,7 +129,7 @@ ReturnValue_t DataPoolAdmin::handleMemoryLoad(uint32_t address,
return ACTIVITY_COMPLETED;
}
ReturnValue_t DataPoolAdmin::handleMemoryDump(uint32_t address, uint32_t size,
ReturnValue_t DataPoolAdmin::handleMemoryDump(uint32_t address, size_t size,
uint8_t** dataPointer, uint8_t* copyHere) {
uint32_t poolId = glob::dataPool.PIDToDataPoolId(address);
uint8_t arrayIndex = glob::dataPool.PIDToArrayIndex(address);
@ -151,7 +151,7 @@ ReturnValue_t DataPoolAdmin::handleMemoryDump(uint32_t address, uint32_t size,
PoolVariableIF::VAR_READ);
status = rawSet.read();
if (status == RETURN_OK) {
uint32_t temp = 0;
size_t temp = 0;
status = variable.getEntryEndianSafe(ptrToCopy, &temp, size);
if (status != RETURN_OK) {
return RETURN_FAILED;
@ -261,7 +261,7 @@ ReturnValue_t DataPoolAdmin::handleParameterCommand(CommandMessage* command) {
//identical to ParameterHelper::sendParameter()
ReturnValue_t DataPoolAdmin::sendParameter(MessageQueueId_t to, uint32_t id,
const DataPoolParameterWrapper* wrapper) {
uint32_t serializedSize = wrapper->getSerializedSize();
size_t serializedSize = wrapper->getSerializedSize();
uint8_t *storeElement;
store_address_t address;
@ -275,7 +275,7 @@ ReturnValue_t DataPoolAdmin::sendParameter(MessageQueueId_t to, uint32_t id,
size_t storeElementSize = 0;
result = wrapper->serialize(&storeElement, &storeElementSize,
serializedSize, true);
serializedSize, SerializeIF::Endianness::BIG);
if (result != HasReturnvaluesIF::RETURN_OK) {
storage->deleteData(address);

View File

@ -30,12 +30,12 @@ public:
MessageQueueId_t getCommandQueue() const;
ReturnValue_t handleMemoryLoad(uint32_t address, const uint8_t* data,
uint32_t size, uint8_t** dataPointer);
ReturnValue_t handleMemoryDump(uint32_t address, uint32_t size,
size_t size, uint8_t** dataPointer);
ReturnValue_t handleMemoryDump(uint32_t address, size_t size,
uint8_t** dataPointer, uint8_t* copyHere);
ReturnValue_t executeAction(ActionId_t actionId,
MessageQueueId_t commandedBy, const uint8_t* data, uint32_t size);
MessageQueueId_t commandedBy, const uint8_t* data, size_t size);
//not implemented as ParameterHelper is no used
ReturnValue_t getParameter(uint8_t domainId, uint16_t parameterId,

View File

@ -34,22 +34,22 @@ ReturnValue_t DataPoolParameterWrapper::set(uint8_t domainId,
}
ReturnValue_t DataPoolParameterWrapper::serialize(uint8_t** buffer,
size_t* size, const size_t max_size, bool bigEndian) const {
size_t* size, size_t maxSize, Endianness streamEndianness) const {
ReturnValue_t result;
result = SerializeAdapter<Type>::serialize(&type, buffer, size, max_size,
bigEndian);
result = SerializeAdapter::serialize(&type, buffer, size, maxSize,
streamEndianness);
if (result != HasReturnvaluesIF::RETURN_OK) {
return result;
}
result = SerializeAdapter<uint8_t>::serialize(&columns, buffer, size,
max_size, bigEndian);
result = SerializeAdapter::serialize(&columns, buffer, size,
maxSize, streamEndianness);
if (result != HasReturnvaluesIF::RETURN_OK) {
return result;
}
result = SerializeAdapter<uint8_t>::serialize(&rows, buffer, size, max_size,
bigEndian);
result = SerializeAdapter::serialize(&rows, buffer, size, maxSize,
streamEndianness);
if (result != HasReturnvaluesIF::RETURN_OK) {
return result;
}
@ -58,7 +58,7 @@ ReturnValue_t DataPoolParameterWrapper::serialize(uint8_t** buffer,
GlobDataSet mySet;
PoolRawAccess raw(poolId, index, &mySet,PoolVariableIF::VAR_READ);
mySet.read();
result = raw.serialize(buffer,size,max_size,bigEndian);
result = raw.serialize(buffer,size,maxSize,streamEndianness);
if (result != HasReturnvaluesIF::RETURN_OK){
return result;
}
@ -68,7 +68,7 @@ ReturnValue_t DataPoolParameterWrapper::serialize(uint8_t** buffer,
//same as ParameterWrapper
size_t DataPoolParameterWrapper::getSerializedSize() const {
uint32_t serializedSize = 0;
size_t serializedSize = 0;
serializedSize += type.getSerializedSize();
serializedSize += sizeof(rows);
serializedSize += sizeof(columns);
@ -78,7 +78,7 @@ size_t DataPoolParameterWrapper::getSerializedSize() const {
}
ReturnValue_t DataPoolParameterWrapper::deSerialize(const uint8_t** buffer,
size_t* size, bool bigEndian) {
size_t* size, Endianness streamEndianness) {
return HasReturnvaluesIF::RETURN_FAILED;
}

View File

@ -12,12 +12,12 @@ public:
ReturnValue_t set(uint8_t domainId, uint16_t parameterId);
virtual ReturnValue_t serialize(uint8_t** buffer, size_t* size,
const size_t max_size, bool bigEndian) const;
size_t maxSize, Endianness streamEndianness) const override;
virtual size_t getSerializedSize() const;
virtual size_t getSerializedSize() const override;
virtual ReturnValue_t deSerialize(const uint8_t** buffer, size_t* size,
bool bigEndian);
Endianness streamEndianness) override;
ReturnValue_t copyFrom(const ParameterWrapper *from,
uint16_t startWritingAtIndex);

View File

@ -44,18 +44,18 @@ PoolEntryIF* GlobalDataPool::getRawData( uint32_t data_pool_id ) {
}
}
ReturnValue_t GlobalDataPool::freeDataPoolLock() {
ReturnValue_t GlobalDataPool::unlockDataPool() {
ReturnValue_t status = mutex->unlockMutex();
if ( status != RETURN_OK ) {
if(status != RETURN_OK) {
sif::error << "DataPool::DataPool: unlock of mutex failed with"
" error code: " << status << std::endl;
}
return status;
}
ReturnValue_t GlobalDataPool::lockDataPool() {
ReturnValue_t status = mutex->lockMutex(MutexIF::NO_TIMEOUT);
if ( status != RETURN_OK ) {
ReturnValue_t GlobalDataPool::lockDataPool(uint32_t timeoutMs) {
ReturnValue_t status = mutex->lockMutex(timeoutMs);
if(status != RETURN_OK) {
sif::error << "DataPool::DataPool: lock of mutex failed "
"with error code: " << status << std::endl;
}

View File

@ -95,12 +95,12 @@ public:
* @brief This is a small helper function to facilitate locking the global data pool.
* @details It fetches the pool's mutex id and tries to acquire the mutex.
*/
ReturnValue_t lockDataPool();
ReturnValue_t lockDataPool(uint32_t timeoutMs = MutexIF::BLOCKING);
/**
* @brief This is a small helper function to facilitate unlocking the global data pool.
* @details It fetches the pool's mutex id and tries to free the mutex.
*/
ReturnValue_t freeDataPoolLock();
ReturnValue_t unlockDataPool();
/**
* @brief The print call is a simple debug method.
* @details It prints the current content of the data pool.

View File

@ -2,28 +2,30 @@
#include <framework/datapoolglob/GlobalDataSet.h>
#include <framework/serviceinterface/ServiceInterfaceStream.h>
GlobDataSet::GlobDataSet(): DataSetBase() {}
GlobDataSet::GlobDataSet(): DataSetBase(
reinterpret_cast<PoolVariableIF**>(&registeredVariables),
DATA_SET_MAX_SIZE) {}
// Don't do anything with your variables, they are dead already!
// (Destructor is already called)
GlobDataSet::~GlobDataSet() {}
ReturnValue_t GlobDataSet::commit(bool valid) {
ReturnValue_t GlobDataSet::commit(bool valid, uint32_t lockTimeout) {
setEntriesValid(valid);
setSetValid(valid);
return commit();
return commit(lockTimeout);
}
ReturnValue_t GlobDataSet::commit() {
return DataSetBase::commit();
ReturnValue_t GlobDataSet::commit(uint32_t lockTimeout) {
return DataSetBase::commit(lockTimeout);
}
ReturnValue_t GlobDataSet::unlockDataPool() {
return glob::dataPool.freeDataPoolLock();
return glob::dataPool.unlockDataPool();
}
ReturnValue_t GlobDataSet::lockDataPool() {
return glob::dataPool.lockDataPool();
ReturnValue_t GlobDataSet::lockDataPool(uint32_t timeoutMs) {
return glob::dataPool.lockDataPool(timeoutMs);
}
void GlobDataSet::setEntriesValid(bool valid) {

View File

@ -1,5 +1,5 @@
#ifndef DATASET_H_
#define DATASET_H_
#ifndef FRAMEWORK_DATAPOOLGLOB_DATASET_H_
#define FRAMEWORK_DATAPOOLGLOB_DATASET_H_
#include <framework/datapool/DataSetBase.h>
@ -44,8 +44,8 @@ public:
* - @c COMMITING_WITHOUT_READING if set was not read yet and
* contains non write-only variables
*/
ReturnValue_t commit(bool valid);
ReturnValue_t commit() override;
ReturnValue_t commit(bool valid, uint32_t lockTimeout = MutexIF::BLOCKING);
ReturnValue_t commit(uint32_t lockTimeout = MutexIF::BLOCKING) override;
/**
* Set all entries
@ -61,6 +61,10 @@ public:
*/
void setEntriesValid(bool valid);
//!< This definition sets the maximum number of variables to
//! register in one DataSet.
static const uint8_t DATA_SET_MAX_SIZE = 63;
private:
/**
* If the valid state of a dataset is always relevant to the whole
@ -74,8 +78,7 @@ private:
* @details
* It makes use of the lockDataPool method offered by the DataPool class.
*/
ReturnValue_t lockDataPool() override;
ReturnValue_t lockDataPool(uint32_t timeoutMs) override;
/**
* @brief This is a small helper function to facilitate
* unlocking the global data pool
@ -86,6 +89,8 @@ private:
void handleAlreadyReadDatasetCommit();
ReturnValue_t handleUnreadDatasetCommit();
PoolVariableIF* registeredVariables[DATA_SET_MAX_SIZE];
};
#endif /* DATASET_H_ */
#endif /* FRAMEWORK_DATAPOOLGLOB_DATASET_H_ */

View File

@ -72,7 +72,49 @@ public:
*/
~GlobPoolVar() {}
/**
* @brief This is a call to read the value from the global data pool.
* @details
* When executed, this operation tries to fetch the pool entry with matching
* data pool id from the global data pool and copies the value and the valid
* information to its local attributes. In case of a failure (wrong type or
* pool id not found), the variable is set to zero and invalid.
* The read call is protected with a lock.
* It is recommended to use DataSets to read and commit multiple variables
* at once to avoid the overhead of unnecessary lock und unlock operations.
*/
ReturnValue_t read(uint32_t lockTimeout) override;
/**
* @brief The commit call writes back the variable's value to the data pool.
* @details
* It checks type and size, as well as if the variable is writable. If so,
* the value is copied and the valid flag is automatically set to "valid".
* The operation does NOT provide any mutual exclusive protection by itself.
* The commit call is protected with a lock.
* It is recommended to use DataSets to read and commit multiple variables
* at once to avoid the overhead of unnecessary lock und unlock operations.
*/
ReturnValue_t commit(uint32_t lockTimeout) override;
protected:
/**
* @brief Like #read, but without a lock protection of the global pool.
* @details
* The operation does NOT provide any mutual exclusive protection by itself.
* This can be used if the lock is handled externally to avoid the overhead
* of consecutive lock und unlock operations.
* Declared protected to discourage free public usage.
*/
ReturnValue_t readWithoutLock() override;
/**
* @brief Like #commit, but without a lock protection of the global pool.
* @details
* The operation does NOT provide any mutual exclusive protection by itself.
* This can be used if the lock is handled externally to avoid the overhead
* of consecutive lock und unlock operations.
* Declared protected to discourage free public usage.
*/
ReturnValue_t commitWithoutLock() override;
/**
* @brief To access the correct data pool entry on read and commit calls,
* the data pool is stored.
@ -91,26 +133,6 @@ protected:
*/
pool_rwm_t readWriteMode;
/**
* @brief This is a call to read the value from the global data pool.
* @details
* When executed, this operation tries to fetch the pool entry with matching
* data pool id from the global data pool and copies the value and the valid
* information to its local attributes. In case of a failure (wrong type or
* pool id not found), the variable is set to zero and invalid.
* The operation does NOT provide any mutual exclusive protection by itself.
*/
ReturnValue_t read() override;
/**
* @brief The commit call writes back the variable's value to the data pool.
* @details It checks type and size, as well as if the variable is writable. If so,
* the value is copied and the valid flag is automatically set to "valid".
* The operation does NOT provide any mutual exclusive protection by itself.
*
*/
ReturnValue_t commit() override;
/**
* Empty ctor for List initialization
*/
@ -138,7 +160,7 @@ public:
uint8_t getValid();
void setValid(uint8_t valid);
void setValid(bool valid) override;
operator T() {
return value;
@ -159,18 +181,20 @@ public:
}
virtual ReturnValue_t serialize(uint8_t** buffer, size_t* size,
const size_t max_size, bool bigEndian) const override {
return SerializeAdapter<T>::serialize(&value, buffer, size, max_size,
bigEndian);
const size_t max_size,
SerializeIF::Endianness streamEndianness) const override {
return SerializeAdapter::serialize(&value, buffer, size, max_size,
streamEndianness);
}
virtual size_t getSerializedSize() const {
return SerializeAdapter<T>::getSerializedSize(&value);
return SerializeAdapter::getSerializedSize(&value);
}
virtual ReturnValue_t deSerialize(const uint8_t** buffer, size_t* size,
bool bigEndian) {
return SerializeAdapter<T>::deSerialize(&value, buffer, size, bigEndian);
SerializeIF::Endianness streamEndianness) {
return SerializeAdapter::deSerialize(&value, buffer, size,
streamEndianness);
}
};

View File

@ -12,8 +12,38 @@ inline GlobPoolVar<T>::GlobPoolVar(uint32_t set_id,
}
}
template<typename T>
inline ReturnValue_t GlobPoolVar<T>::read(uint32_t lockTimeout) {
ReturnValue_t result = glob::dataPool.lockDataPool(lockTimeout);
if(result != HasReturnvaluesIF::RETURN_OK) {
return result;
}
result = readWithoutLock();
ReturnValue_t unlockResult = glob::dataPool.unlockDataPool();
if(unlockResult != HasReturnvaluesIF::RETURN_OK) {
sif::error << "GlobPoolVar::read: Could not unlock global data pool"
<< std::endl;
}
return result;
}
template<typename T>
inline ReturnValue_t GlobPoolVar<T>::commit(uint32_t lockTimeout) {
ReturnValue_t result = glob::dataPool.lockDataPool(lockTimeout);
if(result != HasReturnvaluesIF::RETURN_OK) {
return result;
}
result = commitWithoutLock();
ReturnValue_t unlockResult = glob::dataPool.unlockDataPool();
if(unlockResult != HasReturnvaluesIF::RETURN_OK) {
sif::error << "GlobPoolVar::read: Could not unlock global data pool"
<< std::endl;
}
return result;
}
template <class T>
inline ReturnValue_t GlobPoolVar<T>::read() {
inline ReturnValue_t GlobPoolVar<T>::readWithoutLock() {
PoolEntry<T>* read_out = glob::dataPool.getData<T>(dataPoolId, 1);
if (read_out != NULL) {
valid = read_out->valid;
@ -29,7 +59,7 @@ inline ReturnValue_t GlobPoolVar<T>::read() {
}
template <class T>
inline ReturnValue_t GlobPoolVar<T>::commit() {
inline ReturnValue_t GlobPoolVar<T>::commitWithoutLock() {
PoolEntry<T>* write_back = glob::dataPool.getData<T>(dataPoolId, 1);
if ((write_back != NULL) && (readWriteMode != VAR_READ)) {
write_back->valid = valid;
@ -80,7 +110,7 @@ inline uint8_t GlobPoolVar<T>::getValid() {
}
template <class T>
inline void GlobPoolVar<T>::setValid(uint8_t valid) {
inline void GlobPoolVar<T>::setValid(bool valid) {
this->valid = valid;
}

View File

@ -102,18 +102,18 @@ public:
else
return false;
}
void setValid(uint8_t valid) {this->valid = valid;}
void setValid(bool valid) {this->valid = valid;}
uint8_t getValid() {return valid;}
T &operator [](int i) {return value[i];}
const T &operator [](int i) const {return value[i];}
virtual ReturnValue_t serialize(uint8_t** buffer, size_t* size,
const size_t max_size, bool bigEndian) const override;
size_t max_size, Endianness streamEndianness) const override;
virtual size_t getSerializedSize() const override;
virtual ReturnValue_t deSerialize(const uint8_t** buffer, size_t* size,
bool bigEndian) override;
protected:
Endianness streamEndianness) override;
/**
* @brief This is a call to read the array's values
* from the global data pool.
@ -122,19 +122,43 @@ protected:
* data pool id from the global data pool and copies all array values
* and the valid information to its local attributes.
* In case of a failure (wrong type, size or pool id not found), the
* variable is set to zero and invalid. The operation does NOT provide
* any mutual exclusive protection by itself.
* variable is set to zero and invalid.
* The read call is protected by a lock of the global data pool.
* It is recommended to use DataSets to read and commit multiple variables
* at once to avoid the overhead of unnecessary lock und unlock operations.
*/
ReturnValue_t read();
ReturnValue_t read(uint32_t lockTimeout = MutexIF::BLOCKING) override;
/**
* @brief The commit call copies the array values back to the data pool.
* @details
* It checks type and size, as well as if the variable is writable. If so,
* the value is copied and the valid flag is automatically set to "valid".
* The operation does NOT provide any mutual exclusive protection by itself.
* The commit call is protected by a lock of the global data pool.
* It is recommended to use DataSets to read and commit multiple variables
* at once to avoid the overhead of unnecessary lock und unlock operations.
*/
ReturnValue_t commit();
ReturnValue_t commit(uint32_t lockTimeout = MutexIF::BLOCKING) override;
protected:
/**
* @brief Like #read, but without a lock protection of the global pool.
* @details
* The operation does NOT provide any mutual exclusive protection by itself.
* This can be used if the lock is handled externally to avoid the overhead
* of consecutive lock und unlock operations.
* Declared protected to discourage free public usage.
*/
ReturnValue_t readWithoutLock() override;
/**
* @brief Like #commit, but without a lock protection of the global pool.
* @details
* The operation does NOT provide any mutual exclusive protection by itself.
* This can be used if the lock is handled externally to avoid the overhead
* of consecutive lock und unlock operations.
* Declared protected to discourage free public usage.
*/
ReturnValue_t commitWithoutLock() override;
private:
/**
* @brief To access the correct data pool entry on read and commit calls,

View File

@ -12,8 +12,40 @@ inline GlobPoolVector<T, vectorSize>::GlobPoolVector(uint32_t set_id,
}
}
template<typename T, uint16_t vectorSize>
inline ReturnValue_t GlobPoolVector<T, vectorSize>::read() {
inline ReturnValue_t GlobPoolVector<T, vectorSize>::read(uint32_t lockTimeout) {
ReturnValue_t result = glob::dataPool.lockDataPool(lockTimeout);
if(result != HasReturnvaluesIF::RETURN_OK) {
return result;
}
result = readWithoutLock();
ReturnValue_t unlockResult = glob::dataPool.unlockDataPool();
if(unlockResult != HasReturnvaluesIF::RETURN_OK) {
sif::error << "GlobPoolVar::read: Could not unlock global data pool"
<< std::endl;
}
return result;
}
template<typename T, uint16_t vectorSize>
inline ReturnValue_t GlobPoolVector<T, vectorSize>::commit(
uint32_t lockTimeout) {
ReturnValue_t result = glob::dataPool.lockDataPool(lockTimeout);
if(result != HasReturnvaluesIF::RETURN_OK) {
return result;
}
result = commitWithoutLock();
ReturnValue_t unlockResult = glob::dataPool.unlockDataPool();
if(unlockResult != HasReturnvaluesIF::RETURN_OK) {
sif::error << "GlobPoolVar::read: Could not unlock global data pool"
<< std::endl;
}
return result;
}
template<typename T, uint16_t vectorSize>
inline ReturnValue_t GlobPoolVector<T, vectorSize>::readWithoutLock() {
PoolEntry<T>* read_out = glob::dataPool.getData<T>(this->dataPoolId,
vectorSize);
if (read_out != nullptr) {
@ -33,7 +65,7 @@ inline ReturnValue_t GlobPoolVector<T, vectorSize>::read() {
}
template<typename T, uint16_t vectorSize>
inline ReturnValue_t GlobPoolVector<T, vectorSize>::commit() {
inline ReturnValue_t GlobPoolVector<T, vectorSize>::commitWithoutLock() {
PoolEntry<T>* writeBack = glob::dataPool.getData<T>(this->dataPoolId,
vectorSize);
if ((writeBack != nullptr) && (this->readWriteMode != VAR_READ)) {
@ -47,12 +79,13 @@ inline ReturnValue_t GlobPoolVector<T, vectorSize>::commit() {
template<typename T, uint16_t vectorSize>
inline ReturnValue_t GlobPoolVector<T, vectorSize>::serialize(uint8_t** buffer,
size_t* size, const size_t max_size, bool bigEndian) const {
size_t* size, size_t max_size,
SerializeIF::Endianness streamEndianness) const {
uint16_t i;
ReturnValue_t result;
for (i = 0; i < vectorSize; i++) {
result = SerializeAdapter<T>::serialize(&(value[i]), buffer, size,
max_size, bigEndian);
result = SerializeAdapter::serialize(&(value[i]), buffer, size,
max_size, streamEndianness);
if (result != HasReturnvaluesIF::RETURN_OK) {
return result;
}
@ -62,17 +95,18 @@ inline ReturnValue_t GlobPoolVector<T, vectorSize>::serialize(uint8_t** buffer,
template<typename T, uint16_t vectorSize>
inline size_t GlobPoolVector<T, vectorSize>::getSerializedSize() const {
return vectorSize * SerializeAdapter<T>::getSerializedSize(value);
return vectorSize * SerializeAdapter::getSerializedSize(value);
}
template<typename T, uint16_t vectorSize>
inline ReturnValue_t GlobPoolVector<T, vectorSize>::deSerialize(
const uint8_t** buffer, size_t* size, bool bigEndian) {
const uint8_t** buffer, size_t* size,
SerializeIF::Endianness streamEndianness) {
uint16_t i;
ReturnValue_t result;
for (i = 0; i < vectorSize; i++) {
result = SerializeAdapter<T>::deSerialize(&(value[i]), buffer, size,
bigEndian);
result = SerializeAdapter::deSerialize(&(value[i]), buffer, size,
streamEndianness);
if (result != HasReturnvaluesIF::RETURN_OK) {
return result;
}

View File

@ -15,9 +15,9 @@ class PIDReader: public PoolVariableIF {
protected:
uint32_t parameterId;
uint8_t valid;
ReturnValue_t read() {
ReturnValue_t readWithoutLock() {
uint8_t arrayIndex = GlobalDataPool::PIDToArrayIndex(parameterId);
PoolEntry<T>* read_out = glob::dataPool.getData<T>(
PoolEntry<T> *read_out = glob::dataPool.getData<T>(
GlobalDataPool::PIDToDataPoolId(parameterId), arrayIndex);
if (read_out != NULL) {
valid = read_out->valid;
@ -36,14 +36,19 @@ protected:
* Reason is the possibility to access a single DP vector element, but if we commit,
* we set validity of the whole vector.
*/
ReturnValue_t commit() {
ReturnValue_t commit(uint32_t lockTimeout) override {
return HasReturnvaluesIF::RETURN_FAILED;
}
ReturnValue_t commitWithoutLock() override {
return HasReturnvaluesIF::RETURN_FAILED;
}
/**
* Empty ctor for List initialization
*/
PIDReader() :
parameterId(PoolVariableIF::NO_PARAMETER), valid(PoolVariableIF::INVALID), value(0) {
parameterId(PoolVariableIF::NO_PARAMETER), valid(
PoolVariableIF::INVALID), value(0) {
}
public:
@ -63,18 +68,31 @@ public:
* \param setWritable If this flag is set to true, changes in the value attribute can be
* written back to the data pool, otherwise not.
*/
PIDReader(uint32_t setParameterId, DataSetIF* dataSet) :
parameterId(setParameterId), valid(
PoolVariableIF::INVALID), value(0) {
PIDReader(uint32_t setParameterId, DataSetIF *dataSet) :
parameterId(setParameterId), valid(PoolVariableIF::INVALID), value(
0) {
if (dataSet != NULL) {
dataSet->registerVariable(this);
}
}
ReturnValue_t read(uint32_t lockTimeout) override {
ReturnValue_t result = glob::dataPool.lockDataPool();
if(result != HasReturnvaluesIF::RETURN_OK) {
return result;
}
result = readWithoutLock();
ReturnValue_t unlockResult = glob::dataPool.unlockDataPool();
if(unlockResult != HasReturnvaluesIF::RETURN_OK) {
sif::error << "PIDReader::read: Could not unlock data pool!"
<< std::endl;
}
return result;
}
/**
* Copy ctor to copy classes containing Pool Variables.
*/
PIDReader(const PIDReader& rhs) :
PIDReader(const PIDReader &rhs) :
parameterId(rhs.parameterId), valid(rhs.valid), value(rhs.value) {
}
@ -113,7 +131,7 @@ public:
return valid;
}
void setValid(uint8_t valid) {
void setValid(bool valid) {
this->valid = valid;
}
@ -121,24 +139,25 @@ public:
return value;
}
PIDReader<T> &operator=(T newValue) {
PIDReader<T>& operator=(T newValue) {
value = newValue;
return *this;
}
virtual ReturnValue_t serialize(uint8_t** buffer, size_t* size,
const size_t max_size, bool bigEndian) const {
return SerializeAdapter<T>::serialize(&value, buffer, size, max_size,
bigEndian);
virtual ReturnValue_t serialize(uint8_t **buffer, size_t *size,
size_t maxSize, Endianness streamEndianness) const override {
return SerializeAdapter::serialize(&value, buffer, size, maxSize,
streamEndianness);
}
virtual size_t getSerializedSize() const {
return SerializeAdapter<T>::getSerializedSize(&value);
virtual size_t getSerializedSize() const override {
return SerializeAdapter::getSerializedSize(&value);
}
virtual ReturnValue_t deSerialize(const uint8_t** buffer, size_t* size,
bool bigEndian) {
return SerializeAdapter<T>::deSerialize(&value, buffer, size, bigEndian);
virtual ReturnValue_t deSerialize(const uint8_t **buffer, size_t *size,
Endianness streamEndianness) override {
return SerializeAdapter::deSerialize(&value, buffer, size,
streamEndianness);
}
};

View File

@ -1,7 +1,9 @@
#include <framework/datapoolglob/GlobalDataPool.h>
#include <framework/datapoolglob/PoolRawAccess.h>
#include <framework/serviceinterface/ServiceInterfaceStream.h>
#include <framework/osal/Endiness.h>
#include <framework/serialize/EndianConverter.h>
#include <cstring>
PoolRawAccess::PoolRawAccess(uint32_t set_id, uint8_t setArrayEntry,
DataSetIF* dataSet, ReadWriteMode_t setReadWriteMode) :
@ -16,7 +18,21 @@ PoolRawAccess::PoolRawAccess(uint32_t set_id, uint8_t setArrayEntry,
PoolRawAccess::~PoolRawAccess() {}
ReturnValue_t PoolRawAccess::read() {
ReturnValue_t PoolRawAccess::read(uint32_t lockTimeout) {
ReturnValue_t result = glob::dataPool.lockDataPool(lockTimeout);
if(result != HasReturnvaluesIF::RETURN_OK) {
return result;
}
result = readWithoutLock();
ReturnValue_t unlockResult = glob::dataPool.unlockDataPool();
if(unlockResult != HasReturnvaluesIF::RETURN_OK) {
sif::error << "GlobPoolVar::read: Could not unlock global data pool"
<< std::endl;
}
return result;
}
ReturnValue_t PoolRawAccess::readWithoutLock() {
ReturnValue_t result = RETURN_FAILED;
PoolEntryIF* readOut = glob::dataPool.getRawData(dataPoolId);
if (readOut != nullptr) {
@ -73,7 +89,21 @@ void PoolRawAccess::handleReadError(ReturnValue_t result) {
memset(value, 0, sizeof(value));
}
ReturnValue_t PoolRawAccess::commit() {
ReturnValue_t PoolRawAccess::commit(uint32_t lockTimeout) {
ReturnValue_t result = glob::dataPool.lockDataPool(lockTimeout);
if(result != HasReturnvaluesIF::RETURN_OK) {
return result;
}
result = commitWithoutLock();
ReturnValue_t unlockResult = glob::dataPool.unlockDataPool();
if(unlockResult != HasReturnvaluesIF::RETURN_OK) {
sif::error << "GlobPoolVar::read: Could not unlock global data pool"
<< std::endl;
}
return result;
}
ReturnValue_t PoolRawAccess::commitWithoutLock() {
PoolEntryIF* write_back = glob::dataPool.getRawData(dataPoolId);
if ((write_back != NULL) && (readWriteMode != VAR_READ)) {
write_back->setValid(valid);
@ -91,7 +121,7 @@ uint8_t* PoolRawAccess::getEntry() {
}
ReturnValue_t PoolRawAccess::getEntryEndianSafe(uint8_t* buffer,
uint32_t* writtenBytes, uint32_t max_size) {
size_t* writtenBytes, size_t max_size) {
uint8_t* data_ptr = getEntry();
// debug << "PoolRawAccess::getEntry: Array position: " <<
// index * size_of_type << " Size of T: " << (int)size_of_type <<
@ -100,42 +130,33 @@ ReturnValue_t PoolRawAccess::getEntryEndianSafe(uint8_t* buffer,
return DATA_POOL_ACCESS_FAILED;
if (typeSize > max_size)
return INCORRECT_SIZE;
#ifndef BYTE_ORDER_SYSTEM
#error BYTE_ORDER_SYSTEM not defined
#elif BYTE_ORDER_SYSTEM == LITTLE_ENDIAN
for (uint8_t count = 0; count < typeSize; count++) {
buffer[count] = data_ptr[typeSize - count - 1];
}
#elif BYTE_ORDER_SYSTEM == BIG_ENDIAN
memcpy(buffer, data_ptr, typeSize);
#endif
EndianConverter::convertBigEndian(buffer, data_ptr, typeSize);
*writtenBytes = typeSize;
return HasReturnvaluesIF::RETURN_OK;
}
ReturnValue_t PoolRawAccess::serialize(uint8_t** buffer, size_t* size,
const size_t max_size, bool bigEndian) const {
if (typeSize + *size <= max_size) {
if (bigEndian) {
#ifndef BYTE_ORDER_SYSTEM
#error BYTE_ORDER_SYSTEM not defined
#elif BYTE_ORDER_SYSTEM == LITTLE_ENDIAN
for (uint8_t count = 0; count < typeSize; count++) {
(*buffer)[count] = value[typeSize - count - 1];
}
#elif BYTE_ORDER_SYSTEM == BIG_ENDIAN
memcpy(*buffer, value, typeSize);
#endif
} else {
memcpy(*buffer, value, typeSize);
}
*size += typeSize;
(*buffer) += typeSize;
return HasReturnvaluesIF::RETURN_OK;
} else {
return SerializeIF::BUFFER_TOO_SHORT;
}
size_t maxSize, Endianness streamEndianness) const {
if (typeSize + *size <= maxSize) {
switch(streamEndianness) {
case(Endianness::BIG):
EndianConverter::convertBigEndian(*buffer, value, typeSize);
break;
case(Endianness::LITTLE):
EndianConverter::convertLittleEndian(*buffer, value, typeSize);
break;
case(Endianness::MACHINE):
default:
memcpy(*buffer, value, typeSize);
break;
}
*size += typeSize;
(*buffer) += typeSize;
return HasReturnvaluesIF::RETURN_OK;
} else {
return SerializeIF::BUFFER_TOO_SHORT;
}
}
@ -143,11 +164,11 @@ Type PoolRawAccess::getType() {
return type;
}
uint8_t PoolRawAccess::getSizeOfType() {
size_t PoolRawAccess::getSizeOfType() {
return typeSize;
}
uint8_t PoolRawAccess::getArraySize(){
size_t PoolRawAccess::getArraySize(){
return arraySize;
}
@ -159,22 +180,14 @@ PoolVariableIF::ReadWriteMode_t PoolRawAccess::getReadWriteMode() const {
return readWriteMode;
}
ReturnValue_t PoolRawAccess::setEntryFromBigEndian(const uint8_t* buffer,
uint32_t setSize) {
ReturnValue_t PoolRawAccess::setEntryFromBigEndian(const uint8_t *buffer,
size_t setSize) {
if (typeSize == setSize) {
#ifndef BYTE_ORDER_SYSTEM
#error BYTE_ORDER_SYSTEM not defined
#elif BYTE_ORDER_SYSTEM == LITTLE_ENDIAN
for (uint8_t count = 0; count < typeSize; count++) {
value[count] = buffer[typeSize - count - 1];
}
#elif BYTE_ORDER_SYSTEM == BIG_ENDIAN
memcpy(value, buffer, typeSize);
#endif
EndianConverter::convertBigEndian(value, buffer, typeSize);
return HasReturnvaluesIF::RETURN_OK;
} else {
sif::error << "PoolRawAccess::setEntryFromBigEndian: Illegal sizes: Internal"
<< (uint32_t) typeSize << ", Requested: " << setSize
sif::error << "PoolRawAccess::setEntryFromBigEndian: Illegal sizes: "
"Internal" << (uint32_t) typeSize << ", Requested: " << setSize
<< std::endl;
return INCORRECT_SIZE;
}
@ -187,11 +200,11 @@ bool PoolRawAccess::isValid() const {
return false;
}
void PoolRawAccess::setValid(uint8_t valid) {
void PoolRawAccess::setValid(bool valid) {
this->valid = valid;
}
uint16_t PoolRawAccess::getSizeTillEnd() const {
size_t PoolRawAccess::getSizeTillEnd() const {
return sizeTillEnd;
}
@ -200,29 +213,27 @@ size_t PoolRawAccess::getSerializedSize() const {
return typeSize;
}
ReturnValue_t PoolRawAccess::deSerialize(const uint8_t** buffer, size_t* size,
bool bigEndian) {
// TODO: Needs to be tested!!!
if (*size >= typeSize) {
*size -= typeSize;
if (bigEndian) {
#ifndef BYTE_ORDER_SYSTEM
#error BYTE_ORDER_SYSTEM not defined
#elif BYTE_ORDER_SYSTEM == LITTLE_ENDIAN
for (uint8_t count = 0; count < typeSize; count++) {
value[count] = (*buffer)[typeSize - count - 1];
}
#elif BYTE_ORDER_SYSTEM == BIG_ENDIAN
memcpy(value, *buffer, typeSize);
#endif
}
else {
memcpy(value, *buffer, typeSize);
}
*buffer += typeSize;
return HasReturnvaluesIF::RETURN_OK;
}
else {
return SerializeIF::STREAM_TOO_SHORT;
}
ReturnValue_t PoolRawAccess::deSerialize(const uint8_t **buffer, size_t *size,
Endianness streamEndianness) {
if (*size >= typeSize) {
switch(streamEndianness) {
case(Endianness::BIG):
EndianConverter::convertBigEndian(value, *buffer, typeSize);
break;
case(Endianness::LITTLE):
EndianConverter::convertLittleEndian(value, *buffer, typeSize);
break;
case(Endianness::MACHINE):
default:
memcpy(value, *buffer, typeSize);
break;
}
*size -= typeSize;
*buffer += typeSize;
return HasReturnvaluesIF::RETURN_OK;
}
else {
return SerializeIF::STREAM_TOO_SHORT;
}
}

View File

@ -57,8 +57,8 @@ public:
* @return - @c RETURN_OK if entry could be acquired
* - @c RETURN_FAILED else.
*/
ReturnValue_t getEntryEndianSafe(uint8_t* buffer, uint32_t* size,
uint32_t max_size);
ReturnValue_t getEntryEndianSafe(uint8_t *buffer, size_t *size,
size_t maxSize);
/**
* @brief Serialize raw pool entry into provided buffer directly
@ -69,8 +69,13 @@ public:
* @return - @c RETURN_OK if serialization was successfull
* - @c SerializeIF::BUFFER_TOO_SHORT if range check failed
*/
ReturnValue_t serialize(uint8_t** buffer, size_t* size,
const size_t max_size, bool bigEndian) const;
ReturnValue_t serialize(uint8_t **buffer, size_t *size,
size_t maxSize, Endianness streamEndianness) const override;
size_t getSerializedSize() const override;
ReturnValue_t deSerialize(const uint8_t **buffer, size_t *size,
Endianness streamEndianness) override;
/**
* With this method, the content can be set from a big endian buffer safely.
@ -80,7 +85,7 @@ public:
* - @c RETURN_FAILED on failure
*/
ReturnValue_t setEntryFromBigEndian(const uint8_t* buffer,
uint32_t setSize);
size_t setSize);
/**
* @brief This operation returns the type of the entry currently stored.
*/
@ -88,12 +93,12 @@ public:
/**
* @brief This operation returns the size of the entry currently stored.
*/
uint8_t getSizeOfType();
size_t getSizeOfType();
/**
*
* @return the size of the datapool array
*/
uint8_t getArraySize();
size_t getArraySize();
/**
* @brief This operation returns the data pool id of the variable.
*/
@ -124,42 +129,55 @@ public:
*/
bool isValid() const;
void setValid(uint8_t valid);
void setValid(bool valid);
/**
* Getter for the remaining size.
*/
uint16_t getSizeTillEnd() const;
size_t getSizeTillEnd() const;
size_t getSerializedSize() const;
ReturnValue_t deSerialize(const uint8_t** buffer, size_t* size,
bool bigEndian);
protected:
/**
* @brief This is a call to read the value from the global data pool.
* @details When executed, this operation tries to fetch the pool entry with matching
* data pool id from the global data pool and copies the value and the valid
* information to its local attributes. In case of a failure (wrong type or
* pool id not found), the variable is set to zero and invalid.
* The operation does NOT provide any mutual exclusive protection by itself !
* If reading from the data pool without information about the type is desired,
* initialize the raw pool access by supplying a data set and using the data set
* read function, which calls this read function.
* @details
* When executed, this operation tries to fetch the pool entry with matching
* data pool id from the global data pool and copies the value and the valid
* information to its local attributes. In case of a failure (wrong type or
* pool id not found), the variable is set to zero and invalid.
* The call is protected by a lock of the global data pool.
* @return -@c RETURN_OK Read successfull
* -@c READ_TYPE_TOO_LARGE
* -@c READ_INDEX_TOO_LARGE
* -@c READ_ENTRY_NON_EXISTENT
*/
ReturnValue_t read();
ReturnValue_t read(uint32_t lockTimeout = MutexIF::BLOCKING) override;
/**
* @brief The commit call writes back the variable's value to the data pool.
* @details It checks type and size, as well as if the variable is writable. If so,
* the value is copied and the valid flag is automatically set to "valid".
* The operation does NOT provide any mutual exclusive protection by itself.
* @details
* It checks type and size, as well as if the variable is writable. If so,
* the value is copied and the valid flag is automatically set to "valid".
* The call is protected by a lock of the global data pool.
*
*/
ReturnValue_t commit();
ReturnValue_t commit(uint32_t lockTimeout = MutexIF::BLOCKING) override;
protected:
/**
* @brief Like #read, but without a lock protection of the global pool.
* @details
* The operation does NOT provide any mutual exclusive protection by itself.
* This can be used if the lock is handled externally to avoid the overhead
* of consecutive lock und unlock operations.
* Declared protected to discourage free public usage.
*/
ReturnValue_t readWithoutLock() override;
/**
* @brief Like #commit, but without a lock protection of the global pool.
* @details
* The operation does NOT provide any mutual exclusive protection by itself.
* This can be used if the lock is handled externally to avoid the overhead
* of consecutive lock und unlock operations.
* Declared protected to discourage free public usage.
*/
ReturnValue_t commitWithoutLock() override;
ReturnValue_t handleReadOut(PoolEntryIF* read_out);
void handleReadError(ReturnValue_t result);
@ -184,15 +202,15 @@ private:
/**
* @brief This value contains the size of the data pool entry type in bytes.
*/
uint8_t typeSize;
size_t typeSize;
/**
* The size of the DP array (single values return 1)
*/
uint8_t arraySize;
size_t arraySize;
/**
* The size (in bytes) from the selected entry till the end of this DataPool variable.
*/
uint16_t sizeTillEnd;
size_t sizeTillEnd;
/**
* @brief The information whether the class is read-write or read-only is stored here.
*/

View File

@ -0,0 +1,77 @@
#ifndef FRAMEWORK_DATAPOOL_HASHKPOOLPARAMETERSIF_H_
#define FRAMEWORK_DATAPOOL_HASHKPOOLPARAMETERSIF_H_
#include <framework/datapool/PoolEntryIF.h>
#include <framework/ipc/MessageQueueSenderIF.h>
#include <framework/housekeeping/HousekeepingMessage.h>
#include <map>
class LocalDataPoolManager;
class DataSetIF;
/**
* @brief Type definition for local pool entries.
*/
using lp_id_t = uint32_t;
using LocalDataPool = std::map<lp_id_t, PoolEntryIF*>;
using LocalDataPoolMapIter = LocalDataPool::iterator;
/**
* @brief This interface is implemented by classes which posses a local
* data pool (not the managing class). It defines the relationship
* between the local data pool owner and the LocalDataPoolManager.
* @details
* Any class implementing this interface shall also have a LocalDataPoolManager
* member class which contains the actual pool data structure
* and exposes the public interface for it.
* This is required because the pool entries are templates, which makes
* specifying an interface rather difficult. The local data pool can be
* accessed by using the LocalPoolVariable, LocalPoolVector or LocalDataSet
* classes.
*
* Architectural Note:
* This could be circumvented by using a wrapper/accessor function or
* implementing the templated function in this interface..
* The first solution sounds better than the second but
* the LocalPoolVariable classes are templates as well, so this just shifts
* the problem somewhere else. Interfaces are nice, but the most
* pragmatic solution I found was to offer the client the full interface
* of the LocalDataPoolManager.
*/
class HasLocalDataPoolIF {
public:
virtual~ HasLocalDataPoolIF() {};
static constexpr uint8_t INTERFACE_ID = CLASS_ID::LOCAL_POOL_OWNER_IF;
/** Command queue for housekeeping messages. */
virtual MessageQueueId_t getCommandQueue() const = 0;
/** Is used by pool owner to initialize the pool map once */
virtual ReturnValue_t initializePoolEntries(
LocalDataPool& localDataPoolMap) = 0;
/** Can be used to get a handle to the local data pool manager. */
virtual LocalDataPoolManager* getHkManagerHandle() = 0;
/**
* This function is used by the pool manager to get a valid dataset
* from a SID
* @param sid Corresponding structure ID
* @return
*/
virtual DataSetIF* getDataSetHandle(sid_t sid) = 0;
/* These function can be implemented by pool owner, as they are required
* by the housekeeping message interface */
virtual ReturnValue_t addDataSet(sid_t sid) {
return HasReturnvaluesIF::RETURN_FAILED;
};
virtual ReturnValue_t removeDataSet(sid_t sid) {
return HasReturnvaluesIF::RETURN_FAILED;
};
virtual ReturnValue_t changeCollectionInterval(sid_t sid,
dur_seconds_t newInterval) {
return HasReturnvaluesIF::RETURN_FAILED;
};
};
#endif /* FRAMEWORK_DATAPOOL_HASHKPOOLPARAMETERSIF_H_ */

View File

@ -0,0 +1,218 @@
#include <framework/datapoollocal/LocalDataPoolManager.h>
#include <framework/datapoollocal/LocalDataSet.h>
#include <framework/housekeeping/AcceptsHkPacketsIF.h>
#include <framework/ipc/MutexFactory.h>
#include <framework/ipc/MutexHelper.h>
#include <framework/ipc/QueueFactory.h>
#include <array>
LocalDataPoolManager::LocalDataPoolManager(HasLocalDataPoolIF* owner,
MessageQueueIF* queueToUse, bool appendValidityBuffer):
appendValidityBuffer(appendValidityBuffer) {
if(owner == nullptr) {
sif::error << "HkManager: Invalid supplied owner!" << std::endl;
return;
}
this->owner = owner;
mutex = MutexFactory::instance()->createMutex();
if(mutex == nullptr) {
sif::error << "LocalDataPoolManager::LocalDataPoolManager: "
"Could not create mutex." << std::endl;
}
ipcStore = objectManager->get<StorageManagerIF>(objects::IPC_STORE);
if(ipcStore == nullptr) {
sif::error << "LocalDataPoolManager::LocalDataPoolManager: "
"Could not set IPC store." << std::endl;
}
hkQueue = queueToUse;
}
ReturnValue_t LocalDataPoolManager::initialize(MessageQueueIF* queueToUse,
object_id_t hkDestination) {
if(queueToUse == nullptr) {
sif::error << "LocalDataPoolManager::initialize: Supplied queue "
"invalid!" << std::endl;
}
hkQueue = queueToUse;
if(hkDestination == objects::NO_OBJECT) {
return initializeHousekeepingPoolEntriesOnce();
}
AcceptsHkPacketsIF* hkReceiver =
objectManager->get<AcceptsHkPacketsIF>(hkDestination);
if(hkReceiver != nullptr) {
setHkPacketDestination(hkReceiver->getHkQueue());
}
else {
sif::warning << "LocalDataPoolManager::initialize: Could not retrieve"
" queue ID from HK destination object ID. " << std::flush;
sif::warning << "Make sure it exists and the object impements "
"AcceptsHkPacketsIF!" << std::endl;
}
return initializeHousekeepingPoolEntriesOnce();
}
void LocalDataPoolManager::setHkPacketDestination(
MessageQueueId_t hkDestination) {
this->hkDestination = hkDestination;
}
LocalDataPoolManager::~LocalDataPoolManager() {}
ReturnValue_t LocalDataPoolManager::initializeHousekeepingPoolEntriesOnce() {
if(not mapInitialized) {
ReturnValue_t result = owner->initializePoolEntries(localPoolMap);
if(result == HasReturnvaluesIF::RETURN_OK) {
mapInitialized = true;
}
return result;
}
sif::warning << "HousekeepingManager: The map should only be initialized "
"once!" << std::endl;
return HasReturnvaluesIF::RETURN_OK;
}
ReturnValue_t LocalDataPoolManager::handleHousekeepingMessage(
CommandMessage* message) {
Command_t command = message->getCommand();
switch(command) {
// I think those are the only commands which can be handled here..
case(HousekeepingMessage::ADD_HK_REPORT_STRUCT):
case(HousekeepingMessage::ADD_DIAGNOSTICS_REPORT_STRUCT):
// We should use OwnsLocalPoolDataIF to specify those functions..
return HasReturnvaluesIF::RETURN_OK;
case(HousekeepingMessage::REPORT_DIAGNOSTICS_REPORT_STRUCTURES):
case(HousekeepingMessage::REPORT_HK_REPORT_STRUCTURES):
//return generateSetStructurePacket(message->getSid());
case(HousekeepingMessage::GENERATE_ONE_PARAMETER_REPORT):
case(HousekeepingMessage::GENERATE_ONE_DIAGNOSTICS_REPORT):
//return generateHousekeepingPacket(message->getSid());
default:
return CommandMessageIF::UNKNOWN_COMMAND;
}
}
ReturnValue_t LocalDataPoolManager::printPoolEntry(
lp_id_t localPoolId) {
auto poolIter = localPoolMap.find(localPoolId);
if (poolIter == localPoolMap.end()) {
sif::debug << "HousekeepingManager::fechPoolEntry:"
" Pool entry not found." << std::endl;
return POOL_ENTRY_NOT_FOUND;
}
poolIter->second->print();
return HasReturnvaluesIF::RETURN_OK;
}
MutexIF* LocalDataPoolManager::getMutexHandle() {
return mutex;
}
const HasLocalDataPoolIF* LocalDataPoolManager::getOwner() const {
return owner;
}
ReturnValue_t LocalDataPoolManager::generateHousekeepingPacket(sid_t sid,
MessageQueueId_t sendTo) {
LocalDataSet* dataSetToSerialize = dynamic_cast<LocalDataSet*>(
owner->getDataSetHandle(sid));
if(dataSetToSerialize == nullptr) {
sif::warning << "HousekeepingManager::generateHousekeepingPacket:"
" Set ID not found" << std::endl;
return HasReturnvaluesIF::RETURN_FAILED;
}
store_address_t storeId;
ReturnValue_t result = serializeHkPacketIntoStore(&storeId,
dataSetToSerialize);
if(result != HasReturnvaluesIF::RETURN_OK) {
return result;
}
// and now we set a HK message and send it the HK packet destination.
CommandMessage hkMessage;
HousekeepingMessage::setHkReportMessage(&hkMessage, sid, storeId);
if(hkQueue == nullptr) {
return QUEUE_OR_DESTINATION_NOT_SET;
}
if(sendTo != MessageQueueIF::NO_QUEUE) {
result = hkQueue->sendMessage(sendTo, &hkMessage);
}
else {
if(hkDestination == MessageQueueIF::NO_QUEUE) {
sif::warning << "LocalDataPoolManager::generateHousekeepingPacket:"
" Destination is not set properly!" << std::endl;
return QUEUE_OR_DESTINATION_NOT_SET;
}
else {
result = hkQueue->sendMessage(hkDestination, &hkMessage);
}
}
return result;
}
ReturnValue_t LocalDataPoolManager::generateSetStructurePacket(sid_t sid) {
LocalDataSet* dataSet = dynamic_cast<LocalDataSet*>(
owner->getDataSetHandle(sid));
if(dataSet == nullptr) {
sif::warning << "HousekeepingManager::generateHousekeepingPacket:"
" Set ID not found" << std::endl;
return HasReturnvaluesIF::RETURN_FAILED;
}
size_t expectedSize = dataSet->getFillCount() * sizeof(lp_id_t);
uint8_t* storePtr = nullptr;
store_address_t storeId;
ReturnValue_t result = ipcStore->getFreeElement(&storeId,
expectedSize,&storePtr);
if(result != HasReturnvaluesIF::RETURN_OK) {
sif::error << "HousekeepingManager::generateHousekeepingPacket: "
"Could not get free element from IPC store." << std::endl;
return result;
}
size_t size = 0;
result = dataSet->serializeLocalPoolIds(&storePtr, &size,
expectedSize, SerializeIF::Endianness::BIG);
if(expectedSize != size) {
sif::error << "HousekeepingManager::generateSetStructurePacket: "
"Expected size is not equal to serialized size" << std::endl;
}
return result;
}
void LocalDataPoolManager::setMinimalSamplingFrequency(float frequencySeconds) {
}
ReturnValue_t LocalDataPoolManager::serializeHkPacketIntoStore(
store_address_t *storeId, LocalDataSet* dataSet) {
size_t hkSize = dataSet->getSerializedSize();
uint8_t* storePtr = nullptr;
ReturnValue_t result = ipcStore->getFreeElement(storeId, hkSize,&storePtr);
if(result != HasReturnvaluesIF::RETURN_OK) {
sif::error << "HousekeepingManager::generateHousekeepingPacket: "
"Could not get free element from IPC store." << std::endl;
return result;
}
size_t size = 0;
if(appendValidityBuffer) {
result = dataSet->serializeWithValidityBuffer(&storePtr,
&size, hkSize, SerializeIF::Endianness::MACHINE);
}
else {
result = dataSet->serialize(&storePtr, &size, hkSize,
SerializeIF::Endianness::MACHINE);
}
if(result != HasReturnvaluesIF::RETURN_OK) {
sif::error << "HousekeepingManager::serializeHkPacketIntoStore: "
"Serialization proccess failed!" << std::endl;
}
return result;
}
ReturnValue_t LocalDataPoolManager::performHkOperation() {
return HasReturnvaluesIF::RETURN_OK;
}

View File

@ -0,0 +1,229 @@
#ifndef FRAMEWORK_DATAPOOLLOCAL_LOCALDATAPOOLMANAGER_H_
#define FRAMEWORK_DATAPOOLLOCAL_LOCALDATAPOOLMANAGER_H_
#include <framework/datapool/DataSetIF.h>
#include <framework/objectmanager/SystemObjectIF.h>
#include <framework/ipc/MutexIF.h>
#include <framework/housekeeping/HousekeepingMessage.h>
#include <framework/datapool/PoolEntry.h>
#include <framework/datapoollocal/HasLocalDataPoolIF.h>
#include <framework/ipc/CommandMessage.h>
#include <framework/ipc/MessageQueueIF.h>
#include <framework/ipc/MutexHelper.h>
#include <map>
class LocalDataSet;
/**
* @brief This class is the managing instance for local data pool.
* @details
* The actual data pool structure is a member of this class. Any class which
* has a local data pool shall have this class as a member and implement
* the HasLocalDataPoolIF.
*
* Users of the data pool use the helper classes LocalDataSet,
* LocalPoolVariable and LocalPoolVector to access pool entries in
* a thread-safe and efficient way.
*
* The local data pools employ a blackboard logic: Only the most recent
* value is stored. The helper classes offer a read() and commit() interface
* through the PoolVariableIF which is used to read and update values.
* Each pool entry has a valid state too.
*
*/
class LocalDataPoolManager {
template<typename T>
friend class LocalPoolVar;
template<typename T, uint16_t vecSize>
friend class LocalPoolVector;
friend class LocalDataSet;
public:
static constexpr uint8_t INTERFACE_ID = CLASS_ID::HOUSEKEEPING_MANAGER;
static constexpr ReturnValue_t POOL_ENTRY_NOT_FOUND = MAKE_RETURN_CODE(0x0);
static constexpr ReturnValue_t POOL_ENTRY_TYPE_CONFLICT = MAKE_RETURN_CODE(0x1);
static constexpr ReturnValue_t QUEUE_OR_DESTINATION_NOT_SET = MAKE_RETURN_CODE(0x2);
//static constexpr ReturnValue_t SET_NOT_FOUND = MAKE_RETURN_CODE(0x3);
/**
* This constructor is used by a class which wants to implement
* a personal local data pool. The queueToUse can be supplied if it
* is already known.
*
* initialize() has to be called in any case before using the object!
* @param owner
* @param queueToUse
* @param appendValidityBuffer
*/
LocalDataPoolManager(HasLocalDataPoolIF* owner, MessageQueueIF* queueToUse,
bool appendValidityBuffer = true);
virtual~ LocalDataPoolManager();
/**
* Initializes the map by calling the map initialization function of the
* owner and assigns the queue to use.
* @param queueToUse
* @return
*/
ReturnValue_t initialize(MessageQueueIF* queueToUse,
object_id_t hkDestination);
/**
* This should be called in the periodic handler of the owner.
* It performs all the periodic functionalities of the data pool manager.
* @return
*/
ReturnValue_t performHkOperation();
/**
* This function is used to set the default HK packet destination.
* This destination will usually only be set once.
* @param hkDestination
*/
void setHkPacketDestination(MessageQueueId_t hkDestination);
/**
* Generate a housekeeping packet with a given SID.
* @param sid
* @return
*/
ReturnValue_t generateHousekeepingPacket(sid_t sid, MessageQueueId_t sendTo
= MessageQueueIF::NO_QUEUE);
ReturnValue_t generateSetStructurePacket(sid_t sid);
ReturnValue_t handleHousekeepingMessage(CommandMessage* message);
/**
* This function is used to fill the local data pool map with pool
* entries. It should only be called once by the pool owner.
* @param localDataPoolMap
* @return
*/
ReturnValue_t initializeHousekeepingPoolEntriesOnce();
const HasLocalDataPoolIF* getOwner() const;
ReturnValue_t printPoolEntry(lp_id_t localPoolId);
/**
* Different types of housekeeping reporting are possible.
* 1. PERIODIC: HK packets are generated in fixed intervals
* 2. UPDATED: HK packets are generated if a value was updated
* 3. REQUESTED: HK packets are only generated if explicitely requested
*/
enum class ReportingType: uint8_t {
PERIODIC,
ON_UPDATE,
REQUESTED
};
/* Copying forbidden */
LocalDataPoolManager(const LocalDataPoolManager &) = delete;
LocalDataPoolManager operator=(const LocalDataPoolManager&) = delete;
private:
LocalDataPool localPoolMap;
/** Every housekeeping data manager has a mutex to protect access
* to it's data pool. */
MutexIF* mutex = nullptr;
/** The class which actually owns the manager (and its datapool). */
HasLocalDataPoolIF* owner = nullptr;
/**
* The data pool manager will keep an internal map of HK receivers.
*/
struct HkReceiver {
LocalDataSet* dataSet = nullptr;
MessageQueueId_t destinationQueue = MessageQueueIF::NO_QUEUE;
ReportingType reportingType = ReportingType::PERIODIC;
bool reportingStatus = true;
/** Different members of this union will be used depending on reporting
* type */
union hkParameter {
/** This parameter will be used for the PERIODIC type */
dur_seconds_t collectionInterval = 0;
/** This parameter will be used for the ON_UPDATE type */
bool hkDataChanged;
};
};
/** Using a multimap as the same object might request multiple datasets */
using HkReceiversMap = std::multimap<object_id_t, struct HkReceiver>;
HkReceiversMap hkReceiversMap;
/** This is the map holding the actual data. Should only be initialized
* once ! */
bool mapInitialized = false;
/** This specifies whether a validity buffer is appended at the end
* of generated housekeeping packets. */
bool appendValidityBuffer = true;
/**
* @brief Queue used for communication, for example commands.
* Is also used to send messages. Can be set either in the constructor
* or in the initialize() function.
*/
MessageQueueIF* hkQueue = nullptr;
/**
* HK replies will always be a reply to the commander, but HK packet
* can be sent to another destination by specifying this message queue
* ID, for example to a dedicated housekeeping service implementation.
*/
MessageQueueId_t hkDestination = MessageQueueIF::NO_QUEUE;
/** Global IPC store is used to store all packets. */
StorageManagerIF* ipcStore = nullptr;
/**
* Get the pointer to the mutex. Can be used to lock the data pool
* eternally. Use with care and don't forget to unlock locked mutexes!
* For now, only friend classes can accss this function.
* @return
*/
MutexIF* getMutexHandle();
/**
* Read a variable by supplying its local pool ID and assign the pool
* entry to the supplied PoolEntry pointer. The type of the pool entry
* is deduced automatically. This call is not thread-safe!
* For now, only friend classes like LocalPoolVar may access this
* function.
* @tparam T Type of the pool entry
* @param localPoolId Pool ID of the variable to read
* @param poolVar [out] Corresponding pool entry will be assigned to the
* supplied pointer.
* @return
*/
template <class T> ReturnValue_t fetchPoolEntry(lp_id_t localPoolId,
PoolEntry<T> **poolEntry);
void setMinimalSamplingFrequency(float frequencySeconds);
ReturnValue_t serializeHkPacketIntoStore(store_address_t* storeId,
LocalDataSet* dataSet);
};
template<class T> inline
ReturnValue_t LocalDataPoolManager::fetchPoolEntry(lp_id_t localPoolId,
PoolEntry<T> **poolEntry) {
auto poolIter = localPoolMap.find(localPoolId);
if (poolIter == localPoolMap.end()) {
sif::warning << "HousekeepingManager::fechPoolEntry: Pool entry "
"not found." << std::endl;
return POOL_ENTRY_NOT_FOUND;
}
*poolEntry = dynamic_cast< PoolEntry<T>* >(poolIter->second);
if(*poolEntry == nullptr) {
sif::debug << "HousekeepingManager::fetchPoolEntry:"
" Pool entry not found." << std::endl;
return POOL_ENTRY_TYPE_CONFLICT;
}
return HasReturnvaluesIF::RETURN_OK;
}
#endif /* FRAMEWORK_DATAPOOLLOCAL_LOCALDATAPOOLMANAGER_H_ */

View File

@ -1,66 +1,106 @@
#include <framework/datapoollocal/LocalDataPoolManager.h>
#include <framework/datapoollocal/LocalDataSet.h>
#include <framework/serialize/SerializeAdapter.h>
LocalDataSet::LocalDataSet():
fill_count(0), state(DATA_SET_UNINITIALISED)
{
for (unsigned count = 0; count < DATA_SET_MAX_SIZE; count++) {
registeredVariables[count] = nullptr;
}
#include <cmath>
#include <cstring>
LocalDataSet::LocalDataSet(HasLocalDataPoolIF *hkOwner,
const size_t maxNumberOfVariables):
DataSetBase(poolVarList.data(), maxNumberOfVariables) {
poolVarList.reserve(maxNumberOfVariables);
poolVarList.resize(maxNumberOfVariables);
if(hkOwner == nullptr) {
sif::error << "LocalDataSet::LocalDataSet: Owner can't be nullptr!"
<< std::endl;
return;
}
hkManager = hkOwner->getHkManagerHandle();
}
// who has the responsibility to lock the mutex? the local pool variable
// has access to the HK manager and could call its mutex lock function.
ReturnValue_t LocalDataSet::registerVariable(
PoolVariableIF *variable) {
return RETURN_OK;
LocalDataSet::LocalDataSet(object_id_t ownerId,
const size_t maxNumberOfVariables):
DataSetBase(poolVarList.data(), maxNumberOfVariables) {
poolVarList.reserve(maxNumberOfVariables);
poolVarList.resize(maxNumberOfVariables);
HasLocalDataPoolIF* hkOwner = objectManager->get<HasLocalDataPoolIF>(
ownerId);
if(hkOwner == nullptr) {
sif::error << "LocalDataSet::LocalDataSet: Owner can't be nullptr!"
<< std::endl;
return;
}
hkManager = hkOwner->getHkManagerHandle();
}
LocalDataSet::~LocalDataSet() {
}
ReturnValue_t LocalDataSet::read() {
return RETURN_OK;
ReturnValue_t LocalDataSet::lockDataPool(uint32_t timeoutMs) {
MutexIF* mutex = hkManager->getMutexHandle();
return mutex->lockMutex(timeoutMs);
}
ReturnValue_t LocalDataSet::commit(void) {
return RETURN_OK;
}
ReturnValue_t LocalDataSet::commit(bool valid) {
return RETURN_OK;
}
void LocalDataSet::setSetValid(bool valid) {
}
void LocalDataSet::setEntriesValid(bool valid) {
}
ReturnValue_t LocalDataSet::serialize(uint8_t **buffer,
size_t *size, const size_t max_size, bool bigEndian) const {
return RETURN_OK;
}
size_t LocalDataSet::getSerializedSize() const {
return 0;
}
ReturnValue_t LocalDataSet::deSerialize(const uint8_t **buffer,
size_t *size, bool bigEndian) {
return RETURN_OK;
}
ReturnValue_t LocalDataSet::lockDataPool() {
return RETURN_OK;
ReturnValue_t LocalDataSet::serializeWithValidityBuffer(uint8_t **buffer,
size_t *size, size_t maxSize,
SerializeIF::Endianness streamEndianness) const {
ReturnValue_t result = HasReturnvaluesIF::RETURN_FAILED;
uint8_t validityMaskSize = std::ceil(static_cast<float>(fillCount)/8.0);
uint8_t validityMask[validityMaskSize];
uint8_t validBufferIndex = 0;
uint8_t validBufferIndexBit = 0;
for (uint16_t count = 0; count < fillCount; count++) {
if(registeredVariables[count]->isValid()) {
// set validity buffer here.
this->bitSetter(validityMask + validBufferIndex,
validBufferIndexBit);
if(validBufferIndexBit == 7) {
validBufferIndex ++;
validBufferIndexBit = 0;
}
else {
validBufferIndexBit ++;
}
}
result = registeredVariables[count]->serialize(buffer, size, maxSize,
streamEndianness);
if (result != HasReturnvaluesIF::RETURN_OK) {
return result;
}
}
// copy validity buffer to end
std::memcpy(*buffer, validityMask, validityMaskSize);
*size += validityMaskSize;
return result;
}
ReturnValue_t LocalDataSet::unlockDataPool() {
return RETURN_OK;
MutexIF* mutex = hkManager->getMutexHandle();
return mutex->unlockMutex();
}
void LocalDataSet::handleAlreadyReadDatasetCommit() {
ReturnValue_t LocalDataSet::serializeLocalPoolIds(uint8_t** buffer,
size_t* size, size_t maxSize,
SerializeIF::Endianness streamEndianness) const {
for (uint16_t count = 0; count < fillCount; count++) {
lp_id_t currentPoolId = registeredVariables[count]->getDataPoolId();
auto result = SerializeAdapter::serialize(&currentPoolId, buffer,
size, maxSize, streamEndianness);
if(result != HasReturnvaluesIF::RETURN_OK) {
sif::warning << "LocalDataSet::serializeLocalPoolIds: Serialization"
" error!" << std::endl;
return result;
}
}
return HasReturnvaluesIF::RETURN_OK;
}
ReturnValue_t LocalDataSet::handleUnreadDatasetCommit() {
return RETURN_OK;
void LocalDataSet::bitSetter(uint8_t* byte, uint8_t position) const {
if(position > 7) {
sif::debug << "Pool Raw Access: Bit setting invalid position" << std::endl;
return;
}
uint8_t shiftNumber = position + (7 - 2 * position);
*byte |= 1 << shiftNumber;
}

View File

@ -1,8 +1,14 @@
#ifndef FRAMEWORK_DATAPOOLLOCAL_LOCALDATASET_H_
#define FRAMEWORK_DATAPOOLLOCAL_LOCALDATASET_H_
#include <framework/datapool/DataSetBase.h>
#include <framework/datapool/DataSetIF.h>
#include <framework/datapoollocal/HasLocalDataPoolIF.h>
#include <framework/serialize/SerializeIF.h>
#include <vector>
class LocalDataPoolManager;
/**
* @brief The LocalDataSet class manages a set of locally checked out variables
* for local data pools
@ -24,32 +30,24 @@
*
* @ingroup data_pool
*/
class LocalDataSet:
public DataSetIF,
public HasReturnvaluesIF,
public SerializeIF {
class LocalDataSet: public DataSetBase {
public:
static constexpr uint8_t INTERFACE_ID = CLASS_ID::DATA_SET_CLASS;
static constexpr ReturnValue_t INVALID_PARAMETER_DEFINITION =
MAKE_RETURN_CODE( 0x01 );
static constexpr ReturnValue_t SET_WAS_ALREADY_READ = MAKE_RETURN_CODE( 0x02 );
static constexpr ReturnValue_t COMMITING_WITHOUT_READING =
MAKE_RETURN_CODE(0x03);
static constexpr ReturnValue_t DATA_SET_UNINITIALIZED = MAKE_RETURN_CODE( 0x04 );
static constexpr ReturnValue_t DATA_SET_FULL = MAKE_RETURN_CODE( 0x05 );
static constexpr ReturnValue_t POOL_VAR_NULL = MAKE_RETURN_CODE( 0x06 );
/**
* @brief The constructor simply sets the fill_count to zero and sets
* @brief Constructor for the creator of local pool data.
* The constructor simply sets the fill_count to zero and sets
* the state to "uninitialized".
*/
LocalDataSet();
LocalDataSet(HasLocalDataPoolIF *hkOwner,
const size_t maxNumberOfVariables);
/**
* @brief This operation is used to register the local variables in the set.
* @details It stores the pool variable pointer in a variable list.
* @brief Constructor for users of local pool data. The passed pool
* owner should implement the HasHkPoolParametersIF.
* The constructor simply sets the fill_count to zero and sets
* the state to "uninitialized".
*/
ReturnValue_t registerVariable(PoolVariableIF* variable) override;
LocalDataSet(object_id_t ownerId,
const size_t maxNumberOfVariables);
/**
* @brief The destructor automatically manages writing the valid
@ -62,126 +60,56 @@ public:
~LocalDataSet();
/**
* @brief The read call initializes reading out all registered variables.
* @details
* It iterates through the list of registered variables and calls all read()
* functions of the registered pool variables (which read out their values
* from the data pool) which are not write-only.
* In case of an error (e.g. a wrong data type, or an invalid data pool id),
* the operation is aborted and @c INVALID_PARAMETER_DEFINITION returned.
*
* The data pool is locked during the whole read operation and
* freed afterwards.The state changes to "was written" after this operation.
* @return - @c RETURN_OK if all variables were read successfully.
* - @c INVALID_PARAMETER_DEFINITION if PID, size or type of the
* requested variable is invalid.
* - @c SET_WAS_ALREADY_READ if read() is called twice without
* calling commit() in between
* Special version of the serilization function which appends a
* validity buffer at the end. Each bit of this validity buffer
* denotes whether the container data set entries are valid from left
* to right, MSB first.
* @param buffer
* @param size
* @param maxSize
* @param bigEndian
* @param withValidityBuffer
* @return
*/
ReturnValue_t read();
ReturnValue_t serializeWithValidityBuffer(uint8_t** buffer,
size_t* size, size_t maxSize,
SerializeIF::Endianness streamEndianness) const;
/**
* @brief The commit call initializes writing back the registered variables.
* @details
* It iterates through the list of registered variables and calls the
* commit() method of the remaining registered variables (which write back
* their values to the pool).
*
* The data pool is locked during the whole commit operation and
* freed afterwards. The state changes to "was committed" after this operation.
*
* If the set does contain at least one variable which is not write-only commit()
* can only be called after read(). If the set only contains variables which are
* write only, commit() can be called without a preceding read() call.
* @return - @c RETURN_OK if all variables were read successfully.
* - @c COMMITING_WITHOUT_READING if set was not read yet and
* contains non write-only variables
*/
ReturnValue_t commit(void);
/**
* Variant of method above which sets validity of all elements of the set.
* @param valid Validity information from PoolVariableIF.
* @return - @c RETURN_OK if all variables were read successfully.
* - @c COMMITING_WITHOUT_READING if set was not read yet and
* contains non write-only variables
*/
ReturnValue_t commit(bool valid);
/**
* Set all entries
* @param valid
*/
void setSetValid(bool valid);
/**
* Set the valid information of all variables contained in the set which
* are not read-only
*
* @param valid Validity information from PoolVariableIF.
*/
void setEntriesValid(bool valid);
ReturnValue_t serialize(uint8_t** buffer, size_t* size,
const size_t max_size, bool bigEndian) const override;
size_t getSerializedSize() const override;
ReturnValue_t deSerialize(const uint8_t** buffer, size_t* size,
bool bigEndian) override;
ReturnValue_t serializeLocalPoolIds(uint8_t** buffer,
size_t* size, size_t maxSize,
SerializeIF::Endianness streamEndianness) const;
protected:
private:
// SHOULDDO we could use a linked list of datapool variables
//! This definition sets the maximum number of variables
//! to register in one DataSet.
static const uint8_t DATA_SET_MAX_SIZE = 63;
/**
* @brief This array represents all pool variables registered in this set.
*/
PoolVariableIF* registeredVariables[DATA_SET_MAX_SIZE];
/**
* @brief The fill_count attribute ensures that the variables register in
* the correct array position and that the maximum number of
* variables is not exceeded.
*/
uint16_t fill_count;
/**
* States of the seet.
*/
enum States {
DATA_SET_UNINITIALISED, //!< DATA_SET_UNINITIALISED
DATA_SET_WAS_READ //!< DATA_SET_WAS_READ
};
/**
* @brief state manages the internal state of the data set,
* which is important e.g. for the behavior on destruction.
*/
States state;
/**
* If the valid state of a dataset is always relevant to the whole
* data set we can use this flag.
*/
bool valid = false;
/**
* @brief This is a small helper function to facilitate locking
* the underlying data data pool structure
* the global data pool.
* @details
* It makes use of the lockDataPool method offered by the DataPool class.
*/
ReturnValue_t lockDataPool() override;
ReturnValue_t lockDataPool(uint32_t timeoutMs) override;
/**
* @brief This is a small helper function to facilitate
* unlocking the underlying data data pool structure
* unlocking the global data pool
* @details
* It makes use of the freeDataPoolLock method offered by the DataPool class.
*/
ReturnValue_t unlockDataPool() override;
void handleAlreadyReadDatasetCommit();
ReturnValue_t handleUnreadDatasetCommit();
LocalDataPoolManager* hkManager;
/**
* Set n-th bit of a byte, with n being the position from 0
* (most significant bit) to 7 (least significant bit)
*/
void bitSetter(uint8_t* byte, uint8_t position) const;
std::vector<PoolVariableIF*> poolVarList;
};
#endif /* FRAMEWORK_DATAPOOLLOCAL_LOCALDATASET_H_ */

View File

@ -3,56 +3,68 @@
#include <framework/datapool/PoolVariableIF.h>
#include <framework/datapool/DataSetIF.h>
#include <framework/datapoollocal/HasLocalDataPoolIF.h>
#include <framework/datapoollocal/LocalDataPoolManager.h>
#include <framework/objectmanager/ObjectManagerIF.h>
#include <framework/housekeeping/HousekeepingManager.h>
#include <map>
/**
* @brief This is the access class for non-array local data pool entries.
*
* @details
*
* @tparam T The template parameter sets the type of the variable.
* Currently, all plain data types are supported, but in principle
* any type is possible.
* @ingroup data_pool
*/
#include <framework/serialize/SerializeAdapter.h>
/**
* @brief Local Pool Variable class which is used to access the local pools.
* @details This class is not stored in the map. Instead, it is used to access
* the pool entries by using a pointer to the map storing the pool
* entries. It can also be used to organize these pool entries
* into data sets.
* @tparam T
* @details
* This class is not stored in the map. Instead, it is used to access
* the pool entries by using a pointer to the map storing the pool
* entries. It can also be used to organize these pool entries into data sets.
*
* @tparam T The template parameter sets the type of the variable. Currently,
* all plain data types are supported, but in principle any type is possible.
* @ingroup data_pool
*/
template<typename T>
class LocalPoolVar: public PoolVariableIF, HasReturnvaluesIF {
public:
static constexpr lp_id_t INVALID_POOL_ID = 0xFFFFFFFF;
//! Default ctor is forbidden.
LocalPoolVar() = delete;
/**
* This constructor is used by the data creators to have pool variable
* instances which can also be stored in datasets.
* @param set_id
* @param setReadWriteMode
* @param localPoolMap
* @param dataSet
*
* It does not fetch the current value from the data pool, which
* has to be done by calling the read() operation.
* Datasets can be used to access multiple local pool entries in an
* efficient way. A pointer to a dataset can be passed to register
* the pool variable in that dataset directly.
* @param poolId ID of the local pool entry.
* @param hkOwner Pointer of the owner. This will generally be the calling
* class itself which passes "this".
* @param setReadWriteMode Specify the read-write mode of the pool variable.
* @param dataSet The data set in which the variable shall register itself.
* If nullptr, the variable is not registered.
*/
LocalPoolVar(lp_id_t poolId, HasHkPoolParametersIF* hkOwner,
pool_rwm_t setReadWriteMode, DataSetIF* dataSet = nullptr);
LocalPoolVar(lp_id_t poolId, HasLocalDataPoolIF* hkOwner,
pool_rwm_t setReadWriteMode = pool_rwm_t::VAR_READ_WRITE,
DataSetIF* dataSet = nullptr);
/**
* This constructor is used by data users like controllers to have
* access to the local pool variables of data creators by supplying
* the respective creator object ID.
* @param poolId
* @param poolOwner
* @param setReadWriteMode
* @param dataSet
*
* It does not fetch the current value from the data pool, which
* has to be done by calling the read() operation.
* Datasets can be used to access multiple local pool entries in an
* efficient way. A pointer to a dataset can be passed to register
* the pool variable in that dataset directly.
* @param poolId ID of the local pool entry.
* @param hkOwner object ID of the pool owner.
* @param setReadWriteMode Specify the read-write mode of the pool variable.
* @param dataSet The data set in which the variable shall register itself.
* If nullptr, the variable is not registered.
*/
LocalPoolVar(lp_id_t poolId, object_id_t poolOwner,
pool_rwm_t setReadWriteMode, DataSetIF* dataSet = nullptr);
pool_rwm_t setReadWriteMode = pool_rwm_t::VAR_READ_WRITE,
DataSetIF* dataSet = nullptr);
virtual~ LocalPoolVar() {};
@ -63,33 +75,90 @@ public:
*/
T value = 0;
ReturnValue_t commit() override;
ReturnValue_t read() override;
pool_rwm_t getReadWriteMode() const override;
uint32_t getDataPoolId() const override;
bool isValid() const override;
void setValid(uint8_t validity) override;
ReturnValue_t serialize(uint8_t** buffer, size_t* size,
const size_t max_size, bool bigEndian) const override;
lp_id_t getDataPoolId() const override;
void setDataPoolId(lp_id_t poolId);
bool isValid() const override;
void setValid(bool validity) override;
uint8_t getValid() const;
ReturnValue_t serialize(uint8_t** buffer, size_t* size, size_t maxSize,
SerializeIF::Endianness streamEndianness) const override;
virtual size_t getSerializedSize() const override;
virtual ReturnValue_t deSerialize(const uint8_t** buffer, size_t* size,
bool bigEndian) override;
SerializeIF::Endianness streamEndianness) override;
/**
* @brief This is a call to read the array's values
* from the global data pool.
* @details
* When executed, this operation tries to fetch the pool entry with matching
* data pool id from the data pool and copies all array values and the valid
* information to its local attributes.
* In case of a failure (wrong type, size or pool id not found), the
* variable is set to zero and invalid.
* The read call is protected with a lock.
* It is recommended to use DataSets to read and commit multiple variables
* at once to avoid the overhead of unnecessary lock und unlock operations.
*
*/
ReturnValue_t read(dur_millis_t lockTimeout = MutexIF::BLOCKING) override;
/**
* @brief The commit call copies the array values back to the data pool.
* @details
* It checks type and size, as well as if the variable is writable. If so,
* the value is copied and the local valid flag is written back as well.
* The read call is protected with a lock.
* It is recommended to use DataSets to read and commit multiple variables
* at once to avoid the overhead of unnecessary lock und unlock operations.
*/
ReturnValue_t commit(dur_millis_t lockTimeout = MutexIF::BLOCKING) override;
protected:
/**
* @brief Like #read, but without a lock protection of the global pool.
* @details
* The operation does NOT provide any mutual exclusive protection by itself.
* This can be used if the lock is handled externally to avoid the overhead
* of consecutive lock und unlock operations.
* Declared protected to discourage free public usage.
*/
ReturnValue_t readWithoutLock() override;
/**
* @brief Like #commit, but without a lock protection of the global pool.
* @details
* The operation does NOT provide any mutual exclusive protection by itself.
* This can be used if the lock is handled externally to avoid the overhead
* of consecutive lock und unlock operations.
* Declared protected to discourage free public usage.
*/
ReturnValue_t commitWithoutLock() override;
// std::ostream is the type for object std::cout
template <typename U>
friend std::ostream& operator<< (std::ostream &out,
const LocalPoolVar<U> &var);
private:
lp_id_t localPoolId = INVALID_POOL_ID;
//! @brief Pool ID of pool entry inside the used local pool.
lp_id_t localPoolId = PoolVariableIF::NO_PARAMETER;
//! @brief Read-write mode of the pool variable
pool_rwm_t readWriteMode = pool_rwm_t::VAR_READ_WRITE;
//! @brief Specifies whether the entry is valid or invalid.
bool valid = false;
bool objectValid = true;
//! Pointer to the class which manages the HK pool.
HousekeepingManager* hkManager;
LocalDataPoolManager* hkManager;
};
#include <framework/datapoollocal/LocalPoolVariable.tpp>
template<class T>
using lp_variable = LocalPoolVar<T>;
using lp_bool_t = LocalPoolVar<bool>;
template<class T>
using lp_var_t = LocalPoolVar<T>;
using lp_bool_t = LocalPoolVar<uint8_t>;
using lp_uint8_t = LocalPoolVar<uint8_t>;
using lp_uint16_t = LocalPoolVar<uint16_t>;
using lp_uint32_t = LocalPoolVar<uint32_t>;

View File

@ -1,16 +1,24 @@
#ifndef FRAMEWORK_DATAPOOLLOCAL_LOCALPOOLVARIABLE_TPP_
#define FRAMEWORK_DATAPOOLLOCAL_LOCALPOOLVARIABLE_TPP_
#include <framework/housekeeping/HasHkPoolParametersIF.h>
#include <framework/objectmanager/ObjectManagerIF.h>
#include <framework/serialize/SerializeAdapter.h>
#ifndef FRAMEWORK_DATAPOOLLOCAL_LOCALPOOLVARIABLE_H_
#error Include LocalPoolVariable.h before LocalPoolVariable.tpp!
#endif
template<typename T>
inline LocalPoolVar<T>::LocalPoolVar(lp_id_t poolId,
HasHkPoolParametersIF* hkOwner, pool_rwm_t setReadWriteMode,
HasLocalDataPoolIF* hkOwner, pool_rwm_t setReadWriteMode,
DataSetIF* dataSet):
localPoolId(poolId),readWriteMode(setReadWriteMode) {
if(poolId == PoolVariableIF::NO_PARAMETER) {
sif::warning << "LocalPoolVector: 0 passed as pool ID, which is the "
"NO_PARAMETER value!" << std::endl;
}
if(hkOwner == nullptr) {
sif::error << "LocalPoolVariable: The supplied pool owner is a nullptr!"
<< std::endl;
return;
}
hkManager = hkOwner->getHkManagerHandle();
if(dataSet != nullptr) {
dataSet->registerVariable(this);
@ -21,12 +29,15 @@ template<typename T>
inline LocalPoolVar<T>::LocalPoolVar(lp_id_t poolId, object_id_t poolOwner,
pool_rwm_t setReadWriteMode, DataSetIF *dataSet):
readWriteMode(readWriteMode) {
HasHkPoolParametersIF* hkOwner =
objectManager->get<HasHkPoolParametersIF>(poolOwner);
if(poolId == PoolVariableIF::NO_PARAMETER) {
sif::warning << "LocalPoolVector: 0 passed as pool ID, which is the "
"NO_PARAMETER value!" << std::endl;
}
HasLocalDataPoolIF* hkOwner =
objectManager->get<HasLocalDataPoolIF>(poolOwner);
if(hkOwner == nullptr) {
sif::error << "LocalPoolVariable: The supplied pool owner did not implement"
"the correct interface HasHkPoolParametersIF!" << std::endl;
objectValid = false;
return;
}
hkManager = hkOwner->getHkManagerHandle();
@ -36,38 +47,57 @@ inline LocalPoolVar<T>::LocalPoolVar(lp_id_t poolId, object_id_t poolOwner,
}
template<typename T>
inline ReturnValue_t LocalPoolVar<T>::read() {
inline ReturnValue_t LocalPoolVar<T>::read(dur_millis_t lockTimeout) {
MutexHelper(hkManager->getMutexHandle(), lockTimeout);
return readWithoutLock();
}
template<typename T>
inline ReturnValue_t LocalPoolVar<T>::readWithoutLock() {
if(readWriteMode == pool_rwm_t::VAR_WRITE) {
sif::debug << "LocalPoolVar: Invalid read write "
"mode for read() call." << std::endl;
// TODO: special return value
return HasReturnvaluesIF::RETURN_FAILED;
return PoolVariableIF::INVALID_READ_WRITE_MODE;
}
MutexHelper(hkManager->getMutexHandle(), MutexIF::NO_TIMEOUT);
PoolEntry<T>* poolEntry = nullptr;
ReturnValue_t result = hkManager->fetchPoolEntry(localPoolId, poolEntry);
if(result != RETURN_OK) {
ReturnValue_t result = hkManager->fetchPoolEntry(localPoolId, &poolEntry);
if(result != RETURN_OK and poolEntry != nullptr) {
sif::error << "PoolVector: Read of local pool variable of object "
"0x" << std::hex << std::setw(8) << std::setfill('0') <<
hkManager->getOwner() << " and lp ID 0x" << localPoolId <<
std::dec << " failed.\n" << std::flush;
return result;
}
this->value = *(poolEntry->address);
this->valid = poolEntry->valid;
return RETURN_OK;
}
template<typename T>
inline ReturnValue_t LocalPoolVar<T>::commit() {
inline ReturnValue_t LocalPoolVar<T>::commit(dur_millis_t lockTimeout) {
MutexHelper(hkManager->getMutexHandle(), lockTimeout);
return commitWithoutLock();
}
template<typename T>
inline ReturnValue_t LocalPoolVar<T>::commitWithoutLock() {
if(readWriteMode == pool_rwm_t::VAR_READ) {
sif::debug << "LocalPoolVar: Invalid read write "
"mode for commit() call." << std::endl;
// TODO: special return value
return HasReturnvaluesIF::RETURN_FAILED;
return PoolVariableIF::INVALID_READ_WRITE_MODE;
}
MutexHelper(hkManager->getMutexHandle(), MutexIF::NO_TIMEOUT);
PoolEntry<T>* poolEntry = nullptr;
ReturnValue_t result = hkManager->fetchPoolEntry(localPoolId, poolEntry);
ReturnValue_t result = hkManager->fetchPoolEntry(localPoolId, &poolEntry);
if(result != RETURN_OK) {
sif::error << "PoolVector: Read of local pool variable of object "
"0x" << std::hex << std::setw(8) << std::setfill('0') <<
hkManager->getOwner() << " and lp ID 0x" << localPoolId <<
std::dec << " failed.\n" << std::flush;
return result;
}
*(poolEntry->address) = this->value;
poolEntry->valid = this->valid;
return RETURN_OK;
}
@ -81,32 +111,49 @@ inline lp_id_t LocalPoolVar<T>::getDataPoolId() const {
return localPoolId;
}
template<typename T>
inline void LocalPoolVar<T>::setDataPoolId(lp_id_t poolId) {
this->localPoolId = poolId;
}
template<typename T>
inline bool LocalPoolVar<T>::isValid() const {
return valid;
}
template<typename T>
inline void LocalPoolVar<T>::setValid(uint8_t validity) {
inline void LocalPoolVar<T>::setValid(bool validity) {
this->valid = validity;
}
template<typename T>
inline uint8_t LocalPoolVar<T>::getValid() const {
return valid;
}
template<typename T>
inline ReturnValue_t LocalPoolVar<T>::serialize(uint8_t** buffer, size_t* size,
const size_t max_size, bool bigEndian) const {
return AutoSerializeAdapter::serialize(&value,
buffer, size ,max_size, bigEndian);
const size_t max_size, SerializeIF::Endianness streamEndianness) const {
return SerializeAdapter::serialize(&value,
buffer, size ,max_size, streamEndianness);
}
template<typename T>
inline size_t LocalPoolVar<T>::getSerializedSize() const {
return AutoSerializeAdapter::getSerializedSize(&value);
return SerializeAdapter::getSerializedSize(&value);
}
template<typename T>
inline ReturnValue_t LocalPoolVar<T>::deSerialize(const uint8_t** buffer,
size_t* size, bool bigEndian) {
return AutoSerializeAdapter::deSerialize(&value, buffer, size, bigEndian);
size_t* size, SerializeIF::Endianness streamEndianness) {
return SerializeAdapter::deSerialize(&value, buffer, size, streamEndianness);
}
template<typename T>
inline std::ostream& operator<< (std::ostream &out,
const LocalPoolVar<T> &var) {
out << var.value;
return out;
}
#endif

View File

@ -0,0 +1,200 @@
#ifndef FRAMEWORK_DATAPOOLLOCAL_LOCALPOOLVECTOR_H_
#define FRAMEWORK_DATAPOOLLOCAL_LOCALPOOLVECTOR_H_
#include <framework/datapool/DataSetIF.h>
#include <framework/datapool/PoolEntry.h>
#include <framework/datapool/PoolVariableIF.h>
#include <framework/datapoollocal/LocalDataPoolManager.h>
#include <framework/serialize/SerializeAdapter.h>
#include <framework/serviceinterface/ServiceInterfaceStream.h>
/**
* @brief This is the access class for array-type data pool entries.
* @details
* To ensure safe usage of the data pool, operation is not done directly on the
* data pool entries, but on local copies. This class provides simple type-
* and length-safe access to vector-style data pool entries (i.e. entries with
* length > 1). The class can be instantiated as read-write and read only.
*
* It provides a commit-and-roll-back semantic, which means that no array
* entry in the data pool is changed until the commit call is executed.
* There are two template parameters:
* @tparam T
* This template parameter specifies the data type of an array entry. Currently,
* all plain data types are supported, but in principle any type is possible.
* @tparam vector_size
* This template parameter specifies the vector size of this entry. Using a
* template parameter for this is not perfect, but avoids
* dynamic memory allocation.
* @ingroup data_pool
*/
template<typename T, uint16_t vectorSize>
class LocalPoolVector: public PoolVariableIF, public HasReturnvaluesIF {
public:
LocalPoolVector() = delete;
/**
* This constructor is used by the data creators to have pool variable
* instances which can also be stored in datasets.
* It does not fetch the current value from the data pool. This is performed
* by the read() operation (which is not thread-safe).
* Datasets can be used to access local pool entires in a thread-safe way.
* @param poolId ID of the local pool entry.
* @param hkOwner Pointer of the owner. This will generally be the calling
* class itself which passes "this".
* @param setReadWriteMode Specify the read-write mode of the pool variable.
* @param dataSet The data set in which the variable shall register itself.
* If nullptr, the variable is not registered.
*/
LocalPoolVector(lp_id_t poolId, HasLocalDataPoolIF* hkOwner,
pool_rwm_t setReadWriteMode = pool_rwm_t::VAR_READ_WRITE,
DataSetIF* dataSet = nullptr);
/**
* This constructor is used by data users like controllers to have
* access to the local pool variables of data creators by supplying
* the respective creator object ID.
* It does not fetch the current value from the data pool. This is performed
* by the read() operation (which is not thread-safe).
* Datasets can be used to access local pool entires in a thread-safe way.
* @param poolId ID of the local pool entry.
* @param hkOwner Pointer of the owner. This will generally be the calling
* class itself which passes "this".
* @param setReadWriteMode Specify the read-write mode of the pool variable.
* @param dataSet The data set in which the variable shall register itself.
* If nullptr, the variable is not registered.
*/
LocalPoolVector(lp_id_t poolId, object_id_t poolOwner,
pool_rwm_t setReadWriteMode = pool_rwm_t::VAR_READ_WRITE,
DataSetIF* dataSet = nullptr);
/**
* @brief This is the local copy of the data pool entry.
* @details
* The user can work on this attribute just like he would on a local
* array of this type.
*/
T value[vectorSize];
/**
* @brief The classes destructor is empty.
* @details If commit() was not called, the local value is
* discarded and not written back to the data pool.
*/
~LocalPoolVector() {};
/**
* @brief The operation returns the number of array entries
* in this variable.
*/
uint8_t getSize() {
return vectorSize;
}
uint32_t getDataPoolId() const override;
/**
* @brief This operation sets the data pool ID of the variable.
* @details
* The method is necessary to set id's of data pool member variables
* with bad initialization.
*/
void setDataPoolId(uint32_t poolId);
/**
* This method returns if the variable is write-only, read-write or read-only.
*/
pool_rwm_t getReadWriteMode() const;
/**
* @brief With this call, the valid information of the variable is returned.
*/
bool isValid() const override;
void setValid(bool valid) override;
uint8_t getValid() const;
T& operator [](int i);
const T &operator [](int i) const;
virtual ReturnValue_t serialize(uint8_t** buffer, size_t* size,
const size_t maxSize,
SerializeIF::Endianness streamEndiannes) const override;
virtual size_t getSerializedSize() const override;
virtual ReturnValue_t deSerialize(const uint8_t** buffer, size_t* size,
SerializeIF::Endianness streamEndianness) override;
/**
* @brief This is a call to read the array's values
* from the global data pool.
* @details
* When executed, this operation tries to fetch the pool entry with matching
* data pool id from the data pool and copies all array values and the valid
* information to its local attributes.
* In case of a failure (wrong type, size or pool id not found), the
* variable is set to zero and invalid.
* The read call is protected with a lock.
* It is recommended to use DataSets to read and commit multiple variables
* at once to avoid the overhead of unnecessary lock und unlock operations.
*/
ReturnValue_t read(uint32_t lockTimeout = MutexIF::BLOCKING) override;
/**
* @brief The commit call copies the array values back to the data pool.
* @details
* It checks type and size, as well as if the variable is writable. If so,
* the value is copied and the local valid flag is written back as well.
* The read call is protected with a lock.
* It is recommended to use DataSets to read and commit multiple variables
* at once to avoid the overhead of unnecessary lock und unlock operations.
*/
ReturnValue_t commit(uint32_t lockTimeout = MutexIF::BLOCKING) override;
protected:
/**
* @brief Like #read, but without a lock protection of the global pool.
* @details
* The operation does NOT provide any mutual exclusive protection by itself.
* This can be used if the lock is handled externally to avoid the overhead
* of consecutive lock und unlock operations.
* Declared protected to discourage free public usage.
*/
ReturnValue_t readWithoutLock() override;
/**
* @brief Like #commit, but without a lock protection of the global pool.
* @details
* The operation does NOT provide any mutual exclusive protection by itself.
* This can be used if the lock is handled externally to avoid the overhead
* of consecutive lock und unlock operations.
* Declared protected to discourage free public usage.
*/
ReturnValue_t commitWithoutLock() override;
private:
/**
* @brief To access the correct data pool entry on read and commit calls,
* the data pool id is stored.
*/
uint32_t localPoolId;
/**
* @brief The valid information as it was stored in the data pool
* is copied to this attribute.
*/
bool valid;
/**
* @brief The information whether the class is read-write or
* read-only is stored here.
*/
ReadWriteMode_t readWriteMode;
//! @brief Pointer to the class which manages the HK pool.
LocalDataPoolManager* hkManager;
// std::ostream is the type for object std::cout
template <typename U, uint16_t otherSize>
friend std::ostream& operator<< (std::ostream &out,
const LocalPoolVector<U, otherSize> &var);
};
#include <framework/datapoollocal/LocalPoolVector.tpp>
template<typename T, uint16_t vectorSize>
using lp_vec_t = LocalPoolVector<T, vectorSize>;
#endif /* FRAMEWORK_DATAPOOLLOCAL_LOCALPOOLVECTOR_H_ */

View File

@ -0,0 +1,206 @@
#ifndef FRAMEWORK_DATAPOOLLOCAL_LOCALPOOLVECTOR_TPP_
#define FRAMEWORK_DATAPOOLLOCAL_LOCALPOOLVECTOR_TPP_
#ifndef FRAMEWORK_DATAPOOLLOCAL_LOCALPOOLVECTOR_H_
#error Include LocalPoolVector.h before LocalPoolVector.tpp!
#endif
template<typename T, uint16_t vectorSize>
inline LocalPoolVector<T, vectorSize>::LocalPoolVector(lp_id_t poolId,
HasLocalDataPoolIF* hkOwner, pool_rwm_t setReadWriteMode,
DataSetIF* dataSet) :
localPoolId(poolId), valid(false), readWriteMode(setReadWriteMode) {
if(poolId == PoolVariableIF::NO_PARAMETER) {
sif::warning << "LocalPoolVector: 0 passed as pool ID, which is the "
"NO_PARAMETER value!" << std::endl;
}
memset(this->value, 0, vectorSize * sizeof(T));
hkManager = hkOwner->getHkManagerHandle();
if (dataSet != nullptr) {
dataSet->registerVariable(this);
}
}
template<typename T, uint16_t vectorSize>
inline LocalPoolVector<T, vectorSize>::LocalPoolVector(lp_id_t poolId,
object_id_t poolOwner, pool_rwm_t setReadWriteMode, DataSetIF *dataSet):
readWriteMode(readWriteMode) {
if(poolId == PoolVariableIF::NO_PARAMETER) {
sif::warning << "LocalPoolVector: 0 passed as pool ID, which is the "
"NO_PARAMETER value!" << std::endl;
}
HasLocalDataPoolIF* hkOwner =
objectManager->get<HasLocalDataPoolIF>(poolOwner);
if(hkOwner == nullptr) {
sif::error << "LocalPoolVariable: The supplied pool owner did not implement"
"the correct interface HasHkPoolParametersIF!" << std::endl;
return;
}
hkManager = hkOwner->getHkManagerHandle();
if(dataSet != nullptr) {
dataSet->registerVariable(this);
}
}
template<typename T, uint16_t vectorSize>
inline ReturnValue_t LocalPoolVector<T, vectorSize>::read(uint32_t lockTimeout) {
MutexHelper(hkManager->getMutexHandle(), lockTimeout);
return readWithoutLock();
}
template<typename T, uint16_t vectorSize>
inline ReturnValue_t LocalPoolVector<T, vectorSize>::readWithoutLock() {
if(readWriteMode == pool_rwm_t::VAR_WRITE) {
sif::debug << "LocalPoolVar: Invalid read write "
"mode for read() call." << std::endl;
return PoolVariableIF::INVALID_READ_WRITE_MODE;
}
PoolEntry<T>* poolEntry = nullptr;
ReturnValue_t result = hkManager->fetchPoolEntry(localPoolId, &poolEntry);
memset(this->value, 0, vectorSize * sizeof(T));
if(result != RETURN_OK) {
sif::error << "PoolVector: Read of local pool variable of object "
"0x" << std::hex << std::setw(8) << std::setfill('0') <<
hkManager->getOwner() << "and lp ID 0x" << localPoolId <<
std::dec << " failed." << std::endl;
return result;
}
memcpy(this->value, poolEntry->address, poolEntry->getByteSize());
this->valid = poolEntry->valid;
return RETURN_OK;
}
template<typename T, uint16_t vectorSize>
inline ReturnValue_t LocalPoolVector<T, vectorSize>::commit(
uint32_t lockTimeout) {
MutexHelper(hkManager->getMutexHandle(), lockTimeout);
return commitWithoutLock();
}
template<typename T, uint16_t vectorSize>
inline ReturnValue_t LocalPoolVector<T, vectorSize>::commitWithoutLock() {
if(readWriteMode == pool_rwm_t::VAR_READ) {
sif::debug << "LocalPoolVar: Invalid read write "
"mode for commit() call." << std::endl;
return PoolVariableIF::INVALID_READ_WRITE_MODE;
}
PoolEntry<T>* poolEntry = nullptr;
ReturnValue_t result = hkManager->fetchPoolEntry(localPoolId, &poolEntry);
if(result != RETURN_OK) {
sif::error << "PoolVector: Read of local pool variable of object "
"0x" << std::hex << std::setw(8) << std::setfill('0') <<
hkManager->getOwner() << " and lp ID 0x" << localPoolId <<
std::dec << " failed.\n" << std::flush;
return result;
}
memcpy(poolEntry->address, this->value, poolEntry->getByteSize());
poolEntry->valid = this->valid;
return RETURN_OK;
}
template<typename T, uint16_t vectorSize>
inline T& LocalPoolVector<T, vectorSize>::operator [](int i) {
if(i <= vectorSize) {
return value[i];
}
// If this happens, I have to set some value. I consider this
// a configuration error, but I wont exit here.
sif::error << "LocalPoolVector: Invalid index. Setting or returning"
" last value!" << std::endl;
return value[i];
}
template<typename T, uint16_t vectorSize>
inline const T& LocalPoolVector<T, vectorSize>::operator [](int i) const {
if(i <= vectorSize) {
return value[i];
}
// If this happens, I have to set some value. I consider this
// a configuration error, but I wont exit here.
sif::error << "LocalPoolVector: Invalid index. Setting or returning"
" last value!" << std::endl;
return value[i];
}
template<typename T, uint16_t vectorSize>
inline ReturnValue_t LocalPoolVector<T, vectorSize>::serialize(uint8_t** buffer,
size_t* size, size_t maxSize,
SerializeIF::Endianness streamEndianness) const {
ReturnValue_t result = HasReturnvaluesIF::RETURN_FAILED;
for (uint16_t i = 0; i < vectorSize; i++) {
result = SerializeAdapter::serialize(&(value[i]), buffer, size,
maxSize, streamEndianness);
if (result != HasReturnvaluesIF::RETURN_OK) {
break;
}
}
return result;
}
template<typename T, uint16_t vectorSize>
inline size_t LocalPoolVector<T, vectorSize>::getSerializedSize() const {
return vectorSize * SerializeAdapter::getSerializedSize(value);
}
template<typename T, uint16_t vectorSize>
inline ReturnValue_t LocalPoolVector<T, vectorSize>::deSerialize(
const uint8_t** buffer, size_t* size,
SerializeIF::Endianness streamEndianness) {
ReturnValue_t result = HasReturnvaluesIF::RETURN_FAILED;
for (uint16_t i = 0; i < vectorSize; i++) {
result = SerializeAdapter::deSerialize(&(value[i]), buffer, size,
streamEndianness);
if (result != HasReturnvaluesIF::RETURN_OK) {
break;
}
}
return result;
}
template<typename T, uint16_t vectorSize>
inline pool_rwm_t LocalPoolVector<T, vectorSize>::getReadWriteMode() const {
return this->readWriteMode;
}
template<typename T, uint16_t vectorSize>
inline uint32_t LocalPoolVector<T, vectorSize>::getDataPoolId() const {
return localPoolId;
}
template<typename T, uint16_t vectorSize>
inline void LocalPoolVector<T, vectorSize>::setDataPoolId(uint32_t poolId) {
this->localPoolId = poolId;
}
template<typename T, uint16_t vectorSize>
inline void LocalPoolVector<T, vectorSize>::setValid(bool valid) {
this->valid = valid;
}
template<typename T, uint16_t vectorSize>
inline uint8_t LocalPoolVector<T, vectorSize>::getValid() const {
return valid;
}
template<typename T, uint16_t vectorSize>
inline bool LocalPoolVector<T, vectorSize>::isValid() const {
return valid;
}
template<typename T, uint16_t vectorSize>
inline std::ostream& operator<< (std::ostream &out,
const LocalPoolVector<T, vectorSize> &var) {
out << "Vector: [";
for(int i = 0;i < vectorSize; i++) {
out << var.value[i];
if(i < vectorSize - 1) {
out << ", ";
}
}
out << "]";
return out;
}
#endif

View File

@ -0,0 +1,6 @@
#include <framework/datapoollocal/StaticLocalDataSet.h>

View File

@ -0,0 +1,11 @@
#ifndef FRAMEWORK_DATAPOOLLOCAL_STATICLOCALDATASET_H_
#define FRAMEWORK_DATAPOOLLOCAL_STATICLOCALDATASET_H_
#include <framework/datapool/DataSetBase.h>
class StaticLocalDataSet: public DataSetBase {
};
#endif /* FRAMEWORK_DATAPOOLLOCAL_STATICLOCALDATASET_H_ */

View File

@ -1,15 +1,12 @@
/**
* @file AcceptsDeviceResponsesIF.h
* @brief This file defines the AcceptsDeviceResponsesIF class.
* @date 15.05.2013
* @author baetz
*/
#ifndef ACCEPTSDEVICERESPONSESIF_H_
#define ACCEPTSDEVICERESPONSESIF_H_
#ifndef FRAMEWORK_DEVICEHANDLERS_ACCEPTSDEVICERESPONSESIF_H_
#define FRAMEWORK_DEVICEHANDLERS_ACCEPTSDEVICERESPONSESIF_H_
#include <framework/ipc/MessageQueueSenderIF.h>
/**
* This interface is used by the device handler to send a device response
* to the queue ID, which is returned in the implemented abstract method.
*/
class AcceptsDeviceResponsesIF {
public:
/**
@ -19,4 +16,4 @@ public:
virtual MessageQueueId_t getDeviceQueue() = 0;
};
#endif /* ACCEPTSDEVICERESPONSESIF_H_ */
#endif /* FRAMEWORK_DEVICEHANDLERS_ACCEPTSDEVICERESPONSESIF_H_ */

View File

@ -4,14 +4,18 @@
ChildHandlerBase::ChildHandlerBase(object_id_t setObjectId,
object_id_t deviceCommunication, CookieIF * cookie,
uint32_t maxDeviceReplyLen, uint8_t setDeviceSwitch,
uint32_t thermalStatePoolId, uint32_t thermalRequestPoolId,
uint32_t parent, FailureIsolationBase* customFdir, size_t cmdQueueSize) :
object_id_t hkDestination, uint32_t thermalStatePoolId,
uint32_t thermalRequestPoolId,
object_id_t parent,
FailureIsolationBase* customFdir, size_t cmdQueueSize) :
DeviceHandlerBase(setObjectId, deviceCommunication, cookie,
setDeviceSwitch, thermalStatePoolId,
thermalRequestPoolId, (customFdir == NULL? &childHandlerFdir : customFdir),
(customFdir == nullptr? &childHandlerFdir : customFdir),
cmdQueueSize),
parentId(parent), childHandlerFdir(setObjectId) {
this->setHkDestination(hkDestination);
this->setThermalStateRequestPoolIds(thermalStatePoolId,
thermalRequestPoolId);
}
ChildHandlerBase::~ChildHandlerBase() {
@ -25,7 +29,7 @@ ReturnValue_t ChildHandlerBase::initialize() {
MessageQueueId_t parentQueue = 0;
if (parentId != 0) {
if (parentId != objects::NO_OBJECT) {
SubsystemBase *parent = objectManager->get<SubsystemBase>(parentId);
if (parent == NULL) {
return RETURN_FAILED;
@ -35,7 +39,7 @@ ReturnValue_t ChildHandlerBase::initialize() {
parent->registerChild(getObjectId());
}
healthHelper.setParentQeueue(parentQueue);
healthHelper.setParentQueue(parentQueue);
modeHelper.setParentQueue(parentQueue);

View File

@ -7,10 +7,10 @@
class ChildHandlerBase: public DeviceHandlerBase {
public:
ChildHandlerBase(object_id_t setObjectId, object_id_t deviceCommunication,
CookieIF * cookie, uint32_t maxDeviceReplyLen, uint8_t setDeviceSwitch,
CookieIF * cookie, object_id_t hkDestination,
uint32_t thermalStatePoolId, uint32_t thermalRequestPoolId,
uint32_t parent, FailureIsolationBase* customFdir = nullptr,
size_t cmdQueueSize = 20);
object_id_t parent = objects::NO_OBJECT,
FailureIsolationBase* customFdir = nullptr, size_t cmdQueueSize = 20);
virtual ~ChildHandlerBase();
virtual ReturnValue_t initialize();

View File

@ -1,5 +1,5 @@
#ifndef DEVICECOMMUNICATIONIF_H_
#define DEVICECOMMUNICATIONIF_H_
#ifndef FRAMEWORK_DEVICES_DEVICECOMMUNICATIONIF_H_
#define FRAMEWORK_DEVICES_DEVICECOMMUNICATIONIF_H_
#include <framework/devicehandlers/CookieIF.h>
#include <framework/devicehandlers/DeviceHandlerIF.h>
@ -19,8 +19,8 @@
* the device handler to allow reuse of these components.
* @details
* Documentation: Dissertation Baetz p.138.
* It works with the assumption that received data
* is polled by a component. There are four generic steps of device communication:
* It works with the assumption that received data is polled by a component.
* There are four generic steps of device communication:
*
* 1. Send data to a device
* 2. Get acknowledgement for sending
@ -72,13 +72,13 @@ public:
* by implementing and calling related drivers or wrapper functions.
* @param cookie
* @param data
* @param len
* @param len If this is 0, nothing shall be sent.
* @return
* - @c RETURN_OK for successfull send
* - Everything else triggers failure event with returnvalue as parameter 1
*/
virtual ReturnValue_t sendMessage(CookieIF *cookie, const uint8_t * sendData,
size_t sendLen) = 0;
virtual ReturnValue_t sendMessage(CookieIF *cookie,
const uint8_t * sendData, size_t sendLen) = 0;
/**
* Called by DHB in the GET_WRITE doGetWrite().
@ -103,7 +103,8 @@ public:
* - Everything else triggers failure event with
* returnvalue as parameter 1
*/
virtual ReturnValue_t requestReceiveMessage(CookieIF *cookie, size_t requestLen) = 0;
virtual ReturnValue_t requestReceiveMessage(CookieIF *cookie,
size_t requestLen) = 0;
/**
* Called by DHB in the GET_WRITE doGetRead().
@ -119,8 +120,8 @@ public:
* - Everything else triggers failure event with
* returnvalue as parameter 1
*/
virtual ReturnValue_t readReceivedMessage(CookieIF *cookie, uint8_t **buffer,
size_t *size) = 0;
virtual ReturnValue_t readReceivedMessage(CookieIF *cookie,
uint8_t **buffer, size_t *size) = 0;
};
#endif /* DEVICECOMMUNICATIONIF_H_ */

View File

@ -1,58 +1,70 @@
#include <framework/datapoolglob/GlobalDataSet.h>
#include <framework/devicehandlers/DeviceHandlerBase.h>
#include <framework/objectmanager/ObjectManager.h>
#include <framework/storagemanager/StorageManagerIF.h>
#include <framework/thermal/ThermalComponentIF.h>
#include <framework/devicehandlers/AcceptsDeviceResponsesIF.h>
#include <framework/datapoolglob/GlobalDataSet.h>
#include <framework/datapoolglob/GlobalPoolVariable.h>
#include <framework/devicehandlers/DeviceTmReportingWrapper.h>
#include <framework/globalfunctions/CRC.h>
#include <framework/housekeeping/HousekeepingMessage.h>
#include <framework/ipc/MessageQueueMessage.h>
#include <framework/subsystem/SubsystemBase.h>
#include <framework/ipc/QueueFactory.h>
#include <framework/serviceinterface/ServiceInterfaceStream.h>
#include <iomanip>
object_id_t DeviceHandlerBase::powerSwitcherId = 0;
object_id_t DeviceHandlerBase::rawDataReceiverId = 0;
object_id_t DeviceHandlerBase::defaultFDIRParentId = 0;
object_id_t DeviceHandlerBase::powerSwitcherId = objects::NO_OBJECT;
object_id_t DeviceHandlerBase::rawDataReceiverId = objects::NO_OBJECT;
object_id_t DeviceHandlerBase::defaultFdirParentId = objects::NO_OBJECT;
object_id_t DeviceHandlerBase::defaultHkDestination = objects::NO_OBJECT;
DeviceHandlerBase::DeviceHandlerBase(object_id_t setObjectId,
object_id_t deviceCommunication, CookieIF * comCookie,
uint8_t setDeviceSwitch, uint32_t thermalStatePoolId,
uint32_t thermalRequestPoolId, FailureIsolationBase* fdirInstance,
size_t cmdQueueSize) :
FailureIsolationBase* fdirInstance, size_t cmdQueueSize) :
SystemObject(setObjectId), mode(MODE_OFF), submode(SUBMODE_NONE),
wiretappingMode(OFF), storedRawData(StorageManagerIF::INVALID_ADDRESS),
deviceCommunicationId(deviceCommunication), comCookie(comCookie),
deviceThermalStatePoolId(thermalStatePoolId),
deviceThermalRequestPoolId(thermalRequestPoolId),
healthHelper(this,setObjectId), modeHelper(this), parameterHelper(this),
actionHelper(this, nullptr), hkManager(this, nullptr),
childTransitionFailure(RETURN_OK), fdirInstance(fdirInstance),
hkSwitcher(this), defaultFDIRUsed(fdirInstance == nullptr),
switchOffWasReported(false), actionHelper(this, nullptr), cookieInfo(),
childTransitionDelay(5000),
transitionSourceMode(_MODE_POWER_DOWN), transitionSourceSubMode(
SUBMODE_NONE), deviceSwitch(setDeviceSwitch) {
switchOffWasReported(false), childTransitionDelay(5000),
transitionSourceMode(_MODE_POWER_DOWN),
transitionSourceSubMode(SUBMODE_NONE) {
commandQueue = QueueFactory::instance()->createMessageQueue(cmdQueueSize,
CommandMessage::MAX_MESSAGE_SIZE);
cookieInfo.state = COOKIE_UNUSED;
MessageQueueMessage::MAX_MESSAGE_SIZE);
insertInCommandMap(RAW_COMMAND_ID);
cookieInfo.state = COOKIE_UNUSED;
cookieInfo.pendingCommand = deviceCommandMap.end();
if (comCookie == nullptr) {
sif::error << "DeviceHandlerBase: ObjectID 0x" << std::hex <<
std::setw(8) << std::setfill('0') << this->getObjectId() <<
std::dec << ": Do not pass nullptr as a cookie, consider "
"passing a dummy cookie instead!" << std::endl;
sif::error << "DeviceHandlerBase: ObjectID 0x" << std::hex
<< std::setw(8) << std::setfill('0') << this->getObjectId()
<< std::dec << ": Do not pass nullptr as a cookie, consider "
<< std::setfill(' ') << "passing a dummy cookie instead!"
<< std::endl;
}
if (this->fdirInstance == nullptr) {
this->fdirInstance = new DeviceHandlerFailureIsolation(setObjectId,
defaultFDIRParentId);
defaultFdirParentId);
}
}
void DeviceHandlerBase::setHkDestination(object_id_t hkDestination) {
this->hkDestination = hkDestination;
}
void DeviceHandlerBase::setThermalStateRequestPoolIds(
uint32_t thermalStatePoolId, uint32_t thermalRequestPoolId) {
this->deviceThermalRequestPoolId = thermalStatePoolId;
this->deviceThermalRequestPoolId = thermalRequestPoolId;
}
DeviceHandlerBase::~DeviceHandlerBase() {
//communicationInterface->close(cookie);
delete comCookie;
if (defaultFDIRUsed) {
delete fdirInstance;
}
@ -106,37 +118,56 @@ ReturnValue_t DeviceHandlerBase::initialize() {
communicationInterface = objectManager->get<DeviceCommunicationIF>(
deviceCommunicationId);
if (communicationInterface == NULL) {
return RETURN_FAILED;
if (communicationInterface == nullptr) {
sif::error << "DeviceHandlerBase::initialize: Communication interface "
"invalid." << std::endl;
sif::error << "Make sure it is set up properly and implements"
" DeviceCommunicationIF" << std::endl;
return ObjectManagerIF::CHILD_INIT_FAILED;
}
result = communicationInterface->initializeInterface(comCookie);
if (result != RETURN_OK) {
return result;
sif::error << "DeviceHandlerBase::initialize: Initializing "
"communication interface failed!" << std::endl;
return result;
}
IPCStore = objectManager->get<StorageManagerIF>(objects::IPC_STORE);
if (IPCStore == NULL) {
return RETURN_FAILED;
if (IPCStore == nullptr) {
sif::error << "DeviceHandlerBase::initialize: IPC store not set up in "
"factory." << std::endl;
return ObjectManagerIF::CHILD_INIT_FAILED;
}
AcceptsDeviceResponsesIF *rawReceiver = objectManager->get<
AcceptsDeviceResponsesIF>(rawDataReceiverId);
if(rawDataReceiverId != objects::NO_OBJECT) {
AcceptsDeviceResponsesIF *rawReceiver = objectManager->get<
AcceptsDeviceResponsesIF>(rawDataReceiverId);
if (rawReceiver == NULL) {
return RETURN_FAILED;
if (rawReceiver == nullptr) {
sif::error << "DeviceHandlerBase::initialize: Raw receiver object "
"ID set but no valid object found." << std::endl;
sif::error << "Make sure the raw receiver object is set up properly"
" and implements AcceptsDeviceResponsesIF" << std::endl;
return ObjectManagerIF::CHILD_INIT_FAILED;
}
defaultRawReceiver = rawReceiver->getDeviceQueue();
}
defaultRawReceiver = rawReceiver->getDeviceQueue();
powerSwitcher = objectManager->get<PowerSwitchIF>(powerSwitcherId);
if (powerSwitcher == NULL) {
return RETURN_FAILED;
if(powerSwitcherId != objects::NO_OBJECT) {
powerSwitcher = objectManager->get<PowerSwitchIF>(powerSwitcherId);
if (powerSwitcher == nullptr) {
sif::error << "DeviceHandlerBase::initialize: Power switcher "
<< "object ID set but no valid object found." << std::endl;
sif::error << "Make sure the raw receiver object is set up properly"
<< " and implements PowerSwitchIF" << std::endl;
return ObjectManagerIF::CHILD_INIT_FAILED;
}
}
result = healthHelper.initialize();
if (result != RETURN_OK) {
return result;
return result;
}
result = modeHelper.initialize();
@ -162,6 +193,15 @@ ReturnValue_t DeviceHandlerBase::initialize() {
return result;
}
if(hkDestination == objects::NO_OBJECT) {
hkDestination = defaultHkDestination;
}
result = hkManager.initialize(commandQueue, hkDestination);
if (result != HasReturnvaluesIF::RETURN_OK) {
return result;
}
fillCommandAndReplyMap();
//Set temperature target state to NON_OP.
@ -182,7 +222,7 @@ void DeviceHandlerBase::decrementDeviceReplyMap() {
if (iter->second.delayCycles != 0) {
iter->second.delayCycles--;
if (iter->second.delayCycles == 0) {
if (iter->second.periodic != 0) {
if (iter->second.periodic) {
iter->second.delayCycles = iter->second.maxDelayCycles;
}
replyToReply(iter, TIMEOUT);
@ -198,43 +238,48 @@ void DeviceHandlerBase::readCommandQueue() {
return;
}
CommandMessage message;
ReturnValue_t result = commandQueue->receiveMessage(&message);
CommandMessage command;
ReturnValue_t result = commandQueue->receiveMessage(&command);
if (result != RETURN_OK) {
return;
}
result = healthHelper.handleHealthCommand(&message);
result = healthHelper.handleHealthCommand(&command);
if (result == RETURN_OK) {
return;
}
result = modeHelper.handleModeCommand(&command);
if (result == RETURN_OK) {
return;
}
result = modeHelper.handleModeCommand(&message);
result = actionHelper.handleActionMessage(&command);
if (result == RETURN_OK) {
return;
}
result = actionHelper.handleActionMessage(&message);
result = parameterHelper.handleParameterMessage(&command);
if (result == RETURN_OK) {
return;
}
result = parameterHelper.handleParameterMessage(&message);
result = hkManager.handleHousekeepingMessage(&command);
if (result == RETURN_OK) {
return;
}
result = handleDeviceHandlerMessage(&message);
result = handleDeviceHandlerMessage(&command);
if (result == RETURN_OK) {
return;
}
result = letChildHandleMessage(&message);
result = letChildHandleMessage(&command);
if (result == RETURN_OK) {
return;
}
replyReturnvalueToCommand(CommandMessage::UNKNOW_COMMAND);
replyReturnvalueToCommand(CommandMessage::UNKNOWN_COMMAND);
}
@ -271,7 +316,8 @@ void DeviceHandlerBase::doStateMachine() {
case _MODE_WAIT_ON: {
uint32_t currentUptime;
Clock::getUptime(&currentUptime);
if (currentUptime - timeoutStart >= powerSwitcher->getSwitchDelayMs()) {
if (powerSwitcher != nullptr and currentUptime - timeoutStart >=
powerSwitcher->getSwitchDelayMs()) {
triggerEvent(MODE_TRANSITION_FAILED, PowerSwitchIF::SWITCH_TIMEOUT,
0);
setMode(_MODE_POWER_DOWN);
@ -291,6 +337,12 @@ void DeviceHandlerBase::doStateMachine() {
case _MODE_WAIT_OFF: {
uint32_t currentUptime;
Clock::getUptime(&currentUptime);
if(powerSwitcher == nullptr) {
setMode(MODE_OFF);
break;
}
if (currentUptime - timeoutStart >= powerSwitcher->getSwitchDelayMs()) {
triggerEvent(MODE_TRANSITION_FAILED, PowerSwitchIF::SWITCH_TIMEOUT,
0);
@ -341,9 +393,10 @@ ReturnValue_t DeviceHandlerBase::isModeCombinationValid(Mode_t mode,
}
}
ReturnValue_t DeviceHandlerBase::insertInCommandAndReplyMap(DeviceCommandId_t deviceCommand,
uint16_t maxDelayCycles, size_t replyLen, uint8_t periodic,
bool hasDifferentReplyId, DeviceCommandId_t replyId) {
ReturnValue_t DeviceHandlerBase::insertInCommandAndReplyMap(
DeviceCommandId_t deviceCommand, uint16_t maxDelayCycles,
size_t replyLen, bool periodic, bool hasDifferentReplyId,
DeviceCommandId_t replyId) {
//No need to check, as we may try to insert multiple times.
insertInCommandMap(deviceCommand);
if (hasDifferentReplyId) {
@ -354,7 +407,7 @@ ReturnValue_t DeviceHandlerBase::insertInCommandAndReplyMap(DeviceCommandId_t de
}
ReturnValue_t DeviceHandlerBase::insertInReplyMap(DeviceCommandId_t replyId,
uint16_t maxDelayCycles, size_t replyLen, uint8_t periodic) {
uint16_t maxDelayCycles, size_t replyLen, bool periodic) {
DeviceReplyInfo info;
info.maxDelayCycles = maxDelayCycles;
info.periodic = periodic;
@ -369,7 +422,8 @@ ReturnValue_t DeviceHandlerBase::insertInReplyMap(DeviceCommandId_t replyId,
}
}
ReturnValue_t DeviceHandlerBase::insertInCommandMap(DeviceCommandId_t deviceCommand) {
ReturnValue_t DeviceHandlerBase::insertInCommandMap(
DeviceCommandId_t deviceCommand) {
DeviceCommandInfo info;
info.expectedReplies = 0;
info.isExecuting = false;
@ -383,7 +437,7 @@ ReturnValue_t DeviceHandlerBase::insertInCommandMap(DeviceCommandId_t deviceComm
}
ReturnValue_t DeviceHandlerBase::updateReplyMapEntry(DeviceCommandId_t deviceReply,
uint16_t delayCycles, uint16_t maxDelayCycles, uint8_t periodic) {
uint16_t delayCycles, uint16_t maxDelayCycles, bool periodic) {
std::map<DeviceCommandId_t, DeviceReplyInfo>::iterator iter =
deviceReplyMap.find(deviceReply);
if (iter == deviceReplyMap.end()) {
@ -553,12 +607,12 @@ void DeviceHandlerBase::doSendRead() {
ReturnValue_t result;
size_t requestLen = 0;
DeviceReplyIter iter = deviceReplyMap.find(cookieInfo.pendingCommand->first);
if(iter != deviceReplyMap.end()) {
requestLen = iter->second.replyLen;
}
else {
requestLen = 0;
if(cookieInfo.pendingCommand != deviceCommandMap.end()) {
DeviceReplyIter iter = deviceReplyMap.find(
cookieInfo.pendingCommand->first);
if(iter != deviceReplyMap.end()) {
requestLen = iter->second.replyLen;
}
}
result = communicationInterface->requestReceiveMessage(comCookie, requestLen);
@ -576,11 +630,8 @@ void DeviceHandlerBase::doSendRead() {
}
void DeviceHandlerBase::doGetRead() {
size_t receivedDataLen;
uint8_t *receivedData;
DeviceCommandId_t foundId = 0xFFFFFFFF;
size_t foundLen = 0;
ReturnValue_t result;
size_t receivedDataLen = 0;
uint8_t *receivedData = nullptr;
if (cookieInfo.state != COOKIE_READ_SENT) {
cookieInfo.state = COOKIE_UNUSED;
@ -589,8 +640,8 @@ void DeviceHandlerBase::doGetRead() {
cookieInfo.state = COOKIE_UNUSED;
result = communicationInterface->readReceivedMessage(comCookie,
&receivedData, &receivedDataLen);
ReturnValue_t result = communicationInterface->readReceivedMessage(
comCookie, &receivedData, &receivedDataLen);
if (result != RETURN_OK) {
triggerEvent(DEVICE_REQUESTING_REPLY_FAILED, result);
@ -606,51 +657,109 @@ void DeviceHandlerBase::doGetRead() {
replyRawData(receivedData, receivedDataLen, requestedRawTraffic);
}
if (mode == MODE_RAW) {
if (mode == MODE_RAW and defaultRawReceiver != MessageQueueIF::NO_QUEUE) {
replyRawReplyIfnotWiretapped(receivedData, receivedDataLen);
} else {
//The loop may not execute more often than the number of received bytes (worst case).
//This approach avoids infinite loops due to buggy scanForReply routines (seen in bug 1077).
uint32_t remainingLength = receivedDataLen;
for (uint32_t count = 0; count < receivedDataLen; count++) {
result = scanForReply(receivedData, remainingLength, &foundId,
&foundLen);
switch (result) {
case RETURN_OK:
handleReply(receivedData, foundId, foundLen);
break;
case APERIODIC_REPLY: {
result = interpretDeviceReply(foundId, receivedData);
if (result != RETURN_OK) {
replyRawReplyIfnotWiretapped(receivedData, foundLen);
triggerEvent(DEVICE_INTERPRETING_REPLY_FAILED, result,
foundId);
}
}
else {
parseReply(receivedData, receivedDataLen);
}
}
void DeviceHandlerBase::parseReply(const uint8_t* receivedData,
size_t receivedDataLen) {
ReturnValue_t result = HasReturnvaluesIF::RETURN_FAILED;
DeviceCommandId_t foundId = 0xFFFFFFFF;
size_t foundLen = 0;
// The loop may not execute more often than the number of received bytes
// (worst case). This approach avoids infinite loops due to buggy
// scanForReply routines.
uint32_t remainingLength = receivedDataLen;
for (uint32_t count = 0; count < receivedDataLen; count++) {
result = scanForReply(receivedData, remainingLength, &foundId,
&foundLen);
switch (result) {
case RETURN_OK:
handleReply(receivedData, foundId, foundLen);
if(foundLen == 0) {
sif::warning << "DeviceHandlerBase::parseReply: foundLen is 0!"
" Packet parsing will be stuck." << std::endl;
}
break;
case IGNORE_REPLY_DATA:
break;
case IGNORE_FULL_PACKET:
return;
default:
//We need to wait for timeout.. don't know what command failed and who sent it.
replyRawReplyIfnotWiretapped(receivedData, foundLen);
triggerEvent(DEVICE_READING_REPLY_FAILED, result, foundLen);
break;
break;
case APERIODIC_REPLY: {
result = interpretDeviceReply(foundId, receivedData);
if (result != RETURN_OK) {
replyRawReplyIfnotWiretapped(receivedData, foundLen);
triggerEvent(DEVICE_INTERPRETING_REPLY_FAILED, result,
foundId);
}
receivedData += foundLen;
if (remainingLength > foundLen) {
remainingLength -= foundLen;
} else {
return;
if(foundLen == 0) {
sif::warning << "DeviceHandlerBase::parseReply: foundLen is 0!"
" Packet parsing will be stuck." << std::endl;
}
break;
}
case IGNORE_REPLY_DATA:
break;
case IGNORE_FULL_PACKET:
return;
default:
//We need to wait for timeout.. don't know what command failed and who sent it.
replyRawReplyIfnotWiretapped(receivedData, foundLen);
triggerEvent(DEVICE_READING_REPLY_FAILED, result, foundLen);
break;
}
receivedData += foundLen;
if (remainingLength > foundLen) {
remainingLength -= foundLen;
} else {
return;
}
}
}
void DeviceHandlerBase::handleReply(const uint8_t* receivedData,
DeviceCommandId_t foundId, uint32_t foundLen) {
ReturnValue_t result;
DeviceReplyMap::iterator iter = deviceReplyMap.find(foundId);
if (iter == deviceReplyMap.end()) {
replyRawReplyIfnotWiretapped(receivedData, foundLen);
triggerEvent(DEVICE_UNKNOWN_REPLY, foundId);
return;
}
DeviceReplyInfo *info = &(iter->second);
if (info->delayCycles != 0) {
if (info->periodic != false) {
info->delayCycles = info->maxDelayCycles;
}
else {
info->delayCycles = 0;
}
result = interpretDeviceReply(foundId, receivedData);
if (result != RETURN_OK) {
// Report failed interpretation to FDIR.
replyRawReplyIfnotWiretapped(receivedData, foundLen);
triggerEvent(DEVICE_INTERPRETING_REPLY_FAILED, result, foundId);
}
replyToReply(iter, result);
}
else {
// Other completion failure messages are created by timeout.
// Powering down the device might take some time during which periodic
// replies may still come in.
if (mode != _MODE_WAIT_OFF) {
triggerEvent(DEVICE_UNREQUESTED_REPLY, foundId);
}
}
}
ReturnValue_t DeviceHandlerBase::getStorageData(store_address_t storageAddress,
uint8_t * *data, uint32_t * len) {
uint8_t** data, uint32_t * len) {
size_t lenTmp;
if (IPCStore == nullptr) {
@ -673,7 +782,7 @@ ReturnValue_t DeviceHandlerBase::getStorageData(store_address_t storageAddress,
void DeviceHandlerBase::replyRawData(const uint8_t *data, size_t len,
MessageQueueId_t sendTo, bool isCommand) {
if (IPCStore == NULL || len == 0) {
if (IPCStore == nullptr or len == 0 or sendTo == MessageQueueIF::NO_QUEUE) {
return;
}
store_address_t address;
@ -684,18 +793,17 @@ void DeviceHandlerBase::replyRawData(const uint8_t *data, size_t len,
return;
}
CommandMessage message;
CommandMessage command;
DeviceHandlerMessage::setDeviceHandlerRawReplyMessage(&message,
DeviceHandlerMessage::setDeviceHandlerRawReplyMessage(&command,
getObjectId(), address, isCommand);
// this->DeviceHandlerCommand = CommandMessage::CMD_NONE;
result = commandQueue->sendMessage(sendTo, &message);
result = commandQueue->sendMessage(sendTo, &command);
if (result != RETURN_OK) {
IPCStore->deleteData(address);
//Silently discard data, this indicates heavy TM traffic which should not be increased by additional events.
// Silently discard data, this indicates heavy TM traffic which
// should not be increased by additional events.
}
}
@ -724,57 +832,6 @@ MessageQueueId_t DeviceHandlerBase::getCommandQueue() const {
return commandQueue->getId();
}
void DeviceHandlerBase::handleReply(const uint8_t* receivedData,
DeviceCommandId_t foundId, uint32_t foundLen) {
ReturnValue_t result;
DeviceReplyMap::iterator iter = deviceReplyMap.find(foundId);
if (iter == deviceReplyMap.end()) {
replyRawReplyIfnotWiretapped(receivedData, foundLen);
triggerEvent(DEVICE_UNKNOWN_REPLY, foundId);
return;
}
DeviceReplyInfo *info = &(iter->second);
if (info->delayCycles != 0) {
if (info->periodic != 0) {
info->delayCycles = info->maxDelayCycles;
} else {
info->delayCycles = 0;
}
result = interpretDeviceReply(foundId, receivedData);
if (result != RETURN_OK) {
//Report failed interpretation to FDIR.
replyRawReplyIfnotWiretapped(receivedData, foundLen);
triggerEvent(DEVICE_INTERPRETING_REPLY_FAILED, result, foundId);
}
replyToReply(iter, result);
} else {
//Other completion failure messages are created by timeout.
//Powering down the device might take some time during which periodic replies may still come in.
if (mode != _MODE_WAIT_OFF) {
triggerEvent(DEVICE_UNREQUESTED_REPLY, foundId);
}
}
}
//ReturnValue_t DeviceHandlerBase::switchCookieChannel(object_id_t newChannelId) {
// DeviceCommunicationIF *newCommunication = objectManager->get<
// DeviceCommunicationIF>(newChannelId);
//
// if (newCommunication != NULL) {
// ReturnValue_t result = newCommunication->reOpen(cookie, ioBoardAddress,
// maxDeviceReplyLen);
// if (result != RETURN_OK) {
// return result;
// }
// return RETURN_OK;
// }
// return RETURN_FAILED;
//}
void DeviceHandlerBase::buildRawDeviceCommand(CommandMessage* commandMessage) {
storedRawData = DeviceHandlerMessage::getStoreAddress(commandMessage);
ReturnValue_t result = getStorageData(storedRawData, &rawPacket,
@ -791,6 +848,9 @@ void DeviceHandlerBase::buildRawDeviceCommand(CommandMessage* commandMessage) {
}
void DeviceHandlerBase::commandSwitch(ReturnValue_t onOff) {
if(powerSwitcher == nullptr) {
return;
}
const uint8_t *switches;
uint8_t numberOfSwitches = 0;
ReturnValue_t result = getSwitches(&switches, &numberOfSwitches);
@ -805,9 +865,7 @@ void DeviceHandlerBase::commandSwitch(ReturnValue_t onOff) {
ReturnValue_t DeviceHandlerBase::getSwitches(const uint8_t **switches,
uint8_t *numberOfSwitches) {
*switches = &deviceSwitch;
*numberOfSwitches = 1;
return RETURN_OK;
return DeviceHandlerBase::NO_SWITCH;
}
void DeviceHandlerBase::modeChanged(void) {
@ -843,6 +901,9 @@ uint32_t DeviceHandlerBase::getTransitionDelayMs(Mode_t modeFrom,
}
ReturnValue_t DeviceHandlerBase::getStateOfSwitches(void) {
if(powerSwitcher == nullptr) {
return NO_SWITCH;
}
uint8_t numberOfSwitches = 0;
const uint8_t *switches;
@ -995,8 +1056,8 @@ HasHealthIF::HealthState DeviceHandlerBase::getHealth() {
}
ReturnValue_t DeviceHandlerBase::setHealth(HealthState health) {
healthHelper.setHealth(health);
return HasReturnvaluesIF::RETURN_OK;
healthHelper.setHealth(health);
return HasReturnvaluesIF::RETURN_OK;
}
void DeviceHandlerBase::checkSwitchState() {
@ -1083,7 +1144,7 @@ ReturnValue_t DeviceHandlerBase::handleDeviceHandlerMessage(
void DeviceHandlerBase::setParentQueue(MessageQueueId_t parentQueueId) {
modeHelper.setParentQueue(parentQueueId);
healthHelper.setParentQeueue(parentQueueId);
healthHelper.setParentQueue(parentQueueId);
}
bool DeviceHandlerBase::isAwaitingReply() {
@ -1109,35 +1170,47 @@ void DeviceHandlerBase::handleDeviceTM(SerializeIF* data,
return;
}
DeviceTmReportingWrapper wrapper(getObjectId(), replyId, data);
if (iter->second.command != deviceCommandMap.end()) {//replies to a command
//replies to a command
if (iter->second.command != deviceCommandMap.end())
{
MessageQueueId_t queueId = iter->second.command->second.sendReplyTo;
if (queueId != NO_COMMANDER) {
//This may fail, but we'll ignore the fault.
actionHelper.reportData(queueId, replyId, data);
}
//This check should make sure we get any TM but don't get anything doubled.
if (wiretappingMode == TM && (requestedRawTraffic != queueId)) {
actionHelper.reportData(requestedRawTraffic, replyId, &wrapper);
} else if (forceDirectTm && (defaultRawReceiver != queueId)) {
// hiding of sender needed so the service will handle it as unexpected Data, no matter what state
//(progress or completed) it is in
actionHelper.reportData(defaultRawReceiver, replyId, &wrapper,
true);
}
} else { //unrequested/aperiodic replies
if (wiretappingMode == TM) {
actionHelper.reportData(requestedRawTraffic, replyId, &wrapper);
} else if (forceDirectTm) {
// hiding of sender needed so the service will handle it as unexpected Data, no matter what state
//(progress or completed) it is in
else if (forceDirectTm and (defaultRawReceiver != queueId) and
(defaultRawReceiver != MessageQueueIF::NO_QUEUE))
{
// hiding of sender needed so the service will handle it as
// unexpected Data, no matter what state (progress or completed)
// it is in
actionHelper.reportData(defaultRawReceiver, replyId, &wrapper,
true);
true);
}
}
//Try to cast to GlobDataSet and commit data.
//unrequested/aperiodic replies
else
{
if (wiretappingMode == TM) {
actionHelper.reportData(requestedRawTraffic, replyId, &wrapper);
}
else if (forceDirectTm and defaultRawReceiver !=
MessageQueueIF::NO_QUEUE)
{
// hiding of sender needed so the service will handle it as
// unexpected Data, no matter what state (progress or completed)
// it is in
actionHelper.reportData(defaultRawReceiver, replyId, &wrapper,
true);
}
}
//Try to cast to GlobDataSet and commit data.
if (!neverInDataPool) {
GlobDataSet* dataSet = dynamic_cast<GlobDataSet*>(data);
if (dataSet != NULL) {
@ -1176,18 +1249,23 @@ void DeviceHandlerBase::buildInternalCommand(void) {
if (mode == MODE_NORMAL) {
result = buildNormalDeviceCommand(&deviceCommandId);
if (result == BUSY) {
//so we can track misconfigurations
sif::debug << std::hex << getObjectId()
<< ": DHB::buildInternalCommand busy" << std::endl; //so we can track misconfigurations
<< ": DHB::buildInternalCommand: Busy" << std::endl;
result = NOTHING_TO_SEND; //no need to report this
}
} else if (mode == MODE_RAW) {
}
else if (mode == MODE_RAW) {
result = buildChildRawCommand();
deviceCommandId = RAW_COMMAND_ID;
} else if (mode & TRANSITION_MODE_CHILD_ACTION_MASK) {
}
else if (mode & TRANSITION_MODE_CHILD_ACTION_MASK) {
result = buildTransitionDeviceCommand(&deviceCommandId);
} else {
}
else {
return;
}
if (result == NOTHING_TO_SEND) {
return;
}
@ -1279,11 +1357,41 @@ void DeviceHandlerBase::changeHK(Mode_t mode, Submode_t submode, bool enable) {
}
void DeviceHandlerBase::setTaskIF(PeriodicTaskIF* task_){
executingTask = task_;
executingTask = task_;
}
// Default implementations empty.
void DeviceHandlerBase::debugInterface(uint8_t positionTracker,
object_id_t objectId, uint32_t parameter) {}
void DeviceHandlerBase::performOperationHook() {}
void DeviceHandlerBase::performOperationHook() {
}
ReturnValue_t DeviceHandlerBase::initializePoolEntries(
LocalDataPool &localDataPoolMap) {
return RETURN_OK;
}
LocalDataPoolManager* DeviceHandlerBase::getHkManagerHandle() {
return &hkManager;
}
ReturnValue_t DeviceHandlerBase::initializeAfterTaskCreation() {
// In this function, the task handle should be valid if the task
// was implemented correctly. We still check to be 1000 % sure :-)
if(executingTask != nullptr) {
pstIntervalMs = executingTask->getPeriodMs();
}
return HasReturnvaluesIF::RETURN_OK;
}
DataSetIF* DeviceHandlerBase::getDataSetHandle(sid_t sid) {
auto iter = deviceReplyMap.find(sid.ownerSetId);
if(iter != deviceReplyMap.end()) {
return iter->second.dataSet;
}
else {
return nullptr;
}
}

View File

@ -1,5 +1,5 @@
#ifndef DEVICEHANDLERBASE_H_
#define DEVICEHANDLERBASE_H_
#ifndef FRAMEWORK_DEVICEHANDLERS_DEVICEHANDLERBASE_H_
#define FRAMEWORK_DEVICEHANDLERS_DEVICEHANDLERBASE_H_
#include <framework/objectmanager/SystemObject.h>
#include <framework/tasks/ExecutableObjectIF.h>
@ -11,13 +11,15 @@
#include <framework/modes/HasModesIF.h>
#include <framework/power/PowerSwitchIF.h>
#include <framework/ipc/MessageQueueIF.h>
#include <framework/tasks/PeriodicTaskIF.h>
#include <framework/action/ActionHelper.h>
#include <framework/health/HealthHelper.h>
#include <framework/parameters/ParameterHelper.h>
#include <framework/datapool/HkSwitchHelper.h>
#include <framework/datapoollocal/HasLocalDataPoolIF.h>
#include <framework/datapoollocal/LocalDataPoolManager.h>
#include <framework/devicehandlers/DeviceHandlerFailureIsolation.h>
#include <map>
namespace Factory{
@ -46,14 +48,16 @@ class StorageManagerIF;
* If data has been received (GET_READ), the data will be interpreted.
* The action for each step can be defined by the child class but as most
* device handlers share a 4-call (sendRead-getRead-sendWrite-getWrite) structure,
* a default implementation is provided. NOTE: RMAP is a standard which is used for FLP.
* a default implementation is provided.
* NOTE: RMAP is a standard which is used for FLP.
* RMAP communication is not mandatory for projects implementing the FSFW.
* However, the communication principles are similar to RMAP as there are
* two write and two send calls involved.
*
* Device handler instances should extend this class and implement the abstract functions.
* Components and drivers can send so called cookies which are used for communication
* and contain information about the communcation (e.g. slave address for I2C or RMAP structs).
* Device handler instances should extend this class and implement the abstract
* functions. Components and drivers can send so called cookies which are used
* for communication and contain information about the communcation (e.g. slave
* address for I2C or RMAP structs).
* The following abstract methods must be implemented by a device handler:
* 1. doStartUp()
* 2. doShutDown()
@ -82,7 +86,8 @@ class DeviceHandlerBase: public DeviceHandlerIF,
public HasModesIF,
public HasHealthIF,
public HasActionsIF,
public ReceivesParameterMessagesIF {
public ReceivesParameterMessagesIF,
public HasLocalDataPoolIF {
friend void (Factory::setStaticFrameworkObjectIds)();
public:
/**
@ -100,12 +105,13 @@ public:
* @param cmdQueueSize
*/
DeviceHandlerBase(object_id_t setObjectId, object_id_t deviceCommunication,
CookieIF * comCookie, uint8_t setDeviceSwitch,
uint32_t thermalStatePoolId = PoolVariableIF::NO_PARAMETER,
uint32_t thermalRequestPoolId = PoolVariableIF::NO_PARAMETER,
FailureIsolationBase* fdirInstance = nullptr,
CookieIF * comCookie, FailureIsolationBase* fdirInstance = nullptr,
size_t cmdQueueSize = 20);
void setHkDestination(object_id_t hkDestination);
void setThermalStateRequestPoolIds(uint32_t thermalStatePoolId,
uint32_t thermalRequestPoolId);
/**
* @brief This function is the device handler base core component and is
* called periodically.
@ -150,11 +156,9 @@ public:
* @return
*/
virtual ReturnValue_t initialize();
/**
* Destructor.
*/
/** Destructor. */
virtual ~DeviceHandlerBase();
protected:
/**
* @brief This is used to let the child class handle the transition from
@ -322,12 +326,11 @@ protected:
* - @c RETURN_FAILED when the reply could not be interpreted,
* e.g. logical errors or range violations occurred
*/
virtual ReturnValue_t interpretDeviceReply(DeviceCommandId_t id,
const uint8_t *packet) = 0;
/**
* @brief fill the #deviceCommandMap
* @brief fill the #DeviceCommandMap and #DeviceReplyMap
* called by the initialize() of the base class
* @details
* This is used to let the base class know which replies are expected.
@ -376,13 +379,15 @@ protected:
* @param deviceCommand Identifier of the command to add.
* @param maxDelayCycles The maximum number of delay cycles the command
* waits until it times out.
* @param replyLen Will be supplied to the requestReceiveMessage call of
* the communication interface.
* @param periodic Indicates if the command is periodic (i.e. it is sent
* by the device repeatedly without request) or not. Default is aperiodic (0)
* @return - @c RETURN_OK when the command was successfully inserted,
* - @c RETURN_FAILED else.
*/
ReturnValue_t insertInCommandAndReplyMap(DeviceCommandId_t deviceCommand,
uint16_t maxDelayCycles, size_t replyLen = 0, uint8_t periodic = 0,
uint16_t maxDelayCycles, size_t replyLen = 0, bool periodic = false,
bool hasDifferentReplyId = false, DeviceCommandId_t replyId = 0);
/**
@ -396,7 +401,7 @@ protected:
* - @c RETURN_FAILED else.
*/
ReturnValue_t insertInReplyMap(DeviceCommandId_t deviceCommand,
uint16_t maxDelayCycles, size_t replyLen = 0, uint8_t periodic = 0);
uint16_t maxDelayCycles, size_t replyLen = 0, bool periodic = false);
/**
* @brief A simple command to add a command to the commandList.
@ -422,7 +427,7 @@ protected:
*/
ReturnValue_t updateReplyMapEntry(DeviceCommandId_t deviceReply,
uint16_t delayCycles, uint16_t maxDelayCycles,
uint8_t periodic = 0);
bool periodic = false);
/**
* @brief Can be implemented by child handler to
@ -471,6 +476,18 @@ protected:
virtual ReturnValue_t getSwitches(const uint8_t **switches,
uint8_t *numberOfSwitches);
/**
* This function is used to initialize the local housekeeping pool
* entries. The default implementation leaves the pool empty.
* @param localDataPoolMap
* @return
*/
virtual ReturnValue_t initializePoolEntries(
LocalDataPool& localDataPoolMap) override;
/** Get the HK manager object handle */
virtual LocalDataPoolManager* getHkManagerHandle() override;
/**
* @brief Hook function for child handlers which is called once per
* performOperation(). Default implementation is empty.
@ -528,114 +545,140 @@ protected:
static const DeviceCommandId_t NO_COMMAND_ID = -2;
static const MessageQueueId_t NO_COMMANDER = 0;
/**
* Pointer to the raw packet that will be sent.
*/
/** Pointer to the raw packet that will be sent.*/
uint8_t *rawPacket = nullptr;
/**
* Size of the #rawPacket.
*/
/** Size of the #rawPacket. */
uint32_t rawPacketLen = 0;
/**
* The mode the device handler is currently in.
*
* This should never be changed directly but only with setMode()
*/
Mode_t mode;
/**
* The submode the device handler is currently in.
*
* This should never be changed directly but only with setMode()
*/
Submode_t submode;
/**
* This is the counter value from performOperation().
*/
/** This is the counter value from performOperation(). */
uint8_t pstStep = 0;
uint32_t pstIntervalMs = 0;
/**
* wiretapping flag:
* Wiretapping flag:
*
* indicates either that all raw messages to and from the device should be sent to #theOneWhoWantsToReadRawTraffic
* or that all device TM should be downlinked to #theOneWhoWantsToReadRawTraffic
* indicates either that all raw messages to and from the device should be
* sent to #defaultRawReceiver
* or that all device TM should be downlinked to #defaultRawReceiver.
*/
enum WiretappingMode {
OFF = 0, RAW = 1, TM = 2
} wiretappingMode;
/**
* A message queue that accepts raw replies
* @brief A message queue that accepts raw replies
*
* Statically initialized in initialize() to a configurable object. Used when there is no method
* of finding a recipient, ie raw mode and reporting erreonous replies
* Statically initialized in initialize() to a configurable object.
* Used when there is no method of finding a recipient, ie raw mode and
* reporting erroneous replies
*/
MessageQueueId_t defaultRawReceiver = 0;
MessageQueueId_t defaultRawReceiver = MessageQueueIF::NO_QUEUE;
store_address_t storedRawData;
/**
* the message queue which wants to read all raw traffic
*
* if #isWiretappingActive all raw communication from and to the device will be sent to this queue
* @brief The message queue which wants to read all raw traffic
* If #isWiretappingActive all raw communication from and to the device
* will be sent to this queue
*/
MessageQueueId_t requestedRawTraffic = 0;
/**
* the object used to set power switches
*/
PowerSwitchIF *powerSwitcher = nullptr;
/**
* Pointer to the IPCStore.
*
* This caches the pointer received from the objectManager in the constructor.
*/
StorageManagerIF *IPCStore = nullptr;
/**
* cached for init
*/
/** The comIF object ID is cached for the intialize() function */
object_id_t deviceCommunicationId;
/**
* Communication object used for device communication
*/
/** Communication object used for device communication */
DeviceCommunicationIF * communicationInterface = nullptr;
/**
* Cookie used for communication
*/
/** Cookie used for communication */
CookieIF * comCookie;
/** Health helper for HasHealthIF */
HealthHelper healthHelper;
/** Mode helper for HasModesIF */
ModeHelper modeHelper;
/** Parameter helper for ReceivesParameterMessagesIF */
ParameterHelper parameterHelper;
/** Action helper for HasActionsIF */
ActionHelper actionHelper;
/** Housekeeping Manager */
LocalDataPoolManager hkManager;
/**
* @brief Information about commands
*/
struct DeviceCommandInfo {
bool isExecuting; //!< Indicates if the command is already executing.
uint8_t expectedReplies; //!< Dynamic value to indicate how many replies are expected. Inititated with 0.
MessageQueueId_t sendReplyTo; //!< if this is != NO_COMMANDER, DHB was commanded externally and shall report everything to commander.
//! Indicates if the command is already executing.
bool isExecuting;
//! Dynamic value to indicate how many replies are expected.
//! Inititated with 0.
uint8_t expectedReplies;
//! if this is != NO_COMMANDER, DHB was commanded externally and shall
//! report everything to commander.
MessageQueueId_t sendReplyTo;
};
using DeviceCommandMap = std::map<DeviceCommandId_t, DeviceCommandInfo> ;
/**
* Information about commands
*/
DeviceCommandMap deviceCommandMap;
/**
* @brief Information about expected replies
*
* This is used to keep track of pending replies
* This is used to keep track of pending replies.
*/
struct DeviceReplyInfo {
uint16_t maxDelayCycles; //!< The maximum number of cycles the handler should wait for a reply to this command.
uint16_t delayCycles; //!< The currently remaining cycles the handler should wait for a reply, 0 means there is no reply expected
//! The maximum number of cycles the handler should wait for a reply
//! to this command.
uint16_t maxDelayCycles;
//! The currently remaining cycles the handler should wait for a reply,
//! 0 means there is no reply expected
uint16_t delayCycles;
size_t replyLen = 0; //!< Expected size of the reply.
uint8_t periodic; //!< if this is !=0, the delayCycles will not be reset to 0 but to maxDelayCycles
DeviceCommandMap::iterator command; //!< The command that expects this reply.
//! if this is !=0, the delayCycles will not be reset to 0 but to
//! maxDelayCycles
bool periodic = false;
//! The dataset used to access housekeeping data related to the
//! respective device reply. Will point to a dataset held by
//! the child handler (if one is specified)
DataSetIF* dataSet = nullptr;
float collectionInterval = 0.0;
uint32_t intervalCounter = 0;
//! The command that expects this reply.
DeviceCommandMap::iterator command;
};
using DeviceReplyMap = std::map<DeviceCommandId_t, DeviceReplyInfo> ;
using DeviceReplyIter = DeviceReplyMap::iterator;
/**
* The MessageQueue used to receive device handler commands and to send replies.
* This map is used to check and track correct reception of all replies.
*
* It has multiple use:
* - It stores the information on pending replies. If a command is sent,
* the DeviceCommandInfo.count is incremented.
* - It is used to time-out missing replies. If a command is sent, the
* DeviceCommandInfo.DelayCycles is set to MaxDelayCycles.
* - It is queried to check if a reply from the device can be interpreted.
* scanForReply() returns the id of the command a reply was found for.
* The reply is ignored in the following cases:
* - No entry for the returned id was found
* - The deviceReplyInfo.delayCycles is == 0
*/
DeviceReplyMap deviceReplyMap;
//! The MessageQueue used to receive device handler commands
//! and to send replies.
MessageQueueIF* commandQueue = nullptr;
/**
@ -643,23 +686,14 @@ protected:
*
* can be set to PoolVariableIF::NO_PARAMETER to deactivate thermal checking
*/
uint32_t deviceThermalStatePoolId;
uint32_t deviceThermalStatePoolId = PoolVariableIF::NO_PARAMETER;
/**
* this is the datapool variable with the thermal request of the device
*
* can be set to PoolVariableIF::NO_PARAMETER to deactivate thermal checking
*/
uint32_t deviceThermalRequestPoolId;
/**
* Taking care of the health
*/
HealthHelper healthHelper;
ModeHelper modeHelper;
ParameterHelper parameterHelper;
uint32_t deviceThermalRequestPoolId = PoolVariableIF::NO_PARAMETER;
/**
* Optional Error code
@ -677,13 +711,15 @@ protected:
bool switchOffWasReported; //!< Indicates if SWITCH_WENT_OFF was already thrown.
PeriodicTaskIF* executingTask = nullptr;//!< Pointer to the task which executes this component, is invalid before setTaskIF was called.
//! Pointer to the task which executes this component, is invalid
//! before setTaskIF was called.
PeriodicTaskIF* executingTask = nullptr;
static object_id_t powerSwitcherId; //!< Object which switches power on and off.
static object_id_t rawDataReceiverId; //!< Object which receives RAW data by default.
static object_id_t defaultFDIRParentId; //!< Object which may be the root cause of an identified fault.
static object_id_t defaultFdirParentId; //!< Object which may be the root cause of an identified fault.
/**
* Helper function to report a missed reply
*
@ -966,24 +1002,11 @@ protected:
bool commandIsExecuting(DeviceCommandId_t commandId);
/**
* This map is used to check and track correct reception of all replies.
* set all switches returned by getSwitches()
*
* It has multiple use:
* - it stores the information on pending replies. If a command is sent, the DeviceCommandInfo.count is incremented.
* - it is used to time-out missing replies. If a command is sent, the DeviceCommandInfo.DelayCycles is set to MaxDelayCycles.
* - it is queried to check if a reply from the device can be interpreted. scanForReply() returns the id of the command a reply was found for.
* The reply is ignored in the following cases:
* - No entry for the returned id was found
* - The deviceReplyInfo.delayCycles is == 0
* @param onOff on == @c SWITCH_ON; off != @c SWITCH_ON
*/
DeviceReplyMap deviceReplyMap;
/**
* Information about commands
*/
DeviceCommandMap deviceCommandMap;
ActionHelper actionHelper;
void commandSwitch(ReturnValue_t onOff);
private:
/**
@ -1010,15 +1033,21 @@ private:
};
/**
* Info about the #cookie
*
* @brief Info about the #cookie
* Used to track the state of the communication
*/
CookieInfo cookieInfo;
/** the object used to set power switches */
PowerSwitchIF *powerSwitcher = nullptr;
/** Cached for initialize() */
static object_id_t defaultHkDestination;
/** HK destination can also be set individually */
object_id_t hkDestination = objects::NO_OBJECT;
/**
* Used for timing out mode transitions.
*
* @brief Used for timing out mode transitions.
* Set when setMode() is called.
*/
uint32_t timeoutStart = 0;
@ -1029,11 +1058,12 @@ private:
uint32_t childTransitionDelay;
/**
* The mode the current transition originated from
* @brief The mode the current transition originated from
*
* This is private so the child can not change it and fuck up the timeouts
*
* IMPORTANT: This is not valid during _MODE_SHUT_DOWN and _MODE_START_UP!! (it is _MODE_POWER_DOWN during this modes)
* IMPORTANT: This is not valid during _MODE_SHUT_DOWN and _MODE_START_UP!!
* (it is _MODE_POWER_DOWN during this modes)
*
* is element of [MODE_ON, MODE_NORMAL, MODE_RAW]
*/
@ -1044,13 +1074,6 @@ private:
*/
Submode_t transitionSourceSubMode;
/**
* the switch of the device
*
* for devices using two switches override getSwitches()
*/
const uint8_t deviceSwitch;
/**
* read the command queue
*/
@ -1148,12 +1171,6 @@ private:
ReturnValue_t getStorageData(store_address_t storageAddress, uint8_t **data,
uint32_t *len);
/**
* set all switches returned by getSwitches()
*
* @param onOff on == @c SWITCH_ON; off != @c SWITCH_ON
*/
void commandSwitch(ReturnValue_t onOff);
/**
* @param modeTo either @c MODE_ON, MODE_NORMAL or MODE_RAW NOTHING ELSE!!!
@ -1178,7 +1195,13 @@ private:
ReturnValue_t switchCookieChannel(object_id_t newChannelId);
ReturnValue_t handleDeviceHandlerMessage(CommandMessage *message);
virtual ReturnValue_t initializeAfterTaskCreation() override;
DataSetIF* getDataSetHandle(sid_t sid) override;
void parseReply(const uint8_t* receivedData,
size_t receivedDataLen);
};
#endif /* DEVICEHANDLERBASE_H_ */
#endif /* FRAMEWORK_DEVICEHANDLERS_DEVICEHANDLERBASE_H_ */

View File

@ -7,13 +7,15 @@
object_id_t DeviceHandlerFailureIsolation::powerConfirmationId = 0;
DeviceHandlerFailureIsolation::DeviceHandlerFailureIsolation(object_id_t owner, object_id_t parent) :
FailureIsolationBase(owner, parent), strangeReplyCount(MAX_STRANGE_REPLIES,
STRANGE_REPLIES_TIME_MS, parameterDomainBase++), missedReplyCount(
MAX_MISSED_REPLY_COUNT, MISSED_REPLY_TIME_MS,
parameterDomainBase++), recoveryCounter(MAX_REBOOT,
REBOOT_TIME_MS, parameterDomainBase++), fdirState(NONE), powerConfirmation(
0) {
DeviceHandlerFailureIsolation::DeviceHandlerFailureIsolation(object_id_t owner,
object_id_t parent) :
FailureIsolationBase(owner, parent),
strangeReplyCount(MAX_STRANGE_REPLIES, STRANGE_REPLIES_TIME_MS,
parameterDomainBase++),
missedReplyCount( MAX_MISSED_REPLY_COUNT, MISSED_REPLY_TIME_MS,
parameterDomainBase++),
recoveryCounter(MAX_REBOOT, REBOOT_TIME_MS, parameterDomainBase++),
fdirState(NONE), powerConfirmation(0) {
}
DeviceHandlerFailureIsolation::~DeviceHandlerFailureIsolation() {
@ -68,9 +70,11 @@ ReturnValue_t DeviceHandlerFailureIsolation::eventReceived(EventMessage* event)
break;
//****Power*****
case PowerSwitchIF::SWITCH_WENT_OFF:
result = sendConfirmationRequest(event, powerConfirmation);
if (result == RETURN_OK) {
setFdirState(DEVICE_MIGHT_BE_OFF);
if(hasPowerConfirmation) {
result = sendConfirmationRequest(event, powerConfirmation);
if (result == RETURN_OK) {
setFdirState(DEVICE_MIGHT_BE_OFF);
}
}
break;
case Fuse::FUSE_WENT_OFF:
@ -133,7 +137,7 @@ void DeviceHandlerFailureIsolation::decrementFaultCounters() {
void DeviceHandlerFailureIsolation::handleRecovery(Event reason) {
clearFaultCounters();
if (!recoveryCounter.incrementAndCheck()) {
if (not recoveryCounter.incrementAndCheck()) {
startRecovery(reason);
} else {
setFaulty(reason);
@ -142,7 +146,8 @@ void DeviceHandlerFailureIsolation::handleRecovery(Event reason) {
void DeviceHandlerFailureIsolation::wasParentsFault(EventMessage* event) {
//We'll better ignore the SWITCH_WENT_OFF event and await a system-wide reset.
//This means, no fault message will come through until a MODE_ or HEALTH_INFO message comes through -> Is that ok?
//This means, no fault message will come through until a MODE_ or
//HEALTH_INFO message comes through -> Is that ok?
//Same issue in TxFailureIsolation!
// if ((event->getEvent() == PowerSwitchIF::SWITCH_WENT_OFF)
// && (fdirState != RECOVERY_ONGOING)) {
@ -158,14 +163,17 @@ void DeviceHandlerFailureIsolation::clearFaultCounters() {
ReturnValue_t DeviceHandlerFailureIsolation::initialize() {
ReturnValue_t result = FailureIsolationBase::initialize();
if (result != HasReturnvaluesIF::RETURN_OK) {
sif::error << "DeviceHandlerFailureIsolation::initialize: Could not"
" initialize FailureIsolationBase." << std::endl;
return result;
}
ConfirmsFailuresIF* power = objectManager->get<ConfirmsFailuresIF>(
powerConfirmationId);
if (power == NULL) {
return RETURN_FAILED;
if (power != nullptr) {
powerConfirmation = power->getEventReceptionQueue();
hasPowerConfirmation = true;
}
powerConfirmation = power->getEventReceptionQueue();
return RETURN_OK;
}

View File

@ -28,8 +28,10 @@ protected:
NONE, RECOVERY_ONGOING, DEVICE_MIGHT_BE_OFF, AWAIT_SHUTDOWN
};
FDIRState fdirState;
bool hasPowerConfirmation = false;
MessageQueueId_t powerConfirmation;
static object_id_t powerConfirmationId;
// TODO: Are those hardcoded value? How can they be changed.
static const uint32_t MAX_REBOOT = 1;
static const uint32_t REBOOT_TIME_MS = 180000;
static const uint32_t MAX_STRANGE_REPLIES = 10;

View File

@ -98,7 +98,7 @@ public:
static const uint8_t INTERFACE_ID = CLASS_ID::DEVICE_HANDLER_IF;
// Standard codes used when building commands.
static const ReturnValue_t NO_COMMAND_DATA = MAKE_RETURN_CODE(0xA0); //!< If the command size is 0. Checked in DHB
static const ReturnValue_t NO_COMMAND_DATA = MAKE_RETURN_CODE(0xA0); //!< If no command data was given when expected.
static const ReturnValue_t COMMAND_NOT_SUPPORTED = MAKE_RETURN_CODE(0xA1); //!< Command ID not in commandMap. Checked in DHB
static const ReturnValue_t COMMAND_ALREADY_SENT = MAKE_RETURN_CODE(0xA2); //!< Command was already executed. Checked in DHB
static const ReturnValue_t COMMAND_WAS_NOT_SENT = MAKE_RETURN_CODE(0xA3);

View File

@ -25,7 +25,7 @@ public:
/**
* These are the commands that can be sent to a DeviceHandlerBase
*/
static const uint8_t MESSAGE_ID = MESSAGE_TYPE::DEVICE_HANDLER_COMMAND;
static const uint8_t MESSAGE_ID = messagetypes::DEVICE_HANDLER_COMMAND;
static const Command_t CMD_RAW = MAKE_COMMAND_ID( 1 ); //!< Sends a raw command, setParameter is a ::store_id_t containing the raw packet to send
// static const Command_t CMD_DIRECT = MAKE_COMMAND_ID( 2 ); //!< Sends a direct command, setParameter is a ::DeviceCommandId_t, setParameter2 is a ::store_id_t containing the data needed for the command
static const Command_t CMD_SWITCH_ADDRESS = MAKE_COMMAND_ID( 3 ); //!< Requests a IO-Board switch, setParameter() is the IO-Board identifier

View File

@ -12,18 +12,18 @@ DeviceTmReportingWrapper::~DeviceTmReportingWrapper() {
}
ReturnValue_t DeviceTmReportingWrapper::serialize(uint8_t** buffer,
size_t* size, const size_t max_size, bool bigEndian) const {
ReturnValue_t result = SerializeAdapter<object_id_t>::serialize(&objectId,
buffer, size, max_size, bigEndian);
size_t* size, size_t maxSize, Endianness streamEndianness) const {
ReturnValue_t result = SerializeAdapter::serialize(&objectId,
buffer, size, maxSize, streamEndianness);
if (result != HasReturnvaluesIF::RETURN_OK) {
return result;
}
result = SerializeAdapter<ActionId_t>::serialize(&actionId, buffer,
size, max_size, bigEndian);
result = SerializeAdapter::serialize(&actionId, buffer,
size, maxSize, streamEndianness);
if (result != HasReturnvaluesIF::RETURN_OK) {
return result;
}
return data->serialize(buffer, size, max_size, bigEndian);
return data->serialize(buffer, size, maxSize, streamEndianness);
}
size_t DeviceTmReportingWrapper::getSerializedSize() const {
@ -31,16 +31,16 @@ size_t DeviceTmReportingWrapper::getSerializedSize() const {
}
ReturnValue_t DeviceTmReportingWrapper::deSerialize(const uint8_t** buffer,
size_t* size, bool bigEndian) {
ReturnValue_t result = SerializeAdapter<object_id_t>::deSerialize(&objectId,
buffer, size, bigEndian);
size_t* size, Endianness streamEndianness) {
ReturnValue_t result = SerializeAdapter::deSerialize(&objectId,
buffer, size, streamEndianness);
if (result != HasReturnvaluesIF::RETURN_OK) {
return result;
}
result = SerializeAdapter<ActionId_t>::deSerialize(&actionId, buffer,
size, bigEndian);
result = SerializeAdapter::deSerialize(&actionId, buffer,
size, streamEndianness);
if (result != HasReturnvaluesIF::RETURN_OK) {
return result;
}
return data->deSerialize(buffer, size, bigEndian);
return data->deSerialize(buffer, size, streamEndianness);
}

View File

@ -12,12 +12,12 @@ public:
virtual ~DeviceTmReportingWrapper();
virtual ReturnValue_t serialize(uint8_t** buffer, size_t* size,
const size_t max_size, bool bigEndian) const;
size_t maxSize, Endianness streamEndianness) const override;
virtual size_t getSerializedSize() const;
virtual size_t getSerializedSize() const override;
virtual ReturnValue_t deSerialize(const uint8_t** buffer, size_t* size,
bool bigEndian);
Endianness streamEndianness) override;
private:
object_id_t objectId;
ActionId_t actionId;

View File

@ -5,7 +5,7 @@ HealthDevice::HealthDevice(object_id_t setObjectId,
MessageQueueId_t parentQueue) :
SystemObject(setObjectId), lastHealth(HEALTHY), parentQueue(
parentQueue), commandQueue(), healthHelper(this, setObjectId) {
commandQueue = QueueFactory::instance()->createMessageQueue(3, CommandMessage::COMMAND_MESSAGE_SIZE);
commandQueue = QueueFactory::instance()->createMessageQueue(3, CommandMessage::MINIMUM_COMMAND_MESSAGE_SIZE);
}
HealthDevice::~HealthDevice() {
@ -13,10 +13,10 @@ HealthDevice::~HealthDevice() {
}
ReturnValue_t HealthDevice::performOperation(uint8_t opCode) {
CommandMessage message;
ReturnValue_t result = commandQueue->receiveMessage(&message);
CommandMessage command;
ReturnValue_t result = commandQueue->receiveMessage(&command);
if (result == HasReturnvaluesIF::RETURN_OK) {
healthHelper.handleHealthCommand(&message);
healthHelper.handleHealthCommand(&command);
}
return HasReturnvaluesIF::RETURN_OK;
}
@ -38,7 +38,7 @@ MessageQueueId_t HealthDevice::getCommandQueue() const {
}
void HealthDevice::setParentQueue(MessageQueueId_t parentQueue) {
healthHelper.setParentQeueue(parentQueue);
healthHelper.setParentQueue(parentQueue);
}
bool HealthDevice::hasHealthChanged() {

View File

@ -1,10 +1,10 @@
#ifndef EVENTOBJECT_EVENT_H_
#define EVENTOBJECT_EVENT_H_
#ifndef FRAMEWORK_EVENTS_EVENT_H_
#define FRAMEWORK_EVENTS_EVENT_H_
#include <stdint.h>
#include <cstdint>
#include <framework/events/fwSubsystemIdRanges.h>
//could be move to more suitable location
#include <config/tmtc/subsystemIdRanges.h>
#include <subsystemIdRanges.h>
typedef uint16_t EventId_t;
typedef uint8_t EventSeverity_t;
@ -21,6 +21,7 @@ EventSeverity_t getSeverity(Event event);
Event makeEvent(EventId_t eventId, EventSeverity_t eventSeverity);
}
namespace SEVERITY {
static const EventSeverity_t INFO = 1;
static const EventSeverity_t LOW = 2;
@ -41,4 +42,4 @@ namespace SEVERITY {
// static const EventSeverity_t HIGH = 4;
//};
#endif /* EVENTOBJECT_EVENT_H_ */
#endif /* FRAMEWORK_EVENTS_EVENT_H_ */

View File

@ -8,13 +8,16 @@
const uint16_t EventManager::POOL_SIZES[N_POOLS] = {
sizeof(EventMatchTree::Node), sizeof(EventIdRangeMatcher),
sizeof(ReporterRangeMatcher) };
//If one checks registerListener calls, there are around 40 (to max 50) objects registering for certain events.
//Each listener requires 1 or 2 EventIdMatcher and 1 or 2 ReportRangeMatcher. So a good guess is 75 to a max of 100 pools required for each, which fits well.
// If one checks registerListener calls, there are around 40 (to max 50)
// objects registering for certain events.
// Each listener requires 1 or 2 EventIdMatcher and 1 or 2 ReportRangeMatcher.
// So a good guess is 75 to a max of 100 pools required for each, which fits well.
// SHOULDDO: Shouldn't this be in the config folder and passed via ctor?
const uint16_t EventManager::N_ELEMENTS[N_POOLS] = { 240, 120, 120 };
EventManager::EventManager(object_id_t setObjectId) :
SystemObject(setObjectId), eventReportQueue(NULL), mutex(NULL), factoryBackend(
0, POOL_SIZES, N_ELEMENTS, false, true) {
SystemObject(setObjectId),
factoryBackend(0, POOL_SIZES, N_ELEMENTS, false, true) {
mutex = MutexFactory::instance()->createMutex();
eventReportQueue = QueueFactory::instance()->createMessageQueue(
MAX_EVENTS_PER_CYCLE, EventMessage::EVENT_MESSAGE_SIZE);
@ -49,7 +52,7 @@ void EventManager::notifyListeners(EventMessage* message) {
for (auto iter = listenerList.begin(); iter != listenerList.end(); ++iter) {
if (iter->second.match(message)) {
MessageQueueSenderIF::sendMessage(iter->first, message,
message->getSender());
message->getSender());
}
}
unlockMutex();
@ -130,20 +133,23 @@ void EventManager::printEvent(EventMessage* message) {
break;
default:
string = translateObject(message->getReporter());
sif::error << "EVENT: ";
sif::debug << "EventManager: ";
if (string != 0) {
sif::error << string;
} else {
sif::error << "0x" << std::hex << message->getReporter() << std::dec;
sif::debug << string;
}
sif::error << " reported " << translateEvents(message->getEvent()) << " ("
<< std::dec << message->getEventId() << ") " << std::endl;
sif::error << std::hex << "P1 Hex: 0x" << message->getParameter1() << ", P1 Dec: "
<< std::dec << message->getParameter1() << std::endl;
sif::error << std::hex << "P2 Hex: 0x" << message->getParameter2() << ", P2 Dec: "
<< std::dec << message->getParameter2() << std::endl;
else {
sif::debug << "0x" << std::hex << message->getReporter() << std::dec;
}
sif::debug << " reported " << translateEvents(message->getEvent())
<< " (" << std::dec << message->getEventId() << ") "
<< std::endl;
sif::debug << std::hex << "P1 Hex: 0x" << message->getParameter1()
<< ", P1 Dec: " << std::dec << message->getParameter1()
<< std::endl;
sif::debug << std::hex << "P2 Hex: 0x" << message->getParameter2()
<< ", P2 Dec: " << std::dec << message->getParameter2()
<< std::endl;
break;
}
@ -151,7 +157,7 @@ void EventManager::printEvent(EventMessage* message) {
#endif
void EventManager::lockMutex() {
mutex->lockMutex(MutexIF::NO_TIMEOUT);
mutex->lockMutex(MutexIF::BLOCKING);
}
void EventManager::unlockMutex() {

View File

@ -36,11 +36,11 @@ public:
ReturnValue_t performOperation(uint8_t opCode);
protected:
MessageQueueIF* eventReportQueue;
MessageQueueIF* eventReportQueue = nullptr;
std::map<MessageQueueId_t, EventMatchTree> listenerList;
MutexIF* mutex;
MutexIF* mutex = nullptr;
static const uint8_t N_POOLS = 3;
LocalPool<N_POOLS> factoryBackend;

View File

@ -12,15 +12,15 @@ public:
EventRangeMatcherBase(T from, T till, bool inverted) : rangeMatcher(from, till, inverted) { }
virtual ~EventRangeMatcherBase() { }
ReturnValue_t serialize(uint8_t** buffer, size_t* size,
const size_t max_size, bool bigEndian) const {
return rangeMatcher.serialize(buffer, size, max_size, bigEndian);
size_t maxSize, Endianness streamEndianness) const {
return rangeMatcher.serialize(buffer, size, maxSize, streamEndianness);
}
size_t getSerializedSize() const {
return rangeMatcher.getSerializedSize();
}
ReturnValue_t deSerialize(const uint8_t** buffer, size_t* size,
bool bigEndian) {
return rangeMatcher.deSerialize(buffer, size, bigEndian);
Endianness streamEndianness) {
return rangeMatcher.deSerialize(buffer, size, streamEndianness);
}
protected:
RangeMatcher<T> rangeMatcher;

View File

@ -4,6 +4,7 @@
#include <framework/returnvalues/HasReturnvaluesIF.h>
#include <framework/ipc/MessageQueueSenderIF.h>
// TODO: Documentation.
class ConfirmsFailuresIF {
public:
static const uint8_t INTERFACE_ID = CLASS_ID::HANDLES_FAILURES_IF;

View File

@ -9,7 +9,8 @@ FailureIsolationBase::FailureIsolationBase(object_id_t owner,
object_id_t parent, uint8_t messageDepth, uint8_t parameterDomainBase) :
eventQueue(NULL), ownerId(owner), owner(NULL),
faultTreeParent(parent), parameterDomainBase(parameterDomainBase) {
eventQueue = QueueFactory::instance()->createMessageQueue(messageDepth, EventMessage::EVENT_MESSAGE_SIZE);
eventQueue = QueueFactory::instance()->createMessageQueue(messageDepth,
EventMessage::EVENT_MESSAGE_SIZE);
}
FailureIsolationBase::~FailureIsolationBase() {
@ -19,27 +20,36 @@ FailureIsolationBase::~FailureIsolationBase() {
ReturnValue_t FailureIsolationBase::initialize() {
EventManagerIF* manager = objectManager->get<EventManagerIF>(
objects::EVENT_MANAGER);
if (manager == NULL) {
if (manager == nullptr) {
sif::error << "FailureIsolationBase::initialize: Event Manager has not"
" been initialized!" << std::endl;
return RETURN_FAILED;
}
ReturnValue_t result = manager->registerListener(eventQueue->getId());
if (result != HasReturnvaluesIF::RETURN_OK) {
return result;
}
if (ownerId != 0) {
if (ownerId != objects::NO_OBJECT) {
result = manager->subscribeToAllEventsFrom(eventQueue->getId(), ownerId);
if (result != HasReturnvaluesIF::RETURN_OK) {
return result;
}
owner = objectManager->get<HasHealthIF>(ownerId);
if (owner == NULL) {
return RETURN_FAILED;
if (owner == nullptr) {
sif::error << "FailureIsolationBase::intialize: Owner object "
"invalid. Make sure it implements HasHealthIF" << std::endl;
return ObjectManagerIF::CHILD_INIT_FAILED;
}
}
if (faultTreeParent != 0) {
if (faultTreeParent != objects::NO_OBJECT) {
ConfirmsFailuresIF* parentIF = objectManager->get<ConfirmsFailuresIF>(
faultTreeParent);
if (parentIF == NULL) {
if (parentIF == nullptr) {
sif::error << "FailureIsolationBase::intialize: Parent object"
<< "invalid." << std::endl;
sif::error << "Make sure it implements ConfirmsFailuresIF."
<< std::endl;
return ObjectManagerIF::CHILD_INIT_FAILED;
return RETURN_FAILED;
}
eventQueue->setDefaultDestination(parentIF->getEventReceptionQueue());
@ -94,9 +104,9 @@ MessageQueueId_t FailureIsolationBase::getEventReceptionQueue() {
ReturnValue_t FailureIsolationBase::sendConfirmationRequest(EventMessage* event,
MessageQueueId_t destination) {
event->setMessageId(EventMessage::CONFIRMATION_REQUEST);
if (destination != 0) {
if (destination != MessageQueueIF::NO_QUEUE) {
return eventQueue->sendMessage(destination, event);
} else if (faultTreeParent != 0) {
} else if (faultTreeParent != objects::NO_OBJECT) {
return eventQueue->sendToDefault(event);
}
return RETURN_FAILED;

View File

@ -17,8 +17,11 @@ public:
static const Event FDIR_CHANGED_STATE = MAKE_EVENT(1, SEVERITY::INFO); //!< FDIR has an internal state, which changed from par2 (oldState) to par1 (newState).
static const Event FDIR_STARTS_RECOVERY = MAKE_EVENT(2, SEVERITY::MEDIUM); //!< FDIR tries to restart device. Par1: event that caused recovery.
static const Event FDIR_TURNS_OFF_DEVICE = MAKE_EVENT(3, SEVERITY::MEDIUM); //!< FDIR turns off device. Par1: event that caused recovery.
FailureIsolationBase(object_id_t owner, object_id_t parent = 0,
FailureIsolationBase(object_id_t owner,
object_id_t parent = objects::NO_OBJECT,
uint8_t messageDepth = 10, uint8_t parameterDomainBase = 0xF0);
virtual ~FailureIsolationBase();
virtual ReturnValue_t initialize();
@ -26,7 +29,7 @@ public:
* This is called by the DHB in performOperation()
*/
void checkForFailures();
MessageQueueId_t getEventReceptionQueue();
MessageQueueId_t getEventReceptionQueue() override;
virtual void triggerEvent(Event event, uint32_t parameter1 = 0,
uint32_t parameter2 = 0);
protected:
@ -42,7 +45,7 @@ protected:
virtual ReturnValue_t confirmFault(EventMessage* event);
virtual void decrementFaultCounters() = 0;
ReturnValue_t sendConfirmationRequest(EventMessage* event,
MessageQueueId_t destination = 0);
MessageQueueId_t destination = MessageQueueIF::NO_QUEUE);
void throwFdirEvent(Event event, uint32_t parameter1 = 0,
uint32_t parameter2 = 0);
private:

View File

@ -1,5 +1,5 @@
# This file needs FRAMEWORK_PATH and API set correctly
# Valid API settings: rtems, linux, freeRTOS
# This file needs FRAMEWORK_PATH and OS_FSFW set correctly by another Makefile.
# Valid API settings: rtems, linux, freeRTOS, host
CXXSRC += $(wildcard $(FRAMEWORK_PATH)/action/*.cpp)
CXXSRC += $(wildcard $(FRAMEWORK_PATH)/container/*.cpp)
@ -10,11 +10,11 @@ CXXSRC += $(wildcard $(FRAMEWORK_PATH)/datalinklayer/*.cpp)
CXXSRC += $(wildcard $(FRAMEWORK_PATH)/datapool/*.cpp)
CXXSRC += $(wildcard $(FRAMEWORK_PATH)/datapoolglob/*.cpp)
CXXSRC += $(wildcard $(FRAMEWORK_PATH)/datapoollocal/*.cpp)
CXXSRC += $(wildcard $(FRAMEWORK_PATH)/housekeeping/*.cpp)
CXXSRC += $(wildcard $(FRAMEWORK_PATH)/devicehandlers/*.cpp)
CXXSRC += $(wildcard $(FRAMEWORK_PATH)/events/*.cpp)
CXXSRC += $(wildcard $(FRAMEWORK_PATH)/events/eventmatching/*.cpp)
CXXSRC += $(wildcard $(FRAMEWORK_PATH)/fdir/*.cpp)
CXXSRC += $(wildcard $(FRAMEWORK_PATH)/framework.mk/*.cpp)
CXXSRC += $(wildcard $(FRAMEWORK_PATH)/globalfunctions/*.cpp)
CXXSRC += $(wildcard $(FRAMEWORK_PATH)/globalfunctions/matching/*.cpp)
CXXSRC += $(wildcard $(FRAMEWORK_PATH)/globalfunctions/math/*.cpp)
@ -28,14 +28,16 @@ CXXSRC += $(wildcard $(FRAMEWORK_PATH)/objectmanager/*.cpp)
CXXSRC += $(wildcard $(FRAMEWORK_PATH)/osal/*.cpp)
# select the OS
ifeq ($(OS),rtems)
ifeq ($(OS_FSFW),rtems)
CXXSRC += $(wildcard $(FRAMEWORK_PATH)/osal/rtems/*.cpp)
else ifeq ($(OS),linux)
else ifeq ($(OS_FSFW),linux)
CXXSRC += $(wildcard $(FRAMEWORK_PATH)/osal/linux/*.cpp)
else ifeq ($(OS),freeRTOS)
else ifeq ($(OS_FSFW),freeRTOS)
CXXSRC += $(wildcard $(FRAMEWORK_PATH)/osal/FreeRTOS/*.cpp)
else ifeq ($(OS_FSFW),host)
CXXSRC += $(wildcard $(FRAMEWORK_PATH)/osal/host/*.cpp)
else
$(error invalid OS specified, valid OS are rtems, linux, freeRTOS)
$(error invalid OS specified, valid OS are rtems, linux, freeRTOS, host)
endif
CXXSRC += $(wildcard $(FRAMEWORK_PATH)/parameters/*.cpp)
@ -56,4 +58,4 @@ CXXSRC += $(wildcard $(FRAMEWORK_PATH)/tmtcpacket/*.cpp)
CXXSRC += $(wildcard $(FRAMEWORK_PATH)/tmtcpacket/packetmatcher/*.cpp)
CXXSRC += $(wildcard $(FRAMEWORK_PATH)/tmtcpacket/pus/*.cpp)
CXXSRC += $(wildcard $(FRAMEWORK_PATH)/tmtcservices/*.cpp)
CXXSRC += $(wildcard $(FRAMEWORK_PATH)/test/*.cpp)
CXXSRC += $(wildcard $(FRAMEWORK_PATH)/pus/*.cpp)

View File

@ -1,95 +1,123 @@
#include <framework/globalfunctions/DleEncoder.h>
DleEncoder::DleEncoder() {
}
DleEncoder::DleEncoder() {}
DleEncoder::~DleEncoder() {
}
ReturnValue_t DleEncoder::decode(const uint8_t *sourceStream,
uint32_t sourceStreamLen, uint32_t *readLen, uint8_t *destStream,
uint32_t maxDestStreamlen, uint32_t *decodedLen) {
uint32_t encodedIndex = 0, decodedIndex = 0;
uint8_t nextByte;
if (*sourceStream != STX) {
return RETURN_FAILED;
}
++encodedIndex;
while ((encodedIndex < sourceStreamLen) && (decodedIndex < maxDestStreamlen)
&& (sourceStream[encodedIndex] != ETX)
&& (sourceStream[encodedIndex] != STX)) {
if (sourceStream[encodedIndex] == DLE) {
nextByte = sourceStream[encodedIndex + 1];
if (nextByte == 0x10) {
destStream[decodedIndex] = nextByte;
} else {
if ((nextByte == 0x42) || (nextByte == 0x43)
|| (nextByte == 0x4D)) {
destStream[decodedIndex] = nextByte - 0x40;
} else {
return RETURN_FAILED;
}
}
++encodedIndex;
} else {
destStream[decodedIndex] = sourceStream[encodedIndex];
}
++encodedIndex;
++decodedIndex;
}
if (sourceStream[encodedIndex] != ETX) {
return RETURN_FAILED;
} else {
*readLen = ++encodedIndex;
*decodedLen = decodedIndex;
return RETURN_OK;
}
}
DleEncoder::~DleEncoder() {}
ReturnValue_t DleEncoder::encode(const uint8_t* sourceStream,
uint32_t sourceLen, uint8_t* destStream, uint32_t maxDestLen,
uint32_t* encodedLen, bool addStxEtx) {
size_t sourceLen, uint8_t* destStream, size_t maxDestLen,
size_t* encodedLen, bool addStxEtx) {
if (maxDestLen < 2) {
return RETURN_FAILED;
return STREAM_TOO_SHORT;
}
uint32_t encodedIndex = 0, sourceIndex = 0;
size_t encodedIndex = 0, sourceIndex = 0;
uint8_t nextByte;
if (addStxEtx) {
destStream[0] = STX;
++encodedIndex;
}
while ((encodedIndex < maxDestLen) && (sourceIndex < sourceLen)) {
while (encodedIndex < maxDestLen and sourceIndex < sourceLen)
{
nextByte = sourceStream[sourceIndex];
if ((nextByte == STX) || (nextByte == ETX) || (nextByte == 0x0D)) {
// STX, ETX and CR characters in the stream need to be escaped with DLE
if (nextByte == STX or nextByte == ETX or nextByte == CARRIAGE_RETURN) {
if (encodedIndex + 1 >= maxDestLen) {
return RETURN_FAILED;
} else {
return STREAM_TOO_SHORT;
}
else {
destStream[encodedIndex] = DLE;
++encodedIndex;
/* Escaped byte will be actual byte + 0x40. This prevents
* STX, ETX, and carriage return characters from appearing
* in the encoded data stream at all, so when polling an
* encoded stream, the transmission can be stopped at ETX.
* 0x40 was chosen at random with special requirements:
* - Prevent going from one control char to another
* - Prevent overflow for common characters */
destStream[encodedIndex] = nextByte + 0x40;
}
} else if (nextByte == DLE) {
}
// DLE characters are simply escaped with DLE.
else if (nextByte == DLE) {
if (encodedIndex + 1 >= maxDestLen) {
return RETURN_FAILED;
} else {
return STREAM_TOO_SHORT;
}
else {
destStream[encodedIndex] = DLE;
++encodedIndex;
destStream[encodedIndex] = DLE;
}
} else {
}
else {
destStream[encodedIndex] = nextByte;
}
++encodedIndex;
++sourceIndex;
}
if ((sourceIndex == sourceLen) && (encodedIndex < maxDestLen)) {
if (sourceIndex == sourceLen and encodedIndex < maxDestLen) {
if (addStxEtx) {
destStream[encodedIndex] = ETX;
++encodedIndex;
}
*encodedLen = encodedIndex;
return RETURN_OK;
} else {
return RETURN_FAILED;
}
else {
return STREAM_TOO_SHORT;
}
}
ReturnValue_t DleEncoder::decode(const uint8_t *sourceStream,
size_t sourceStreamLen, size_t *readLen, uint8_t *destStream,
size_t maxDestStreamlen, size_t *decodedLen) {
size_t encodedIndex = 0, decodedIndex = 0;
uint8_t nextByte;
if (*sourceStream != STX) {
return DECODING_ERROR;
}
++encodedIndex;
while ((encodedIndex < sourceStreamLen) && (decodedIndex < maxDestStreamlen)
&& (sourceStream[encodedIndex] != ETX)
&& (sourceStream[encodedIndex] != STX)) {
if (sourceStream[encodedIndex] == DLE) {
nextByte = sourceStream[encodedIndex + 1];
// The next byte is a DLE character that was escaped by another
// DLE character, so we can write it to the destination stream.
if (nextByte == DLE) {
destStream[decodedIndex] = nextByte;
}
else {
/* The next byte is a STX, DTX or 0x0D character which
* was escaped by a DLE character. The actual byte was
* also encoded by adding + 0x40 to preven having control chars,
* in the stream at all, so we convert it back. */
if (nextByte == 0x42 or nextByte == 0x43 or nextByte == 0x4D) {
destStream[decodedIndex] = nextByte - 0x40;
}
else {
return DECODING_ERROR;
}
}
++encodedIndex;
}
else {
destStream[decodedIndex] = sourceStream[encodedIndex];
}
++encodedIndex;
++decodedIndex;
}
if (sourceStream[encodedIndex] != ETX) {
return DECODING_ERROR;
}
else {
*readLen = ++encodedIndex;
*decodedLen = decodedIndex;
return RETURN_OK;
}
}

View File

@ -1,25 +1,79 @@
#ifndef DLEENCODER_H_
#define DLEENCODER_H_
#ifndef FRAMEWORK_GLOBALFUNCTIONS_DLEENCODER_H_
#define FRAMEWORK_GLOBALFUNCTIONS_DLEENCODER_H_
#include <framework/returnvalues/HasReturnvaluesIF.h>
#include <cstddef>
/**
* @brief This DLE Encoder (Data Link Encoder) can be used to encode and
* decode arbitrary data with ASCII control characters
* @details
* List of control codes:
* https://en.wikipedia.org/wiki/C0_and_C1_control_codes
*
* This encoder can be used to achieve a basic transport layer when using
* char based transmission systems.
* The passed source strean is converted into a encoded stream by adding
* a STX marker at the start of the stream and an ETX marker at the end of
* the stream. Any STX, ETX, DLE and CR occurences in the source stream are
* escaped by a DLE character. The encoder also replaces escaped control chars
* by another char, so STX, ETX and CR should not appear anywhere in the actual
* encoded data stream.
*
* When using a strictly char based reception of packets enoded with DLE,
* STX can be used to notify a reader that actual data will start to arrive
* while ETX can be used to notify the reader that the data has ended.
*/
class DleEncoder: public HasReturnvaluesIF {
private:
DleEncoder();
virtual ~DleEncoder();
public:
static const uint8_t STX = 0x02;
static const uint8_t ETX = 0x03;
static const uint8_t DLE = 0x10;
static constexpr uint8_t INTERFACE_ID = CLASS_ID::DLE_ENCODER;
static constexpr ReturnValue_t STREAM_TOO_SHORT = MAKE_RETURN_CODE(0x01);
static constexpr ReturnValue_t DECODING_ERROR = MAKE_RETURN_CODE(0x02);
//! Start Of Text character. First character is encoded stream
static constexpr uint8_t STX = 0x02;
//! End Of Text character. Last character in encoded stream
static constexpr uint8_t ETX = 0x03;
//! Data Link Escape character. Used to escape STX, ETX and DLE occurences
//! in the source stream.
static constexpr uint8_t DLE = 0x10;
static constexpr uint8_t CARRIAGE_RETURN = 0x0D;
/**
* Encodes the give data stream by preceding it with the STX marker
* and ending it with an ETX marker. STX, ETX and DLE characters inside
* the stream are escaped by DLE characters and also replaced by adding
* 0x40 (which is reverted in the decoing process).
* @param sourceStream
* @param sourceLen
* @param destStream
* @param maxDestLen
* @param encodedLen
* @param addStxEtx
* Adding STX and ETX can be omitted, if they are added manually.
* @return
*/
static ReturnValue_t encode(const uint8_t *sourceStream, size_t sourceLen,
uint8_t *destStream, size_t maxDestLen, size_t *encodedLen,
bool addStxEtx = true);
/**
* Converts an encoded stream back.
* @param sourceStream
* @param sourceStreamLen
* @param readLen
* @param destStream
* @param maxDestStreamlen
* @param decodedLen
* @return
*/
static ReturnValue_t decode(const uint8_t *sourceStream,
uint32_t sourceStreamLen, uint32_t *readLen, uint8_t *destStream,
uint32_t maxDestStreamlen, uint32_t *decodedLen);
static ReturnValue_t encode(const uint8_t *sourceStream, uint32_t sourceLen,
uint8_t *destStream, uint32_t maxDestLen, uint32_t *encodedLen,
bool addStxEtx = true);
size_t sourceStreamLen, size_t *readLen, uint8_t *destStream,
size_t maxDestStreamlen, size_t *decodedLen);
};
#endif /* DLEENCODER_H_ */
#endif /* FRAMEWORK_GLOBALFUNCTIONS_DLEENCODER_H_ */

View File

@ -59,7 +59,7 @@ uint8_t Type::getSize() const {
}
ReturnValue_t Type::serialize(uint8_t** buffer, size_t* size,
const size_t max_size, bool bigEndian) const {
size_t maxSize, Endianness streamEndianness) const {
uint8_t ptc;
uint8_t pfc;
ReturnValue_t result = getPtcPfc(&ptc, &pfc);
@ -67,14 +67,14 @@ ReturnValue_t Type::serialize(uint8_t** buffer, size_t* size,
return result;
}
result = SerializeAdapter<uint8_t>::serialize(&ptc, buffer, size, max_size,
bigEndian);
result = SerializeAdapter::serialize(&ptc, buffer, size, maxSize,
streamEndianness);
if (result != HasReturnvaluesIF::RETURN_OK) {
return result;
}
result = SerializeAdapter<uint8_t>::serialize(&pfc, buffer, size, max_size,
bigEndian);
result = SerializeAdapter::serialize(&pfc, buffer, size, maxSize,
streamEndianness);
return result;
@ -82,21 +82,21 @@ ReturnValue_t Type::serialize(uint8_t** buffer, size_t* size,
size_t Type::getSerializedSize() const {
uint8_t dontcare = 0;
return 2 * SerializeAdapter<uint8_t>::getSerializedSize(&dontcare);
return 2 * SerializeAdapter::getSerializedSize(&dontcare);
}
ReturnValue_t Type::deSerialize(const uint8_t** buffer, size_t* size,
bool bigEndian) {
Endianness streamEndianness) {
uint8_t ptc;
uint8_t pfc;
ReturnValue_t result = SerializeAdapter<uint8_t>::deSerialize(&ptc, buffer,
size, bigEndian);
ReturnValue_t result = SerializeAdapter::deSerialize(&ptc, buffer,
size, streamEndianness);
if (result != HasReturnvaluesIF::RETURN_OK) {
return result;
}
result = SerializeAdapter<uint8_t>::deSerialize(&pfc, buffer, size,
bigEndian);
result = SerializeAdapter::deSerialize(&pfc, buffer, size,
streamEndianness);
if (result != HasReturnvaluesIF::RETURN_OK) {
return result;
}

View File

@ -25,7 +25,7 @@ public:
Type(ActualType_t actualType);
Type(const Type& type);
Type(const Type &type);
Type& operator=(Type rhs);
@ -33,8 +33,8 @@ public:
operator ActualType_t() const;
bool operator==(const Type& rhs);
bool operator!=(const Type& rhs);
bool operator==(const Type &rhs);
bool operator!=(const Type &rhs);
uint8_t getSize() const;
@ -42,13 +42,13 @@ public:
static ActualType_t getActualType(uint8_t ptc, uint8_t pfc);
virtual ReturnValue_t serialize(uint8_t** buffer, size_t* size,
const size_t max_size, bool bigEndian) const;
virtual ReturnValue_t serialize(uint8_t **buffer, size_t *size,
size_t maxSize, Endianness streamEndianness) const override;
virtual size_t getSerializedSize() const;
virtual size_t getSerializedSize() const override;
virtual ReturnValue_t deSerialize(const uint8_t** buffer, size_t* size,
bool bigEndian);
virtual ReturnValue_t deSerialize(const uint8_t **buffer, size_t *size,
Endianness streamEndianness) override;
private:
ActualType_t actualType;

View File

@ -1,25 +1,25 @@
#include <framework/globalfunctions/printer.h>
#include <framework/globalfunctions/arrayprinter.h>
#include <framework/serviceinterface/ServiceInterfaceStream.h>
#include <bitset>
void printer::print(const uint8_t *data, size_t size, OutputType type,
void arrayprinter::print(const uint8_t *data, size_t size, OutputType type,
bool printInfo, size_t maxCharPerLine) {
if(printInfo) {
sif::info << "Printing data with size " << size << ": ";
}
sif::info << "[";
if(type == OutputType::HEX) {
printer::printHex(data, size, maxCharPerLine);
arrayprinter::printHex(data, size, maxCharPerLine);
}
else if (type == OutputType::DEC) {
printer::printDec(data, size, maxCharPerLine);
arrayprinter::printDec(data, size, maxCharPerLine);
}
else if(type == OutputType::BIN) {
printer::printBin(data, size);
arrayprinter::printBin(data, size);
}
}
void printer::printHex(const uint8_t *data, size_t size,
void arrayprinter::printHex(const uint8_t *data, size_t size,
size_t maxCharPerLine) {
sif::info << std::hex;
for(size_t i = 0; i < size; i++) {
@ -36,7 +36,7 @@ void printer::printHex(const uint8_t *data, size_t size,
sif::info << "]" << std::endl;
}
void printer::printDec(const uint8_t *data, size_t size,
void arrayprinter::printDec(const uint8_t *data, size_t size,
size_t maxCharPerLine) {
sif::info << std::dec;
for(size_t i = 0; i < size; i++) {
@ -51,7 +51,7 @@ void printer::printDec(const uint8_t *data, size_t size,
sif::info << "]" << std::endl;
}
void printer::printBin(const uint8_t *data, size_t size) {
void arrayprinter::printBin(const uint8_t *data, size_t size) {
sif::info << "\n" << std::flush;
for(size_t i = 0; i < size; i++) {
sif::info << "Byte " << i + 1 << ": 0b"<<

View File

@ -1,16 +1,15 @@
#ifndef FRAMEWORK_GLOBALFUNCTIONS_PRINTER_H_
#define FRAMEWORK_GLOBALFUNCTIONS_PRINTER_H_
#ifndef FRAMEWORK_GLOBALFUNCTIONS_ARRAYPRINTER_H_
#define FRAMEWORK_GLOBALFUNCTIONS_ARRAYPRINTER_H_
#include <cstdint>
#include <cstddef>
namespace printer {
enum class OutputType {
DEC,
HEX,
BIN
};
namespace arrayprinter {
void print(const uint8_t* data, size_t size, OutputType type = OutputType::HEX,
bool printInfo = true, size_t maxCharPerLine = 12);
void printHex(const uint8_t* data, size_t size, size_t maxCharPerLine = 12);
@ -18,4 +17,4 @@ void printDec(const uint8_t* data, size_t size, size_t maxCharPerLine = 12);
void printBin(const uint8_t* data, size_t size);
}
#endif /* FRAMEWORK_GLOBALFUNCTIONS_PRINTER_H_ */
#endif /* FRAMEWORK_GLOBALFUNCTIONS_ARRAYPRINTER_H_ */

View File

@ -1,104 +0,0 @@
#include <framework/globalfunctions/conversion.h>
#include <framework/osal/Endiness.h>
#include <cstring>
//SHOULDDO: This shall be optimized (later)!
void convertToByteStream( uint16_t value, uint8_t* buffer, uint32_t* size ) {
buffer[0] = (value & 0xFF00) >> 8;
buffer[1] = (value & 0x00FF);
*size += 2;
}
void convertToByteStream( uint32_t value, uint8_t* buffer, uint32_t* size ) {
buffer[0] = (value & 0xFF000000) >> 24;
buffer[1] = (value & 0x00FF0000) >> 16;
buffer[2] = (value & 0x0000FF00) >> 8;
buffer[3] = (value & 0x000000FF);
*size +=4;
}
void convertToByteStream( int16_t value, uint8_t* buffer, uint32_t* size ) {
buffer[0] = (value & 0xFF00) >> 8;
buffer[1] = (value & 0x00FF);
*size += 2;
}
void convertToByteStream( int32_t value, uint8_t* buffer, uint32_t* size ) {
buffer[0] = (value & 0xFF000000) >> 24;
buffer[1] = (value & 0x00FF0000) >> 16;
buffer[2] = (value & 0x0000FF00) >> 8;
buffer[3] = (value & 0x000000FF);
*size += 4;
}
//void convertToByteStream( uint64_t value, uint8_t* buffer, uint32_t* size ) {
// buffer[0] = (value & 0xFF00000000000000) >> 56;
// buffer[1] = (value & 0x00FF000000000000) >> 48;
// buffer[2] = (value & 0x0000FF0000000000) >> 40;
// buffer[3] = (value & 0x000000FF00000000) >> 32;
// buffer[4] = (value & 0x00000000FF000000) >> 24;
// buffer[5] = (value & 0x0000000000FF0000) >> 16;
// buffer[6] = (value & 0x000000000000FF00) >> 8;
// buffer[7] = (value & 0x00000000000000FF);
// *size+=8;
//}
//
//void convertToByteStream( int64_t value, uint8_t* buffer, uint32_t* size ) {
// buffer[0] = (value & 0xFF00000000000000) >> 56;
// buffer[1] = (value & 0x00FF000000000000) >> 48;
// buffer[2] = (value & 0x0000FF0000000000) >> 40;
// buffer[3] = (value & 0x000000FF00000000) >> 32;
// buffer[4] = (value & 0x00000000FF000000) >> 24;
// buffer[5] = (value & 0x0000000000FF0000) >> 16;
// buffer[6] = (value & 0x000000000000FF00) >> 8;
// buffer[7] = (value & 0x00000000000000FF);
// *size+=8;
//}
void convertToByteStream( float in_value, uint8_t* buffer, uint32_t* size ) {
#ifndef BYTE_ORDER_SYSTEM
#error BYTE_ORDER_SYSTEM not defined
#elif BYTE_ORDER_SYSTEM == LITTLE_ENDIAN
union float_union {
float value;
uint8_t chars[4];
};
float_union temp;
temp.value = in_value;
buffer[0] = temp.chars[3];
buffer[1] = temp.chars[2];
buffer[2] = temp.chars[1];
buffer[3] = temp.chars[0];
*size += 4;
#elif BYTE_ORDER_SYSTEM == BIG_ENDIAN
memcpy(buffer, &in_value, sizeof(in_value));
*size += sizeof(in_value);
#endif
}
void convertToByteStream( double in_value, uint8_t* buffer, uint32_t* size ) {
#ifndef BYTE_ORDER_SYSTEM
#error BYTE_ORDER_SYSTEM not defined
#elif BYTE_ORDER_SYSTEM == LITTLE_ENDIAN
union double_union {
double value;
uint8_t chars[8];
};
double_union temp;
temp.value = in_value;
buffer[0] = temp.chars[7];
buffer[1] = temp.chars[6];
buffer[2] = temp.chars[5];
buffer[3] = temp.chars[4];
buffer[4] = temp.chars[3];
buffer[5] = temp.chars[2];
buffer[6] = temp.chars[1];
buffer[7] = temp.chars[0];
*size += 8;
#elif BYTE_ORDER_SYSTEM == BIG_ENDIAN
memcpy(buffer, &in_value, sizeof(in_value));
*size += sizeof(in_value);
#endif
}

View File

@ -1,24 +0,0 @@
#ifndef CONVERSION_H_
#define CONVERSION_H_
#include <stdint.h>
void convertToByteStream( uint16_t value, uint8_t* buffer, uint32_t* size );
void convertToByteStream( uint32_t value, uint8_t* buffer, uint32_t* size );
void convertToByteStream( int16_t value, uint8_t* buffer, uint32_t* size );
void convertToByteStream( int32_t value, uint8_t* buffer, uint32_t* size );
//void convertToByteStream( uint64_t value, uint8_t* buffer, uint32_t* size );
//
//void convertToByteStream( int64_t value, uint8_t* buffer, uint32_t* size );
void convertToByteStream( float value, uint8_t* buffer, uint32_t* size );
void convertToByteStream( double value, uint8_t* buffer, uint32_t* size );
#endif /* CONVERSION_H_ */

View File

@ -46,37 +46,37 @@ public:
}
ReturnValue_t serialize(uint8_t** buffer, size_t* size,
const size_t max_size, bool bigEndian) const {
size_t maxSize, SerializeIF::Endianness streamEndianness) const override {
iterator iter = this->begin();
uint8_t count = this->countRight(iter);
ReturnValue_t result = SerializeAdapter<uint8_t>::serialize(&count,
buffer, size, max_size, bigEndian);
ReturnValue_t result = SerializeAdapter::serialize(&count,
buffer, size, maxSize, streamEndianness);
if (result != HasReturnvaluesIF::RETURN_OK) {
return result;
}
if (iter == this->end()) {
return HasReturnvaluesIF::RETURN_OK;
}
result = iter->serialize(buffer, size, max_size, bigEndian);
result = iter->serialize(buffer, size, maxSize, streamEndianness);
if (result != HasReturnvaluesIF::RETURN_OK) {
return result;
}
if (maxDepth > 0) {
MatchTree<T> temp(iter.left(), maxDepth - 1);
result = temp.serialize(buffer, size, max_size, bigEndian);
result = temp.serialize(buffer, size, maxSize, streamEndianness);
}
if (result != HasReturnvaluesIF::RETURN_OK) {
return result;
}
iter = iter.right();
while (iter != this->end()) {
result = iter->serialize(buffer, size, max_size, bigEndian);
result = iter->serialize(buffer, size, maxSize, streamEndianness);
if (result != HasReturnvaluesIF::RETURN_OK) {
return result;
}
if (maxDepth > 0) {
MatchTree<T> temp(iter.left(), maxDepth - 1);
result = temp.serialize(buffer, size, max_size, bigEndian);
result = temp.serialize(buffer, size, maxSize, streamEndianness);
}
if (result != HasReturnvaluesIF::RETURN_OK) {
return result;
@ -86,7 +86,7 @@ public:
return result;
}
size_t getSerializedSize() const {
size_t getSerializedSize() const override {
//Analogous to serialize!
uint32_t size = 1; //One for count
iterator iter = this->begin();
@ -116,7 +116,7 @@ public:
}
ReturnValue_t deSerialize(const uint8_t** buffer, size_t* size,
bool bigEndian) {
SerializeIF::Endianness streamEndianness) override {
return HasReturnvaluesIF::RETURN_OK;
}

View File

@ -4,7 +4,6 @@
#include <framework/globalfunctions/matching/SerializeableMatcherIF.h>
#include <framework/serialize/SerializeAdapter.h>
template<typename T>
class RangeMatcher: public SerializeableMatcherIF<T> {
public:
@ -27,40 +26,40 @@ public:
}
}
ReturnValue_t serialize(uint8_t** buffer, size_t* size,
const size_t max_size, bool bigEndian) const {
ReturnValue_t result = SerializeAdapter<T>::serialize(&lowerBound,
buffer, size, max_size, bigEndian);
ReturnValue_t serialize(uint8_t **buffer, size_t *size, size_t maxSize,
SerializeIF::Endianness streamEndianness) const override {
ReturnValue_t result = SerializeAdapter::serialize(&lowerBound, buffer,
size, maxSize, streamEndianness);
if (result != HasReturnvaluesIF::RETURN_OK) {
return result;
}
result = SerializeAdapter<T>::serialize(&upperBound, buffer, size,
max_size, bigEndian);
result = SerializeAdapter::serialize(&upperBound, buffer, size,
maxSize, streamEndianness);
if (result != HasReturnvaluesIF::RETURN_OK) {
return result;
}
return SerializeAdapter<bool>::serialize(&inverted, buffer, size,
max_size, bigEndian);
return SerializeAdapter::serialize(&inverted, buffer, size, maxSize,
streamEndianness);
}
size_t getSerializedSize() const {
size_t getSerializedSize() const override {
return sizeof(lowerBound) + sizeof(upperBound) + sizeof(bool);
}
ReturnValue_t deSerialize(const uint8_t** buffer, size_t* size,
bool bigEndian) {
ReturnValue_t result = SerializeAdapter<T>::deSerialize(&lowerBound,
buffer, size, bigEndian);
ReturnValue_t deSerialize(const uint8_t **buffer, size_t *size,
SerializeIF::Endianness streamEndianness) override {
ReturnValue_t result = SerializeAdapter::deSerialize(&lowerBound,
buffer, size, streamEndianness);
if (result != HasReturnvaluesIF::RETURN_OK) {
return result;
}
result = SerializeAdapter<T>::deSerialize(&upperBound, buffer,
size, bigEndian);
result = SerializeAdapter::deSerialize(&upperBound, buffer, size,
streamEndianness);
if (result != HasReturnvaluesIF::RETURN_OK) {
return result;
}
return SerializeAdapter<bool>::deSerialize(&inverted, buffer,
size, bigEndian);
return SerializeAdapter::deSerialize(&inverted, buffer, size,
streamEndianness);
}
protected:
bool doMatch(T input) {

View File

@ -90,3 +90,10 @@ double timevalOperations::toDouble(const timeval timeval) {
double result = timeval.tv_sec * 1000000. + timeval.tv_usec;
return result / 1000000.;
}
timeval timevalOperations::toTimeval(const double seconds) {
timeval tval;
tval.tv_sec = seconds;
tval.tv_usec = seconds *(double) 1e6 - (tval.tv_sec *1e6);
return tval;
}

View File

@ -41,6 +41,7 @@ namespace timevalOperations {
* @return seconds
*/
double toDouble(const timeval timeval);
timeval toTimeval(const double seconds);
}
#endif /* TIMEVALOPERATIONS_H_ */

View File

@ -1,9 +1,8 @@
#include <framework/health/HealthHelper.h>
#include <framework/ipc/MessageQueueSenderIF.h>
#include <framework/serviceinterface/ServiceInterfaceStream.h>
HealthHelper::HealthHelper(HasHealthIF* owner, object_id_t objectId) :
healthTable(NULL), eventSender(NULL), objectId(objectId), parentQueue(
0), owner(owner) {
objectId(objectId), owner(owner) {
}
HealthHelper::~HealthHelper() {
@ -29,20 +28,30 @@ HasHealthIF::HealthState HealthHelper::getHealth() {
}
ReturnValue_t HealthHelper::initialize(MessageQueueId_t parentQueue) {
setParentQeueue(parentQueue);
setParentQueue(parentQueue);
return initialize();
}
void HealthHelper::setParentQeueue(MessageQueueId_t parentQueue) {
void HealthHelper::setParentQueue(MessageQueueId_t parentQueue) {
this->parentQueue = parentQueue;
}
ReturnValue_t HealthHelper::initialize() {
healthTable = objectManager->get<HealthTableIF>(objects::HEALTH_TABLE);
eventSender = objectManager->get<EventReportingProxyIF>(objectId);
if ((healthTable == NULL) || eventSender == NULL) {
return HasReturnvaluesIF::RETURN_FAILED;
if (healthTable == nullptr) {
sif::error << "HealthHelper::initialize: Health table object needs"
"to be created in factory." << std::endl;
return ObjectManagerIF::CHILD_INIT_FAILED;
}
if(eventSender == nullptr) {
sif::error << "HealthHelper::initialize: Owner has to implement "
"ReportingProxyIF." << std::endl;
return ObjectManagerIF::CHILD_INIT_FAILED;
}
ReturnValue_t result = healthTable->registerObject(objectId,
HasHealthIF::HEALTHY);
if (result != HasReturnvaluesIF::RETURN_OK) {
@ -62,22 +71,22 @@ void HealthHelper::setHealth(HasHealthIF::HealthState health) {
void HealthHelper::informParent(HasHealthIF::HealthState health,
HasHealthIF::HealthState oldHealth) {
if (parentQueue == 0) {
if (parentQueue == MessageQueueMessageIF::NO_QUEUE) {
return;
}
CommandMessage message;
HealthMessage::setHealthMessage(&message, HealthMessage::HEALTH_INFO,
CommandMessage information;
HealthMessage::setHealthMessage(&information, HealthMessage::HEALTH_INFO,
health, oldHealth);
if (MessageQueueSenderIF::sendMessage(parentQueue, &message,
owner->getCommandQueue()) != HasReturnvaluesIF::RETURN_OK) {
if (MessageQueueSenderIF::sendMessage(parentQueue, &information,
owner->getCommandQueue()) != HasReturnvaluesIF::RETURN_OK) {
sif::debug << "HealthHelper::informParent: sending health reply failed."
<< std::endl;
}
}
void HealthHelper::handleSetHealthCommand(CommandMessage* message) {
ReturnValue_t result = owner->setHealth(HealthMessage::getHealth(message));
if (message->getSender() == 0) {
void HealthHelper::handleSetHealthCommand(CommandMessage* command) {
ReturnValue_t result = owner->setHealth(HealthMessage::getHealth(command));
if (command->getSender() == MessageQueueMessageIF::NO_QUEUE) {
return;
}
CommandMessage reply;
@ -85,10 +94,10 @@ void HealthHelper::handleSetHealthCommand(CommandMessage* message) {
HealthMessage::setHealthMessage(&reply,
HealthMessage::REPLY_HEALTH_SET);
} else {
reply.setReplyRejected(result, message->getCommand());
reply.setReplyRejected(result, command->getCommand());
}
if (MessageQueueSenderIF::sendMessage(message->getSender(), &reply,
owner->getCommandQueue()) != HasReturnvaluesIF::RETURN_OK) {
if (MessageQueueSenderIF::sendMessage(command->getSender(), &reply,
owner->getCommandQueue()) != HasReturnvaluesIF::RETURN_OK) {
sif::debug << "HealthHelper::handleHealthCommand: sending health "
"reply failed." << std::endl;

View File

@ -1,11 +1,12 @@
#ifndef HEALTHHELPER_H_
#define HEALTHHELPER_H_
#ifndef FRAMEWORK_HEALTH_HEALTHHELPER_H_
#define FRAMEWORK_HEALTH_HEALTHHELPER_H_
#include <framework/events/EventManagerIF.h>
#include <framework/events/EventReportingProxyIF.h>
#include <framework/health/HasHealthIF.h>
#include <framework/health/HealthMessage.h>
#include <framework/health/HealthTableIF.h>
#include <framework/ipc/MessageQueueIF.h>
#include <framework/objectmanager/ObjectManagerIF.h>
#include <framework/returnvalues/HasReturnvaluesIF.h>
@ -39,12 +40,12 @@ public:
*
* only valid after initialize() has been called
*/
HealthTableIF *healthTable;
HealthTableIF *healthTable = nullptr;
/**
* Proxy to forward events.
*/
EventReportingProxyIF* eventSender;
EventReportingProxyIF* eventSender = nullptr;
/**
* Try to handle the message.
@ -78,7 +79,7 @@ public:
/**
* @param parentQueue the Queue id of the parent object. Set to 0 if no parent present
*/
void setParentQeueue(MessageQueueId_t parentQueue);
void setParentQueue(MessageQueueId_t parentQueue);
/**
*
@ -100,7 +101,7 @@ private:
/**
* The Queue of the parent
*/
MessageQueueId_t parentQueue;
MessageQueueId_t parentQueue = MessageQueueIF::NO_QUEUE;
/**
* The one using the healthHelper.

View File

@ -6,7 +6,7 @@
class HealthMessage {
public:
static const uint8_t MESSAGE_ID = MESSAGE_TYPE::HEALTH_COMMAND;
static const uint8_t MESSAGE_ID = messagetypes::HEALTH_COMMAND;
static const Command_t HEALTH_SET = MAKE_COMMAND_ID(1);//REPLY_COMMAND_OK/REPLY_REJECTED
static const Command_t HEALTH_ANNOUNCE = MAKE_COMMAND_ID(3); //NO REPLY!
static const Command_t HEALTH_INFO = MAKE_COMMAND_ID(5);

View File

@ -26,7 +26,7 @@ ReturnValue_t HealthTable::registerObject(object_id_t object,
void HealthTable::setHealth(object_id_t object,
HasHealthIF::HealthState newState) {
mutex->lockMutex(MutexIF::NO_TIMEOUT);
mutex->lockMutex(MutexIF::BLOCKING);
HealthMap::iterator iter = healthMap.find(object);
if (iter != healthMap.end()) {
iter->second = newState;
@ -36,7 +36,7 @@ void HealthTable::setHealth(object_id_t object,
HasHealthIF::HealthState HealthTable::getHealth(object_id_t object) {
HasHealthIF::HealthState state = HasHealthIF::HEALTHY;
mutex->lockMutex(MutexIF::NO_TIMEOUT);
mutex->lockMutex(MutexIF::BLOCKING);
HealthMap::iterator iter = healthMap.find(object);
if (iter != healthMap.end()) {
state = iter->second;
@ -46,7 +46,7 @@ HasHealthIF::HealthState HealthTable::getHealth(object_id_t object) {
}
uint32_t HealthTable::getPrintSize() {
mutex->lockMutex(MutexIF::NO_TIMEOUT);
mutex->lockMutex(MutexIF::BLOCKING);
uint32_t size = healthMap.size() * 5 + 2;
mutex->unlockMutex();
return size;
@ -54,7 +54,7 @@ uint32_t HealthTable::getPrintSize() {
bool HealthTable::hasHealth(object_id_t object) {
bool exits = false;
mutex->lockMutex(MutexIF::NO_TIMEOUT);
mutex->lockMutex(MutexIF::BLOCKING);
HealthMap::iterator iter = healthMap.find(object);
if (iter != healthMap.end()) {
exits = true;
@ -63,21 +63,21 @@ bool HealthTable::hasHealth(object_id_t object) {
return exits;
}
void HealthTable::printAll(uint8_t* pointer, uint32_t maxSize) {
mutex->lockMutex(MutexIF::NO_TIMEOUT);
void HealthTable::printAll(uint8_t* pointer, size_t maxSize) {
mutex->lockMutex(MutexIF::BLOCKING);
size_t size = 0;
uint16_t count = healthMap.size();
ReturnValue_t result = SerializeAdapter<uint16_t>::serialize(&count,
&pointer, &size, maxSize, true);
ReturnValue_t result = SerializeAdapter::serialize(&count,
&pointer, &size, maxSize, SerializeIF::Endianness::BIG);
HealthMap::iterator iter;
for (iter = healthMap.begin();
iter != healthMap.end() && result == HasReturnvaluesIF::RETURN_OK;
++iter) {
result = SerializeAdapter<object_id_t>::serialize(&iter->first,
&pointer, &size, maxSize, true);
result = SerializeAdapter::serialize(&iter->first,
&pointer, &size, maxSize, SerializeIF::Endianness::BIG);
uint8_t health = iter->second;
result = SerializeAdapter<uint8_t>::serialize(&health, &pointer, &size,
maxSize, true);
result = SerializeAdapter::serialize(&health, &pointer, &size,
maxSize, SerializeIF::Endianness::BIG);
}
mutex->unlockMutex();
}
@ -85,7 +85,7 @@ void HealthTable::printAll(uint8_t* pointer, uint32_t maxSize) {
ReturnValue_t HealthTable::iterate(
std::pair<object_id_t, HasHealthIF::HealthState> *value, bool reset) {
ReturnValue_t result = HasReturnvaluesIF::RETURN_OK;
mutex->lockMutex(MutexIF::NO_TIMEOUT);
mutex->lockMutex(MutexIF::BLOCKING);
if (reset) {
mapIterator = healthMap.begin();
}

View File

@ -1,5 +1,5 @@
#ifndef HEALTHTABLE_H_
#define HEALTHTABLE_H_
#ifndef FRAMEWORK_HEALTH_HEALTHTABLE_H_
#define FRAMEWORK_HEALTH_HEALTHTABLE_H_
#include <framework/health/HealthTableIF.h>
#include <framework/objectmanager/SystemObject.h>
@ -21,7 +21,7 @@ public:
virtual HasHealthIF::HealthState getHealth(object_id_t);
virtual uint32_t getPrintSize();
virtual void printAll(uint8_t *pointer, uint32_t maxSize);
virtual void printAll(uint8_t *pointer, size_t maxSize);
protected:
MutexIF* mutex;

View File

@ -1,5 +1,5 @@
#ifndef HEALTHTABLEIF_H_
#define HEALTHTABLEIF_H_
#ifndef FRAMEWORK_HEALTH_HEALTHTABLEIF_H_
#define FRAMEWORK_HEALTH_HEALTHTABLEIF_H_
#include <framework/health/ManagesHealthIF.h>
#include <framework/objectmanager/ObjectManagerIF.h>
@ -8,6 +8,8 @@
class HealthTableIF: public ManagesHealthIF {
// TODO: This is in the mission folder and not in the framework folder.
// delete it?
friend class HealthCommandingService;
public:
virtual ~HealthTableIF() {
@ -17,10 +19,10 @@ public:
HasHealthIF::HealthState initilialState = HasHealthIF::HEALTHY) = 0;
virtual uint32_t getPrintSize() = 0;
virtual void printAll(uint8_t *pointer, uint32_t maxSize) = 0;
virtual void printAll(uint8_t *pointer, size_t maxSize) = 0;
protected:
virtual ReturnValue_t iterate(std::pair<object_id_t,HasHealthIF::HealthState> *value, bool reset = false) = 0;
};
#endif /* HEALTHTABLEIF_H_ */
#endif /* FRAMEWORK_HEALTH_HEALTHTABLEIF_H_ */

View File

@ -0,0 +1,11 @@
#ifndef FRAMEWORK_HOUSEKEEPING_ACCEPTSHKPACKETSIF_H_
#define FRAMEWORK_HOUSEKEEPING_ACCEPTSHKPACKETSIF_H_
#include <framework/ipc/MessageQueueMessageIF.h>
class AcceptsHkPacketsIF {
public:
virtual~ AcceptsHkPacketsIF() {};
virtual MessageQueueId_t getHkQueue() const = 0;
};
#endif /* FRAMEWORK_HOUSEKEEPING_ACCEPTSHKPACKETSIF_H_ */

View File

@ -1,29 +0,0 @@
#ifndef FRAMEWORK_DATAPOOL_HASHKPOOLPARAMETERSIF_H_
#define FRAMEWORK_DATAPOOL_HASHKPOOLPARAMETERSIF_H_
#include <framework/datapool/PoolEntryIF.h>
#include <framework/ipc/MessageQueueSenderIF.h>
#include <map>
class HousekeepingManager;
/**
* @brief Type definition for local pool entries.
*/
using lp_id_t = uint32_t;
using LocalDataPoolMap = std::map<lp_id_t, PoolEntryIF*>;
using LocalDataPoolMapIter = LocalDataPoolMap::iterator;
/**
* @brief
*/
class HasHkPoolParametersIF {
public:
virtual~ HasHkPoolParametersIF() {};
virtual MessageQueueId_t getCommandQueue() const = 0;
virtual ReturnValue_t initializeHousekeepingPoolEntries(
LocalDataPoolMap& localDataPoolMap) = 0;
virtual float setMinimalHkSamplingFrequency() = 0;
virtual HousekeepingManager* getHkManagerHandle() = 0;
};
#endif /* FRAMEWORK_DATAPOOL_HASHKPOOLPARAMETERSIF_H_ */

View File

@ -1,50 +0,0 @@
#include <framework/housekeeping/HousekeepingManager.h>
#include <framework/returnvalues/HasReturnvaluesIF.h>
#include <framework/ipc/MutexFactory.h>
#include <framework/ipc/MutexHelper.h>
HousekeepingManager::HousekeepingManager(HasHkPoolParametersIF* owner) {
//todo :: nullptr check owner.
if(owner == nullptr) {
sif::error << "HkManager: Invalid supplied owner!" << std::endl;
std::exit(0);
}
this->owner = owner;
mutex = MutexFactory::instance()->createMutex();
owner->setMinimalHkSamplingFrequency();
}
HousekeepingManager::~HousekeepingManager() {}
ReturnValue_t HousekeepingManager::initializeHousekeepingPoolEntriesOnce() {
if(not mapInitialized) {
ReturnValue_t result = owner->initializeHousekeepingPoolEntries(localDpMap);
if(result == HasReturnvaluesIF::RETURN_OK) {
mapInitialized = true;
}
return result;
}
sif::warning << "hk manager says no" << std::endl;
return HasReturnvaluesIF::RETURN_OK;
}
ReturnValue_t HousekeepingManager::handleHousekeepingMessage(
CommandMessage *message) {
return HasReturnvaluesIF::RETURN_OK;
}
MutexIF* HousekeepingManager::getMutexHandle() {
return mutex;
}
void HousekeepingManager::setMinimalSamplingFrequency(float frequencySeconds) {
this->samplingFrequency = frequencySeconds;
}
void HousekeepingManager::generateHousekeepingPacket(DataSetIF *dataSet) {
}
void HousekeepingManager::setHkPacketQueue(MessageQueueIF *msgQueue) {
this->hkPacketQueue = msgQueue;
}

View File

@ -1,95 +0,0 @@
#ifndef FRAMEWORK_HK_HOUSEKEEPINGHELPER_H_
#define FRAMEWORK_HK_HOUSEKEEPINGHELPER_H_
#include <framework/datapool/DataSetIF.h>
#include <framework/objectmanager/SystemObjectIF.h>
#include <framework/housekeeping/HasHkPoolParametersIF.h>
#include <framework/ipc/MutexIF.h>
#include <framework/datapool/PoolEntry.h>
#include <framework/ipc/CommandMessage.h>
#include <framework/ipc/MessageQueueIF.h>
#include <framework/ipc/MutexHelper.h>
#include <map>
class HousekeepingManager {
public:
static constexpr float MINIMAL_SAMPLING_FREQUENCY = 0.2;
HousekeepingManager(HasHkPoolParametersIF* owner);
virtual~ HousekeepingManager();
MutexIF* getMutexHandle();
// propably will just call respective local data set functions.
void generateHousekeepingPacket(DataSetIF* dataSet);
ReturnValue_t handleHousekeepingMessage(CommandMessage* message);
/**
* Read a variable by supplying its local pool ID and assign the pool
* entry to the supplied PoolEntry pointer. The type of the pool entry
* is deduced automatically. This call is not thread-safe!
* @tparam T Type of the pool entry
* @param localPoolId Pool ID of the variable to read
* @param poolVar [out] Corresponding pool entry will be assigned to the
* supplied pointer.
* @return
*/
template <class T>
ReturnValue_t fetchPoolEntry(lp_id_t localPoolId, PoolEntry<T> *poolEntry);
void setMinimalSamplingFrequency(float frequencySeconds);
/**
* This function is used to fill the local data pool map with pool
* entries. The default implementation is empty.
* @param localDataPoolMap
* @return
*/
ReturnValue_t initializeHousekeepingPoolEntriesOnce();
void setHkPacketQueue(MessageQueueIF* msgQueue);
private:
//! this depends on the PST frequency.. maybe it would be better to just
//! set this manually with a global configuration value which is also
//! passed to the PST. Or force setting this in device handler.
float samplingFrequency = MINIMAL_SAMPLING_FREQUENCY;
//! This is the map holding the actual data. Should only be initialized
//! once !
bool mapInitialized = false;
LocalDataPoolMap localDpMap;
//! Every housekeeping data manager has a mutex to protect access
//! to it's data pool.
MutexIF * mutex = nullptr;
//! The class which actually owns the manager (and its datapool).
HasHkPoolParametersIF* owner = nullptr;
//! Used for replies.
//! (maybe we dont need this, the sender can be retrieved from command
//! message..)
MessageQueueIF* hkReplyQueue = nullptr;
//! Used for HK packets, which are generated without requests.
MessageQueueIF* hkPacketQueue = nullptr;
};
template<class T> inline
ReturnValue_t HousekeepingManager::fetchPoolEntry(lp_id_t localPoolId,
PoolEntry<T> *poolEntry) {
auto poolIter = localDpMap.find(localPoolId);
if (poolIter == localDpMap.end()) {
// todo: special returnvalue.
return HasReturnvaluesIF::RETURN_FAILED;
}
poolEntry = dynamic_cast< PoolEntry<T>* >(poolIter->second);
if(poolEntry == nullptr) {
// todo: special returnvalue.
return HasReturnvaluesIF::RETURN_FAILED;
}
return HasReturnvaluesIF::RETURN_OK;
}
#endif /* FRAMEWORK_HK_HOUSEKEEPINGHELPER_H_ */

View File

@ -1,10 +1,48 @@
#include <framework/housekeeping/HousekeepingMessage.h>
#include <cstring>
void HousekeepingMessage::setAddHkReportStructMessage(CommandMessage *message,
set_t setId, store_address_t packet) {
message->setCommand(ADD_HK_REPORT_STRUCT);
message->setParameter(setId);
message->setParameter2(packet.raw);
HousekeepingMessage::~HousekeepingMessage() {}
void HousekeepingMessage::setHkReportMessage(CommandMessage* message, sid_t sid,
store_address_t storeId) {
message->setCommand(HK_REPORT);
message->setMessageSize(HK_MESSAGE_SIZE);
setSid(message, sid);
setParameter(message, storeId.raw);
}
//void Housekeeping
void HousekeepingMessage::setHkDiagnosticsMessage(CommandMessage* message,
sid_t sid, store_address_t storeId) {
message->setCommand(DIAGNOSTICS_REPORT);
message->setMessageSize(HK_MESSAGE_SIZE);
setSid(message, sid);
setParameter(message, storeId.raw);
}
sid_t HousekeepingMessage::getHkReportMessage(const CommandMessage *message,
store_address_t *storeIdToSet) {
if(storeIdToSet != nullptr) {
*storeIdToSet = getParameter(message);
}
return getSid(message);
}
sid_t HousekeepingMessage::getSid(const CommandMessage* message) {
sid_t sid;
std::memcpy(&sid.raw, message->getData(), sizeof(sid.raw));
return sid;
}
void HousekeepingMessage::setSid(CommandMessage *message, sid_t sid) {
std::memcpy(message->getData(), &sid.raw, sizeof(sid.raw));
}
void HousekeepingMessage::setParameter(CommandMessage *message,
uint32_t parameter) {
message->setParameter3(parameter);
}
uint32_t HousekeepingMessage::getParameter(const CommandMessage *message) {
return message->getParameter3();
}

Some files were not shown because too many files have changed in this diff Show More