Merge pull request 'applied clang script' (#534) from mueller/apply-clang-script into development

Reviewed-on: fsfw/fsfw#534
This commit is contained in:
Robin Müller 2022-02-02 10:38:07 +01:00
commit bf5a11cbd3
809 changed files with 52010 additions and 56052 deletions

View File

@ -1,8 +1,8 @@
#include "fsfw_hal/common/gpio/GpioCookie.h" #include "fsfw_hal/common/gpio/GpioCookie.h"
#include "fsfw/serviceinterface/ServiceInterface.h" #include "fsfw/serviceinterface/ServiceInterface.h"
GpioCookie::GpioCookie() { GpioCookie::GpioCookie() {}
}
ReturnValue_t GpioCookie::addGpio(gpioId_t gpioId, GpioBase* gpioConfig) { ReturnValue_t GpioCookie::addGpio(gpioId_t gpioId, GpioBase* gpioConfig) {
if (gpioConfig == nullptr) { if (gpioConfig == nullptr) {
@ -19,8 +19,8 @@ ReturnValue_t GpioCookie::addGpio(gpioId_t gpioId, GpioBase* gpioConfig) {
if (statusPair.second == false) { if (statusPair.second == false) {
#if FSFW_VERBOSE_LEVEL >= 1 #if FSFW_VERBOSE_LEVEL >= 1
#if FSFW_CPP_OSTREAM_ENABLED == 1 #if FSFW_CPP_OSTREAM_ENABLED == 1
sif::warning << "GpioCookie::addGpio: Failed to add GPIO " << gpioId << sif::warning << "GpioCookie::addGpio: Failed to add GPIO " << gpioId << " to GPIO map"
" to GPIO map" << std::endl; << std::endl;
#else #else
sif::printWarning("GpioCookie::addGpio: Failed to add GPIO %d to GPIO map\n", gpioId); sif::printWarning("GpioCookie::addGpio: Failed to add GPIO %d to GPIO map\n", gpioId);
#endif #endif
@ -39,9 +39,7 @@ ReturnValue_t GpioCookie::addGpio(gpioId_t gpioId, GpioBase* gpioConfig) {
return HasReturnvaluesIF::RETURN_FAILED; return HasReturnvaluesIF::RETURN_FAILED;
} }
GpioMap GpioCookie::getGpioMap() const { GpioMap GpioCookie::getGpioMap() const { return gpioMap; }
return gpioMap;
}
GpioCookie::~GpioCookie() { GpioCookie::~GpioCookie() {
for (auto& config : gpioMap) { for (auto& config : gpioMap) {

View File

@ -1,12 +1,12 @@
#ifndef COMMON_GPIO_GPIOCOOKIE_H_ #ifndef COMMON_GPIO_GPIOCOOKIE_H_
#define COMMON_GPIO_GPIOCOOKIE_H_ #define COMMON_GPIO_GPIOCOOKIE_H_
#include "GpioIF.h"
#include "gpioDefinitions.h"
#include <fsfw/devicehandlers/CookieIF.h> #include <fsfw/devicehandlers/CookieIF.h>
#include <fsfw/returnvalues/HasReturnvaluesIF.h> #include <fsfw/returnvalues/HasReturnvaluesIF.h>
#include "GpioIF.h"
#include "gpioDefinitions.h"
/** /**
* @brief Cookie for the GpioIF. Allows the GpioIF to determine which * @brief Cookie for the GpioIF. Allows the GpioIF to determine which
* GPIOs to initialize and whether they should be configured as in- or * GPIOs to initialize and whether they should be configured as in- or
@ -19,7 +19,6 @@
*/ */
class GpioCookie : public CookieIF { class GpioCookie : public CookieIF {
public: public:
GpioCookie(); GpioCookie();
virtual ~GpioCookie(); virtual ~GpioCookie();

View File

@ -1,9 +1,10 @@
#ifndef COMMON_GPIO_GPIOIF_H_ #ifndef COMMON_GPIO_GPIOIF_H_
#define COMMON_GPIO_GPIOIF_H_ #define COMMON_GPIO_GPIOIF_H_
#include "gpioDefinitions.h"
#include <fsfw/returnvalues/HasReturnvaluesIF.h>
#include <fsfw/devicehandlers/CookieIF.h> #include <fsfw/devicehandlers/CookieIF.h>
#include <fsfw/returnvalues/HasReturnvaluesIF.h>
#include "gpioDefinitions.h"
class GpioCookie; class GpioCookie;
@ -14,7 +15,6 @@ class GpioCookie;
*/ */
class GpioIF : public HasReturnvaluesIF { class GpioIF : public HasReturnvaluesIF {
public: public:
virtual ~GpioIF(){}; virtual ~GpioIF(){};
/** /**

View File

@ -1,29 +1,19 @@
#ifndef COMMON_GPIO_GPIODEFINITIONS_H_ #ifndef COMMON_GPIO_GPIODEFINITIONS_H_
#define COMMON_GPIO_GPIODEFINITIONS_H_ #define COMMON_GPIO_GPIODEFINITIONS_H_
#include <map>
#include <string> #include <string>
#include <unordered_map> #include <unordered_map>
#include <map>
using gpioId_t = uint16_t; using gpioId_t = uint16_t;
namespace gpio { namespace gpio {
enum Levels: uint8_t { enum Levels : uint8_t { LOW = 0, HIGH = 1, NONE = 99 };
LOW = 0,
HIGH = 1,
NONE = 99
};
enum Direction: uint8_t { enum Direction : uint8_t { IN = 0, OUT = 1 };
IN = 0,
OUT = 1
};
enum GpioOperation { enum GpioOperation { READ, WRITE };
READ,
WRITE
};
enum class GpioTypes { enum class GpioTypes {
NONE, NONE,
@ -38,7 +28,7 @@ static constexpr gpioId_t NO_GPIO = -1;
using gpio_cb_t = void (*)(gpioId_t gpioId, gpio::GpioOperation gpioOp, gpio::Levels value, using gpio_cb_t = void (*)(gpioId_t gpioId, gpio::GpioOperation gpioOp, gpio::Levels value,
void* args); void* args);
} } // namespace gpio
/** /**
* @brief Struct containing information about the GPIO to use. This is * @brief Struct containing information about the GPIO to use. This is
@ -56,12 +46,11 @@ using gpio_cb_t = void (*) (gpioId_t gpioId, gpio::GpioOperation gpioOp, gpio::L
*/ */
class GpioBase { class GpioBase {
public: public:
GpioBase() = default; GpioBase() = default;
GpioBase(gpio::GpioTypes gpioType, std::string consumer, gpio::Direction direction, GpioBase(gpio::GpioTypes gpioType, std::string consumer, gpio::Direction direction,
gpio::Levels initValue): gpio::Levels initValue)
gpioType(gpioType), consumer(consumer),direction(direction), initValue(initValue) {} : gpioType(gpioType), consumer(consumer), direction(direction), initValue(initValue) {}
virtual ~GpioBase(){}; virtual ~GpioBase(){};
@ -75,14 +64,13 @@ public:
class GpiodRegularBase : public GpioBase { class GpiodRegularBase : public GpioBase {
public: public:
GpiodRegularBase(gpio::GpioTypes gpioType, std::string consumer, gpio::Direction direction, GpiodRegularBase(gpio::GpioTypes gpioType, std::string consumer, gpio::Direction direction,
gpio::Levels initValue, int lineNum): gpio::Levels initValue, int lineNum)
GpioBase(gpioType, consumer, direction, initValue), lineNum(lineNum) { : GpioBase(gpioType, consumer, direction, initValue), lineNum(lineNum) {}
}
// line number will be configured at a later point for the open by line name configuration // line number will be configured at a later point for the open by line name configuration
GpiodRegularBase(gpio::GpioTypes gpioType, std::string consumer, gpio::Direction direction, GpiodRegularBase(gpio::GpioTypes gpioType, std::string consumer, gpio::Direction direction,
gpio::Levels initValue): GpioBase(gpioType, consumer, direction, initValue) { gpio::Levels initValue)
} : GpioBase(gpioType, consumer, direction, initValue) {}
int lineNum = 0; int lineNum = 0;
struct gpiod_line* lineHandle = nullptr; struct gpiod_line* lineHandle = nullptr;
@ -90,23 +78,20 @@ public:
class GpiodRegularByChip : public GpiodRegularBase { class GpiodRegularByChip : public GpiodRegularBase {
public: public:
GpiodRegularByChip() : GpiodRegularByChip()
GpiodRegularBase(gpio::GpioTypes::GPIO_REGULAR_BY_CHIP, : GpiodRegularBase(gpio::GpioTypes::GPIO_REGULAR_BY_CHIP, std::string(), gpio::Direction::IN,
std::string(), gpio::Direction::IN, gpio::LOW, 0) { gpio::LOW, 0) {}
}
GpiodRegularByChip(std::string chipname_, int lineNum_, std::string consumer_, GpiodRegularByChip(std::string chipname_, int lineNum_, std::string consumer_,
gpio::Direction direction_, gpio::Levels initValue_) : gpio::Direction direction_, gpio::Levels initValue_)
GpiodRegularBase(gpio::GpioTypes::GPIO_REGULAR_BY_CHIP, : GpiodRegularBase(gpio::GpioTypes::GPIO_REGULAR_BY_CHIP, consumer_, direction_, initValue_,
consumer_, direction_, initValue_, lineNum_), lineNum_),
chipname(chipname_){ chipname(chipname_) {}
}
GpiodRegularByChip(std::string chipname_, int lineNum_, std::string consumer_) : GpiodRegularByChip(std::string chipname_, int lineNum_, std::string consumer_)
GpiodRegularBase(gpio::GpioTypes::GPIO_REGULAR_BY_CHIP, consumer_, : GpiodRegularBase(gpio::GpioTypes::GPIO_REGULAR_BY_CHIP, consumer_, gpio::Direction::IN,
gpio::Direction::IN, gpio::LOW, lineNum_), gpio::LOW, lineNum_),
chipname(chipname_) { chipname(chipname_) {}
}
std::string chipname; std::string chipname;
}; };
@ -114,17 +99,15 @@ public:
class GpiodRegularByLabel : public GpiodRegularBase { class GpiodRegularByLabel : public GpiodRegularBase {
public: public:
GpiodRegularByLabel(std::string label_, int lineNum_, std::string consumer_, GpiodRegularByLabel(std::string label_, int lineNum_, std::string consumer_,
gpio::Direction direction_, gpio::Levels initValue_) : gpio::Direction direction_, gpio::Levels initValue_)
GpiodRegularBase(gpio::GpioTypes::GPIO_REGULAR_BY_LABEL, consumer_, : GpiodRegularBase(gpio::GpioTypes::GPIO_REGULAR_BY_LABEL, consumer_, direction_, initValue_,
direction_, initValue_, lineNum_), lineNum_),
label(label_) { label(label_) {}
}
GpiodRegularByLabel(std::string label_, int lineNum_, std::string consumer_) : GpiodRegularByLabel(std::string label_, int lineNum_, std::string consumer_)
GpiodRegularBase(gpio::GpioTypes::GPIO_REGULAR_BY_LABEL, consumer_, : GpiodRegularBase(gpio::GpioTypes::GPIO_REGULAR_BY_LABEL, consumer_, gpio::Direction::IN,
gpio::Direction::IN, gpio::LOW, lineNum_), gpio::LOW, lineNum_),
label(label_) { label(label_) {}
}
std::string label; std::string label;
}; };
@ -137,15 +120,15 @@ public:
class GpiodRegularByLineName : public GpiodRegularBase { class GpiodRegularByLineName : public GpiodRegularBase {
public: public:
GpiodRegularByLineName(std::string lineName_, std::string consumer_, gpio::Direction direction_, GpiodRegularByLineName(std::string lineName_, std::string consumer_, gpio::Direction direction_,
gpio::Levels initValue_) : gpio::Levels initValue_)
GpiodRegularBase(gpio::GpioTypes::GPIO_REGULAR_BY_LINE_NAME, consumer_, direction_, : GpiodRegularBase(gpio::GpioTypes::GPIO_REGULAR_BY_LINE_NAME, consumer_, direction_,
initValue_), lineName(lineName_) { initValue_),
} lineName(lineName_) {}
GpiodRegularByLineName(std::string lineName_, std::string consumer_) : GpiodRegularByLineName(std::string lineName_, std::string consumer_)
GpiodRegularBase(gpio::GpioTypes::GPIO_REGULAR_BY_LINE_NAME, consumer_, : GpiodRegularBase(gpio::GpioTypes::GPIO_REGULAR_BY_LINE_NAME, consumer_, gpio::Direction::IN,
gpio::Direction::IN, gpio::LOW), lineName(lineName_) { gpio::LOW),
} lineName(lineName_) {}
std::string lineName; std::string lineName;
}; };
@ -153,15 +136,15 @@ public:
class GpioCallback : public GpioBase { class GpioCallback : public GpioBase {
public: public:
GpioCallback(std::string consumer, gpio::Direction direction_, gpio::Levels initValue_, GpioCallback(std::string consumer, gpio::Direction direction_, gpio::Levels initValue_,
gpio::gpio_cb_t callback, void* callbackArgs): gpio::gpio_cb_t callback, void* callbackArgs)
GpioBase(gpio::GpioTypes::CALLBACK, consumer, direction_, initValue_), : GpioBase(gpio::GpioTypes::CALLBACK, consumer, direction_, initValue_),
callback(callback), callbackArgs(callbackArgs) {} callback(callback),
callbackArgs(callbackArgs) {}
gpio::gpio_cb_t callback = nullptr; gpio::gpio_cb_t callback = nullptr;
void* callbackArgs = nullptr; void* callbackArgs = nullptr;
}; };
using GpioMap = std::map<gpioId_t, GpioBase*>; using GpioMap = std::map<gpioId_t, GpioBase*>;
using GpioUnorderedMap = std::unordered_map<gpioId_t, GpioBase*>; using GpioUnorderedMap = std::unordered_map<gpioId_t, GpioBase*>;
using GpioMapIter = GpioMap::iterator; using GpioMapIter = GpioMap::iterator;

View File

@ -5,12 +5,7 @@
namespace spi { namespace spi {
enum SpiModes: uint8_t { enum SpiModes : uint8_t { MODE_0, MODE_1, MODE_2, MODE_3 };
MODE_0,
MODE_1,
MODE_2,
MODE_3
};
} }

View File

@ -1,13 +1,14 @@
#include "GyroL3GD20Handler.h" #include "GyroL3GD20Handler.h"
#include "fsfw/datapool/PoolReadGuard.h"
#include <cmath> #include <cmath>
#include "fsfw/datapool/PoolReadGuard.h"
GyroHandlerL3GD20H::GyroHandlerL3GD20H(object_id_t objectId, object_id_t deviceCommunication, GyroHandlerL3GD20H::GyroHandlerL3GD20H(object_id_t objectId, object_id_t deviceCommunication,
CookieIF *comCookie, uint32_t transitionDelayMs): CookieIF *comCookie, uint32_t transitionDelayMs)
DeviceHandlerBase(objectId, deviceCommunication, comCookie), : DeviceHandlerBase(objectId, deviceCommunication, comCookie),
transitionDelayMs(transitionDelayMs), dataset(this) { transitionDelayMs(transitionDelayMs),
dataset(this) {
#if FSFW_HAL_L3GD20_GYRO_DEBUG == 1 #if FSFW_HAL_L3GD20_GYRO_DEBUG == 1
debugDivider = new PeriodicOperationDivider(3); debugDivider = new PeriodicOperationDivider(3);
#endif #endif
@ -32,8 +33,7 @@ void GyroHandlerL3GD20H::doStartUp() {
internalState = InternalState::NORMAL; internalState = InternalState::NORMAL;
if (goNormalModeImmediately) { if (goNormalModeImmediately) {
setMode(MODE_NORMAL); setMode(MODE_NORMAL);
} } else {
else {
setMode(_MODE_TO_ON); setMode(_MODE_TO_ON);
} }
commandExecuted = false; commandExecuted = false;
@ -41,9 +41,7 @@ void GyroHandlerL3GD20H::doStartUp() {
} }
} }
void GyroHandlerL3GD20H::doShutDown() { void GyroHandlerL3GD20H::doShutDown() { setMode(_MODE_POWER_DOWN); }
setMode(_MODE_POWER_DOWN);
}
ReturnValue_t GyroHandlerL3GD20H::buildTransitionDeviceCommand(DeviceCommandId_t *id) { ReturnValue_t GyroHandlerL3GD20H::buildTransitionDeviceCommand(DeviceCommandId_t *id) {
switch (internalState) { switch (internalState) {
@ -69,9 +67,11 @@ ReturnValue_t GyroHandlerL3GD20H::buildTransitionDeviceCommand(DeviceCommandId_t
#if FSFW_CPP_OSTREAM_ENABLED == 1 #if FSFW_CPP_OSTREAM_ENABLED == 1
/* Might be a configuration error. */ /* Might be a configuration error. */
sif::warning << "GyroL3GD20Handler::buildTransitionDeviceCommand: " sif::warning << "GyroL3GD20Handler::buildTransitionDeviceCommand: "
"Unknown internal state!" << std::endl; "Unknown internal state!"
<< std::endl;
#else #else
sif::printDebug("GyroL3GD20Handler::buildTransitionDeviceCommand: " sif::printDebug(
"GyroL3GD20Handler::buildTransitionDeviceCommand: "
"Unknown internal state!\n"); "Unknown internal state!\n");
#endif #endif
return HasReturnvaluesIF::RETURN_OK; return HasReturnvaluesIF::RETURN_OK;
@ -84,8 +84,8 @@ ReturnValue_t GyroHandlerL3GD20H::buildNormalDeviceCommand(DeviceCommandId_t *id
return buildCommandFromCommand(*id, nullptr, 0); return buildCommandFromCommand(*id, nullptr, 0);
} }
ReturnValue_t GyroHandlerL3GD20H::buildCommandFromCommand( ReturnValue_t GyroHandlerL3GD20H::buildCommandFromCommand(DeviceCommandId_t deviceCommand,
DeviceCommandId_t deviceCommand, const uint8_t *commandData, const uint8_t *commandData,
size_t commandDataLen) { size_t commandDataLen) {
switch (deviceCommand) { switch (deviceCommand) {
case (L3GD20H::READ_REGS): { case (L3GD20H::READ_REGS): {
@ -112,11 +112,9 @@ ReturnValue_t GyroHandlerL3GD20H::buildCommandFromCommand(
if (not fsH and not fsL) { if (not fsH and not fsL) {
sensitivity = L3GD20H::SENSITIVITY_00; sensitivity = L3GD20H::SENSITIVITY_00;
} } else if (not fsH and fsL) {
else if(not fsH and fsL) {
sensitivity = L3GD20H::SENSITIVITY_01; sensitivity = L3GD20H::SENSITIVITY_01;
} } else {
else {
sensitivity = L3GD20H::SENSITIVITY_11; sensitivity = L3GD20H::SENSITIVITY_11;
} }
@ -131,8 +129,7 @@ ReturnValue_t GyroHandlerL3GD20H::buildCommandFromCommand(
break; break;
} }
case (L3GD20H::READ_CTRL_REGS): { case (L3GD20H::READ_CTRL_REGS): {
commandBuffer[0] = L3GD20H::READ_START | L3GD20H::AUTO_INCREMENT_MASK | commandBuffer[0] = L3GD20H::READ_START | L3GD20H::AUTO_INCREMENT_MASK | L3GD20H::READ_MASK;
L3GD20H::READ_MASK;
std::memset(commandBuffer + 1, 0, 5); std::memset(commandBuffer + 1, 0, 5);
rawPacket = commandBuffer; rawPacket = commandBuffer;
@ -167,8 +164,7 @@ ReturnValue_t GyroHandlerL3GD20H::interpretDeviceReply(DeviceCommandId_t id,
packet[3] == ctrlReg3Value and packet[4] == ctrlReg4Value and packet[3] == ctrlReg3Value and packet[4] == ctrlReg4Value and
packet[5] == ctrlReg5Value) { packet[5] == ctrlReg5Value) {
commandExecuted = true; commandExecuted = true;
} } else {
else {
// Attempt reconfiguration // Attempt reconfiguration
internalState = InternalState::CONFIGURE; internalState = InternalState::CONFIGURE;
return DeviceHandlerIF::DEVICE_REPLY_INVALID; return DeviceHandlerIF::DEVICE_REPLY_INVALID;
@ -180,8 +176,7 @@ ReturnValue_t GyroHandlerL3GD20H::interpretDeviceReply(DeviceCommandId_t id,
packet[3] != ctrlReg3Value and packet[4] != ctrlReg4Value and packet[3] != ctrlReg3Value and packet[4] != ctrlReg4Value and
packet[5] != ctrlReg5Value) { packet[5] != ctrlReg5Value) {
return DeviceHandlerIF::DEVICE_REPLY_INVALID; return DeviceHandlerIF::DEVICE_REPLY_INVALID;
} } else {
else {
if (internalState == InternalState::CHECK_REGS) { if (internalState == InternalState::CHECK_REGS) {
commandExecuted = true; commandExecuted = true;
} }
@ -220,24 +215,21 @@ ReturnValue_t GyroHandlerL3GD20H::interpretDeviceReply(DeviceCommandId_t id,
if (std::abs(angVelocX) < this->absLimitX) { if (std::abs(angVelocX) < this->absLimitX) {
dataset.angVelocX = angVelocX; dataset.angVelocX = angVelocX;
dataset.angVelocX.setValid(true); dataset.angVelocX.setValid(true);
} } else {
else {
dataset.angVelocX.setValid(false); dataset.angVelocX.setValid(false);
} }
if (std::abs(angVelocY) < this->absLimitY) { if (std::abs(angVelocY) < this->absLimitY) {
dataset.angVelocY = angVelocY; dataset.angVelocY = angVelocY;
dataset.angVelocY.setValid(true); dataset.angVelocY.setValid(true);
} } else {
else {
dataset.angVelocY.setValid(false); dataset.angVelocY.setValid(false);
} }
if (std::abs(angVelocZ) < this->absLimitZ) { if (std::abs(angVelocZ) < this->absLimitZ) {
dataset.angVelocZ = angVelocZ; dataset.angVelocZ = angVelocZ;
dataset.angVelocZ.setValid(true); dataset.angVelocZ.setValid(true);
} } else {
else {
dataset.angVelocZ.setValid(false); dataset.angVelocZ.setValid(false);
} }
@ -252,17 +244,14 @@ ReturnValue_t GyroHandlerL3GD20H::interpretDeviceReply(DeviceCommandId_t id,
return result; return result;
} }
uint32_t GyroHandlerL3GD20H::getTransitionDelayMs(Mode_t from, Mode_t to) { uint32_t GyroHandlerL3GD20H::getTransitionDelayMs(Mode_t from, Mode_t to) {
return this->transitionDelayMs; return this->transitionDelayMs;
} }
void GyroHandlerL3GD20H::setToGoToNormalMode(bool enable) { void GyroHandlerL3GD20H::setToGoToNormalMode(bool enable) { this->goNormalModeImmediately = true; }
this->goNormalModeImmediately = true;
}
ReturnValue_t GyroHandlerL3GD20H::initializeLocalDataPool( ReturnValue_t GyroHandlerL3GD20H::initializeLocalDataPool(localpool::DataPool &localDataPoolMap,
localpool::DataPool &localDataPoolMap, LocalDataPoolManager &poolManager) { LocalDataPoolManager &poolManager) {
localDataPoolMap.emplace(L3GD20H::ANG_VELOC_X, new PoolEntry<float>({0.0})); localDataPoolMap.emplace(L3GD20H::ANG_VELOC_X, new PoolEntry<float>({0.0}));
localDataPoolMap.emplace(L3GD20H::ANG_VELOC_Y, new PoolEntry<float>({0.0})); localDataPoolMap.emplace(L3GD20H::ANG_VELOC_Y, new PoolEntry<float>({0.0}));
localDataPoolMap.emplace(L3GD20H::ANG_VELOC_Z, new PoolEntry<float>({0.0})); localDataPoolMap.emplace(L3GD20H::ANG_VELOC_Z, new PoolEntry<float>({0.0}));
@ -276,9 +265,7 @@ void GyroHandlerL3GD20H::fillCommandAndReplyMap() {
insertInCommandAndReplyMap(L3GD20H::READ_CTRL_REGS, 1); insertInCommandAndReplyMap(L3GD20H::READ_CTRL_REGS, 1);
} }
void GyroHandlerL3GD20H::modeChanged() { void GyroHandlerL3GD20H::modeChanged() { internalState = InternalState::NONE; }
internalState = InternalState::NONE;
}
void GyroHandlerL3GD20H::setAbsoluteLimits(float limitX, float limitY, float limitZ) { void GyroHandlerL3GD20H::setAbsoluteLimits(float limitX, float limitY, float limitZ) {
this->absLimitX = limitX; this->absLimitX = limitX;

View File

@ -1,12 +1,12 @@
#ifndef MISSION_DEVICES_GYROL3GD20HANDLER_H_ #ifndef MISSION_DEVICES_GYROL3GD20HANDLER_H_
#define MISSION_DEVICES_GYROL3GD20HANDLER_H_ #define MISSION_DEVICES_GYROL3GD20HANDLER_H_
#include "fsfw/FSFW.h"
#include "devicedefinitions/GyroL3GD20Definitions.h"
#include <fsfw/devicehandlers/DeviceHandlerBase.h> #include <fsfw/devicehandlers/DeviceHandlerBase.h>
#include <fsfw/globalfunctions/PeriodicOperationDivider.h> #include <fsfw/globalfunctions/PeriodicOperationDivider.h>
#include "devicedefinitions/GyroL3GD20Definitions.h"
#include "fsfw/FSFW.h"
/** /**
* @brief Device Handler for the L3GD20H gyroscope sensor * @brief Device Handler for the L3GD20H gyroscope sensor
* (https://www.st.com/en/mems-and-sensors/l3gd20h.html) * (https://www.st.com/en/mems-and-sensors/l3gd20h.html)
@ -18,8 +18,8 @@
*/ */
class GyroHandlerL3GD20H : public DeviceHandlerBase { class GyroHandlerL3GD20H : public DeviceHandlerBase {
public: public:
GyroHandlerL3GD20H(object_id_t objectId, object_id_t deviceCommunication, GyroHandlerL3GD20H(object_id_t objectId, object_id_t deviceCommunication, CookieIF *comCookie,
CookieIF* comCookie, uint32_t transitionDelayMs); uint32_t transitionDelayMs);
virtual ~GyroHandlerL3GD20H(); virtual ~GyroHandlerL3GD20H();
/** /**
@ -35,22 +35,18 @@ public:
* @brief Configure device handler to go to normal mode immediately * @brief Configure device handler to go to normal mode immediately
*/ */
void setToGoToNormalMode(bool enable); void setToGoToNormalMode(bool enable);
protected:
protected:
/* DeviceHandlerBase overrides */ /* DeviceHandlerBase overrides */
ReturnValue_t buildTransitionDeviceCommand( ReturnValue_t buildTransitionDeviceCommand(DeviceCommandId_t *id) override;
DeviceCommandId_t *id) override;
void doStartUp() override; void doStartUp() override;
void doShutDown() override; void doShutDown() override;
ReturnValue_t buildNormalDeviceCommand( ReturnValue_t buildNormalDeviceCommand(DeviceCommandId_t *id) override;
DeviceCommandId_t *id) override; ReturnValue_t buildCommandFromCommand(DeviceCommandId_t deviceCommand, const uint8_t *commandData,
ReturnValue_t buildCommandFromCommand(
DeviceCommandId_t deviceCommand, const uint8_t *commandData,
size_t commandDataLen) override; size_t commandDataLen) override;
ReturnValue_t scanForReply(const uint8_t *start, size_t len, ReturnValue_t scanForReply(const uint8_t *start, size_t len, DeviceCommandId_t *foundId,
DeviceCommandId_t *foundId, size_t *foundLen) override; size_t *foundLen) override;
virtual ReturnValue_t interpretDeviceReply(DeviceCommandId_t id, virtual ReturnValue_t interpretDeviceReply(DeviceCommandId_t id, const uint8_t *packet) override;
const uint8_t *packet) override;
void fillCommandAndReplyMap() override; void fillCommandAndReplyMap() override;
void modeChanged() override; void modeChanged() override;
@ -66,12 +62,7 @@ private:
float absLimitY = L3GD20H::RANGE_DPS_00; float absLimitY = L3GD20H::RANGE_DPS_00;
float absLimitZ = L3GD20H::RANGE_DPS_00; float absLimitZ = L3GD20H::RANGE_DPS_00;
enum class InternalState { enum class InternalState { NONE, CONFIGURE, CHECK_REGS, NORMAL };
NONE,
CONFIGURE,
CHECK_REGS,
NORMAL
};
InternalState internalState = InternalState::NONE; InternalState internalState = InternalState::NONE;
bool commandExecuted = false; bool commandExecuted = false;
@ -94,6 +85,4 @@ private:
#endif #endif
}; };
#endif /* MISSION_DEVICES_GYROL3GD20HANDLER_H_ */ #endif /* MISSION_DEVICES_GYROL3GD20HANDLER_H_ */

View File

@ -8,9 +8,10 @@
#include <cmath> #include <cmath>
MgmLIS3MDLHandler::MgmLIS3MDLHandler(object_id_t objectId, object_id_t deviceCommunication, MgmLIS3MDLHandler::MgmLIS3MDLHandler(object_id_t objectId, object_id_t deviceCommunication,
CookieIF* comCookie, uint32_t transitionDelay): CookieIF *comCookie, uint32_t transitionDelay)
DeviceHandlerBase(objectId, deviceCommunication, comCookie), : DeviceHandlerBase(objectId, deviceCommunication, comCookie),
dataset(this), transitionDelay(transitionDelay) { dataset(this),
transitionDelay(transitionDelay) {
#if FSFW_HAL_LIS3MDL_MGM_DEBUG == 1 #if FSFW_HAL_LIS3MDL_MGM_DEBUG == 1
debugDivider = new PeriodicOperationDivider(3); debugDivider = new PeriodicOperationDivider(3);
#endif #endif
@ -20,12 +21,9 @@ MgmLIS3MDLHandler::MgmLIS3MDLHandler(object_id_t objectId, object_id_t deviceCom
registers[2] = MGMLIS3MDL::CTRL_REG3_DEFAULT; registers[2] = MGMLIS3MDL::CTRL_REG3_DEFAULT;
registers[3] = MGMLIS3MDL::CTRL_REG4_DEFAULT; registers[3] = MGMLIS3MDL::CTRL_REG4_DEFAULT;
registers[4] = MGMLIS3MDL::CTRL_REG5_DEFAULT; registers[4] = MGMLIS3MDL::CTRL_REG5_DEFAULT;
}
MgmLIS3MDLHandler::~MgmLIS3MDLHandler() {
} }
MgmLIS3MDLHandler::~MgmLIS3MDLHandler() {}
void MgmLIS3MDLHandler::doStartUp() { void MgmLIS3MDLHandler::doStartUp() {
switch (internalState) { switch (internalState) {
@ -51,8 +49,7 @@ void MgmLIS3MDLHandler::doStartUp() {
commandExecuted = false; commandExecuted = false;
if (goToNormalMode) { if (goToNormalMode) {
setMode(MODE_NORMAL); setMode(MODE_NORMAL);
} } else {
else {
setMode(_MODE_TO_ON); setMode(_MODE_TO_ON);
} }
} }
@ -61,15 +58,11 @@ void MgmLIS3MDLHandler::doStartUp() {
default: default:
break; break;
} }
} }
void MgmLIS3MDLHandler::doShutDown() { void MgmLIS3MDLHandler::doShutDown() { setMode(_MODE_POWER_DOWN); }
setMode(_MODE_POWER_DOWN);
}
ReturnValue_t MgmLIS3MDLHandler::buildTransitionDeviceCommand( ReturnValue_t MgmLIS3MDLHandler::buildTransitionDeviceCommand(DeviceCommandId_t *id) {
DeviceCommandId_t *id) {
switch (internalState) { switch (internalState) {
case (InternalState::STATE_NONE): case (InternalState::STATE_NONE):
case (InternalState::STATE_NORMAL): { case (InternalState::STATE_NORMAL): {
@ -90,14 +83,13 @@ ReturnValue_t MgmLIS3MDLHandler::buildTransitionDeviceCommand(
default: { default: {
/* might be a configuration error. */ /* might be a configuration error. */
#if FSFW_CPP_OSTREAM_ENABLED == 1 #if FSFW_CPP_OSTREAM_ENABLED == 1
sif::warning << "GyroHandler::buildTransitionDeviceCommand: Unknown internal state!" << sif::warning << "GyroHandler::buildTransitionDeviceCommand: Unknown internal state!"
std::endl; << std::endl;
#else #else
sif::printWarning("GyroHandler::buildTransitionDeviceCommand: Unknown internal state!\n"); sif::printWarning("GyroHandler::buildTransitionDeviceCommand: Unknown internal state!\n");
#endif /* FSFW_CPP_OSTREAM_ENABLED == 1 */ #endif /* FSFW_CPP_OSTREAM_ENABLED == 1 */
return HasReturnvaluesIF::RETURN_OK; return HasReturnvaluesIF::RETURN_OK;
} }
} }
return buildCommandFromCommand(*id, NULL, 0); return buildCommandFromCommand(*id, NULL, 0);
} }
@ -119,7 +111,6 @@ uint8_t MgmLIS3MDLHandler::writeCommand(uint8_t command, bool continuousCom) {
} }
void MgmLIS3MDLHandler::setupMgm() { void MgmLIS3MDLHandler::setupMgm() {
registers[0] = MGMLIS3MDL::CTRL_REG1_DEFAULT; registers[0] = MGMLIS3MDL::CTRL_REG1_DEFAULT;
registers[1] = MGMLIS3MDL::CTRL_REG2_DEFAULT; registers[1] = MGMLIS3MDL::CTRL_REG2_DEFAULT;
registers[2] = MGMLIS3MDL::CTRL_REG3_DEFAULT; registers[2] = MGMLIS3MDL::CTRL_REG3_DEFAULT;
@ -129,24 +120,21 @@ void MgmLIS3MDLHandler::setupMgm() {
prepareCtrlRegisterWrite(); prepareCtrlRegisterWrite();
} }
ReturnValue_t MgmLIS3MDLHandler::buildNormalDeviceCommand( ReturnValue_t MgmLIS3MDLHandler::buildNormalDeviceCommand(DeviceCommandId_t *id) {
DeviceCommandId_t *id) {
// Data/config register will be read in an alternating manner. // Data/config register will be read in an alternating manner.
if (communicationStep == CommunicationStep::DATA) { if (communicationStep == CommunicationStep::DATA) {
*id = MGMLIS3MDL::READ_CONFIG_AND_DATA; *id = MGMLIS3MDL::READ_CONFIG_AND_DATA;
communicationStep = CommunicationStep::TEMPERATURE; communicationStep = CommunicationStep::TEMPERATURE;
return buildCommandFromCommand(*id, NULL, 0); return buildCommandFromCommand(*id, NULL, 0);
} } else {
else {
*id = MGMLIS3MDL::READ_TEMPERATURE; *id = MGMLIS3MDL::READ_TEMPERATURE;
communicationStep = CommunicationStep::DATA; communicationStep = CommunicationStep::DATA;
return buildCommandFromCommand(*id, NULL, 0); return buildCommandFromCommand(*id, NULL, 0);
} }
} }
ReturnValue_t MgmLIS3MDLHandler::buildCommandFromCommand( ReturnValue_t MgmLIS3MDLHandler::buildCommandFromCommand(DeviceCommandId_t deviceCommand,
DeviceCommandId_t deviceCommand, const uint8_t *commandData, const uint8_t *commandData,
size_t commandDataLen) { size_t commandDataLen) {
switch (deviceCommand) { switch (deviceCommand) {
case (MGMLIS3MDL::READ_CONFIG_AND_DATA): { case (MGMLIS3MDL::READ_CONFIG_AND_DATA): {
@ -195,16 +183,15 @@ ReturnValue_t MgmLIS3MDLHandler::identifyDevice() {
return RETURN_OK; return RETURN_OK;
} }
ReturnValue_t MgmLIS3MDLHandler::scanForReply(const uint8_t *start, ReturnValue_t MgmLIS3MDLHandler::scanForReply(const uint8_t *start, size_t len,
size_t len, DeviceCommandId_t *foundId, size_t *foundLen) { DeviceCommandId_t *foundId, size_t *foundLen) {
*foundLen = len; *foundLen = len;
if (len == MGMLIS3MDL::NR_OF_DATA_AND_CFG_REGISTERS + 1) { if (len == MGMLIS3MDL::NR_OF_DATA_AND_CFG_REGISTERS + 1) {
*foundLen = len; *foundLen = len;
*foundId = MGMLIS3MDL::READ_CONFIG_AND_DATA; *foundId = MGMLIS3MDL::READ_CONFIG_AND_DATA;
// Check validity by checking config registers // Check validity by checking config registers
if (start[1] != registers[0] or start[2] != registers[1] or if (start[1] != registers[0] or start[2] != registers[1] or start[3] != registers[2] or
start[3] != registers[2] or start[4] != registers[3] or start[4] != registers[3] or start[5] != registers[4]) {
start[5] != registers[4]) {
#if FSFW_VERBOSE_LEVEL >= 1 #if FSFW_VERBOSE_LEVEL >= 1
#if FSFW_CPP_OSTREAM_ENABLED == 1 #if FSFW_CPP_OSTREAM_ENABLED == 1
sif::warning << "MGMHandlerLIS3MDL::scanForReply: Invalid registers!" << std::endl; sif::warning << "MGMHandlerLIS3MDL::scanForReply: Invalid registers!" << std::endl;
@ -218,16 +205,13 @@ ReturnValue_t MgmLIS3MDLHandler::scanForReply(const uint8_t *start,
commandExecuted = true; commandExecuted = true;
} }
} } else if (len == MGMLIS3MDL::TEMPERATURE_REPLY_LEN) {
else if(len == MGMLIS3MDL::TEMPERATURE_REPLY_LEN) {
*foundLen = len; *foundLen = len;
*foundId = MGMLIS3MDL::READ_TEMPERATURE; *foundId = MGMLIS3MDL::READ_TEMPERATURE;
} } else if (len == MGMLIS3MDL::SETUP_REPLY_LEN) {
else if (len == MGMLIS3MDL::SETUP_REPLY_LEN) {
*foundLen = len; *foundLen = len;
*foundId = MGMLIS3MDL::SETUP_MGM; *foundId = MGMLIS3MDL::SETUP_MGM;
} } else if (len == SINGLE_COMMAND_ANSWER_LEN) {
else if (len == SINGLE_COMMAND_ANSWER_LEN) {
*foundLen = len; *foundLen = len;
*foundId = getPendingCommand(); *foundId = getPendingCommand();
if (*foundId == MGMLIS3MDL::IDENTIFY_DEVICE) { if (*foundId == MGMLIS3MDL::IDENTIFY_DEVICE) {
@ -235,9 +219,11 @@ ReturnValue_t MgmLIS3MDLHandler::scanForReply(const uint8_t *start,
#if FSFW_VERBOSE_LEVEL >= 1 #if FSFW_VERBOSE_LEVEL >= 1
#if FSFW_CPP_OSTREAM_ENABLED == 1 #if FSFW_CPP_OSTREAM_ENABLED == 1
sif::warning << "MGMHandlerLIS3MDL::scanForReply: " sif::warning << "MGMHandlerLIS3MDL::scanForReply: "
"Device identification failed!" << std::endl; "Device identification failed!"
<< std::endl;
#else #else
sif::printWarning("MGMHandlerLIS3MDL::scanForReply: " sif::printWarning(
"MGMHandlerLIS3MDL::scanForReply: "
"Device identification failed!\n"); "Device identification failed!\n");
#endif #endif
#endif #endif
@ -248,23 +234,18 @@ ReturnValue_t MgmLIS3MDLHandler::scanForReply(const uint8_t *start,
commandExecuted = true; commandExecuted = true;
} }
} }
} } else {
else {
return DeviceHandlerIF::INVALID_DATA; return DeviceHandlerIF::INVALID_DATA;
} }
/* Data with SPI Interface always has this answer */ /* Data with SPI Interface always has this answer */
if (start[0] == 0b11111111) { if (start[0] == 0b11111111) {
return RETURN_OK; return RETURN_OK;
} } else {
else {
return DeviceHandlerIF::INVALID_DATA; return DeviceHandlerIF::INVALID_DATA;
} }
} }
ReturnValue_t MgmLIS3MDLHandler::interpretDeviceReply(DeviceCommandId_t id, ReturnValue_t MgmLIS3MDLHandler::interpretDeviceReply(DeviceCommandId_t id, const uint8_t *packet) {
const uint8_t *packet) {
switch (id) { switch (id) {
case MGMLIS3MDL::IDENTIFY_DEVICE: { case MGMLIS3MDL::IDENTIFY_DEVICE: {
break; break;
@ -276,26 +257,27 @@ ReturnValue_t MgmLIS3MDLHandler::interpretDeviceReply(DeviceCommandId_t id,
// TODO: Store configuration in new local datasets. // TODO: Store configuration in new local datasets.
float sensitivityFactor = getSensitivityFactor(getSensitivity(registers[2])); float sensitivityFactor = getSensitivityFactor(getSensitivity(registers[2]));
int16_t mgmMeasurementRawX = packet[MGMLIS3MDL::X_HIGHBYTE_IDX] << 8 int16_t mgmMeasurementRawX =
| packet[MGMLIS3MDL::X_LOWBYTE_IDX] ; packet[MGMLIS3MDL::X_HIGHBYTE_IDX] << 8 | packet[MGMLIS3MDL::X_LOWBYTE_IDX];
int16_t mgmMeasurementRawY = packet[MGMLIS3MDL::Y_HIGHBYTE_IDX] << 8 int16_t mgmMeasurementRawY =
| packet[MGMLIS3MDL::Y_LOWBYTE_IDX] ; packet[MGMLIS3MDL::Y_HIGHBYTE_IDX] << 8 | packet[MGMLIS3MDL::Y_LOWBYTE_IDX];
int16_t mgmMeasurementRawZ = packet[MGMLIS3MDL::Z_HIGHBYTE_IDX] << 8 int16_t mgmMeasurementRawZ =
| packet[MGMLIS3MDL::Z_LOWBYTE_IDX] ; packet[MGMLIS3MDL::Z_HIGHBYTE_IDX] << 8 | packet[MGMLIS3MDL::Z_LOWBYTE_IDX];
/* Target value in microtesla */ /* Target value in microtesla */
float mgmX = static_cast<float>(mgmMeasurementRawX) * sensitivityFactor float mgmX = static_cast<float>(mgmMeasurementRawX) * sensitivityFactor *
* MGMLIS3MDL::GAUSS_TO_MICROTESLA_FACTOR; MGMLIS3MDL::GAUSS_TO_MICROTESLA_FACTOR;
float mgmY = static_cast<float>(mgmMeasurementRawY) * sensitivityFactor float mgmY = static_cast<float>(mgmMeasurementRawY) * sensitivityFactor *
* MGMLIS3MDL::GAUSS_TO_MICROTESLA_FACTOR; MGMLIS3MDL::GAUSS_TO_MICROTESLA_FACTOR;
float mgmZ = static_cast<float>(mgmMeasurementRawZ) * sensitivityFactor float mgmZ = static_cast<float>(mgmMeasurementRawZ) * sensitivityFactor *
* MGMLIS3MDL::GAUSS_TO_MICROTESLA_FACTOR; MGMLIS3MDL::GAUSS_TO_MICROTESLA_FACTOR;
#if FSFW_HAL_LIS3MDL_MGM_DEBUG == 1 #if FSFW_HAL_LIS3MDL_MGM_DEBUG == 1
if (debugDivider->checkAndIncrement()) { if (debugDivider->checkAndIncrement()) {
#if FSFW_CPP_OSTREAM_ENABLED == 1 #if FSFW_CPP_OSTREAM_ENABLED == 1
sif::info << "MGMHandlerLIS3: Magnetic field strength in" sif::info << "MGMHandlerLIS3: Magnetic field strength in"
" microtesla:" << std::endl; " microtesla:"
<< std::endl;
sif::info << "X: " << mgmX << " uT" << std::endl; sif::info << "X: " << mgmX << " uT" << std::endl;
sif::info << "Y: " << mgmY << " uT" << std::endl; sif::info << "Y: " << mgmY << " uT" << std::endl;
sif::info << "Z: " << mgmZ << " uT" << std::endl; sif::info << "Z: " << mgmZ << " uT" << std::endl;
@ -312,24 +294,21 @@ ReturnValue_t MgmLIS3MDLHandler::interpretDeviceReply(DeviceCommandId_t id,
if (std::abs(mgmX) < absLimitX) { if (std::abs(mgmX) < absLimitX) {
dataset.fieldStrengthX = mgmX; dataset.fieldStrengthX = mgmX;
dataset.fieldStrengthX.setValid(true); dataset.fieldStrengthX.setValid(true);
} } else {
else {
dataset.fieldStrengthX.setValid(false); dataset.fieldStrengthX.setValid(false);
} }
if (std::abs(mgmY) < absLimitY) { if (std::abs(mgmY) < absLimitY) {
dataset.fieldStrengthY = mgmY; dataset.fieldStrengthY = mgmY;
dataset.fieldStrengthY.setValid(true); dataset.fieldStrengthY.setValid(true);
} } else {
else {
dataset.fieldStrengthY.setValid(false); dataset.fieldStrengthY.setValid(false);
} }
if (std::abs(mgmZ) < absLimitZ) { if (std::abs(mgmZ) < absLimitZ) {
dataset.fieldStrengthZ = mgmZ; dataset.fieldStrengthZ = mgmZ;
dataset.fieldStrengthZ.setValid(true); dataset.fieldStrengthZ.setValid(true);
} } else {
else {
dataset.fieldStrengthZ.setValid(false); dataset.fieldStrengthZ.setValid(false);
} }
} }
@ -342,8 +321,7 @@ ReturnValue_t MgmLIS3MDLHandler::interpretDeviceReply(DeviceCommandId_t id,
#if FSFW_HAL_LIS3MDL_MGM_DEBUG == 1 #if FSFW_HAL_LIS3MDL_MGM_DEBUG == 1
if (debugDivider->check()) { if (debugDivider->check()) {
#if FSFW_CPP_OSTREAM_ENABLED == 1 #if FSFW_CPP_OSTREAM_ENABLED == 1
sif::info << "MGMHandlerLIS3: Temperature: " << tempValue << " C" << sif::info << "MGMHandlerLIS3: Temperature: " << tempValue << " C" << std::endl;
std::endl;
#else #else
sif::printInfo("MGMHandlerLIS3: Temperature: %f C\n"); sif::printInfo("MGMHandlerLIS3: Temperature: %f C\n");
#endif #endif
@ -360,7 +338,6 @@ ReturnValue_t MgmLIS3MDLHandler::interpretDeviceReply(DeviceCommandId_t id,
default: { default: {
return DeviceHandlerIF::UNKNOWN_DEVICE_REPLY; return DeviceHandlerIF::UNKNOWN_DEVICE_REPLY;
} }
} }
return RETURN_OK; return RETURN_OK;
} }
@ -400,9 +377,8 @@ float MgmLIS3MDLHandler::getSensitivityFactor(MGMLIS3MDL::Sensitivies sens) {
} }
} }
ReturnValue_t MgmLIS3MDLHandler::enableTemperatureSensor(const uint8_t *commandData,
ReturnValue_t MgmLIS3MDLHandler::enableTemperatureSensor( size_t commandDataLen) {
const uint8_t *commandData, size_t commandDataLen) {
triggerEvent(CHANGE_OF_SETUP_PARAMETER); triggerEvent(CHANGE_OF_SETUP_PARAMETER);
uint32_t size = 2; uint32_t size = 2;
commandBuffer[0] = writeCommand(MGMLIS3MDL::CTRL_REG1); commandBuffer[0] = writeCommand(MGMLIS3MDL::CTRL_REG1);
@ -471,9 +447,7 @@ void MgmLIS3MDLHandler::fillCommandAndReplyMap() {
insertInCommandAndReplyMap(MGMLIS3MDL::ACCURACY_OP_MODE_SET, 1); insertInCommandAndReplyMap(MGMLIS3MDL::ACCURACY_OP_MODE_SET, 1);
} }
void MgmLIS3MDLHandler::setToGoToNormalMode(bool enable) { void MgmLIS3MDLHandler::setToGoToNormalMode(bool enable) { this->goToNormalMode = enable; }
this->goToNormalMode = enable;
}
ReturnValue_t MgmLIS3MDLHandler::prepareCtrlRegisterWrite() { ReturnValue_t MgmLIS3MDLHandler::prepareCtrlRegisterWrite() {
commandBuffer[0] = writeCommand(MGMLIS3MDL::CTRL_REG1, true); commandBuffer[0] = writeCommand(MGMLIS3MDL::CTRL_REG1, true);
@ -488,28 +462,18 @@ ReturnValue_t MgmLIS3MDLHandler::prepareCtrlRegisterWrite() {
return RETURN_OK; return RETURN_OK;
} }
void MgmLIS3MDLHandler::doTransition(Mode_t modeFrom, Submode_t subModeFrom) { void MgmLIS3MDLHandler::doTransition(Mode_t modeFrom, Submode_t subModeFrom) {}
} uint32_t MgmLIS3MDLHandler::getTransitionDelayMs(Mode_t from, Mode_t to) { return transitionDelay; }
uint32_t MgmLIS3MDLHandler::getTransitionDelayMs(Mode_t from, Mode_t to) { void MgmLIS3MDLHandler::modeChanged(void) { internalState = InternalState::STATE_NONE; }
return transitionDelay;
}
void MgmLIS3MDLHandler::modeChanged(void) { ReturnValue_t MgmLIS3MDLHandler::initializeLocalDataPool(localpool::DataPool &localDataPoolMap,
internalState = InternalState::STATE_NONE; LocalDataPoolManager &poolManager) {
} localDataPoolMap.emplace(MGMLIS3MDL::FIELD_STRENGTH_X, new PoolEntry<float>({0.0}));
localDataPoolMap.emplace(MGMLIS3MDL::FIELD_STRENGTH_Y, new PoolEntry<float>({0.0}));
ReturnValue_t MgmLIS3MDLHandler::initializeLocalDataPool( localDataPoolMap.emplace(MGMLIS3MDL::FIELD_STRENGTH_Z, new PoolEntry<float>({0.0}));
localpool::DataPool &localDataPoolMap, LocalDataPoolManager &poolManager) { localDataPoolMap.emplace(MGMLIS3MDL::TEMPERATURE_CELCIUS, new PoolEntry<float>({0.0}));
localDataPoolMap.emplace(MGMLIS3MDL::FIELD_STRENGTH_X,
new PoolEntry<float>({0.0}));
localDataPoolMap.emplace(MGMLIS3MDL::FIELD_STRENGTH_Y,
new PoolEntry<float>({0.0}));
localDataPoolMap.emplace(MGMLIS3MDL::FIELD_STRENGTH_Z,
new PoolEntry<float>({0.0}));
localDataPoolMap.emplace(MGMLIS3MDL::TEMPERATURE_CELCIUS,
new PoolEntry<float>({0.0}));
return HasReturnvaluesIF::RETURN_OK; return HasReturnvaluesIF::RETURN_OK;
} }

View File

@ -1,10 +1,9 @@
#ifndef MISSION_DEVICES_MGMLIS3MDLHANDLER_H_ #ifndef MISSION_DEVICES_MGMLIS3MDLHANDLER_H_
#define MISSION_DEVICES_MGMLIS3MDLHANDLER_H_ #define MISSION_DEVICES_MGMLIS3MDLHANDLER_H_
#include "fsfw/FSFW.h"
#include "events/subsystemIdRanges.h"
#include "devicedefinitions/MgmLIS3HandlerDefs.h" #include "devicedefinitions/MgmLIS3HandlerDefs.h"
#include "events/subsystemIdRanges.h"
#include "fsfw/FSFW.h"
#include "fsfw/devicehandlers/DeviceHandlerBase.h" #include "fsfw/devicehandlers/DeviceHandlerBase.h"
class PeriodicOperationDivider; class PeriodicOperationDivider;
@ -20,10 +19,7 @@ class PeriodicOperationDivider;
*/ */
class MgmLIS3MDLHandler : public DeviceHandlerBase { class MgmLIS3MDLHandler : public DeviceHandlerBase {
public: public:
enum class CommunicationStep { enum class CommunicationStep { DATA, TEMPERATURE };
DATA,
TEMPERATURE
};
static const uint8_t INTERFACE_ID = CLASS_ID::MGM_LIS3MDL; static const uint8_t INTERFACE_ID = CLASS_ID::MGM_LIS3MDL;
static const uint8_t SUBSYSTEM_ID = SUBSYSTEM_ID::MGM_LIS3MDL; static const uint8_t SUBSYSTEM_ID = SUBSYSTEM_ID::MGM_LIS3MDL;
@ -45,21 +41,17 @@ public:
void setToGoToNormalMode(bool enable); void setToGoToNormalMode(bool enable);
protected: protected:
/** DeviceHandlerBase overrides */ /** DeviceHandlerBase overrides */
void doShutDown() override; void doShutDown() override;
void doStartUp() override; void doStartUp() override;
void doTransition(Mode_t modeFrom, Submode_t subModeFrom) override; void doTransition(Mode_t modeFrom, Submode_t subModeFrom) override;
virtual uint32_t getTransitionDelayMs(Mode_t from, Mode_t to) override; virtual uint32_t getTransitionDelayMs(Mode_t from, Mode_t to) override;
ReturnValue_t buildCommandFromCommand( ReturnValue_t buildCommandFromCommand(DeviceCommandId_t deviceCommand, const uint8_t *commandData,
DeviceCommandId_t deviceCommand, const uint8_t *commandData,
size_t commandDataLen) override; size_t commandDataLen) override;
ReturnValue_t buildTransitionDeviceCommand( ReturnValue_t buildTransitionDeviceCommand(DeviceCommandId_t *id) override;
DeviceCommandId_t *id) override; ReturnValue_t buildNormalDeviceCommand(DeviceCommandId_t *id) override;
ReturnValue_t buildNormalDeviceCommand( ReturnValue_t scanForReply(const uint8_t *start, size_t len, DeviceCommandId_t *foundId,
DeviceCommandId_t *id) override; size_t *foundLen) override;
ReturnValue_t scanForReply(const uint8_t *start, size_t len,
DeviceCommandId_t *foundId, size_t *foundLen) override;
/** /**
* This implementation is tailored towards space applications and will flag values larger * This implementation is tailored towards space applications and will flag values larger
* than 100 microtesla on X,Y and 150 microtesla on Z as invalid * than 100 microtesla on X,Y and 150 microtesla on Z as invalid
@ -67,8 +59,7 @@ protected:
* @param packet * @param packet
* @return * @return
*/ */
virtual ReturnValue_t interpretDeviceReply(DeviceCommandId_t id, virtual ReturnValue_t interpretDeviceReply(DeviceCommandId_t id, const uint8_t *packet) override;
const uint8_t *packet) override;
void fillCommandAndReplyMap() override; void fillCommandAndReplyMap() override;
void modeChanged(void) override; void modeChanged(void) override;
ReturnValue_t initializeLocalDataPool(localpool::DataPool &localDataPoolMap, ReturnValue_t initializeLocalDataPool(localpool::DataPool &localDataPoolMap,
@ -159,16 +150,14 @@ private:
* @param commandData On or Off * @param commandData On or Off
* @param length of the commandData: has to be 1 * @param length of the commandData: has to be 1
*/ */
virtual ReturnValue_t enableTemperatureSensor(const uint8_t *commandData, virtual ReturnValue_t enableTemperatureSensor(const uint8_t *commandData, size_t commandDataLen);
size_t commandDataLen);
/** /**
* Sets the accuracy of the measurement of the axis. The noise is changing. * Sets the accuracy of the measurement of the axis. The noise is changing.
* @param commandData LOW, MEDIUM, HIGH, ULTRA * @param commandData LOW, MEDIUM, HIGH, ULTRA
* @param length of the command, has to be 1 * @param length of the command, has to be 1
*/ */
virtual ReturnValue_t setOperatingMode(const uint8_t *commandData, virtual ReturnValue_t setOperatingMode(const uint8_t *commandData, size_t commandDataLen);
size_t commandDataLen);
/** /**
* We always update all registers together, so this method updates * We always update all registers together, so this method updates

View File

@ -1,16 +1,16 @@
#include "MgmRM3100Handler.h" #include "MgmRM3100Handler.h"
#include "fsfw/datapool/PoolReadGuard.h" #include "fsfw/datapool/PoolReadGuard.h"
#include "fsfw/globalfunctions/bitutility.h"
#include "fsfw/devicehandlers/DeviceHandlerMessage.h" #include "fsfw/devicehandlers/DeviceHandlerMessage.h"
#include "fsfw/globalfunctions/bitutility.h"
#include "fsfw/objectmanager/SystemObjectIF.h" #include "fsfw/objectmanager/SystemObjectIF.h"
#include "fsfw/returnvalues/HasReturnvaluesIF.h" #include "fsfw/returnvalues/HasReturnvaluesIF.h"
MgmRM3100Handler::MgmRM3100Handler(object_id_t objectId, object_id_t deviceCommunication,
MgmRM3100Handler::MgmRM3100Handler(object_id_t objectId, CookieIF *comCookie, uint32_t transitionDelay)
object_id_t deviceCommunication, CookieIF* comCookie, uint32_t transitionDelay): : DeviceHandlerBase(objectId, deviceCommunication, comCookie),
DeviceHandlerBase(objectId, deviceCommunication, comCookie), primaryDataset(this),
primaryDataset(this), transitionDelay(transitionDelay) { transitionDelay(transitionDelay) {
#if FSFW_HAL_RM3100_MGM_DEBUG == 1 #if FSFW_HAL_RM3100_MGM_DEBUG == 1
debugDivider = new PeriodicOperationDivider(3); debugDivider = new PeriodicOperationDivider(3);
#endif #endif
@ -45,8 +45,7 @@ void MgmRM3100Handler::doStartUp() {
internalState = InternalState::NORMAL; internalState = InternalState::NORMAL;
if (goToNormalModeAtStartup) { if (goToNormalModeAtStartup) {
setMode(MODE_NORMAL); setMode(MODE_NORMAL);
} } else {
else {
setMode(_MODE_TO_ON); setMode(_MODE_TO_ON);
} }
} }
@ -58,12 +57,9 @@ void MgmRM3100Handler::doStartUp() {
} }
} }
void MgmRM3100Handler::doShutDown() { void MgmRM3100Handler::doShutDown() { setMode(_MODE_POWER_DOWN); }
setMode(_MODE_POWER_DOWN);
}
ReturnValue_t MgmRM3100Handler::buildTransitionDeviceCommand( ReturnValue_t MgmRM3100Handler::buildTransitionDeviceCommand(DeviceCommandId_t *id) {
DeviceCommandId_t *id) {
size_t commandLen = 0; size_t commandLen = 0;
switch (internalState) { switch (internalState) {
case (InternalState::NONE): case (InternalState::NONE):
@ -93,9 +89,11 @@ ReturnValue_t MgmRM3100Handler::buildTransitionDeviceCommand(
#if FSFW_CPP_OSTREAM_ENABLED == 1 #if FSFW_CPP_OSTREAM_ENABLED == 1
// Might be a configuration error // Might be a configuration error
sif::warning << "MgmRM3100Handler::buildTransitionDeviceCommand: " sif::warning << "MgmRM3100Handler::buildTransitionDeviceCommand: "
"Unknown internal state" << std::endl; "Unknown internal state"
<< std::endl;
#else #else
sif::printWarning("MgmRM3100Handler::buildTransitionDeviceCommand: " sif::printWarning(
"MgmRM3100Handler::buildTransitionDeviceCommand: "
"Unknown internal state\n"); "Unknown internal state\n");
#endif #endif
#endif #endif
@ -106,7 +104,8 @@ ReturnValue_t MgmRM3100Handler::buildTransitionDeviceCommand(
} }
ReturnValue_t MgmRM3100Handler::buildCommandFromCommand(DeviceCommandId_t deviceCommand, ReturnValue_t MgmRM3100Handler::buildCommandFromCommand(DeviceCommandId_t deviceCommand,
const uint8_t *commandData, size_t commandDataLen) { const uint8_t *commandData,
size_t commandDataLen) {
switch (deviceCommand) { switch (deviceCommand) {
case (RM3100::CONFIGURE_CMM): { case (RM3100::CONFIGURE_CMM): {
commandBuffer[0] = RM3100::CMM_REGISTER; commandBuffer[0] = RM3100::CMM_REGISTER;
@ -154,16 +153,13 @@ ReturnValue_t MgmRM3100Handler::buildCommandFromCommand(DeviceCommandId_t device
return RETURN_OK; return RETURN_OK;
} }
ReturnValue_t MgmRM3100Handler::buildNormalDeviceCommand( ReturnValue_t MgmRM3100Handler::buildNormalDeviceCommand(DeviceCommandId_t *id) {
DeviceCommandId_t *id) {
*id = RM3100::READ_DATA; *id = RM3100::READ_DATA;
return buildCommandFromCommand(*id, nullptr, 0); return buildCommandFromCommand(*id, nullptr, 0);
} }
ReturnValue_t MgmRM3100Handler::scanForReply(const uint8_t *start, ReturnValue_t MgmRM3100Handler::scanForReply(const uint8_t *start, size_t len,
size_t len, DeviceCommandId_t *foundId, DeviceCommandId_t *foundId, size_t *foundLen) {
size_t *foundLen) {
// For SPI, ID will always be the one of the last sent command // For SPI, ID will always be the one of the last sent command
*foundId = this->getPendingCommand(); *foundId = this->getPendingCommand();
*foundLen = len; *foundLen = len;
@ -189,8 +185,7 @@ ReturnValue_t MgmRM3100Handler::interpretDeviceReply(DeviceCommandId_t id, const
bitutil::clear(&cmmValue, 6); bitutil::clear(&cmmValue, 6);
if (cmmValue == cmmRegValue and internalState == InternalState::READ_CMM) { if (cmmValue == cmmRegValue and internalState == InternalState::READ_CMM) {
commandExecuted = true; commandExecuted = true;
} } else {
else {
// Attempt reconfiguration // Attempt reconfiguration
internalState = InternalState::CONFIGURE_CMM; internalState = InternalState::CONFIGURE_CMM;
return DeviceHandlerIF::DEVICE_REPLY_INVALID; return DeviceHandlerIF::DEVICE_REPLY_INVALID;
@ -204,8 +199,7 @@ ReturnValue_t MgmRM3100Handler::interpretDeviceReply(DeviceCommandId_t id, const
if (mode != _MODE_START_UP) { if (mode != _MODE_START_UP) {
triggerEvent(tmrcSet, tmrcRegValue, 0); triggerEvent(tmrcSet, tmrcRegValue, 0);
} }
} } else {
else {
// Attempt reconfiguration // Attempt reconfiguration
internalState = InternalState::STATE_CONFIGURE_TMRC; internalState = InternalState::STATE_CONFIGURE_TMRC;
return DeviceHandlerIF::DEVICE_REPLY_INVALID; return DeviceHandlerIF::DEVICE_REPLY_INVALID;
@ -239,7 +233,8 @@ ReturnValue_t MgmRM3100Handler::interpretDeviceReply(DeviceCommandId_t id, const
} }
ReturnValue_t MgmRM3100Handler::handleCycleCountConfigCommand(DeviceCommandId_t deviceCommand, ReturnValue_t MgmRM3100Handler::handleCycleCountConfigCommand(DeviceCommandId_t deviceCommand,
const uint8_t *commandData, size_t commandDataLen) { const uint8_t *commandData,
size_t commandDataLen) {
if (commandData == nullptr) { if (commandData == nullptr) {
return DeviceHandlerIF::INVALID_COMMAND_PARAMETER; return DeviceHandlerIF::INVALID_COMMAND_PARAMETER;
} }
@ -247,11 +242,9 @@ ReturnValue_t MgmRM3100Handler::handleCycleCountConfigCommand(DeviceCommandId_t
// Set cycle count // Set cycle count
if (commandDataLen == 2) { if (commandDataLen == 2) {
handleCycleCommand(true, commandData, commandDataLen); handleCycleCommand(true, commandData, commandDataLen);
} } else if (commandDataLen == 6) {
else if(commandDataLen == 6) {
handleCycleCommand(false, commandData, commandDataLen); handleCycleCommand(false, commandData, commandDataLen);
} } else {
else {
return DeviceHandlerIF::INVALID_COMMAND_PARAMETER; return DeviceHandlerIF::INVALID_COMMAND_PARAMETER;
} }
@ -264,11 +257,11 @@ ReturnValue_t MgmRM3100Handler::handleCycleCountConfigCommand(DeviceCommandId_t
return HasReturnvaluesIF::RETURN_OK; return HasReturnvaluesIF::RETURN_OK;
} }
ReturnValue_t MgmRM3100Handler::handleCycleCommand(bool oneCycleValue, ReturnValue_t MgmRM3100Handler::handleCycleCommand(bool oneCycleValue, const uint8_t *commandData,
const uint8_t *commandData, size_t commandDataLen) { size_t commandDataLen) {
RM3100::CycleCountCommand command(oneCycleValue); RM3100::CycleCountCommand command(oneCycleValue);
ReturnValue_t result = command.deSerialize(&commandData, &commandDataLen, ReturnValue_t result =
SerializeIF::Endianness::BIG); command.deSerialize(&commandData, &commandDataLen, SerializeIF::Endianness::BIG);
if (result != HasReturnvaluesIF::RETURN_OK) { if (result != HasReturnvaluesIF::RETURN_OK) {
return result; return result;
} }
@ -289,7 +282,8 @@ ReturnValue_t MgmRM3100Handler::handleCycleCommand(bool oneCycleValue,
} }
ReturnValue_t MgmRM3100Handler::handleTmrcConfigCommand(DeviceCommandId_t deviceCommand, ReturnValue_t MgmRM3100Handler::handleTmrcConfigCommand(DeviceCommandId_t deviceCommand,
const uint8_t *commandData, size_t commandDataLen) { const uint8_t *commandData,
size_t commandDataLen) {
if (commandData == nullptr or commandDataLen != 1) { if (commandData == nullptr or commandDataLen != 1) {
return DeviceHandlerIF::INVALID_COMMAND_PARAMETER; return DeviceHandlerIF::INVALID_COMMAND_PARAMETER;
} }
@ -315,12 +309,10 @@ void MgmRM3100Handler::fillCommandAndReplyMap() {
insertInCommandAndReplyMap(RM3100::READ_DATA, 3, &primaryDataset); insertInCommandAndReplyMap(RM3100::READ_DATA, 3, &primaryDataset);
} }
void MgmRM3100Handler::modeChanged(void) { void MgmRM3100Handler::modeChanged(void) { internalState = InternalState::NONE; }
internalState = InternalState::NONE;
}
ReturnValue_t MgmRM3100Handler::initializeLocalDataPool( ReturnValue_t MgmRM3100Handler::initializeLocalDataPool(localpool::DataPool &localDataPoolMap,
localpool::DataPool &localDataPoolMap, LocalDataPoolManager &poolManager) { LocalDataPoolManager &poolManager) {
localDataPoolMap.emplace(RM3100::FIELD_STRENGTH_X, new PoolEntry<float>({0.0})); localDataPoolMap.emplace(RM3100::FIELD_STRENGTH_X, new PoolEntry<float>({0.0}));
localDataPoolMap.emplace(RM3100::FIELD_STRENGTH_Y, new PoolEntry<float>({0.0})); localDataPoolMap.emplace(RM3100::FIELD_STRENGTH_Y, new PoolEntry<float>({0.0}));
localDataPoolMap.emplace(RM3100::FIELD_STRENGTH_Z, new PoolEntry<float>({0.0})); localDataPoolMap.emplace(RM3100::FIELD_STRENGTH_Z, new PoolEntry<float>({0.0}));
@ -331,9 +323,7 @@ uint32_t MgmRM3100Handler::getTransitionDelayMs(Mode_t from, Mode_t to) {
return this->transitionDelay; return this->transitionDelay;
} }
void MgmRM3100Handler::setToGoToNormalMode(bool enable) { void MgmRM3100Handler::setToGoToNormalMode(bool enable) { goToNormalModeAtStartup = enable; }
goToNormalModeAtStartup = enable;
}
ReturnValue_t MgmRM3100Handler::handleDataReadout(const uint8_t *packet) { ReturnValue_t MgmRM3100Handler::handleDataReadout(const uint8_t *packet) {
// Analyze data here. The sensor generates 24 bit signed values so we need to do some bitshift // Analyze data here. The sensor generates 24 bit signed values so we need to do some bitshift
@ -351,7 +341,8 @@ ReturnValue_t MgmRM3100Handler::handleDataReadout(const uint8_t *packet) {
if (debugDivider->checkAndIncrement()) { if (debugDivider->checkAndIncrement()) {
#if FSFW_CPP_OSTREAM_ENABLED == 1 #if FSFW_CPP_OSTREAM_ENABLED == 1
sif::info << "MgmRM3100Handler: Magnetic field strength in" sif::info << "MgmRM3100Handler: Magnetic field strength in"
" microtesla:" << std::endl; " microtesla:"
<< std::endl;
sif::info << "X: " << fieldStrengthX << " uT" << std::endl; sif::info << "X: " << fieldStrengthX << " uT" << std::endl;
sif::info << "Y: " << fieldStrengthY << " uT" << std::endl; sif::info << "Y: " << fieldStrengthY << " uT" << std::endl;
sif::info << "Z: " << fieldStrengthZ << " uT" << std::endl; sif::info << "Z: " << fieldStrengthZ << " uT" << std::endl;

View File

@ -1,8 +1,8 @@
#ifndef MISSION_DEVICES_MGMRM3100HANDLER_H_ #ifndef MISSION_DEVICES_MGMRM3100HANDLER_H_
#define MISSION_DEVICES_MGMRM3100HANDLER_H_ #define MISSION_DEVICES_MGMRM3100HANDLER_H_
#include "fsfw/FSFW.h"
#include "devicedefinitions/MgmRM3100HandlerDefs.h" #include "devicedefinitions/MgmRM3100HandlerDefs.h"
#include "fsfw/FSFW.h"
#include "fsfw/devicehandlers/DeviceHandlerBase.h" #include "fsfw/devicehandlers/DeviceHandlerBase.h"
#if FSFW_HAL_RM3100_MGM_DEBUG == 1 #if FSFW_HAL_RM3100_MGM_DEBUG == 1
@ -21,17 +21,16 @@ public:
static const uint8_t INTERFACE_ID = CLASS_ID::MGM_RM3100; static const uint8_t INTERFACE_ID = CLASS_ID::MGM_RM3100;
//! [EXPORT] : [COMMENT] P1: TMRC value which was set, P2: 0 //! [EXPORT] : [COMMENT] P1: TMRC value which was set, P2: 0
static constexpr Event tmrcSet = event::makeEvent(SUBSYSTEM_ID::MGM_RM3100, static constexpr Event tmrcSet = event::makeEvent(SUBSYSTEM_ID::MGM_RM3100, 0x00, severity::INFO);
0x00, severity::INFO);
//! [EXPORT] : [COMMENT] Cycle counter set. P1: First two bytes new Cycle Count X //! [EXPORT] : [COMMENT] Cycle counter set. P1: First two bytes new Cycle Count X
//! P1: Second two bytes new Cycle Count Y //! P1: Second two bytes new Cycle Count Y
//! P2: New cycle count Z //! P2: New cycle count Z
static constexpr Event cycleCountersSet = event::makeEvent( static constexpr Event cycleCountersSet =
SUBSYSTEM_ID::MGM_RM3100, 0x01, severity::INFO); event::makeEvent(SUBSYSTEM_ID::MGM_RM3100, 0x01, severity::INFO);
MgmRM3100Handler(object_id_t objectId, object_id_t deviceCommunication, MgmRM3100Handler(object_id_t objectId, object_id_t deviceCommunication, CookieIF *comCookie,
CookieIF* comCookie, uint32_t transitionDelay); uint32_t transitionDelay);
virtual ~MgmRM3100Handler(); virtual ~MgmRM3100Handler();
/** /**
@ -41,17 +40,15 @@ public:
void setToGoToNormalMode(bool enable); void setToGoToNormalMode(bool enable);
protected: protected:
/* DeviceHandlerBase overrides */ /* DeviceHandlerBase overrides */
ReturnValue_t buildTransitionDeviceCommand( ReturnValue_t buildTransitionDeviceCommand(DeviceCommandId_t *id) override;
DeviceCommandId_t *id) override;
void doStartUp() override; void doStartUp() override;
void doShutDown() override; void doShutDown() override;
ReturnValue_t buildNormalDeviceCommand(DeviceCommandId_t *id) override; ReturnValue_t buildNormalDeviceCommand(DeviceCommandId_t *id) override;
ReturnValue_t buildCommandFromCommand(DeviceCommandId_t deviceCommand, ReturnValue_t buildCommandFromCommand(DeviceCommandId_t deviceCommand, const uint8_t *commandData,
const uint8_t *commandData, size_t commandDataLen) override; size_t commandDataLen) override;
ReturnValue_t scanForReply(const uint8_t *start, size_t len, ReturnValue_t scanForReply(const uint8_t *start, size_t len, DeviceCommandId_t *foundId,
DeviceCommandId_t *foundId, size_t *foundLen) override; size_t *foundLen) override;
ReturnValue_t interpretDeviceReply(DeviceCommandId_t id, const uint8_t *packet) override; ReturnValue_t interpretDeviceReply(DeviceCommandId_t id, const uint8_t *packet) override;
void fillCommandAndReplyMap() override; void fillCommandAndReplyMap() override;
@ -61,7 +58,6 @@ protected:
LocalDataPoolManager &poolManager) override; LocalDataPoolManager &poolManager) override;
private: private:
enum class InternalState { enum class InternalState {
NONE, NONE,
CONFIGURE_CMM, CONFIGURE_CMM,
@ -95,11 +91,11 @@ private:
ReturnValue_t handleCycleCountConfigCommand(DeviceCommandId_t deviceCommand, ReturnValue_t handleCycleCountConfigCommand(DeviceCommandId_t deviceCommand,
const uint8_t *commandData, size_t commandDataLen); const uint8_t *commandData, size_t commandDataLen);
ReturnValue_t handleCycleCommand(bool oneCycleValue, ReturnValue_t handleCycleCommand(bool oneCycleValue, const uint8_t *commandData,
const uint8_t *commandData, size_t commandDataLen); size_t commandDataLen);
ReturnValue_t handleTmrcConfigCommand(DeviceCommandId_t deviceCommand, ReturnValue_t handleTmrcConfigCommand(DeviceCommandId_t deviceCommand, const uint8_t *commandData,
const uint8_t *commandData,size_t commandDataLen); size_t commandDataLen);
ReturnValue_t handleDataReadout(const uint8_t *packet); ReturnValue_t handleDataReadout(const uint8_t *packet);
#if FSFW_HAL_RM3100_MGM_DEBUG == 1 #if FSFW_HAL_RM3100_MGM_DEBUG == 1

View File

@ -3,6 +3,7 @@
#include <fsfw/datapoollocal/StaticLocalDataSet.h> #include <fsfw/datapoollocal/StaticLocalDataSet.h>
#include <fsfw/devicehandlers/DeviceHandlerIF.h> #include <fsfw/devicehandlers/DeviceHandlerIF.h>
#include <cstdint> #include <cstdint>
namespace L3GD20H { namespace L3GD20H {
@ -36,8 +37,8 @@ static constexpr uint8_t SET_Z_ENABLE = 1 << 2;
static constexpr uint8_t SET_X_ENABLE = 1 << 1; static constexpr uint8_t SET_X_ENABLE = 1 << 1;
static constexpr uint8_t SET_Y_ENABLE = 1; static constexpr uint8_t SET_Y_ENABLE = 1;
static constexpr uint8_t CTRL_REG_1_VAL = SET_POWER_NORMAL_MODE | SET_Z_ENABLE | static constexpr uint8_t CTRL_REG_1_VAL =
SET_Y_ENABLE | SET_X_ENABLE; SET_POWER_NORMAL_MODE | SET_Z_ENABLE | SET_Y_ENABLE | SET_X_ENABLE;
/* Register 2 */ /* Register 2 */
static constexpr uint8_t EXTERNAL_EDGE_ENB = 1 << 7; static constexpr uint8_t EXTERNAL_EDGE_ENB = 1 << 7;
@ -104,40 +105,29 @@ static constexpr DeviceCommandId_t READ_CTRL_REGS = 2;
static constexpr uint32_t GYRO_DATASET_ID = READ_REGS; static constexpr uint32_t GYRO_DATASET_ID = READ_REGS;
enum GyroPoolIds: lp_id_t { enum GyroPoolIds : lp_id_t { ANG_VELOC_X, ANG_VELOC_Y, ANG_VELOC_Z, TEMPERATURE };
ANG_VELOC_X,
ANG_VELOC_Y,
ANG_VELOC_Z,
TEMPERATURE
};
} } // namespace L3GD20H
class GyroPrimaryDataset : public StaticLocalDataSet<5> { class GyroPrimaryDataset : public StaticLocalDataSet<5> {
public: public:
/** Constructor for data users like controllers */ /** Constructor for data users like controllers */
GyroPrimaryDataset(object_id_t mgmId): GyroPrimaryDataset(object_id_t mgmId)
StaticLocalDataSet(sid_t(mgmId, L3GD20H::GYRO_DATASET_ID)) { : StaticLocalDataSet(sid_t(mgmId, L3GD20H::GYRO_DATASET_ID)) {
setAllVariablesReadOnly(); setAllVariablesReadOnly();
} }
/* Angular velocities in degrees per second (DPS) */ /* Angular velocities in degrees per second (DPS) */
lp_var_t<float> angVelocX = lp_var_t<float>(sid.objectId, lp_var_t<float> angVelocX = lp_var_t<float>(sid.objectId, L3GD20H::ANG_VELOC_X, this);
L3GD20H::ANG_VELOC_X, this); lp_var_t<float> angVelocY = lp_var_t<float>(sid.objectId, L3GD20H::ANG_VELOC_Y, this);
lp_var_t<float> angVelocY = lp_var_t<float>(sid.objectId, lp_var_t<float> angVelocZ = lp_var_t<float>(sid.objectId, L3GD20H::ANG_VELOC_Z, this);
L3GD20H::ANG_VELOC_Y, this); lp_var_t<float> temperature = lp_var_t<float>(sid.objectId, L3GD20H::TEMPERATURE, this);
lp_var_t<float> angVelocZ = lp_var_t<float>(sid.objectId,
L3GD20H::ANG_VELOC_Z, this);
lp_var_t<float> temperature = lp_var_t<float>(sid.objectId,
L3GD20H::TEMPERATURE, this);
private:
private:
friend class GyroHandlerL3GD20H; friend class GyroHandlerL3GD20H;
/** Constructor for the data creator */ /** Constructor for the data creator */
GyroPrimaryDataset(HasLocalDataPoolIF* hkOwner): GyroPrimaryDataset(HasLocalDataPoolIF* hkOwner)
StaticLocalDataSet(hkOwner, L3GD20H::GYRO_DATASET_ID) {} : StaticLocalDataSet(hkOwner, L3GD20H::GYRO_DATASET_ID) {}
}; };
#endif /* MISSION_DEVICES_DEVICEDEFINITIONS_GYROL3GD20DEFINITIONS_H_ */ #endif /* MISSION_DEVICES_DEVICEDEFINITIONS_GYROL3GD20DEFINITIONS_H_ */

View File

@ -1,26 +1,18 @@
#ifndef MISSION_DEVICES_DEVICEDEFINITIONS_MGMLIS3HANDLERDEFS_H_ #ifndef MISSION_DEVICES_DEVICEDEFINITIONS_MGMLIS3HANDLERDEFS_H_
#define MISSION_DEVICES_DEVICEDEFINITIONS_MGMLIS3HANDLERDEFS_H_ #define MISSION_DEVICES_DEVICEDEFINITIONS_MGMLIS3HANDLERDEFS_H_
#include <fsfw/datapoollocal/StaticLocalDataSet.h>
#include <fsfw/datapoollocal/LocalPoolVariable.h> #include <fsfw/datapoollocal/LocalPoolVariable.h>
#include <fsfw/datapoollocal/StaticLocalDataSet.h>
#include <fsfw/devicehandlers/DeviceHandlerIF.h> #include <fsfw/devicehandlers/DeviceHandlerIF.h>
#include <cstdint> #include <cstdint>
namespace MGMLIS3MDL { namespace MGMLIS3MDL {
enum Set { enum Set { ON, OFF };
ON, OFF enum OpMode { LOW, MEDIUM, HIGH, ULTRA };
};
enum OpMode {
LOW, MEDIUM, HIGH, ULTRA
};
enum Sensitivies: uint8_t { enum Sensitivies : uint8_t { GAUSS_4 = 4, GAUSS_8 = 8, GAUSS_12 = 12, GAUSS_16 = 16 };
GAUSS_4 = 4,
GAUSS_8 = 8,
GAUSS_12 = 12,
GAUSS_16 = 16
};
/* Actually 15, we just round up a bit */ /* Actually 15, we just round up a bit */
static constexpr size_t MAX_BUFFER_SIZE = 16; static constexpr size_t MAX_BUFFER_SIZE = 16;
@ -114,8 +106,8 @@ static const uint8_t DO2 = 4; // Output data rate bit 4
static const uint8_t OM0 = 5; // XY operating mode bit 5 static const uint8_t OM0 = 5; // XY operating mode bit 5
static const uint8_t OM1 = 6; // XY operating mode bit 6 static const uint8_t OM1 = 6; // XY operating mode bit 6
static const uint8_t TEMP_EN = 7; // Temperature sensor enable enabled = 1 static const uint8_t TEMP_EN = 7; // Temperature sensor enable enabled = 1
static const uint8_t CTRL_REG1_DEFAULT = (1 << TEMP_EN) | (1 << OM1) | static const uint8_t CTRL_REG1_DEFAULT =
(1 << DO0) | (1 << DO1) | (1 << DO2); (1 << TEMP_EN) | (1 << OM1) | (1 << DO0) | (1 << DO1) | (1 << DO2);
/* CTRL_REG2 bits */ /* CTRL_REG2 bits */
// reset configuration registers and user registers // reset configuration registers and user registers
@ -156,23 +148,16 @@ enum MgmPoolIds: lp_id_t {
class MgmPrimaryDataset : public StaticLocalDataSet<4> { class MgmPrimaryDataset : public StaticLocalDataSet<4> {
public: public:
MgmPrimaryDataset(HasLocalDataPoolIF* hkOwner): MgmPrimaryDataset(HasLocalDataPoolIF* hkOwner) : StaticLocalDataSet(hkOwner, MGM_DATA_SET_ID) {}
StaticLocalDataSet(hkOwner, MGM_DATA_SET_ID) {}
MgmPrimaryDataset(object_id_t mgmId): MgmPrimaryDataset(object_id_t mgmId) : StaticLocalDataSet(sid_t(mgmId, MGM_DATA_SET_ID)) {}
StaticLocalDataSet(sid_t(mgmId, MGM_DATA_SET_ID)) {}
lp_var_t<float> fieldStrengthX = lp_var_t<float>(sid.objectId, lp_var_t<float> fieldStrengthX = lp_var_t<float>(sid.objectId, FIELD_STRENGTH_X, this);
FIELD_STRENGTH_X, this); lp_var_t<float> fieldStrengthY = lp_var_t<float>(sid.objectId, FIELD_STRENGTH_Y, this);
lp_var_t<float> fieldStrengthY = lp_var_t<float>(sid.objectId, lp_var_t<float> fieldStrengthZ = lp_var_t<float>(sid.objectId, FIELD_STRENGTH_Z, this);
FIELD_STRENGTH_Y, this); lp_var_t<float> temperature = lp_var_t<float>(sid.objectId, TEMPERATURE_CELCIUS, this);
lp_var_t<float> fieldStrengthZ = lp_var_t<float>(sid.objectId,
FIELD_STRENGTH_Z, this);
lp_var_t<float> temperature = lp_var_t<float>(sid.objectId,
TEMPERATURE_CELCIUS, this);
}; };
} } // namespace MGMLIS3MDL
#endif /* MISSION_DEVICES_DEVICEDEFINITIONS_MGMLIS3HANDLERDEFS_H_ */ #endif /* MISSION_DEVICES_DEVICEDEFINITIONS_MGMLIS3HANDLERDEFS_H_ */

View File

@ -1,10 +1,11 @@
#ifndef MISSION_DEVICES_DEVICEDEFINITIONS_MGMHANDLERRM3100DEFINITIONS_H_ #ifndef MISSION_DEVICES_DEVICEDEFINITIONS_MGMHANDLERRM3100DEFINITIONS_H_
#define MISSION_DEVICES_DEVICEDEFINITIONS_MGMHANDLERRM3100DEFINITIONS_H_ #define MISSION_DEVICES_DEVICEDEFINITIONS_MGMHANDLERRM3100DEFINITIONS_H_
#include <fsfw/datapoollocal/StaticLocalDataSet.h>
#include <fsfw/datapoollocal/LocalPoolVariable.h> #include <fsfw/datapoollocal/LocalPoolVariable.h>
#include <fsfw/datapoollocal/StaticLocalDataSet.h>
#include <fsfw/devicehandlers/DeviceHandlerIF.h> #include <fsfw/devicehandlers/DeviceHandlerIF.h>
#include <fsfw/serialize/SerialLinkedListAdapter.h> #include <fsfw/serialize/SerialLinkedListAdapter.h>
#include <cstdint> #include <cstdint>
namespace RM3100 { namespace RM3100 {
@ -24,8 +25,8 @@ static constexpr uint8_t SET_CMM_DRDM = 1 << 2;
static constexpr uint8_t SET_CMM_START = 1; static constexpr uint8_t SET_CMM_START = 1;
static constexpr uint8_t CMM_REGISTER = 0x01; static constexpr uint8_t CMM_REGISTER = 0x01;
static constexpr uint8_t CMM_VALUE = SET_CMM_CMZ | SET_CMM_CMY | SET_CMM_CMX | static constexpr uint8_t CMM_VALUE =
SET_CMM_DRDM | SET_CMM_START; SET_CMM_CMZ | SET_CMM_CMY | SET_CMM_CMX | SET_CMM_DRDM | SET_CMM_START;
/*----------------------------------------------------------------------------*/ /*----------------------------------------------------------------------------*/
/* Cycle count register */ /* Cycle count register */
@ -33,8 +34,7 @@ static constexpr uint8_t CMM_VALUE = SET_CMM_CMZ | SET_CMM_CMY | SET_CMM_CMX |
// Default value (200) // Default value (200)
static constexpr uint8_t CYCLE_COUNT_VALUE = 0xC8; static constexpr uint8_t CYCLE_COUNT_VALUE = 0xC8;
static constexpr float DEFAULT_GAIN = static_cast<float>(CYCLE_COUNT_VALUE) / static constexpr float DEFAULT_GAIN = static_cast<float>(CYCLE_COUNT_VALUE) / 100 * 38;
100 * 38;
static constexpr uint8_t CYCLE_COUNT_START_REGISTER = 0x04; static constexpr uint8_t CYCLE_COUNT_START_REGISTER = 0x04;
/*----------------------------------------------------------------------------*/ /*----------------------------------------------------------------------------*/
@ -75,8 +75,7 @@ public:
ReturnValue_t deSerialize(const uint8_t** buffer, size_t* size, ReturnValue_t deSerialize(const uint8_t** buffer, size_t* size,
Endianness streamEndianness) override { Endianness streamEndianness) override {
ReturnValue_t result = SerialLinkedListAdapter::deSerialize(buffer, ReturnValue_t result = SerialLinkedListAdapter::deSerialize(buffer, size, streamEndianness);
size, streamEndianness);
if (oneCycleCount) { if (oneCycleCount) {
cycleCountY = cycleCountX; cycleCountY = cycleCountX;
cycleCountZ = cycleCountX; cycleCountZ = cycleCountX;
@ -110,23 +109,16 @@ enum MgmPoolIds: lp_id_t {
class Rm3100PrimaryDataset : public StaticLocalDataSet<3> { class Rm3100PrimaryDataset : public StaticLocalDataSet<3> {
public: public:
Rm3100PrimaryDataset(HasLocalDataPoolIF* hkOwner): Rm3100PrimaryDataset(HasLocalDataPoolIF* hkOwner) : StaticLocalDataSet(hkOwner, MGM_DATASET_ID) {}
StaticLocalDataSet(hkOwner, MGM_DATASET_ID) {}
Rm3100PrimaryDataset(object_id_t mgmId): Rm3100PrimaryDataset(object_id_t mgmId) : StaticLocalDataSet(sid_t(mgmId, MGM_DATASET_ID)) {}
StaticLocalDataSet(sid_t(mgmId, MGM_DATASET_ID)) {}
// Field strengths in micro Tesla. // Field strengths in micro Tesla.
lp_var_t<float> fieldStrengthX = lp_var_t<float>(sid.objectId, lp_var_t<float> fieldStrengthX = lp_var_t<float>(sid.objectId, FIELD_STRENGTH_X, this);
FIELD_STRENGTH_X, this); lp_var_t<float> fieldStrengthY = lp_var_t<float>(sid.objectId, FIELD_STRENGTH_Y, this);
lp_var_t<float> fieldStrengthY = lp_var_t<float>(sid.objectId, lp_var_t<float> fieldStrengthZ = lp_var_t<float>(sid.objectId, FIELD_STRENGTH_Z, this);
FIELD_STRENGTH_Y, this);
lp_var_t<float> fieldStrengthZ = lp_var_t<float>(sid.objectId,
FIELD_STRENGTH_Z, this);
}; };
} } // namespace RM3100
#endif /* MISSION_DEVICES_DEVICEDEFINITIONS_MGMHANDLERRM3100DEFINITIONS_H_ */ #endif /* MISSION_DEVICES_DEVICEDEFINITIONS_MGMHANDLERRM3100DEFINITIONS_H_ */

View File

@ -1,15 +1,14 @@
#include "CommandExecutor.h" #include "CommandExecutor.h"
#include "fsfw/serviceinterface.h"
#include "fsfw/container/SimpleRingBuffer.h"
#include "fsfw/container/DynamicFIFO.h"
#include <unistd.h> #include <unistd.h>
#include <cstring> #include <cstring>
CommandExecutor::CommandExecutor(const size_t maxSize): #include "fsfw/container/DynamicFIFO.h"
readVec(maxSize) { #include "fsfw/container/SimpleRingBuffer.h"
#include "fsfw/serviceinterface.h"
CommandExecutor::CommandExecutor(const size_t maxSize) : readVec(maxSize) {
waiter.events = POLLIN; waiter.events = POLLIN;
} }
@ -30,8 +29,7 @@ ReturnValue_t CommandExecutor::load(std::string command, bool blocking, bool pri
ReturnValue_t CommandExecutor::execute() { ReturnValue_t CommandExecutor::execute() {
if (state == States::IDLE) { if (state == States::IDLE) {
return NO_COMMAND_LOADED_OR_PENDING; return NO_COMMAND_LOADED_OR_PENDING;
} } else if (state == States::PENDING) {
else if(state == States::PENDING) {
return COMMAND_PENDING; return COMMAND_PENDING;
} }
currentCmdFile = popen(currentCmd.c_str(), "r"); currentCmdFile = popen(currentCmd.c_str(), "r");
@ -43,8 +41,7 @@ ReturnValue_t CommandExecutor::execute() {
ReturnValue_t result = executeBlocking(); ReturnValue_t result = executeBlocking();
state = States::IDLE; state = States::IDLE;
return result; return result;
} } else {
else {
currentFd = fileno(currentCmdFile); currentFd = fileno(currentCmdFile);
waiter.fd = currentFd; waiter.fd = currentFd;
} }
@ -65,11 +62,11 @@ ReturnValue_t CommandExecutor::close() {
void CommandExecutor::printLastError(std::string funcName) const { void CommandExecutor::printLastError(std::string funcName) const {
if (lastError != 0) { if (lastError != 0) {
#if FSFW_CPP_OSTREAM_ENABLED == 1 #if FSFW_CPP_OSTREAM_ENABLED == 1
sif::warning << funcName << " pclose failed with code " << lastError << ": " << sif::warning << funcName << " pclose failed with code " << lastError << ": "
strerror(lastError) << std::endl; << strerror(lastError) << std::endl;
#else #else
sif::printError("%s pclose failed with code %d: %s\n", sif::printError("%s pclose failed with code %d: %s\n", funcName, lastError,
funcName, lastError, strerror(lastError)); strerror(lastError));
#endif #endif
} }
} }
@ -107,13 +104,13 @@ ReturnValue_t CommandExecutor::check(bool& replyReceived) {
// Should not happen // Should not happen
#if FSFW_CPP_OSTREAM_ENABLED == 1 #if FSFW_CPP_OSTREAM_ENABLED == 1
sif::warning << "CommandExecutor::check: No bytes read " sif::warning << "CommandExecutor::check: No bytes read "
"after poll event.." << std::endl; "after poll event.."
<< std::endl;
#else #else
sif::printWarning("CommandExecutor::check: No bytes read after poll event..\n"); sif::printWarning("CommandExecutor::check: No bytes read after poll event..\n");
#endif #endif
break; break;
} } else if (readBytes > 0) {
else if(readBytes > 0) {
replyReceived = true; replyReceived = true;
if (printOutput) { if (printOutput) {
// It is assumed the command output is line terminated // It is assumed the command output is line terminated
@ -124,20 +121,18 @@ ReturnValue_t CommandExecutor::check(bool& replyReceived) {
#endif #endif
} }
if (ringBuffer != nullptr) { if (ringBuffer != nullptr) {
ringBuffer->writeData(reinterpret_cast<const uint8_t*>( ringBuffer->writeData(reinterpret_cast<const uint8_t*>(readVec.data()), readBytes);
readVec.data()), readBytes);
} }
if (sizesFifo != nullptr) { if (sizesFifo != nullptr) {
if (not sizesFifo->full()) { if (not sizesFifo->full()) {
sizesFifo->insert(readBytes); sizesFifo->insert(readBytes);
} }
} }
} } else {
else {
// Should also not happen // Should also not happen
#if FSFW_CPP_OSTREAM_ENABLED == 1 #if FSFW_CPP_OSTREAM_ENABLED == 1
sif::warning << "CommandExecutor::check: Error " << errno << ": " << sif::warning << "CommandExecutor::check: Error " << errno << ": " << strerror(errno)
strerror(errno) << std::endl; << std::endl;
#else #else
sif::printWarning("CommandExecutor::check: Error %d: %s\n", errno, strerror(errno)); sif::printWarning("CommandExecutor::check: Error %d: %s\n", errno, strerror(errno));
#endif #endif
@ -177,13 +172,12 @@ void CommandExecutor::reset() {
} }
int CommandExecutor::getLastError() const { int CommandExecutor::getLastError() const {
// See: https://stackoverflow.com/questions/808541/any-benefit-in-using-wexitstatus-macro-in-c-over-division-by-256-on-exit-statu // See:
// https://stackoverflow.com/questions/808541/any-benefit-in-using-wexitstatus-macro-in-c-over-division-by-256-on-exit-statu
return WEXITSTATUS(this->lastError); return WEXITSTATUS(this->lastError);
} }
CommandExecutor::States CommandExecutor::getCurrentState() const { CommandExecutor::States CommandExecutor::getCurrentState() const { return state; }
return state;
}
ReturnValue_t CommandExecutor::executeBlocking() { ReturnValue_t CommandExecutor::executeBlocking() {
while (fgets(readVec.data(), readVec.size(), currentCmdFile) != nullptr) { while (fgets(readVec.data(), readVec.size(), currentCmdFile) != nullptr) {

View File

@ -1,16 +1,17 @@
#ifndef FSFW_SRC_FSFW_OSAL_LINUX_COMMANDEXECUTOR_H_ #ifndef FSFW_SRC_FSFW_OSAL_LINUX_COMMANDEXECUTOR_H_
#define FSFW_SRC_FSFW_OSAL_LINUX_COMMANDEXECUTOR_H_ #define FSFW_SRC_FSFW_OSAL_LINUX_COMMANDEXECUTOR_H_
#include "fsfw/returnvalues/HasReturnvaluesIF.h"
#include "fsfw/returnvalues/FwClassIds.h"
#include <poll.h> #include <poll.h>
#include <string> #include <string>
#include <vector> #include <vector>
#include "fsfw/returnvalues/FwClassIds.h"
#include "fsfw/returnvalues/HasReturnvaluesIF.h"
class SimpleRingBuffer; class SimpleRingBuffer;
template <typename T> class DynamicFIFO; template <typename T>
class DynamicFIFO;
/** /**
* @brief Helper class to execute shell commands in blocking and non-blocking mode * @brief Helper class to execute shell commands in blocking and non-blocking mode
@ -25,11 +26,7 @@ template <typename T> class DynamicFIFO;
*/ */
class CommandExecutor { class CommandExecutor {
public: public:
enum class States { enum class States { IDLE, COMMAND_LOADED, PENDING };
IDLE,
COMMAND_LOADED,
PENDING
};
static constexpr uint8_t CLASS_ID = CLASS_ID::LINUX_OSAL; static constexpr uint8_t CLASS_ID = CLASS_ID::LINUX_OSAL;
@ -39,19 +36,15 @@ public:
//! [EXPORT] : [COMMENT] Command is pending. This will also be returned if the user tries //! [EXPORT] : [COMMENT] Command is pending. This will also be returned if the user tries
//! to load another command but a command is still pending //! to load another command but a command is still pending
static constexpr ReturnValue_t COMMAND_PENDING = static constexpr ReturnValue_t COMMAND_PENDING = HasReturnvaluesIF::makeReturnCode(CLASS_ID, 1);
HasReturnvaluesIF::makeReturnCode(CLASS_ID, 1);
//! [EXPORT] : [COMMENT] Some bytes have been read from the executing process //! [EXPORT] : [COMMENT] Some bytes have been read from the executing process
static constexpr ReturnValue_t BYTES_READ = static constexpr ReturnValue_t BYTES_READ = HasReturnvaluesIF::makeReturnCode(CLASS_ID, 2);
HasReturnvaluesIF::makeReturnCode(CLASS_ID, 2);
//! [EXPORT] : [COMMENT] Command execution failed //! [EXPORT] : [COMMENT] Command execution failed
static constexpr ReturnValue_t COMMAND_ERROR = static constexpr ReturnValue_t COMMAND_ERROR = HasReturnvaluesIF::makeReturnCode(CLASS_ID, 3);
HasReturnvaluesIF::makeReturnCode(CLASS_ID, 3);
//! [EXPORT] : [COMMENT] //! [EXPORT] : [COMMENT]
static constexpr ReturnValue_t NO_COMMAND_LOADED_OR_PENDING = static constexpr ReturnValue_t NO_COMMAND_LOADED_OR_PENDING =
HasReturnvaluesIF::makeReturnCode(CLASS_ID, 4); HasReturnvaluesIF::makeReturnCode(CLASS_ID, 4);
static constexpr ReturnValue_t PCLOSE_CALL_ERROR = static constexpr ReturnValue_t PCLOSE_CALL_ERROR = HasReturnvaluesIF::makeReturnCode(CLASS_ID, 6);
HasReturnvaluesIF::makeReturnCode(CLASS_ID, 6);
/** /**
* Constructor. Is initialized with maximum size of internal buffer to read data from the * Constructor. Is initialized with maximum size of internal buffer to read data from the
@ -115,6 +108,7 @@ public:
* commands can be loaded and executed * commands can be loaded and executed
*/ */
void reset(); void reset();
private: private:
std::string currentCmd; std::string currentCmd;
bool blocking = true; bool blocking = true;

View File

@ -1,13 +1,14 @@
#include "fsfw/FSFW.h"
#include "fsfw/serviceinterface.h"
#include "fsfw_hal/linux/UnixFileGuard.h" #include "fsfw_hal/linux/UnixFileGuard.h"
#include <cerrno> #include <cerrno>
#include <cstring> #include <cstring>
#include "fsfw/FSFW.h"
#include "fsfw/serviceinterface.h"
UnixFileGuard::UnixFileGuard(std::string device, int* fileDescriptor, int flags, UnixFileGuard::UnixFileGuard(std::string device, int* fileDescriptor, int flags,
std::string diagnosticPrefix): std::string diagnosticPrefix)
fileDescriptor(fileDescriptor) { : fileDescriptor(fileDescriptor) {
if (fileDescriptor == nullptr) { if (fileDescriptor == nullptr) {
return; return;
} }
@ -15,11 +16,11 @@ UnixFileGuard::UnixFileGuard(std::string device, int* fileDescriptor, int flags,
if (*fileDescriptor < 0) { if (*fileDescriptor < 0) {
#if FSFW_VERBOSE_LEVEL >= 1 #if FSFW_VERBOSE_LEVEL >= 1
#if FSFW_CPP_OSTREAM_ENABLED == 1 #if FSFW_CPP_OSTREAM_ENABLED == 1
sif::warning << diagnosticPrefix << ": Opening device failed with error code " << sif::warning << diagnosticPrefix << ": Opening device failed with error code " << errno << ": "
errno << ": " << strerror(errno) << std::endl; << strerror(errno) << std::endl;
#else #else
sif::printWarning("%s: Opening device failed with error code %d: %s\n", sif::printWarning("%s: Opening device failed with error code %d: %s\n", diagnosticPrefix, errno,
diagnosticPrefix, errno, strerror(errno)); strerror(errno));
#endif /* FSFW_CPP_OSTREAM_ENABLED == 1 */ #endif /* FSFW_CPP_OSTREAM_ENABLED == 1 */
#endif /* FSFW_VERBOSE_LEVEL >= 1 */ #endif /* FSFW_VERBOSE_LEVEL >= 1 */
openStatus = OPEN_FILE_FAILED; openStatus = OPEN_FILE_FAILED;
@ -32,6 +33,4 @@ UnixFileGuard::~UnixFileGuard() {
} }
} }
ReturnValue_t UnixFileGuard::getOpenResult() const { ReturnValue_t UnixFileGuard::getOpenResult() const { return openStatus; }
return openStatus;
}

View File

@ -1,13 +1,11 @@
#ifndef LINUX_UTILITY_UNIXFILEGUARD_H_ #ifndef LINUX_UTILITY_UNIXFILEGUARD_H_
#define LINUX_UTILITY_UNIXFILEGUARD_H_ #define LINUX_UTILITY_UNIXFILEGUARD_H_
#include <fsfw/returnvalues/HasReturnvaluesIF.h>
#include <string>
#include <fcntl.h> #include <fcntl.h>
#include <fsfw/returnvalues/HasReturnvaluesIF.h>
#include <unistd.h> #include <unistd.h>
#include <string>
class UnixFileGuard { class UnixFileGuard {
public: public:
@ -23,11 +21,10 @@ public:
virtual ~UnixFileGuard(); virtual ~UnixFileGuard();
ReturnValue_t getOpenResult() const; ReturnValue_t getOpenResult() const;
private: private:
int* fileDescriptor = nullptr; int* fileDescriptor = nullptr;
ReturnValue_t openStatus = HasReturnvaluesIF::RETURN_OK; ReturnValue_t openStatus = HasReturnvaluesIF::RETURN_OK;
}; };
#endif /* LINUX_UTILITY_UNIXFILEGUARD_H_ */ #endif /* LINUX_UTILITY_UNIXFILEGUARD_H_ */

View File

@ -1,16 +1,15 @@
#include "LinuxLibgpioIF.h" #include "LinuxLibgpioIF.h"
#include "fsfw_hal/common/gpio/gpioDefinitions.h" #include <gpiod.h>
#include "fsfw_hal/common/gpio/GpioCookie.h" #include <unistd.h>
#include "fsfw/serviceinterface/ServiceInterface.h"
#include <utility> #include <utility>
#include <unistd.h>
#include <gpiod.h>
LinuxLibgpioIF::LinuxLibgpioIF(object_id_t objectId) : SystemObject(objectId) { #include "fsfw/serviceinterface/ServiceInterface.h"
} #include "fsfw_hal/common/gpio/GpioCookie.h"
#include "fsfw_hal/common/gpio/gpioDefinitions.h"
LinuxLibgpioIF::LinuxLibgpioIF(object_id_t objectId) : SystemObject(objectId) {}
LinuxLibgpioIF::~LinuxLibgpioIF() { LinuxLibgpioIF::~LinuxLibgpioIF() {
for (auto& config : gpioMap) { for (auto& config : gpioMap) {
@ -96,19 +95,17 @@ ReturnValue_t LinuxLibgpioIF::configureGpioByLabel(gpioId_t gpioId,
sif::warning << "LinuxLibgpioIF::configureGpioByLabel: Failed to open gpio from gpio " sif::warning << "LinuxLibgpioIF::configureGpioByLabel: Failed to open gpio from gpio "
<< "group with label " << label << ". Gpio ID: " << gpioId << std::endl; << "group with label " << label << ". Gpio ID: " << gpioId << std::endl;
return RETURN_FAILED; return RETURN_FAILED;
} }
std::string failOutput = "label: " + label; std::string failOutput = "label: " + label;
return configureRegularGpio(gpioId, chip, gpioByLabel, failOutput); return configureRegularGpio(gpioId, chip, gpioByLabel, failOutput);
} }
ReturnValue_t LinuxLibgpioIF::configureGpioByChip(gpioId_t gpioId, ReturnValue_t LinuxLibgpioIF::configureGpioByChip(gpioId_t gpioId, GpiodRegularByChip& gpioByChip) {
GpiodRegularByChip &gpioByChip) {
std::string& chipname = gpioByChip.chipname; std::string& chipname = gpioByChip.chipname;
struct gpiod_chip* chip = gpiod_chip_open_by_name(chipname.c_str()); struct gpiod_chip* chip = gpiod_chip_open_by_name(chipname.c_str());
if (chip == nullptr) { if (chip == nullptr) {
sif::warning << "LinuxLibgpioIF::configureGpioByChip: Failed to open chip " sif::warning << "LinuxLibgpioIF::configureGpioByChip: Failed to open chip " << chipname
<< chipname << ". Gpio ID: " << gpioId << std::endl; << ". Gpio ID: " << gpioId << std::endl;
return RETURN_FAILED; return RETURN_FAILED;
} }
std::string failOutput = "chipname: " + chipname; std::string failOutput = "chipname: " + chipname;
@ -121,8 +118,8 @@ ReturnValue_t LinuxLibgpioIF::configureGpioByLineName(gpioId_t gpioId,
char chipname[MAX_CHIPNAME_LENGTH]; char chipname[MAX_CHIPNAME_LENGTH];
unsigned int lineOffset; unsigned int lineOffset;
int result = gpiod_ctxless_find_line(lineName.c_str(), chipname, MAX_CHIPNAME_LENGTH, int result =
&lineOffset); gpiod_ctxless_find_line(lineName.c_str(), chipname, MAX_CHIPNAME_LENGTH, &lineOffset);
if (result != LINE_FOUND) { if (result != LINE_FOUND) {
parseFindeLineResult(result, lineName); parseFindeLineResult(result, lineName);
return RETURN_FAILED; return RETURN_FAILED;
@ -132,8 +129,8 @@ ReturnValue_t LinuxLibgpioIF::configureGpioByLineName(gpioId_t gpioId,
struct gpiod_chip* chip = gpiod_chip_open_by_name(chipname); struct gpiod_chip* chip = gpiod_chip_open_by_name(chipname);
if (chip == nullptr) { if (chip == nullptr) {
sif::warning << "LinuxLibgpioIF::configureGpioByLineName: Failed to open chip " sif::warning << "LinuxLibgpioIF::configureGpioByLineName: Failed to open chip " << chipname
<< chipname << ". <Gpio ID: " << gpioId << std::endl; << ". <Gpio ID: " << gpioId << std::endl;
return RETURN_FAILED; return RETURN_FAILED;
} }
std::string failOutput = "line name: " + lineName; std::string failOutput = "line name: " + lineName;
@ -141,7 +138,8 @@ ReturnValue_t LinuxLibgpioIF::configureGpioByLineName(gpioId_t gpioId,
} }
ReturnValue_t LinuxLibgpioIF::configureRegularGpio(gpioId_t gpioId, struct gpiod_chip* chip, ReturnValue_t LinuxLibgpioIF::configureRegularGpio(gpioId_t gpioId, struct gpiod_chip* chip,
GpiodRegularBase& regularGpio, std::string failOutput) { GpiodRegularBase& regularGpio,
std::string failOutput) {
unsigned int lineNum; unsigned int lineNum;
gpio::Direction direction; gpio::Direction direction;
std::string consumer; std::string consumer;
@ -152,8 +150,8 @@ ReturnValue_t LinuxLibgpioIF::configureRegularGpio(gpioId_t gpioId, struct gpiod
lineHandle = gpiod_chip_get_line(chip, lineNum); lineHandle = gpiod_chip_get_line(chip, lineNum);
if (!lineHandle) { if (!lineHandle) {
sif::warning << "LinuxLibgpioIF::configureRegularGpio: Failed to open line " << std::endl; sif::warning << "LinuxLibgpioIF::configureRegularGpio: Failed to open line " << std::endl;
sif::warning << "GPIO ID: " << gpioId << ", line number: " << lineNum << sif::warning << "GPIO ID: " << gpioId << ", line number: " << lineNum << ", " << failOutput
", " << failOutput << std::endl; << std::endl;
sif::warning << "Check if Linux GPIO configuration has changed. " << std::endl; sif::warning << "Check if Linux GPIO configuration has changed. " << std::endl;
gpiod_chip_close(chip); gpiod_chip_close(chip);
return RETURN_FAILED; return RETURN_FAILED;
@ -164,8 +162,7 @@ ReturnValue_t LinuxLibgpioIF::configureRegularGpio(gpioId_t gpioId, struct gpiod
/* Configure direction and add a description to the GPIO */ /* Configure direction and add a description to the GPIO */
switch (direction) { switch (direction) {
case (gpio::OUT): { case (gpio::OUT): {
result = gpiod_line_request_output(lineHandle, consumer.c_str(), result = gpiod_line_request_output(lineHandle, consumer.c_str(), regularGpio.initValue);
regularGpio.initValue);
break; break;
} }
case (gpio::IN): { case (gpio::IN): {
@ -173,23 +170,23 @@ ReturnValue_t LinuxLibgpioIF::configureRegularGpio(gpioId_t gpioId, struct gpiod
break; break;
} }
default: { default: {
sif::error << "LinuxLibgpioIF::configureGpios: Invalid direction specified" sif::error << "LinuxLibgpioIF::configureGpios: Invalid direction specified" << std::endl;
<< std::endl;
return GPIO_INVALID_INSTANCE; return GPIO_INVALID_INSTANCE;
} }
if (result < 0) { if (result < 0) {
#if FSFW_CPP_OSTREAM_ENABLED == 1 #if FSFW_CPP_OSTREAM_ENABLED == 1
sif::error << "LinuxLibgpioIF::configureRegularGpio: Failed to request line " << sif::error << "LinuxLibgpioIF::configureRegularGpio: Failed to request line " << lineNum
lineNum << " from GPIO instance with ID: " << gpioId << std::endl; << " from GPIO instance with ID: " << gpioId << std::endl;
#else #else
sif::printError("LinuxLibgpioIF::configureRegularGpio: " sif::printError(
"Failed to request line %d from GPIO instance with ID: %d\n", lineNum, gpioId); "LinuxLibgpioIF::configureRegularGpio: "
"Failed to request line %d from GPIO instance with ID: %d\n",
lineNum, gpioId);
#endif #endif
gpiod_line_release(lineHandle); gpiod_line_release(lineHandle);
return RETURN_FAILED; return RETURN_FAILED;
} }
} }
/** /**
* Write line handle to GPIO configuration instance so it can later be used to set or * Write line handle to GPIO configuration instance so it can later be used to set or
@ -207,22 +204,21 @@ ReturnValue_t LinuxLibgpioIF::pullHigh(gpioId_t gpioId) {
} }
auto gpioType = gpioMapIter->second->gpioType; auto gpioType = gpioMapIter->second->gpioType;
if (gpioType == gpio::GpioTypes::GPIO_REGULAR_BY_CHIP if (gpioType == gpio::GpioTypes::GPIO_REGULAR_BY_CHIP or
or gpioType == gpio::GpioTypes::GPIO_REGULAR_BY_LABEL gpioType == gpio::GpioTypes::GPIO_REGULAR_BY_LABEL or
or gpioType == gpio::GpioTypes::GPIO_REGULAR_BY_LINE_NAME) { gpioType == gpio::GpioTypes::GPIO_REGULAR_BY_LINE_NAME) {
auto regularGpio = dynamic_cast<GpiodRegularBase*>(gpioMapIter->second); auto regularGpio = dynamic_cast<GpiodRegularBase*>(gpioMapIter->second);
if (regularGpio == nullptr) { if (regularGpio == nullptr) {
return GPIO_TYPE_FAILURE; return GPIO_TYPE_FAILURE;
} }
return driveGpio(gpioId, *regularGpio, gpio::HIGH); return driveGpio(gpioId, *regularGpio, gpio::HIGH);
} } else {
else {
auto gpioCallback = dynamic_cast<GpioCallback*>(gpioMapIter->second); auto gpioCallback = dynamic_cast<GpioCallback*>(gpioMapIter->second);
if (gpioCallback->callback == nullptr) { if (gpioCallback->callback == nullptr) {
return GPIO_INVALID_INSTANCE; return GPIO_INVALID_INSTANCE;
} }
gpioCallback->callback(gpioMapIter->first, gpio::GpioOperation::WRITE, gpioCallback->callback(gpioMapIter->first, gpio::GpioOperation::WRITE, gpio::Levels::HIGH,
gpio::Levels::HIGH, gpioCallback->callbackArgs); gpioCallback->callbackArgs);
return RETURN_OK; return RETURN_OK;
} }
return GPIO_TYPE_FAILURE; return GPIO_TYPE_FAILURE;
@ -240,37 +236,38 @@ ReturnValue_t LinuxLibgpioIF::pullLow(gpioId_t gpioId) {
} }
auto& gpioType = gpioMapIter->second->gpioType; auto& gpioType = gpioMapIter->second->gpioType;
if (gpioType == gpio::GpioTypes::GPIO_REGULAR_BY_CHIP if (gpioType == gpio::GpioTypes::GPIO_REGULAR_BY_CHIP or
or gpioType == gpio::GpioTypes::GPIO_REGULAR_BY_LABEL gpioType == gpio::GpioTypes::GPIO_REGULAR_BY_LABEL or
or gpioType == gpio::GpioTypes::GPIO_REGULAR_BY_LINE_NAME) { gpioType == gpio::GpioTypes::GPIO_REGULAR_BY_LINE_NAME) {
auto regularGpio = dynamic_cast<GpiodRegularBase*>(gpioMapIter->second); auto regularGpio = dynamic_cast<GpiodRegularBase*>(gpioMapIter->second);
if (regularGpio == nullptr) { if (regularGpio == nullptr) {
return GPIO_TYPE_FAILURE; return GPIO_TYPE_FAILURE;
} }
return driveGpio(gpioId, *regularGpio, gpio::LOW); return driveGpio(gpioId, *regularGpio, gpio::LOW);
} } else {
else {
auto gpioCallback = dynamic_cast<GpioCallback*>(gpioMapIter->second); auto gpioCallback = dynamic_cast<GpioCallback*>(gpioMapIter->second);
if (gpioCallback->callback == nullptr) { if (gpioCallback->callback == nullptr) {
return GPIO_INVALID_INSTANCE; return GPIO_INVALID_INSTANCE;
} }
gpioCallback->callback(gpioMapIter->first, gpio::GpioOperation::WRITE, gpioCallback->callback(gpioMapIter->first, gpio::GpioOperation::WRITE, gpio::Levels::LOW,
gpio::Levels::LOW, gpioCallback->callbackArgs); gpioCallback->callbackArgs);
return RETURN_OK; return RETURN_OK;
} }
return GPIO_TYPE_FAILURE; return GPIO_TYPE_FAILURE;
} }
ReturnValue_t LinuxLibgpioIF::driveGpio(gpioId_t gpioId, ReturnValue_t LinuxLibgpioIF::driveGpio(gpioId_t gpioId, GpiodRegularBase& regularGpio,
GpiodRegularBase& regularGpio, gpio::Levels logicLevel) { gpio::Levels logicLevel) {
int result = gpiod_line_set_value(regularGpio.lineHandle, logicLevel); int result = gpiod_line_set_value(regularGpio.lineHandle, logicLevel);
if (result < 0) { if (result < 0) {
#if FSFW_CPP_OSTREAM_ENABLED == 1 #if FSFW_CPP_OSTREAM_ENABLED == 1
sif::warning << "LinuxLibgpioIF::driveGpio: Failed to pull GPIO with ID " << gpioId << sif::warning << "LinuxLibgpioIF::driveGpio: Failed to pull GPIO with ID " << gpioId
" to logic level " << logicLevel << std::endl; << " to logic level " << logicLevel << std::endl;
#else #else
sif::printWarning("LinuxLibgpioIF::driveGpio: Failed to pull GPIO with ID %d to " sif::printWarning(
"logic level %d\n", gpioId, logicLevel); "LinuxLibgpioIF::driveGpio: Failed to pull GPIO with ID %d to "
"logic level %d\n",
gpioId, logicLevel);
#endif #endif
return DRIVE_GPIO_FAILURE; return DRIVE_GPIO_FAILURE;
} }
@ -290,22 +287,21 @@ ReturnValue_t LinuxLibgpioIF::readGpio(gpioId_t gpioId, int* gpioState) {
} }
auto gpioType = gpioMapIter->second->gpioType; auto gpioType = gpioMapIter->second->gpioType;
if (gpioType == gpio::GpioTypes::GPIO_REGULAR_BY_CHIP if (gpioType == gpio::GpioTypes::GPIO_REGULAR_BY_CHIP or
or gpioType == gpio::GpioTypes::GPIO_REGULAR_BY_LABEL gpioType == gpio::GpioTypes::GPIO_REGULAR_BY_LABEL or
or gpioType == gpio::GpioTypes::GPIO_REGULAR_BY_LINE_NAME) { gpioType == gpio::GpioTypes::GPIO_REGULAR_BY_LINE_NAME) {
auto regularGpio = dynamic_cast<GpiodRegularBase*>(gpioMapIter->second); auto regularGpio = dynamic_cast<GpiodRegularBase*>(gpioMapIter->second);
if (regularGpio == nullptr) { if (regularGpio == nullptr) {
return GPIO_TYPE_FAILURE; return GPIO_TYPE_FAILURE;
} }
*gpioState = gpiod_line_get_value(regularGpio->lineHandle); *gpioState = gpiod_line_get_value(regularGpio->lineHandle);
} } else {
else {
auto gpioCallback = dynamic_cast<GpioCallback*>(gpioMapIter->second); auto gpioCallback = dynamic_cast<GpioCallback*>(gpioMapIter->second);
if (gpioCallback->callback == nullptr) { if (gpioCallback->callback == nullptr) {
return GPIO_INVALID_INSTANCE; return GPIO_INVALID_INSTANCE;
} }
gpioCallback->callback(gpioMapIter->first, gpio::GpioOperation::READ, gpioCallback->callback(gpioMapIter->first, gpio::GpioOperation::READ, gpio::Levels::NONE,
gpio::Levels::NONE, gpioCallback->callbackArgs); gpioCallback->callbackArgs);
return RETURN_OK; return RETURN_OK;
} }
return RETURN_OK; return RETURN_OK;
@ -336,8 +332,7 @@ ReturnValue_t LinuxLibgpioIF::checkForConflicts(GpioMap& mapToAdd){
return GPIO_TYPE_FAILURE; return GPIO_TYPE_FAILURE;
} }
// Check for conflicts and remove duplicates if necessary // Check for conflicts and remove duplicates if necessary
result = checkForConflictsById(gpioConfig.first, result = checkForConflictsById(gpioConfig.first, gpioConfig.second->gpioType, mapToAdd);
gpioConfig.second->gpioType, mapToAdd);
if (result != HasReturnvaluesIF::RETURN_OK) { if (result != HasReturnvaluesIF::RETURN_OK) {
status = result; status = result;
} }
@ -345,8 +340,7 @@ ReturnValue_t LinuxLibgpioIF::checkForConflicts(GpioMap& mapToAdd){
} }
default: { default: {
#if FSFW_CPP_OSTREAM_ENABLED == 1 #if FSFW_CPP_OSTREAM_ENABLED == 1
sif::warning << "Invalid GPIO type detected for GPIO ID " << gpioConfig.first sif::warning << "Invalid GPIO type detected for GPIO ID " << gpioConfig.first << std::endl;
<< std::endl;
#else #else
sif::printWarning("Invalid GPIO type detected for GPIO ID %d\n", gpioConfig.first); sif::printWarning("Invalid GPIO type detected for GPIO ID %d\n", gpioConfig.first);
#endif #endif
@ -358,7 +352,8 @@ ReturnValue_t LinuxLibgpioIF::checkForConflicts(GpioMap& mapToAdd){
} }
ReturnValue_t LinuxLibgpioIF::checkForConflictsById(gpioId_t gpioIdToCheck, ReturnValue_t LinuxLibgpioIF::checkForConflictsById(gpioId_t gpioIdToCheck,
gpio::GpioTypes expectedType, GpioMap& mapToAdd) { gpio::GpioTypes expectedType,
GpioMap& mapToAdd) {
// Cross check with private map // Cross check with private map
gpioMapIter = gpioMap.find(gpioIdToCheck); gpioMapIter = gpioMap.find(gpioIdToCheck);
if (gpioMapIter != gpioMap.end()) { if (gpioMapIter != gpioMap.end()) {
@ -385,11 +380,13 @@ ReturnValue_t LinuxLibgpioIF::checkForConflictsById(gpioId_t gpioIdToCheck,
if (eraseDuplicateDifferentType) { if (eraseDuplicateDifferentType) {
#if FSFW_CPP_OSTREAM_ENABLED == 1 #if FSFW_CPP_OSTREAM_ENABLED == 1
sif::warning << "LinuxLibgpioIF::checkForConflicts: ID already exists for " sif::warning << "LinuxLibgpioIF::checkForConflicts: ID already exists for "
"different GPIO type " << gpioIdToCheck << "different GPIO type "
". Removing duplicate from map to add" << std::endl; << gpioIdToCheck << ". Removing duplicate from map to add" << std::endl;
#else #else
sif::printWarning("LinuxLibgpioIF::checkForConflicts: ID already exists for " sif::printWarning(
"different GPIO type %d. Removing duplicate from map to add\n", gpioIdToCheck); "LinuxLibgpioIF::checkForConflicts: ID already exists for "
"different GPIO type %d. Removing duplicate from map to add\n",
gpioIdToCheck);
#endif #endif
mapToAdd.erase(gpioIdToCheck); mapToAdd.erase(gpioIdToCheck);
return GPIO_DUPLICATE_DETECTED; return GPIO_DUPLICATE_DETECTED;
@ -398,11 +395,14 @@ ReturnValue_t LinuxLibgpioIF::checkForConflictsById(gpioId_t gpioIdToCheck,
// Remove element from map to add because a entry for this GPIO already exists // Remove element from map to add because a entry for this GPIO already exists
#if FSFW_CPP_OSTREAM_ENABLED == 1 #if FSFW_CPP_OSTREAM_ENABLED == 1
sif::warning << "LinuxLibgpioIF::checkForConflictsRegularGpio: Duplicate GPIO " sif::warning << "LinuxLibgpioIF::checkForConflictsRegularGpio: Duplicate GPIO "
"definition with ID " << gpioIdToCheck << " detected. " << "definition with ID "
"Duplicate will be removed from map to add" << std::endl; << gpioIdToCheck << " detected. "
<< "Duplicate will be removed from map to add" << std::endl;
#else #else
sif::printWarning("LinuxLibgpioIF::checkForConflictsRegularGpio: Duplicate GPIO definition " sif::printWarning(
"with ID %d detected. Duplicate will be removed from map to add\n", gpioIdToCheck); "LinuxLibgpioIF::checkForConflictsRegularGpio: Duplicate GPIO definition "
"with ID %d detected. Duplicate will be removed from map to add\n",
gpioIdToCheck);
#endif #endif
mapToAdd.erase(gpioIdToCheck); mapToAdd.erase(gpioIdToCheck);
return GPIO_DUPLICATE_DETECTED; return GPIO_DUPLICATE_DETECTED;
@ -415,28 +415,32 @@ void LinuxLibgpioIF::parseFindeLineResult(int result, std::string& lineName) {
#if FSFW_CPP_OSTREAM_ENABLED == 1 #if FSFW_CPP_OSTREAM_ENABLED == 1
case LINE_NOT_EXISTS: case LINE_NOT_EXISTS:
case LINE_ERROR: { case LINE_ERROR: {
sif::warning << "LinuxLibgpioIF::parseFindeLineResult: Line with name " << lineName << sif::warning << "LinuxLibgpioIF::parseFindeLineResult: Line with name " << lineName
" does not exist" << std::endl; << " does not exist" << std::endl;
break; break;
} }
default: { default: {
sif::warning << "LinuxLibgpioIF::parseFindeLineResult: Unknown return code for line " sif::warning << "LinuxLibgpioIF::parseFindeLineResult: Unknown return code for line "
"with name " << lineName << std::endl; "with name "
<< lineName << std::endl;
break; break;
} }
#else #else
case LINE_NOT_EXISTS: case LINE_NOT_EXISTS:
case LINE_ERROR: { case LINE_ERROR: {
sif::printWarning("LinuxLibgpioIF::parseFindeLineResult: Line with name %s " sif::printWarning(
"does not exist\n", lineName); "LinuxLibgpioIF::parseFindeLineResult: Line with name %s "
"does not exist\n",
lineName);
break; break;
} }
default: { default: {
sif::printWarning("LinuxLibgpioIF::parseFindeLineResult: Unknown return code for line " sif::printWarning(
"with name %s\n", lineName); "LinuxLibgpioIF::parseFindeLineResult: Unknown return code for line "
"with name %s\n",
lineName);
break; break;
} }
#endif #endif
} }
} }

View File

@ -1,9 +1,9 @@
#ifndef LINUX_GPIO_LINUXLIBGPIOIF_H_ #ifndef LINUX_GPIO_LINUXLIBGPIOIF_H_
#define LINUX_GPIO_LINUXLIBGPIOIF_H_ #define LINUX_GPIO_LINUXLIBGPIOIF_H_
#include "fsfw/objectmanager/SystemObject.h"
#include "fsfw/returnvalues/FwClassIds.h" #include "fsfw/returnvalues/FwClassIds.h"
#include "fsfw_hal/common/gpio/GpioIF.h" #include "fsfw_hal/common/gpio/GpioIF.h"
#include "fsfw/objectmanager/SystemObject.h"
class GpioCookie; class GpioCookie;
class GpiodRegularIF; class GpiodRegularIF;
@ -17,7 +17,6 @@ class GpiodRegularIF;
*/ */
class LinuxLibgpioIF : public GpioIF, public SystemObject { class LinuxLibgpioIF : public GpioIF, public SystemObject {
public: public:
static const uint8_t gpioRetvalId = CLASS_ID::HAL_GPIO; static const uint8_t gpioRetvalId = CLASS_ID::HAL_GPIO;
static constexpr ReturnValue_t UNKNOWN_GPIO_ID = static constexpr ReturnValue_t UNKNOWN_GPIO_ID =
@ -40,7 +39,6 @@ public:
ReturnValue_t readGpio(gpioId_t gpioId, int* gpioState) override; ReturnValue_t readGpio(gpioId_t gpioId, int* gpioState) override;
private: private:
static const size_t MAX_CHIPNAME_LENGTH = 11; static const size_t MAX_CHIPNAME_LENGTH = 11;
static const int LINE_NOT_EXISTS = 0; static const int LINE_NOT_EXISTS = 0;
static const int LINE_ERROR = -1; static const int LINE_ERROR = -1;
@ -56,13 +54,11 @@ private:
* @param gpioId The GPIO ID of the GPIO to drive. * @param gpioId The GPIO ID of the GPIO to drive.
* @param logiclevel The logic level to set. O or 1. * @param logiclevel The logic level to set. O or 1.
*/ */
ReturnValue_t driveGpio(gpioId_t gpioId, GpiodRegularBase& regularGpio, ReturnValue_t driveGpio(gpioId_t gpioId, GpiodRegularBase& regularGpio, gpio::Levels logicLevel);
gpio::Levels logicLevel);
ReturnValue_t configureGpioByLabel(gpioId_t gpioId, GpiodRegularByLabel& gpioByLabel); ReturnValue_t configureGpioByLabel(gpioId_t gpioId, GpiodRegularByLabel& gpioByLabel);
ReturnValue_t configureGpioByChip(gpioId_t gpioId, GpiodRegularByChip& gpioByChip); ReturnValue_t configureGpioByChip(gpioId_t gpioId, GpiodRegularByChip& gpioByChip);
ReturnValue_t configureGpioByLineName(gpioId_t gpioId, ReturnValue_t configureGpioByLineName(gpioId_t gpioId, GpiodRegularByLineName& gpioByLineName);
GpiodRegularByLineName &gpioByLineName);
ReturnValue_t configureRegularGpio(gpioId_t gpioId, struct gpiod_chip* chip, ReturnValue_t configureRegularGpio(gpioId_t gpioId, struct gpiod_chip* chip,
GpiodRegularBase& regularGpio, std::string failOutput); GpiodRegularBase& regularGpio, std::string failOutput);
@ -77,8 +73,7 @@ private:
*/ */
ReturnValue_t checkForConflicts(GpioMap& mapToAdd); ReturnValue_t checkForConflicts(GpioMap& mapToAdd);
ReturnValue_t checkForConflictsById(gpioId_t gpiodId, gpio::GpioTypes type, ReturnValue_t checkForConflictsById(gpioId_t gpiodId, gpio::GpioTypes type, GpioMap& mapToAdd);
GpioMap& mapToAdd);
/** /**
* @brief Performs the initial configuration of all GPIOs specified in the GpioMap mapToAdd. * @brief Performs the initial configuration of all GPIOs specified in the GpioMap mapToAdd.

View File

@ -1,27 +1,23 @@
#include "fsfw/FSFW.h"
#include "fsfw_hal/linux/i2c/I2cComIF.h" #include "fsfw_hal/linux/i2c/I2cComIF.h"
#include "fsfw_hal/linux/utility.h"
#include "fsfw_hal/linux/UnixFileGuard.h"
#include "fsfw/serviceinterface.h"
#include <unistd.h>
#include <fcntl.h>
#include <sys/ioctl.h>
#include <linux/i2c-dev.h>
#include <errno.h> #include <errno.h>
#include <fcntl.h>
#include <linux/i2c-dev.h>
#include <sys/ioctl.h>
#include <unistd.h>
#include <cstring> #include <cstring>
#include "fsfw/FSFW.h"
#include "fsfw/serviceinterface.h"
#include "fsfw_hal/linux/UnixFileGuard.h"
#include "fsfw_hal/linux/utility.h"
I2cComIF::I2cComIF(object_id_t objectId): SystemObject(objectId){ I2cComIF::I2cComIF(object_id_t objectId) : SystemObject(objectId) {}
}
I2cComIF::~I2cComIF() {} I2cComIF::~I2cComIF() {}
ReturnValue_t I2cComIF::initializeInterface(CookieIF* cookie) { ReturnValue_t I2cComIF::initializeInterface(CookieIF* cookie) {
address_t i2cAddress; address_t i2cAddress;
std::string deviceFile; std::string deviceFile;
@ -48,8 +44,9 @@ ReturnValue_t I2cComIF::initializeInterface(CookieIF* cookie) {
auto statusPair = i2cDeviceMap.emplace(i2cAddress, i2cInstance); auto statusPair = i2cDeviceMap.emplace(i2cAddress, i2cInstance);
if (not statusPair.second) { if (not statusPair.second) {
#if FSFW_CPP_OSTREAM_ENABLED == 1 #if FSFW_CPP_OSTREAM_ENABLED == 1
sif::error << "I2cComIF::initializeInterface: Failed to insert device with address " << sif::error << "I2cComIF::initializeInterface: Failed to insert device with address "
i2cAddress << "to I2C device " << "map" << std::endl; << i2cAddress << "to I2C device "
<< "map" << std::endl;
#endif #endif
return HasReturnvaluesIF::RETURN_FAILED; return HasReturnvaluesIF::RETURN_FAILED;
} }
@ -57,23 +54,20 @@ ReturnValue_t I2cComIF::initializeInterface(CookieIF* cookie) {
} }
#if FSFW_CPP_OSTREAM_ENABLED == 1 #if FSFW_CPP_OSTREAM_ENABLED == 1
sif::error << "I2cComIF::initializeInterface: Device with address " << i2cAddress << sif::error << "I2cComIF::initializeInterface: Device with address " << i2cAddress
"already in use" << std::endl; << "already in use" << std::endl;
#endif #endif
return HasReturnvaluesIF::RETURN_FAILED; return HasReturnvaluesIF::RETURN_FAILED;
} }
ReturnValue_t I2cComIF::sendMessage(CookieIF *cookie, ReturnValue_t I2cComIF::sendMessage(CookieIF* cookie, const uint8_t* sendData, size_t sendLen) {
const uint8_t *sendData, size_t sendLen) {
ReturnValue_t result; ReturnValue_t result;
int fd; int fd;
std::string deviceFile; std::string deviceFile;
if (sendData == nullptr) { if (sendData == nullptr) {
#if FSFW_CPP_OSTREAM_ENABLED == 1 #if FSFW_CPP_OSTREAM_ENABLED == 1
sif::error << "I2cComIF::sendMessage: Send Data is nullptr" sif::error << "I2cComIF::sendMessage: Send Data is nullptr" << std::endl;
<< std::endl;
#endif #endif
return HasReturnvaluesIF::RETURN_FAILED; return HasReturnvaluesIF::RETURN_FAILED;
} }
@ -113,20 +107,17 @@ ReturnValue_t I2cComIF::sendMessage(CookieIF *cookie,
if (write(fd, sendData, sendLen) != static_cast<int>(sendLen)) { if (write(fd, sendData, sendLen) != static_cast<int>(sendLen)) {
#if FSFW_CPP_OSTREAM_ENABLED == 1 #if FSFW_CPP_OSTREAM_ENABLED == 1
sif::error << "I2cComIF::sendMessage: Failed to send data to I2C " sif::error << "I2cComIF::sendMessage: Failed to send data to I2C "
"device with error code " << errno << ". Error description: " "device with error code "
<< strerror(errno) << std::endl; << errno << ". Error description: " << strerror(errno) << std::endl;
#endif #endif
return HasReturnvaluesIF::RETURN_FAILED; return HasReturnvaluesIF::RETURN_FAILED;
} }
return HasReturnvaluesIF::RETURN_OK; return HasReturnvaluesIF::RETURN_OK;
} }
ReturnValue_t I2cComIF::getSendSuccess(CookieIF *cookie) { ReturnValue_t I2cComIF::getSendSuccess(CookieIF* cookie) { return HasReturnvaluesIF::RETURN_OK; }
return HasReturnvaluesIF::RETURN_OK;
}
ReturnValue_t I2cComIF::requestReceiveMessage(CookieIF *cookie, ReturnValue_t I2cComIF::requestReceiveMessage(CookieIF* cookie, size_t requestLen) {
size_t requestLen) {
ReturnValue_t result; ReturnValue_t result;
int fd; int fd;
std::string deviceFile; std::string deviceFile;
@ -174,12 +165,13 @@ ReturnValue_t I2cComIF::requestReceiveMessage(CookieIF *cookie,
sif::error << "I2cComIF::requestReceiveMessage: Reading from I2C " sif::error << "I2cComIF::requestReceiveMessage: Reading from I2C "
<< "device failed with error code " << errno << ". Description" << "device failed with error code " << errno << ". Description"
<< " of error: " << strerror(errno) << std::endl; << " of error: " << strerror(errno) << std::endl;
sif::error << "I2cComIF::requestReceiveMessage: Read only " << readLen << " from " sif::error << "I2cComIF::requestReceiveMessage: Read only " << readLen << " from " << requestLen
<< requestLen << " bytes" << std::endl; << " bytes" << std::endl;
#endif #endif
i2cDeviceMapIter->second.replyLen = 0; i2cDeviceMapIter->second.replyLen = 0;
#if FSFW_CPP_OSTREAM_ENABLED == 1 #if FSFW_CPP_OSTREAM_ENABLED == 1
sif::debug << "I2cComIF::requestReceiveMessage: Read " << readLen << " of " << requestLen << " bytes" << std::endl; sif::debug << "I2cComIF::requestReceiveMessage: Read " << readLen << " of " << requestLen
<< " bytes" << std::endl;
#endif #endif
return HasReturnvaluesIF::RETURN_FAILED; return HasReturnvaluesIF::RETURN_FAILED;
} }
@ -188,8 +180,7 @@ ReturnValue_t I2cComIF::requestReceiveMessage(CookieIF *cookie,
return HasReturnvaluesIF::RETURN_OK; return HasReturnvaluesIF::RETURN_OK;
} }
ReturnValue_t I2cComIF::readReceivedMessage(CookieIF *cookie, ReturnValue_t I2cComIF::readReceivedMessage(CookieIF* cookie, uint8_t** buffer, size_t* size) {
uint8_t **buffer, size_t* size) {
I2cCookie* i2cCookie = dynamic_cast<I2cCookie*>(cookie); I2cCookie* i2cCookie = dynamic_cast<I2cCookie*>(cookie);
if (i2cCookie == nullptr) { if (i2cCookie == nullptr) {
#if FSFW_CPP_OSTREAM_ENABLED == 1 #if FSFW_CPP_OSTREAM_ENABLED == 1
@ -213,9 +204,8 @@ ReturnValue_t I2cComIF::readReceivedMessage(CookieIF *cookie,
return HasReturnvaluesIF::RETURN_OK; return HasReturnvaluesIF::RETURN_OK;
} }
ReturnValue_t I2cComIF::openDevice(std::string deviceFile, ReturnValue_t I2cComIF::openDevice(std::string deviceFile, address_t i2cAddress,
address_t i2cAddress, int* fileDescriptor) { int* fileDescriptor) {
if (ioctl(*fileDescriptor, I2C_SLAVE, i2cAddress) < 0) { if (ioctl(*fileDescriptor, I2C_SLAVE, i2cAddress) < 0) {
#if FSFW_VERBOSE_LEVEL >= 1 #if FSFW_VERBOSE_LEVEL >= 1
#if FSFW_CPP_OSTREAM_ENABLED == 1 #if FSFW_CPP_OSTREAM_ENABLED == 1

View File

@ -1,13 +1,14 @@
#ifndef LINUX_I2C_I2COMIF_H_ #ifndef LINUX_I2C_I2COMIF_H_
#define LINUX_I2C_I2COMIF_H_ #define LINUX_I2C_I2COMIF_H_
#include "I2cCookie.h"
#include <fsfw/objectmanager/SystemObject.h>
#include <fsfw/devicehandlers/DeviceCommunicationIF.h> #include <fsfw/devicehandlers/DeviceCommunicationIF.h>
#include <fsfw/objectmanager/SystemObject.h>
#include <unordered_map> #include <unordered_map>
#include <vector> #include <vector>
#include "I2cCookie.h"
/** /**
* @brief This is the communication interface for I2C devices connected * @brief This is the communication interface for I2C devices connected
* to a system running a Linux OS. * to a system running a Linux OS.
@ -23,16 +24,12 @@ public:
virtual ~I2cComIF(); virtual ~I2cComIF();
ReturnValue_t initializeInterface(CookieIF *cookie) override; ReturnValue_t initializeInterface(CookieIF *cookie) override;
ReturnValue_t sendMessage(CookieIF *cookie,const uint8_t *sendData, ReturnValue_t sendMessage(CookieIF *cookie, const uint8_t *sendData, size_t sendLen) override;
size_t sendLen) override;
ReturnValue_t getSendSuccess(CookieIF *cookie) override; ReturnValue_t getSendSuccess(CookieIF *cookie) override;
ReturnValue_t requestReceiveMessage(CookieIF *cookie, ReturnValue_t requestReceiveMessage(CookieIF *cookie, size_t requestLen) override;
size_t requestLen) override; ReturnValue_t readReceivedMessage(CookieIF *cookie, uint8_t **buffer, size_t *size) override;
ReturnValue_t readReceivedMessage(CookieIF *cookie, uint8_t **buffer,
size_t *size) override;
private: private:
struct I2cInstance { struct I2cInstance {
std::vector<uint8_t> replyBuffer; std::vector<uint8_t> replyBuffer;
size_t replyLen; size_t replyLen;
@ -54,8 +51,7 @@ private:
* @param fileDescriptor Pointer to device descriptor. * @param fileDescriptor Pointer to device descriptor.
* @return RETURN_OK if successful, otherwise RETURN_FAILED. * @return RETURN_OK if successful, otherwise RETURN_FAILED.
*/ */
ReturnValue_t openDevice(std::string deviceFile, ReturnValue_t openDevice(std::string deviceFile, address_t i2cAddress, int *fileDescriptor);
address_t i2cAddress, int* fileDescriptor);
}; };
#endif /* LINUX_I2C_I2COMIF_H_ */ #endif /* LINUX_I2C_I2COMIF_H_ */

View File

@ -1,20 +1,12 @@
#include "fsfw_hal/linux/i2c/I2cCookie.h" #include "fsfw_hal/linux/i2c/I2cCookie.h"
I2cCookie::I2cCookie(address_t i2cAddress_, size_t maxReplyLen_, I2cCookie::I2cCookie(address_t i2cAddress_, size_t maxReplyLen_, std::string deviceFile_)
std::string deviceFile_) : : i2cAddress(i2cAddress_), maxReplyLen(maxReplyLen_), deviceFile(deviceFile_) {}
i2cAddress(i2cAddress_), maxReplyLen(maxReplyLen_), deviceFile(deviceFile_) {
}
address_t I2cCookie::getAddress() const { address_t I2cCookie::getAddress() const { return i2cAddress; }
return i2cAddress;
}
size_t I2cCookie::getMaxReplyLen() const { size_t I2cCookie::getMaxReplyLen() const { return maxReplyLen; }
return maxReplyLen;
}
std::string I2cCookie::getDeviceFile() const { std::string I2cCookie::getDeviceFile() const { return deviceFile; }
return deviceFile;
}
I2cCookie::~I2cCookie() {} I2cCookie::~I2cCookie() {}

View File

@ -2,6 +2,7 @@
#define LINUX_I2C_I2CCOOKIE_H_ #define LINUX_I2C_I2CCOOKIE_H_
#include <fsfw/devicehandlers/CookieIF.h> #include <fsfw/devicehandlers/CookieIF.h>
#include <string> #include <string>
/** /**
@ -11,7 +12,6 @@
*/ */
class I2cCookie : public CookieIF { class I2cCookie : public CookieIF {
public: public:
/** /**
* @brief Constructor for the I2C cookie. * @brief Constructor for the I2C cookie.
* @param i2cAddress_ The i2c address of the target device. * @param i2cAddress_ The i2c address of the target device.
@ -19,8 +19,7 @@ public:
* target device. * target device.
* @param devicFile_ The device file specifying the i2c interface to use. E.g. "/dev/i2c-0". * @param devicFile_ The device file specifying the i2c interface to use. E.g. "/dev/i2c-0".
*/ */
I2cCookie(address_t i2cAddress_, size_t maxReplyLen_, I2cCookie(address_t i2cAddress_, size_t maxReplyLen_, std::string deviceFile_);
std::string deviceFile_);
virtual ~I2cCookie(); virtual ~I2cCookie();
@ -29,7 +28,6 @@ public:
std::string getDeviceFile() const; std::string getDeviceFile() const;
private: private:
address_t i2cAddress = 0; address_t i2cAddress = 0;
size_t maxReplyLen = 0; size_t maxReplyLen = 0;
std::string deviceFile; std::string deviceFile;

View File

@ -1,13 +1,13 @@
#include "fsfw/FSFW.h"
#include "fsfw_hal/linux/rpi/GpioRPi.h" #include "fsfw_hal/linux/rpi/GpioRPi.h"
#include "fsfw_hal/common/gpio/GpioCookie.h"
#include <fsfw/serviceinterface/ServiceInterface.h> #include <fsfw/serviceinterface/ServiceInterface.h>
#include "fsfw/FSFW.h"
#include "fsfw_hal/common/gpio/GpioCookie.h"
ReturnValue_t gpio::createRpiGpioConfig(GpioCookie* cookie, gpioId_t gpioId, int bcmPin, ReturnValue_t gpio::createRpiGpioConfig(GpioCookie* cookie, gpioId_t gpioId, int bcmPin,
std::string consumer, gpio::Direction direction, int initValue) { std::string consumer, gpio::Direction direction,
int initValue) {
if (cookie == nullptr) { if (cookie == nullptr) {
return HasReturnvaluesIF::RETURN_FAILED; return HasReturnvaluesIF::RETURN_FAILED;
} }

View File

@ -2,6 +2,7 @@
#define BSP_RPI_GPIO_GPIORPI_H_ #define BSP_RPI_GPIO_GPIORPI_H_
#include <fsfw/returnvalues/HasReturnvaluesIF.h> #include <fsfw/returnvalues/HasReturnvaluesIF.h>
#include "../../common/gpio/gpioDefinitions.h" #include "../../common/gpio/gpioDefinitions.h"
class GpioCookie; class GpioCookie;
@ -21,6 +22,6 @@ namespace gpio {
*/ */
ReturnValue_t createRpiGpioConfig(GpioCookie* cookie, gpioId_t gpioId, int bcmPin, ReturnValue_t createRpiGpioConfig(GpioCookie* cookie, gpioId_t gpioId, int bcmPin,
std::string consumer, gpio::Direction direction, int initValue); std::string consumer, gpio::Direction direction, int initValue);
} } // namespace gpio
#endif /* BSP_RPI_GPIO_GPIORPI_H_ */ #endif /* BSP_RPI_GPIO_GPIORPI_H_ */

View File

@ -1,22 +1,22 @@
#include "fsfw/FSFW.h"
#include "fsfw_hal/linux/spi/SpiComIF.h" #include "fsfw_hal/linux/spi/SpiComIF.h"
#include "fsfw_hal/linux/spi/SpiCookie.h"
#include "fsfw_hal/linux/utility.h"
#include "fsfw_hal/linux/UnixFileGuard.h"
#include <fsfw/ipc/MutexFactory.h>
#include <fsfw/globalfunctions/arrayprinter.h>
#include <linux/spi/spidev.h>
#include <fcntl.h> #include <fcntl.h>
#include <unistd.h> #include <fsfw/globalfunctions/arrayprinter.h>
#include <fsfw/ipc/MutexFactory.h>
#include <linux/spi/spidev.h>
#include <sys/ioctl.h> #include <sys/ioctl.h>
#include <unistd.h>
#include <cerrno> #include <cerrno>
#include <cstring> #include <cstring>
SpiComIF::SpiComIF(object_id_t objectId, GpioIF* gpioComIF): #include "fsfw/FSFW.h"
SystemObject(objectId), gpioComIF(gpioComIF) { #include "fsfw_hal/linux/UnixFileGuard.h"
#include "fsfw_hal/linux/spi/SpiCookie.h"
#include "fsfw_hal/linux/utility.h"
SpiComIF::SpiComIF(object_id_t objectId, GpioIF* gpioComIF)
: SystemObject(objectId), gpioComIF(gpioComIF) {
if (gpioComIF == nullptr) { if (gpioComIF == nullptr) {
#if FSFW_VERBOSE_LEVEL >= 1 #if FSFW_VERBOSE_LEVEL >= 1
#if FSFW_CPP_OSTREAM_ENABLED == 1 #if FSFW_CPP_OSTREAM_ENABLED == 1
@ -47,11 +47,13 @@ ReturnValue_t SpiComIF::initializeInterface(CookieIF *cookie) {
if (not statusPair.second) { if (not statusPair.second) {
#if FSFW_VERBOSE_LEVEL >= 1 #if FSFW_VERBOSE_LEVEL >= 1
#if FSFW_CPP_OSTREAM_ENABLED == 1 #if FSFW_CPP_OSTREAM_ENABLED == 1
sif::error << "SpiComIF::initializeInterface: Failed to insert device with address " << sif::error << "SpiComIF::initializeInterface: Failed to insert device with address "
spiAddress << "to SPI device map" << std::endl; << spiAddress << "to SPI device map" << std::endl;
#else #else
sif::printError("SpiComIF::initializeInterface: Failed to insert device with address " sif::printError(
"%lu to SPI device map\n", static_cast<unsigned long>(spiAddress)); "SpiComIF::initializeInterface: Failed to insert device with address "
"%lu to SPI device map\n",
static_cast<unsigned long>(spiAddress));
#endif /* FSFW_CPP_OSTREAM_ENABLED == 1 */ #endif /* FSFW_CPP_OSTREAM_ENABLED == 1 */
#endif /* FSFW_VERBOSE_LEVEL >= 1 */ #endif /* FSFW_VERBOSE_LEVEL >= 1 */
return HasReturnvaluesIF::RETURN_FAILED; return HasReturnvaluesIF::RETURN_FAILED;
@ -59,8 +61,7 @@ ReturnValue_t SpiComIF::initializeInterface(CookieIF *cookie) {
/* Now we emplaced the read buffer in the map, we still need to assign that location /* Now we emplaced the read buffer in the map, we still need to assign that location
to the SPI driver transfer struct */ to the SPI driver transfer struct */
spiCookie->assignReadBuffer(statusPair.first->second.replyBuffer.data()); spiCookie->assignReadBuffer(statusPair.first->second.replyBuffer.data());
} } else {
else {
#if FSFW_VERBOSE_LEVEL >= 1 #if FSFW_VERBOSE_LEVEL >= 1
#if FSFW_CPP_OSTREAM_ENABLED == 1 #if FSFW_CPP_OSTREAM_ENABLED == 1
sif::error << "SpiComIF::initializeInterface: SPI address already exists!" << std::endl; sif::error << "SpiComIF::initializeInterface: SPI address already exists!" << std::endl;
@ -123,7 +124,8 @@ ReturnValue_t SpiComIF::initializeInterface(CookieIF *cookie) {
if (params.bitsPerWord != 8) { if (params.bitsPerWord != 8) {
retval = ioctl(fileDescriptor, SPI_IOC_WR_BITS_PER_WORD, &params.bitsPerWord); retval = ioctl(fileDescriptor, SPI_IOC_WR_BITS_PER_WORD, &params.bitsPerWord);
if (retval != 0) { if (retval != 0) {
utility::handleIoctlError("SpiComIF::initializeInterface: " utility::handleIoctlError(
"SpiComIF::initializeInterface: "
"Could not write bits per word!"); "Could not write bits per word!");
} }
} }
@ -141,11 +143,14 @@ ReturnValue_t SpiComIF::sendMessage(CookieIF *cookie, const uint8_t *sendData, s
if (sendLen > spiCookie->getMaxBufferSize()) { if (sendLen > spiCookie->getMaxBufferSize()) {
#if FSFW_VERBOSE_LEVEL >= 1 #if FSFW_VERBOSE_LEVEL >= 1
#if FSFW_CPP_OSTREAM_ENABLED == 1 #if FSFW_CPP_OSTREAM_ENABLED == 1
sif::warning << "SpiComIF::sendMessage: Too much data sent, send length " << sendLen << sif::warning << "SpiComIF::sendMessage: Too much data sent, send length " << sendLen
"larger than maximum buffer length " << spiCookie->getMaxBufferSize() << std::endl; << "larger than maximum buffer length " << spiCookie->getMaxBufferSize()
<< std::endl;
#else #else
sif::printWarning("SpiComIF::sendMessage: Too much data sent, send length %lu larger " sif::printWarning(
"than maximum buffer length %lu!\n", static_cast<unsigned long>(sendLen), "SpiComIF::sendMessage: Too much data sent, send length %lu larger "
"than maximum buffer length %lu!\n",
static_cast<unsigned long>(sendLen),
static_cast<unsigned long>(spiCookie->getMaxBufferSize())); static_cast<unsigned long>(spiCookie->getMaxBufferSize()));
#endif /* FSFW_CPP_OSTREAM_ENABLED == 1 */ #endif /* FSFW_CPP_OSTREAM_ENABLED == 1 */
#endif /* FSFW_VERBOSE_LEVEL >= 1 */ #endif /* FSFW_VERBOSE_LEVEL >= 1 */
@ -154,8 +159,7 @@ ReturnValue_t SpiComIF::sendMessage(CookieIF *cookie, const uint8_t *sendData, s
if (spiCookie->getComIfMode() == spi::SpiComIfModes::REGULAR) { if (spiCookie->getComIfMode() == spi::SpiComIfModes::REGULAR) {
result = performRegularSendOperation(spiCookie, sendData, sendLen); result = performRegularSendOperation(spiCookie, sendData, sendLen);
} } else if (spiCookie->getComIfMode() == spi::SpiComIfModes::CALLBACK) {
else if(spiCookie->getComIfMode() == spi::SpiComIfModes::CALLBACK) {
spi::send_callback_function_t sendFunc = nullptr; spi::send_callback_function_t sendFunc = nullptr;
void* funcArgs = nullptr; void* funcArgs = nullptr;
spiCookie->getCallback(&sendFunc, &funcArgs); spiCookie->getCallback(&sendFunc, &funcArgs);
@ -230,14 +234,12 @@ ReturnValue_t SpiComIF::performRegularSendOperation(SpiCookie *spiCookie, const
#if FSFW_HAL_SPI_WIRETAPPING == 1 #if FSFW_HAL_SPI_WIRETAPPING == 1
performSpiWiretapping(spiCookie); performSpiWiretapping(spiCookie);
#endif /* FSFW_LINUX_SPI_WIRETAPPING == 1 */ #endif /* FSFW_LINUX_SPI_WIRETAPPING == 1 */
} } else {
else {
/* We write with a blocking half-duplex transfer here */ /* We write with a blocking half-duplex transfer here */
if (write(fileDescriptor, sendData, sendLen) != static_cast<ssize_t>(sendLen)) { if (write(fileDescriptor, sendData, sendLen) != static_cast<ssize_t>(sendLen)) {
#if FSFW_VERBOSE_LEVEL >= 1 #if FSFW_VERBOSE_LEVEL >= 1
#if FSFW_CPP_OSTREAM_ENABLED == 1 #if FSFW_CPP_OSTREAM_ENABLED == 1
sif::warning << "SpiComIF::sendMessage: Half-Duplex write operation failed!" << sif::warning << "SpiComIF::sendMessage: Half-Duplex write operation failed!" << std::endl;
std::endl;
#else #else
sif::printWarning("SpiComIF::sendMessage: Half-Duplex write operation failed!\n"); sif::printWarning("SpiComIF::sendMessage: Half-Duplex write operation failed!\n");
#endif /* FSFW_CPP_OSTREAM_ENABLED == 1 */ #endif /* FSFW_CPP_OSTREAM_ENABLED == 1 */
@ -259,9 +261,7 @@ ReturnValue_t SpiComIF::performRegularSendOperation(SpiCookie *spiCookie, const
return result; return result;
} }
ReturnValue_t SpiComIF::getSendSuccess(CookieIF *cookie) { ReturnValue_t SpiComIF::getSendSuccess(CookieIF* cookie) { return HasReturnvaluesIF::RETURN_OK; }
return HasReturnvaluesIF::RETURN_OK;
}
ReturnValue_t SpiComIF::requestReceiveMessage(CookieIF* cookie, size_t requestLen) { ReturnValue_t SpiComIF::requestReceiveMessage(CookieIF* cookie, size_t requestLen) {
SpiCookie* spiCookie = dynamic_cast<SpiCookie*>(cookie); SpiCookie* spiCookie = dynamic_cast<SpiCookie*>(cookie);
@ -276,13 +276,11 @@ ReturnValue_t SpiComIF::requestReceiveMessage(CookieIF *cookie, size_t requestLe
return performHalfDuplexReception(spiCookie); return performHalfDuplexReception(spiCookie);
} }
ReturnValue_t SpiComIF::performHalfDuplexReception(SpiCookie* spiCookie) { ReturnValue_t SpiComIF::performHalfDuplexReception(SpiCookie* spiCookie) {
ReturnValue_t result = HasReturnvaluesIF::RETURN_OK; ReturnValue_t result = HasReturnvaluesIF::RETURN_OK;
std::string device = spiCookie->getSpiDevice(); std::string device = spiCookie->getSpiDevice();
int fileDescriptor = 0; int fileDescriptor = 0;
UnixFileGuard fileHelper(device, &fileDescriptor, O_RDWR, UnixFileGuard fileHelper(device, &fileDescriptor, O_RDWR, "SpiComIF::requestReceiveMessage");
"SpiComIF::requestReceiveMessage");
if (fileHelper.getOpenResult() != HasReturnvaluesIF::RETURN_OK) { if (fileHelper.getOpenResult() != HasReturnvaluesIF::RETURN_OK) {
return OPENING_FILE_FAILED; return OPENING_FILE_FAILED;
} }
@ -391,9 +389,7 @@ ReturnValue_t SpiComIF::getReadBuffer(address_t spiAddress, uint8_t** buffer) {
return HasReturnvaluesIF::RETURN_OK; return HasReturnvaluesIF::RETURN_OK;
} }
GpioIF* SpiComIF::getGpioInterface() { GpioIF* SpiComIF::getGpioInterface() { return gpioComIF; }
return gpioComIF;
}
void SpiComIF::setSpiSpeedAndMode(int spiFd, spi::SpiModes mode, uint32_t speed) { void SpiComIF::setSpiSpeedAndMode(int spiFd, spi::SpiModes mode, uint32_t speed) {
int retval = ioctl(spiFd, SPI_IOC_WR_MODE, reinterpret_cast<uint8_t*>(&mode)); int retval = ioctl(spiFd, SPI_IOC_WR_MODE, reinterpret_cast<uint8_t*>(&mode));

View File

@ -1,16 +1,15 @@
#ifndef LINUX_SPI_SPICOMIF_H_ #ifndef LINUX_SPI_SPICOMIF_H_
#define LINUX_SPI_SPICOMIF_H_ #define LINUX_SPI_SPICOMIF_H_
#include "fsfw/FSFW.h" #include <unordered_map>
#include "spiDefinitions.h" #include <vector>
#include "returnvalues/classIds.h"
#include "fsfw_hal/common/gpio/GpioIF.h"
#include "fsfw/FSFW.h"
#include "fsfw/devicehandlers/DeviceCommunicationIF.h" #include "fsfw/devicehandlers/DeviceCommunicationIF.h"
#include "fsfw/objectmanager/SystemObject.h" #include "fsfw/objectmanager/SystemObject.h"
#include "fsfw_hal/common/gpio/GpioIF.h"
#include <vector> #include "returnvalues/classIds.h"
#include <unordered_map> #include "spiDefinitions.h"
class SpiCookie; class SpiCookie;
@ -36,13 +35,10 @@ public:
SpiComIF(object_id_t objectId, GpioIF* gpioComIF); SpiComIF(object_id_t objectId, GpioIF* gpioComIF);
ReturnValue_t initializeInterface(CookieIF* cookie) override; ReturnValue_t initializeInterface(CookieIF* cookie) override;
ReturnValue_t sendMessage(CookieIF *cookie,const uint8_t *sendData, ReturnValue_t sendMessage(CookieIF* cookie, const uint8_t* sendData, size_t sendLen) override;
size_t sendLen) override;
ReturnValue_t getSendSuccess(CookieIF* cookie) override; ReturnValue_t getSendSuccess(CookieIF* cookie) override;
ReturnValue_t requestReceiveMessage(CookieIF *cookie, ReturnValue_t requestReceiveMessage(CookieIF* cookie, size_t requestLen) override;
size_t requestLen) override; ReturnValue_t readReceivedMessage(CookieIF* cookie, uint8_t** buffer, size_t* size) override;
ReturnValue_t readReceivedMessage(CookieIF *cookie, uint8_t **buffer,
size_t *size) override;
/** /**
* @brief This function returns the mutex which can be used to protect the spi bus when * @brief This function returns the mutex which can be used to protect the spi bus when
@ -68,7 +64,6 @@ public:
ReturnValue_t getReadBuffer(address_t spiAddress, uint8_t** buffer); ReturnValue_t getReadBuffer(address_t spiAddress, uint8_t** buffer);
private: private:
struct SpiInstance { struct SpiInstance {
SpiInstance(size_t maxRecvSize) : replyBuffer(std::vector<uint8_t>(maxRecvSize)) {} SpiInstance(size_t maxRecvSize) : replyBuffer(std::vector<uint8_t>(maxRecvSize)) {}
std::vector<uint8_t> replyBuffer; std::vector<uint8_t> replyBuffer;

View File

@ -1,35 +1,34 @@
#include "fsfw_hal/linux/spi/SpiCookie.h" #include "fsfw_hal/linux/spi/SpiCookie.h"
SpiCookie::SpiCookie(address_t spiAddress, gpioId_t chipSelect, std::string spiDev, SpiCookie::SpiCookie(address_t spiAddress, gpioId_t chipSelect, std::string spiDev,
const size_t maxSize, spi::SpiModes spiMode, uint32_t spiSpeed): const size_t maxSize, spi::SpiModes spiMode, uint32_t spiSpeed)
SpiCookie(spi::SpiComIfModes::REGULAR, spiAddress, chipSelect, spiDev, maxSize, spiMode, : SpiCookie(spi::SpiComIfModes::REGULAR, spiAddress, chipSelect, spiDev, maxSize, spiMode,
spiSpeed, nullptr, nullptr) { spiSpeed, nullptr, nullptr) {}
}
SpiCookie::SpiCookie(address_t spiAddress, std::string spiDev, const size_t maxSize, SpiCookie::SpiCookie(address_t spiAddress, std::string spiDev, const size_t maxSize,
spi::SpiModes spiMode, uint32_t spiSpeed): spi::SpiModes spiMode, uint32_t spiSpeed)
SpiCookie(spiAddress, gpio::NO_GPIO, spiDev, maxSize, spiMode, spiSpeed) { : SpiCookie(spiAddress, gpio::NO_GPIO, spiDev, maxSize, spiMode, spiSpeed) {}
}
SpiCookie::SpiCookie(address_t spiAddress, gpioId_t chipSelect, std::string spiDev, SpiCookie::SpiCookie(address_t spiAddress, gpioId_t chipSelect, std::string spiDev,
const size_t maxSize, spi::SpiModes spiMode, uint32_t spiSpeed, const size_t maxSize, spi::SpiModes spiMode, uint32_t spiSpeed,
spi::send_callback_function_t callback, void *args): spi::send_callback_function_t callback, void* args)
SpiCookie(spi::SpiComIfModes::CALLBACK, spiAddress, chipSelect, spiDev, maxSize, : SpiCookie(spi::SpiComIfModes::CALLBACK, spiAddress, chipSelect, spiDev, maxSize, spiMode,
spiMode, spiSpeed, callback, args) { spiSpeed, callback, args) {}
}
SpiCookie::SpiCookie(spi::SpiComIfModes comIfMode, address_t spiAddress, gpioId_t chipSelect, SpiCookie::SpiCookie(spi::SpiComIfModes comIfMode, address_t spiAddress, gpioId_t chipSelect,
std::string spiDev, const size_t maxSize, spi::SpiModes spiMode, uint32_t spiSpeed, std::string spiDev, const size_t maxSize, spi::SpiModes spiMode,
spi::send_callback_function_t callback, void* args): uint32_t spiSpeed, spi::send_callback_function_t callback, void* args)
spiAddress(spiAddress), chipSelectPin(chipSelect), spiDevice(spiDev), : spiAddress(spiAddress),
comIfMode(comIfMode), maxSize(maxSize), spiMode(spiMode), spiSpeed(spiSpeed), chipSelectPin(chipSelect),
sendCallback(callback), callbackArgs(args) { spiDevice(spiDev),
} comIfMode(comIfMode),
maxSize(maxSize),
spiMode(spiMode),
spiSpeed(spiSpeed),
sendCallback(callback),
callbackArgs(args) {}
spi::SpiComIfModes SpiCookie::getComIfMode() const { spi::SpiComIfModes SpiCookie::getComIfMode() const { return this->comIfMode; }
return this->comIfMode;
}
void SpiCookie::getSpiParameters(spi::SpiModes& spiMode, uint32_t& spiSpeed, void SpiCookie::getSpiParameters(spi::SpiModes& spiMode, uint32_t& spiSpeed,
UncommonParameters* parameters) const { UncommonParameters* parameters) const {
@ -45,41 +44,25 @@ void SpiCookie::getSpiParameters(spi::SpiModes& spiMode, uint32_t& spiSpeed,
} }
} }
gpioId_t SpiCookie::getChipSelectPin() const { gpioId_t SpiCookie::getChipSelectPin() const { return chipSelectPin; }
return chipSelectPin;
}
size_t SpiCookie::getMaxBufferSize() const { size_t SpiCookie::getMaxBufferSize() const { return maxSize; }
return maxSize;
}
address_t SpiCookie::getSpiAddress() const { address_t SpiCookie::getSpiAddress() const { return spiAddress; }
return spiAddress;
}
std::string SpiCookie::getSpiDevice() const { std::string SpiCookie::getSpiDevice() const { return spiDevice; }
return spiDevice;
}
void SpiCookie::setThreeWireSpi(bool enable) { void SpiCookie::setThreeWireSpi(bool enable) { uncommonParameters.threeWireSpi = enable; }
uncommonParameters.threeWireSpi = enable;
}
void SpiCookie::setLsbFirst(bool enable) { void SpiCookie::setLsbFirst(bool enable) { uncommonParameters.lsbFirst = enable; }
uncommonParameters.lsbFirst = enable;
}
void SpiCookie::setNoCs(bool enable) { void SpiCookie::setNoCs(bool enable) { uncommonParameters.noCs = enable; }
uncommonParameters.noCs = enable;
}
void SpiCookie::setBitsPerWord(uint8_t bitsPerWord) { void SpiCookie::setBitsPerWord(uint8_t bitsPerWord) {
uncommonParameters.bitsPerWord = bitsPerWord; uncommonParameters.bitsPerWord = bitsPerWord;
} }
void SpiCookie::setCsHigh(bool enable) { void SpiCookie::setCsHigh(bool enable) { uncommonParameters.csHigh = enable; }
uncommonParameters.csHigh = enable;
}
void SpiCookie::activateCsDeselect(bool deselectCs, uint16_t delayUsecs) { void SpiCookie::activateCsDeselect(bool deselectCs, uint16_t delayUsecs) {
spiTransferStruct.cs_change = deselectCs; spiTransferStruct.cs_change = deselectCs;
@ -98,47 +81,29 @@ void SpiCookie::assignWriteBuffer(const uint8_t* tx) {
} }
} }
void SpiCookie::setCallbackMode(spi::send_callback_function_t callback, void SpiCookie::setCallbackMode(spi::send_callback_function_t callback, void* args) {
void *args) {
this->comIfMode = spi::SpiComIfModes::CALLBACK; this->comIfMode = spi::SpiComIfModes::CALLBACK;
this->sendCallback = callback; this->sendCallback = callback;
this->callbackArgs = args; this->callbackArgs = args;
} }
void SpiCookie::setCallbackArgs(void *args) { void SpiCookie::setCallbackArgs(void* args) { this->callbackArgs = args; }
this->callbackArgs = args;
}
spi_ioc_transfer* SpiCookie::getTransferStructHandle() { spi_ioc_transfer* SpiCookie::getTransferStructHandle() { return &spiTransferStruct; }
return &spiTransferStruct;
}
void SpiCookie::setFullOrHalfDuplex(bool halfDuplex) { void SpiCookie::setFullOrHalfDuplex(bool halfDuplex) { this->halfDuplex = halfDuplex; }
this->halfDuplex = halfDuplex;
}
bool SpiCookie::isFullDuplex() const { bool SpiCookie::isFullDuplex() const { return not this->halfDuplex; }
return not this->halfDuplex;
}
void SpiCookie::setTransferSize(size_t transferSize) { void SpiCookie::setTransferSize(size_t transferSize) { spiTransferStruct.len = transferSize; }
spiTransferStruct.len = transferSize;
}
size_t SpiCookie::getCurrentTransferSize() const { size_t SpiCookie::getCurrentTransferSize() const { return spiTransferStruct.len; }
return spiTransferStruct.len;
}
void SpiCookie::setSpiSpeed(uint32_t newSpeed) { void SpiCookie::setSpiSpeed(uint32_t newSpeed) { this->spiSpeed = newSpeed; }
this->spiSpeed = newSpeed;
}
void SpiCookie::setSpiMode(spi::SpiModes newMode) { void SpiCookie::setSpiMode(spi::SpiModes newMode) { this->spiMode = newMode; }
this->spiMode = newMode;
}
void SpiCookie::getCallback(spi::send_callback_function_t *callback, void SpiCookie::getCallback(spi::send_callback_function_t* callback, void** args) {
void **args) {
*callback = this->sendCallback; *callback = this->sendCallback;
*args = this->callbackArgs; *args = this->callbackArgs;
} }

View File

@ -1,13 +1,12 @@
#ifndef LINUX_SPI_SPICOOKIE_H_ #ifndef LINUX_SPI_SPICOOKIE_H_
#define LINUX_SPI_SPICOOKIE_H_ #define LINUX_SPI_SPICOOKIE_H_
#include "spiDefinitions.h"
#include "../../common/gpio/gpioDefinitions.h"
#include <fsfw/devicehandlers/CookieIF.h> #include <fsfw/devicehandlers/CookieIF.h>
#include <linux/spi/spidev.h> #include <linux/spi/spidev.h>
#include "../../common/gpio/gpioDefinitions.h"
#include "spiDefinitions.h"
/** /**
* @brief This cookie class is passed to the SPI communication interface * @brief This cookie class is passed to the SPI communication interface
* @details * @details
@ -30,8 +29,8 @@ public:
* @param spiDev * @param spiDev
* @param maxSize * @param maxSize
*/ */
SpiCookie(address_t spiAddress, gpioId_t chipSelect, std::string spiDev, SpiCookie(address_t spiAddress, gpioId_t chipSelect, std::string spiDev, const size_t maxSize,
const size_t maxSize, spi::SpiModes spiMode, uint32_t spiSpeed); spi::SpiModes spiMode, uint32_t spiSpeed);
/** /**
* Like constructor above, but without a dedicated GPIO CS. Can be used for hardware * Like constructor above, but without a dedicated GPIO CS. Can be used for hardware
@ -141,8 +140,8 @@ public:
void activateCsDeselect(bool deselectCs, uint16_t delayUsecs); void activateCsDeselect(bool deselectCs, uint16_t delayUsecs);
spi_ioc_transfer* getTransferStructHandle(); spi_ioc_transfer* getTransferStructHandle();
private:
private:
/** /**
* Internal constructor which initializes every field * Internal constructor which initializes every field
* @param spiAddress * @param spiAddress
@ -178,6 +177,4 @@ private:
UncommonParameters uncommonParameters; UncommonParameters uncommonParameters;
}; };
#endif /* LINUX_SPI_SPICOOKIE_H_ */ #endif /* LINUX_SPI_SPICOOKIE_H_ */

View File

@ -1,28 +1,25 @@
#ifndef LINUX_SPI_SPIDEFINITONS_H_ #ifndef LINUX_SPI_SPIDEFINITONS_H_
#define LINUX_SPI_SPIDEFINITONS_H_ #define LINUX_SPI_SPIDEFINITONS_H_
#include "../../common/gpio/gpioDefinitions.h"
#include "../../common/spi/spiCommon.h"
#include "fsfw/returnvalues/HasReturnvaluesIF.h"
#include <linux/spi/spidev.h> #include <linux/spi/spidev.h>
#include <cstdint> #include <cstdint>
#include "../../common/gpio/gpioDefinitions.h"
#include "../../common/spi/spiCommon.h"
#include "fsfw/returnvalues/HasReturnvaluesIF.h"
class SpiCookie; class SpiCookie;
class SpiComIF; class SpiComIF;
namespace spi { namespace spi {
enum SpiComIfModes { enum SpiComIfModes { REGULAR, CALLBACK };
REGULAR,
CALLBACK
};
using send_callback_function_t = ReturnValue_t (*)(SpiComIF* comIf, SpiCookie* cookie, using send_callback_function_t = ReturnValue_t (*)(SpiComIF* comIf, SpiCookie* cookie,
const uint8_t *sendData, size_t sendLen, void* args); const uint8_t* sendData, size_t sendLen,
void* args);
} } // namespace spi
#endif /* LINUX_SPI_SPIDEFINITONS_H_ */ #endif /* LINUX_SPI_SPIDEFINITONS_H_ */

View File

@ -1,22 +1,21 @@
#include "UartComIF.h" #include "UartComIF.h"
#include "fsfw/FSFW.h"
#include "fsfw_hal/linux/utility.h"
#include "fsfw/serviceinterface.h"
#include <cstring>
#include <fcntl.h>
#include <errno.h> #include <errno.h>
#include <fcntl.h>
#include <termios.h> #include <termios.h>
#include <unistd.h> #include <unistd.h>
UartComIF::UartComIF(object_id_t objectId): SystemObject(objectId){ #include <cstring>
}
#include "fsfw/FSFW.h"
#include "fsfw/serviceinterface.h"
#include "fsfw_hal/linux/utility.h"
UartComIF::UartComIF(object_id_t objectId) : SystemObject(objectId) {}
UartComIF::~UartComIF() {} UartComIF::~UartComIF() {}
ReturnValue_t UartComIF::initializeInterface(CookieIF* cookie) { ReturnValue_t UartComIF::initializeInterface(CookieIF* cookie) {
std::string deviceFile; std::string deviceFile;
UartDeviceMapIter uartDeviceMapIter; UartDeviceMapIter uartDeviceMapIter;
@ -45,16 +44,15 @@ ReturnValue_t UartComIF::initializeInterface(CookieIF* cookie) {
auto status = uartDeviceMap.emplace(deviceFile, uartElements); auto status = uartDeviceMap.emplace(deviceFile, uartElements);
if (status.second == false) { if (status.second == false) {
#if FSFW_CPP_OSTREAM_ENABLED == 1 #if FSFW_CPP_OSTREAM_ENABLED == 1
sif::warning << "UartComIF::initializeInterface: Failed to insert device " << sif::warning << "UartComIF::initializeInterface: Failed to insert device " << deviceFile
deviceFile << "to UART device map" << std::endl; << "to UART device map" << std::endl;
#endif #endif
return RETURN_FAILED; return RETURN_FAILED;
} }
} } else {
else {
#if FSFW_CPP_OSTREAM_ENABLED == 1 #if FSFW_CPP_OSTREAM_ENABLED == 1
sif::warning << "UartComIF::initializeInterface: UART device " << deviceFile << sif::warning << "UartComIF::initializeInterface: UART device " << deviceFile
" already in use" << std::endl; << " already in use" << std::endl;
#endif #endif
return RETURN_FAILED; return RETURN_FAILED;
} }
@ -63,7 +61,6 @@ ReturnValue_t UartComIF::initializeInterface(CookieIF* cookie) {
} }
int UartComIF::configureUartPort(UartCookie* uartCookie) { int UartComIF::configureUartPort(UartCookie* uartCookie) {
struct termios options = {}; struct termios options = {};
std::string deviceFile = uartCookie->getDeviceFile(); std::string deviceFile = uartCookie->getDeviceFile();
@ -77,8 +74,8 @@ int UartComIF::configureUartPort(UartCookie* uartCookie) {
if (fd < 0) { if (fd < 0) {
#if FSFW_CPP_OSTREAM_ENABLED == 1 #if FSFW_CPP_OSTREAM_ENABLED == 1
sif::warning << "UartComIF::configureUartPort: Failed to open uart " << deviceFile << sif::warning << "UartComIF::configureUartPort: Failed to open uart " << deviceFile
"with error code " << errno << strerror(errno) << std::endl; << "with error code " << errno << strerror(errno) << std::endl;
#endif #endif
return fd; return fd;
} }
@ -86,8 +83,8 @@ int UartComIF::configureUartPort(UartCookie* uartCookie) {
/* Read in existing settings */ /* Read in existing settings */
if (tcgetattr(fd, &options) != 0) { if (tcgetattr(fd, &options) != 0) {
#if FSFW_CPP_OSTREAM_ENABLED == 1 #if FSFW_CPP_OSTREAM_ENABLED == 1
sif::warning << "UartComIF::configureUartPort: Error " << errno << "from tcgetattr: " sif::warning << "UartComIF::configureUartPort: Error " << errno
<< strerror(errno) << std::endl; << "from tcgetattr: " << strerror(errno) << std::endl;
#endif #endif
return fd; return fd;
} }
@ -110,8 +107,8 @@ int UartComIF::configureUartPort(UartCookie* uartCookie) {
/* Save option settings */ /* Save option settings */
if (tcsetattr(fd, TCSANOW, &options) != 0) { if (tcsetattr(fd, TCSANOW, &options) != 0) {
#if FSFW_CPP_OSTREAM_ENABLED == 1 #if FSFW_CPP_OSTREAM_ENABLED == 1
sif::warning << "UartComIF::configureUartPort: Failed to set options with error " << sif::warning << "UartComIF::configureUartPort: Failed to set options with error " << errno
errno << ": " << strerror(errno); << ": " << strerror(errno);
#endif #endif
return fd; return fd;
} }
@ -280,8 +277,7 @@ void UartComIF::configureBaudrate(struct termios* options, UartCookie* uartCooki
} }
} }
ReturnValue_t UartComIF::sendMessage(CookieIF *cookie, ReturnValue_t UartComIF::sendMessage(CookieIF* cookie, const uint8_t* sendData, size_t sendLen) {
const uint8_t *sendData, size_t sendLen) {
int fd = 0; int fd = 0;
std::string deviceFile; std::string deviceFile;
UartDeviceMapIter uartDeviceMapIter; UartDeviceMapIter uartDeviceMapIter;
@ -309,8 +305,8 @@ ReturnValue_t UartComIF::sendMessage(CookieIF *cookie,
uartDeviceMapIter = uartDeviceMap.find(deviceFile); uartDeviceMapIter = uartDeviceMap.find(deviceFile);
if (uartDeviceMapIter == uartDeviceMap.end()) { if (uartDeviceMapIter == uartDeviceMap.end()) {
#if FSFW_CPP_OSTREAM_ENABLED == 1 #if FSFW_CPP_OSTREAM_ENABLED == 1
sif::debug << "UartComIF::sendMessage: Device file " << deviceFile << sif::debug << "UartComIF::sendMessage: Device file " << deviceFile << "not in UART map"
"not in UART map" << std::endl; << std::endl;
#endif #endif
return RETURN_FAILED; return RETURN_FAILED;
} }
@ -319,8 +315,8 @@ ReturnValue_t UartComIF::sendMessage(CookieIF *cookie,
if (write(fd, sendData, sendLen) != static_cast<int>(sendLen)) { if (write(fd, sendData, sendLen) != static_cast<int>(sendLen)) {
#if FSFW_CPP_OSTREAM_ENABLED == 1 #if FSFW_CPP_OSTREAM_ENABLED == 1
sif::error << "UartComIF::sendMessage: Failed to send data with error code " << sif::error << "UartComIF::sendMessage: Failed to send data with error code " << errno
errno << ": Error description: " << strerror(errno) << std::endl; << ": Error description: " << strerror(errno) << std::endl;
#endif #endif
return RETURN_FAILED; return RETURN_FAILED;
} }
@ -328,9 +324,7 @@ ReturnValue_t UartComIF::sendMessage(CookieIF *cookie,
return RETURN_OK; return RETURN_OK;
} }
ReturnValue_t UartComIF::getSendSuccess(CookieIF *cookie) { ReturnValue_t UartComIF::getSendSuccess(CookieIF* cookie) { return RETURN_OK; }
return RETURN_OK;
}
ReturnValue_t UartComIF::requestReceiveMessage(CookieIF* cookie, size_t requestLen) { ReturnValue_t UartComIF::requestReceiveMessage(CookieIF* cookie, size_t requestLen) {
std::string deviceFile; std::string deviceFile;
@ -362,11 +356,9 @@ ReturnValue_t UartComIF::requestReceiveMessage(CookieIF *cookie, size_t requestL
if (uartMode == UartModes::CANONICAL) { if (uartMode == UartModes::CANONICAL) {
return handleCanonicalRead(*uartCookie, uartDeviceMapIter, requestLen); return handleCanonicalRead(*uartCookie, uartDeviceMapIter, requestLen);
} } else if (uartMode == UartModes::NON_CANONICAL) {
else if (uartMode == UartModes::NON_CANONICAL) {
return handleNoncanonicalRead(*uartCookie, uartDeviceMapIter, requestLen); return handleNoncanonicalRead(*uartCookie, uartDeviceMapIter, requestLen);
} } else {
else {
return HasReturnvaluesIF::RETURN_FAILED; return HasReturnvaluesIF::RETURN_FAILED;
} }
} }
@ -392,14 +384,14 @@ ReturnValue_t UartComIF::handleCanonicalRead(UartCookie& uartCookie, UartDeviceM
sif::warning << "UartComIF::requestReceiveMessage: Next read would cause overflow!" sif::warning << "UartComIF::requestReceiveMessage: Next read would cause overflow!"
<< std::endl; << std::endl;
#else #else
sif::printWarning("UartComIF::requestReceiveMessage: " sif::printWarning(
"UartComIF::requestReceiveMessage: "
"Next read would cause overflow!"); "Next read would cause overflow!");
#endif #endif
#endif #endif
result = UART_RX_BUFFER_TOO_SMALL; result = UART_RX_BUFFER_TOO_SMALL;
break; break;
} } else {
else {
allowedReadSize = maxReplySize - currentBytesRead; allowedReadSize = maxReplySize - currentBytesRead;
} }
@ -409,18 +401,17 @@ ReturnValue_t UartComIF::handleCanonicalRead(UartCookie& uartCookie, UartDeviceM
if (errno != EAGAIN) { if (errno != EAGAIN) {
#if FSFW_VERBOSE_LEVEL >= 1 #if FSFW_VERBOSE_LEVEL >= 1
#if FSFW_CPP_OSTREAM_ENABLED == 1 #if FSFW_CPP_OSTREAM_ENABLED == 1
sif::warning << "UartComIF::handleCanonicalRead: read failed with code" << sif::warning << "UartComIF::handleCanonicalRead: read failed with code" << errno << ": "
errno << ": " << strerror(errno) << std::endl; << strerror(errno) << std::endl;
#else #else
sif::printWarning("UartComIF::handleCanonicalRead: read failed with code %d: %s\n", sif::printWarning("UartComIF::handleCanonicalRead: read failed with code %d: %s\n", errno,
errno, strerror(errno)); strerror(errno));
#endif #endif
#endif #endif
return RETURN_FAILED; return RETURN_FAILED;
} }
} } else if (bytesRead > 0) {
else if(bytesRead > 0) {
iter->second.replyLen += bytesRead; iter->second.replyLen += bytesRead;
bufferPtr += bytesRead; bufferPtr += bytesRead;
currentBytesRead += bytesRead; currentBytesRead += bytesRead;
@ -441,7 +432,8 @@ ReturnValue_t UartComIF::handleNoncanonicalRead(UartCookie &uartCookie, UartDevi
sif::warning << "UartComIF::requestReceiveMessage: Next read would cause overflow!" sif::warning << "UartComIF::requestReceiveMessage: Next read would cause overflow!"
<< std::endl; << std::endl;
#else #else
sif::printWarning("UartComIF::requestReceiveMessage: " sif::printWarning(
"UartComIF::requestReceiveMessage: "
"Next read would cause overflow!"); "Next read would cause overflow!");
#endif #endif
#endif #endif
@ -450,12 +442,11 @@ ReturnValue_t UartComIF::handleNoncanonicalRead(UartCookie &uartCookie, UartDevi
int bytesRead = read(fd, bufferPtr, requestLen); int bytesRead = read(fd, bufferPtr, requestLen);
if (bytesRead < 0) { if (bytesRead < 0) {
return RETURN_FAILED; return RETURN_FAILED;
} } else if (bytesRead != static_cast<int>(requestLen)) {
else if (bytesRead != static_cast<int>(requestLen)) {
if (uartCookie.isReplySizeFixed()) { if (uartCookie.isReplySizeFixed()) {
#if FSFW_CPP_OSTREAM_ENABLED == 1 #if FSFW_CPP_OSTREAM_ENABLED == 1
sif::warning << "UartComIF::requestReceiveMessage: Only read " << bytesRead << sif::warning << "UartComIF::requestReceiveMessage: Only read " << bytesRead << " of "
" of " << requestLen << " bytes" << std::endl; << requestLen << " bytes" << std::endl;
#endif #endif
return RETURN_FAILED; return RETURN_FAILED;
} }
@ -464,9 +455,7 @@ ReturnValue_t UartComIF::handleNoncanonicalRead(UartCookie &uartCookie, UartDevi
return HasReturnvaluesIF::RETURN_OK; return HasReturnvaluesIF::RETURN_OK;
} }
ReturnValue_t UartComIF::readReceivedMessage(CookieIF *cookie, ReturnValue_t UartComIF::readReceivedMessage(CookieIF* cookie, uint8_t** buffer, size_t* size) {
uint8_t **buffer, size_t* size) {
std::string deviceFile; std::string deviceFile;
UartDeviceMapIter uartDeviceMapIter; UartDeviceMapIter uartDeviceMapIter;
@ -482,8 +471,8 @@ ReturnValue_t UartComIF::readReceivedMessage(CookieIF *cookie,
uartDeviceMapIter = uartDeviceMap.find(deviceFile); uartDeviceMapIter = uartDeviceMap.find(deviceFile);
if (uartDeviceMapIter == uartDeviceMap.end()) { if (uartDeviceMapIter == uartDeviceMap.end()) {
#if FSFW_CPP_OSTREAM_ENABLED == 1 #if FSFW_CPP_OSTREAM_ENABLED == 1
sif::debug << "UartComIF::readReceivedMessage: Device file " << deviceFile << sif::debug << "UartComIF::readReceivedMessage: Device file " << deviceFile << " not in uart map"
" not in uart map" << std::endl; << std::endl;
#endif #endif
return RETURN_FAILED; return RETURN_FAILED;
} }
@ -562,8 +551,7 @@ void UartComIF::setUartMode(struct termios *options, UartCookie &uartCookie) {
if (uartMode == UartModes::NON_CANONICAL) { if (uartMode == UartModes::NON_CANONICAL) {
/* Disable canonical mode */ /* Disable canonical mode */
options->c_lflag &= ~ICANON; options->c_lflag &= ~ICANON;
} } else if (uartMode == UartModes::CANONICAL) {
else if(uartMode == UartModes::CANONICAL) {
options->c_lflag |= ICANON; options->c_lflag |= ICANON;
} }
} }

View File

@ -1,13 +1,14 @@
#ifndef BSP_Q7S_COMIF_UARTCOMIF_H_ #ifndef BSP_Q7S_COMIF_UARTCOMIF_H_
#define BSP_Q7S_COMIF_UARTCOMIF_H_ #define BSP_Q7S_COMIF_UARTCOMIF_H_
#include "UartCookie.h"
#include <fsfw/objectmanager/SystemObject.h>
#include <fsfw/devicehandlers/DeviceCommunicationIF.h> #include <fsfw/devicehandlers/DeviceCommunicationIF.h>
#include <fsfw/objectmanager/SystemObject.h>
#include <unordered_map> #include <unordered_map>
#include <vector> #include <vector>
#include "UartCookie.h"
/** /**
* @brief This is the communication interface to access serial ports on linux based operating * @brief This is the communication interface to access serial ports on linux based operating
* systems. * systems.
@ -33,13 +34,10 @@ public:
virtual ~UartComIF(); virtual ~UartComIF();
ReturnValue_t initializeInterface(CookieIF* cookie) override; ReturnValue_t initializeInterface(CookieIF* cookie) override;
ReturnValue_t sendMessage(CookieIF *cookie,const uint8_t *sendData, ReturnValue_t sendMessage(CookieIF* cookie, const uint8_t* sendData, size_t sendLen) override;
size_t sendLen) override;
ReturnValue_t getSendSuccess(CookieIF* cookie) override; ReturnValue_t getSendSuccess(CookieIF* cookie) override;
ReturnValue_t requestReceiveMessage(CookieIF *cookie, ReturnValue_t requestReceiveMessage(CookieIF* cookie, size_t requestLen) override;
size_t requestLen) override; ReturnValue_t readReceivedMessage(CookieIF* cookie, uint8_t** buffer, size_t* size) override;
ReturnValue_t readReceivedMessage(CookieIF *cookie, uint8_t **buffer,
size_t *size) override;
/** /**
* @brief This function discards all data received but not read in the UART buffer. * @brief This function discards all data received but not read in the UART buffer.
@ -57,7 +55,6 @@ public:
ReturnValue_t flushUartTxAndRxBuf(CookieIF* cookie); ReturnValue_t flushUartTxAndRxBuf(CookieIF* cookie);
private: private:
using UartDeviceFile_t = std::string; using UartDeviceFile_t = std::string;
struct UartElements { struct UartElements {
@ -119,7 +116,6 @@ private:
size_t requestLen); size_t requestLen);
ReturnValue_t handleNoncanonicalRead(UartCookie& uartCookie, UartDeviceMapIter& iter, ReturnValue_t handleNoncanonicalRead(UartCookie& uartCookie, UartDeviceMapIter& iter,
size_t requestLen); size_t requestLen);
}; };
#endif /* BSP_Q7S_COMIF_UARTCOMIF_H_ */ #endif /* BSP_Q7S_COMIF_UARTCOMIF_H_ */

View File

@ -3,36 +3,26 @@
#include <fsfw/serviceinterface.h> #include <fsfw/serviceinterface.h>
UartCookie::UartCookie(object_id_t handlerId, std::string deviceFile, UartModes uartMode, UartCookie::UartCookie(object_id_t handlerId, std::string deviceFile, UartModes uartMode,
uint32_t baudrate, size_t maxReplyLen): uint32_t baudrate, size_t maxReplyLen)
handlerId(handlerId), deviceFile(deviceFile), uartMode(uartMode), : handlerId(handlerId),
baudrate(baudrate), maxReplyLen(maxReplyLen) { deviceFile(deviceFile),
} uartMode(uartMode),
baudrate(baudrate),
maxReplyLen(maxReplyLen) {}
UartCookie::~UartCookie() {} UartCookie::~UartCookie() {}
uint32_t UartCookie::getBaudrate() const { uint32_t UartCookie::getBaudrate() const { return baudrate; }
return baudrate;
}
size_t UartCookie::getMaxReplyLen() const { size_t UartCookie::getMaxReplyLen() const { return maxReplyLen; }
return maxReplyLen;
}
std::string UartCookie::getDeviceFile() const { std::string UartCookie::getDeviceFile() const { return deviceFile; }
return deviceFile;
}
void UartCookie::setParityOdd() { void UartCookie::setParityOdd() { parity = Parity::ODD; }
parity = Parity::ODD;
}
void UartCookie::setParityEven() { void UartCookie::setParityEven() { parity = Parity::EVEN; }
parity = Parity::EVEN;
}
Parity UartCookie::getParity() const { Parity UartCookie::getParity() const { return parity; }
return parity;
}
void UartCookie::setBitsPerWord(uint8_t bitsPerWord_) { void UartCookie::setBitsPerWord(uint8_t bitsPerWord_) {
switch (bitsPerWord_) { switch (bitsPerWord_) {
@ -50,50 +40,26 @@ void UartCookie::setBitsPerWord(uint8_t bitsPerWord_) {
bitsPerWord = bitsPerWord_; bitsPerWord = bitsPerWord_;
} }
uint8_t UartCookie::getBitsPerWord() const { uint8_t UartCookie::getBitsPerWord() const { return bitsPerWord; }
return bitsPerWord;
}
StopBits UartCookie::getStopBits() const { StopBits UartCookie::getStopBits() const { return stopBits; }
return stopBits;
}
void UartCookie::setTwoStopBits() { void UartCookie::setTwoStopBits() { stopBits = StopBits::TWO_STOP_BITS; }
stopBits = StopBits::TWO_STOP_BITS;
}
void UartCookie::setOneStopBit() { void UartCookie::setOneStopBit() { stopBits = StopBits::ONE_STOP_BIT; }
stopBits = StopBits::ONE_STOP_BIT;
}
UartModes UartCookie::getUartMode() const { UartModes UartCookie::getUartMode() const { return uartMode; }
return uartMode;
}
void UartCookie::setReadCycles(uint8_t readCycles) { void UartCookie::setReadCycles(uint8_t readCycles) { this->readCycles = readCycles; }
this->readCycles = readCycles;
}
void UartCookie::setToFlushInput(bool enable) { void UartCookie::setToFlushInput(bool enable) { this->flushInput = enable; }
this->flushInput = enable;
}
uint8_t UartCookie::getReadCycles() const { uint8_t UartCookie::getReadCycles() const { return readCycles; }
return readCycles;
}
bool UartCookie::getInputShouldBeFlushed() { bool UartCookie::getInputShouldBeFlushed() { return this->flushInput; }
return this->flushInput;
}
object_id_t UartCookie::getHandlerId() const { object_id_t UartCookie::getHandlerId() const { return this->handlerId; }
return this->handlerId;
}
void UartCookie::setNoFixedSizeReply() { void UartCookie::setNoFixedSizeReply() { replySizeFixed = false; }
replySizeFixed = false;
}
bool UartCookie::isReplySizeFixed() { bool UartCookie::isReplySizeFixed() { return replySizeFixed; }
return replySizeFixed;
}

View File

@ -6,21 +6,11 @@
#include <string> #include <string>
enum class Parity { enum class Parity { NONE, EVEN, ODD };
NONE,
EVEN,
ODD
};
enum class StopBits { enum class StopBits { ONE_STOP_BIT, TWO_STOP_BITS };
ONE_STOP_BIT,
TWO_STOP_BITS
};
enum class UartModes { enum class UartModes { CANONICAL, NON_CANONICAL };
CANONICAL,
NON_CANONICAL
};
/** /**
* @brief Cookie for the UartComIF. There are many options available to configure the UART driver. * @brief Cookie for the UartComIF. There are many options available to configure the UART driver.
@ -31,7 +21,6 @@ enum class UartModes {
*/ */
class UartCookie : public CookieIF { class UartCookie : public CookieIF {
public: public:
/** /**
* @brief Constructor for the uart cookie. * @brief Constructor for the uart cookie.
* @param deviceFile The device file specifying the uart to use, e.g. "/dev/ttyPS1" * @param deviceFile The device file specifying the uart to use, e.g. "/dev/ttyPS1"
@ -47,8 +36,8 @@ public:
* 8 databits (number of bits transfered with one uart frame) * 8 databits (number of bits transfered with one uart frame)
* One stop bit * One stop bit
*/ */
UartCookie(object_id_t handlerId, std::string deviceFile, UartModes uartMode, UartCookie(object_id_t handlerId, std::string deviceFile, UartModes uartMode, uint32_t baudrate,
uint32_t baudrate, size_t maxReplyLen); size_t maxReplyLen);
virtual ~UartCookie(); virtual ~UartCookie();
@ -104,7 +93,6 @@ public:
bool isReplySizeFixed(); bool isReplySizeFixed();
private: private:
const object_id_t handlerId; const object_id_t handlerId;
std::string deviceFile; std::string deviceFile;
const UartModes uartMode; const UartModes uartMode;

View File

@ -1,18 +1,18 @@
#include "fsfw/FSFW.h"
#include "fsfw/serviceinterface/ServiceInterface.h"
#include "fsfw_hal/linux/utility.h" #include "fsfw_hal/linux/utility.h"
#include <cerrno> #include <cerrno>
#include <cstring> #include <cstring>
#include "fsfw/FSFW.h"
#include "fsfw/serviceinterface/ServiceInterface.h"
void utility::handleIoctlError(const char* const customPrintout) { void utility::handleIoctlError(const char* const customPrintout) {
#if FSFW_VERBOSE_LEVEL >= 1 #if FSFW_VERBOSE_LEVEL >= 1
#if FSFW_CPP_OSTREAM_ENABLED == 1 #if FSFW_CPP_OSTREAM_ENABLED == 1
if (customPrintout != nullptr) { if (customPrintout != nullptr) {
sif::warning << customPrintout << std::endl; sif::warning << customPrintout << std::endl;
} }
sif::warning << "handleIoctlError: Error code " << errno << ", "<< strerror(errno) << sif::warning << "handleIoctlError: Error code " << errno << ", " << strerror(errno) << std::endl;
std::endl;
#else #else
if (customPrintout != nullptr) { if (customPrintout != nullptr) {
sif::printWarning("%s\n", customPrintout); sif::printWarning("%s\n", customPrintout);
@ -20,7 +20,4 @@ void utility::handleIoctlError(const char* const customPrintout) {
sif::printWarning("handleIoctlError: Error code %d, %s\n", errno, strerror(errno)); sif::printWarning("handleIoctlError: Error code %d, %s\n", errno, strerror(errno));
#endif /* FSFW_CPP_OSTREAM_ENABLED == 1 */ #endif /* FSFW_CPP_OSTREAM_ENABLED == 1 */
#endif /* FSFW_VERBOSE_LEVEL >= 1 */ #endif /* FSFW_VERBOSE_LEVEL >= 1 */
} }

View File

@ -2,6 +2,7 @@
#define FSFW_HAL_STM32H7_DEFINITIONS_H_ #define FSFW_HAL_STM32H7_DEFINITIONS_H_
#include <utility> #include <utility>
#include "stm32h7xx.h" #include "stm32h7xx.h"
namespace stm32h7 { namespace stm32h7 {
@ -13,13 +14,13 @@ namespace stm32h7 {
struct GpioCfg { struct GpioCfg {
GpioCfg() : port(nullptr), pin(0), altFnc(0){}; GpioCfg() : port(nullptr), pin(0), altFnc(0){};
GpioCfg(GPIO_TypeDef* port, uint16_t pin, uint8_t altFnc = 0): GpioCfg(GPIO_TypeDef* port, uint16_t pin, uint8_t altFnc = 0)
port(port), pin(pin), altFnc(altFnc) {}; : port(port), pin(pin), altFnc(altFnc){};
GPIO_TypeDef* port; GPIO_TypeDef* port;
uint16_t pin; uint16_t pin;
uint8_t altFnc; uint8_t altFnc;
}; };
} } // namespace stm32h7
#endif /* #ifndef FSFW_HAL_STM32H7_DEFINITIONS_H_ */ #endif /* #ifndef FSFW_HAL_STM32H7_DEFINITIONS_H_ */

View File

@ -1,29 +1,26 @@
#include "fsfw_hal/stm32h7/devicetest/GyroL3GD20H.h" #include "fsfw_hal/stm32h7/devicetest/GyroL3GD20H.h"
#include "fsfw_hal/stm32h7/spi/mspInit.h"
#include "fsfw_hal/stm32h7/spi/spiDefinitions.h"
#include "fsfw_hal/stm32h7/spi/spiCore.h"
#include "fsfw_hal/stm32h7/spi/spiInterrupts.h"
#include "fsfw_hal/stm32h7/spi/stm32h743zi.h"
#include "fsfw/tasks/TaskFactory.h"
#include "fsfw/serviceinterface/ServiceInterface.h"
#include "stm32h7xx_hal_spi.h"
#include "stm32h7xx_hal_rcc.h"
#include <cstring> #include <cstring>
#include "fsfw/serviceinterface/ServiceInterface.h"
#include "fsfw/tasks/TaskFactory.h"
#include "fsfw_hal/stm32h7/spi/mspInit.h"
#include "fsfw_hal/stm32h7/spi/spiCore.h"
#include "fsfw_hal/stm32h7/spi/spiDefinitions.h"
#include "fsfw_hal/stm32h7/spi/spiInterrupts.h"
#include "fsfw_hal/stm32h7/spi/stm32h743zi.h"
#include "stm32h7xx_hal_rcc.h"
#include "stm32h7xx_hal_spi.h"
alignas(32) std::array<uint8_t, GyroL3GD20H::recvBufferSize> GyroL3GD20H::rxBuffer; alignas(32) std::array<uint8_t, GyroL3GD20H::recvBufferSize> GyroL3GD20H::rxBuffer;
alignas(32) std::array<uint8_t, GyroL3GD20H::txBufferSize> alignas(32) std::array<uint8_t, GyroL3GD20H::txBufferSize> GyroL3GD20H::txBuffer
GyroL3GD20H::txBuffer __attribute__((section(".dma_buffer"))); __attribute__((section(".dma_buffer")));
TransferStates transferState = TransferStates::IDLE; TransferStates transferState = TransferStates::IDLE;
spi::TransferModes GyroL3GD20H::transferMode = spi::TransferModes::POLLING; spi::TransferModes GyroL3GD20H::transferMode = spi::TransferModes::POLLING;
GyroL3GD20H::GyroL3GD20H(SPI_HandleTypeDef *spiHandle, spi::TransferModes transferMode_)
GyroL3GD20H::GyroL3GD20H(SPI_HandleTypeDef *spiHandle, spi::TransferModes transferMode_): : spiHandle(spiHandle) {
spiHandle(spiHandle) {
txDmaHandle = new DMA_HandleTypeDef(); txDmaHandle = new DMA_HandleTypeDef();
rxDmaHandle = new DMA_HandleTypeDef(); rxDmaHandle = new DMA_HandleTypeDef();
spi::setSpiHandle(spiHandle); spi::setSpiHandle(spiHandle);
@ -34,16 +31,15 @@ GyroL3GD20H::GyroL3GD20H(SPI_HandleTypeDef *spiHandle, spi::TransferModes transf
auto typedCfg = dynamic_cast<spi::MspDmaConfigStruct *>(mspCfg); auto typedCfg = dynamic_cast<spi::MspDmaConfigStruct *>(mspCfg);
spi::setDmaHandles(txDmaHandle, rxDmaHandle); spi::setDmaHandles(txDmaHandle, rxDmaHandle);
stm32h7::h743zi::standardDmaCfg(*typedCfg, IrqPriorities::HIGHEST_FREERTOS, stm32h7::h743zi::standardDmaCfg(*typedCfg, IrqPriorities::HIGHEST_FREERTOS,
IrqPriorities::HIGHEST_FREERTOS, IrqPriorities::HIGHEST_FREERTOS); IrqPriorities::HIGHEST_FREERTOS,
IrqPriorities::HIGHEST_FREERTOS);
spi::setSpiDmaMspFunctions(typedCfg); spi::setSpiDmaMspFunctions(typedCfg);
} } else if (transferMode == spi::TransferModes::INTERRUPT) {
else if(transferMode == spi::TransferModes::INTERRUPT) {
mspCfg = new spi::MspIrqConfigStruct(); mspCfg = new spi::MspIrqConfigStruct();
auto typedCfg = dynamic_cast<spi::MspIrqConfigStruct *>(mspCfg); auto typedCfg = dynamic_cast<spi::MspIrqConfigStruct *>(mspCfg);
stm32h7::h743zi::standardInterruptCfg(*typedCfg, IrqPriorities::HIGHEST_FREERTOS); stm32h7::h743zi::standardInterruptCfg(*typedCfg, IrqPriorities::HIGHEST_FREERTOS);
spi::setSpiIrqMspFunctions(typedCfg); spi::setSpiIrqMspFunctions(typedCfg);
} } else if (transferMode == spi::TransferModes::POLLING) {
else if(transferMode == spi::TransferModes::POLLING) {
mspCfg = new spi::MspPollingConfigStruct(); mspCfg = new spi::MspPollingConfigStruct();
auto typedCfg = dynamic_cast<spi::MspPollingConfigStruct *>(mspCfg); auto typedCfg = dynamic_cast<spi::MspPollingConfigStruct *>(mspCfg);
stm32h7::h743zi::standardPollingCfg(*typedCfg); stm32h7::h743zi::standardPollingCfg(*typedCfg);
@ -155,8 +151,10 @@ ReturnValue_t GyroL3GD20H::handleDmaTransferInit() {
case (TransferStates::SUCCESS): { case (TransferStates::SUCCESS): {
uint8_t whoAmIVal = rxBuffer[1]; uint8_t whoAmIVal = rxBuffer[1];
if (whoAmIVal != EXPECTED_WHO_AM_I_VAL) { if (whoAmIVal != EXPECTED_WHO_AM_I_VAL) {
sif::printDebug("GyroL3GD20H::initialize: " sif::printDebug(
"Read WHO AM I value %d not equal to expected value!\n", whoAmIVal); "GyroL3GD20H::initialize: "
"Read WHO AM I value %d not equal to expected value!\n",
whoAmIVal);
} }
transferState = TransferStates::IDLE; transferState = TransferStates::IDLE;
break; break;
@ -203,7 +201,6 @@ ReturnValue_t GyroL3GD20H::handleDmaTransferInit() {
} }
} }
txBuffer[0] = CTRL_REG_1 | STM_AUTO_INCREMENT_MASK | STM_READ_MASK; txBuffer[0] = CTRL_REG_1 | STM_AUTO_INCREMENT_MASK | STM_READ_MASK;
std::memset(txBuffer.data() + 1, 0, 5); std::memset(txBuffer.data() + 1, 0, 5);
result = performDmaTransfer(6); result = performDmaTransfer(6);
@ -222,8 +219,7 @@ ReturnValue_t GyroL3GD20H::handleDmaTransferInit() {
rxBuffer[3] != configRegs[2] or rxBuffer[4] != configRegs[3] or rxBuffer[3] != configRegs[2] or rxBuffer[4] != configRegs[3] or
rxBuffer[5] != configRegs[4]) { rxBuffer[5] != configRegs[4]) {
sif::printWarning("GyroL3GD20H::initialize: Configuration failure\n"); sif::printWarning("GyroL3GD20H::initialize: Configuration failure\n");
} } else {
else {
sif::printInfo("GyroL3GD20H::initialize: Configuration success\n"); sif::printInfo("GyroL3GD20H::initialize: Configuration success\n");
} }
transferState = TransferStates::IDLE; transferState = TransferStates::IDLE;
@ -293,8 +289,10 @@ ReturnValue_t GyroL3GD20H::handlePollingTransferInit() {
sif::printInfo("GyroL3GD20H::initialize: Polling transfer success\n"); sif::printInfo("GyroL3GD20H::initialize: Polling transfer success\n");
uint8_t whoAmIVal = rxBuffer[1]; uint8_t whoAmIVal = rxBuffer[1];
if (whoAmIVal != EXPECTED_WHO_AM_I_VAL) { if (whoAmIVal != EXPECTED_WHO_AM_I_VAL) {
sif::printDebug("GyroL3GD20H::performOperation: " sif::printDebug(
"Read WHO AM I value %d not equal to expected value!\n", whoAmIVal); "GyroL3GD20H::performOperation: "
"Read WHO AM I value %d not equal to expected value!\n",
whoAmIVal);
} }
break; break;
} }
@ -348,8 +346,7 @@ ReturnValue_t GyroL3GD20H::handlePollingTransferInit() {
rxBuffer[3] != configRegs[2] or rxBuffer[4] != configRegs[3] or rxBuffer[3] != configRegs[2] or rxBuffer[4] != configRegs[3] or
rxBuffer[5] != configRegs[4]) { rxBuffer[5] != configRegs[4]) {
sif::printWarning("GyroL3GD20H::initialize: Configuration failure\n"); sif::printWarning("GyroL3GD20H::initialize: Configuration failure\n");
} } else {
else {
sif::printInfo("GyroL3GD20H::initialize: Configuration success\n"); sif::printInfo("GyroL3GD20H::initialize: Configuration success\n");
} }
break; break;
@ -408,8 +405,10 @@ ReturnValue_t GyroL3GD20H::handleInterruptTransferInit() {
uint8_t whoAmIVal = rxBuffer[1]; uint8_t whoAmIVal = rxBuffer[1];
if (whoAmIVal != EXPECTED_WHO_AM_I_VAL) { if (whoAmIVal != EXPECTED_WHO_AM_I_VAL) {
sif::printDebug("GyroL3GD20H::initialize: " sif::printDebug(
"Read WHO AM I value %d not equal to expected value!\n", whoAmIVal); "GyroL3GD20H::initialize: "
"Read WHO AM I value %d not equal to expected value!\n",
whoAmIVal);
} }
break; break;
} }
@ -457,8 +456,7 @@ ReturnValue_t GyroL3GD20H::handleInterruptTransferInit() {
rxBuffer[3] != configRegs[2] or rxBuffer[4] != configRegs[3] or rxBuffer[3] != configRegs[2] or rxBuffer[4] != configRegs[3] or
rxBuffer[5] != configRegs[4]) { rxBuffer[5] != configRegs[4]) {
sif::printWarning("GyroL3GD20H::initialize: Configuration failure\n"); sif::printWarning("GyroL3GD20H::initialize: Configuration failure\n");
} } else {
else {
sif::printInfo("GyroL3GD20H::initialize: Configuration success\n"); sif::printInfo("GyroL3GD20H::initialize: Configuration success\n");
} }
break; break;
@ -516,7 +514,8 @@ uint8_t GyroL3GD20H::readRegPolling(uint8_t reg) {
txBuf[0] = reg | STM_READ_MASK; txBuf[0] = reg | STM_READ_MASK;
HAL_GPIO_WritePin(GPIOD, GPIO_PIN_14, GPIO_PIN_RESET); HAL_GPIO_WritePin(GPIOD, GPIO_PIN_14, GPIO_PIN_RESET);
auto result = HAL_SPI_TransmitReceive(spiHandle, txBuf, rxBuf, 2, 1000); auto result = HAL_SPI_TransmitReceive(spiHandle, txBuf, rxBuf, 2, 1000);
if(result) {}; if (result) {
};
HAL_GPIO_WritePin(GPIOD, GPIO_PIN_14, GPIO_PIN_SET); HAL_GPIO_WritePin(GPIOD, GPIO_PIN_14, GPIO_PIN_SET);
return rxBuf[1]; return rxBuf[1];
} }
@ -535,7 +534,6 @@ void GyroL3GD20H::handleSensorReadout() {
sif::printInfo("Gyro Z: %f\n", gyroZ); sif::printInfo("Gyro Z: %f\n", gyroZ);
} }
void GyroL3GD20H::spiTransferCompleteCallback(SPI_HandleTypeDef *hspi, void *args) { void GyroL3GD20H::spiTransferCompleteCallback(SPI_HandleTypeDef *hspi, void *args) {
transferState = TransferStates::SUCCESS; transferState = TransferStates::SUCCESS;
HAL_GPIO_WritePin(GPIOD, GPIO_PIN_14, GPIO_PIN_SET); HAL_GPIO_WritePin(GPIOD, GPIO_PIN_14, GPIO_PIN_SET);

View File

@ -1,22 +1,16 @@
#ifndef FSFW_HAL_STM32H7_DEVICETEST_GYRO_L3GD20H_H_ #ifndef FSFW_HAL_STM32H7_DEVICETEST_GYRO_L3GD20H_H_
#define FSFW_HAL_STM32H7_DEVICETEST_GYRO_L3GD20H_H_ #define FSFW_HAL_STM32H7_DEVICETEST_GYRO_L3GD20H_H_
#include "stm32h7xx_hal.h" #include <array>
#include "stm32h7xx_hal_spi.h" #include <cstdint>
#include "../spi/mspInit.h" #include "../spi/mspInit.h"
#include "../spi/spiDefinitions.h" #include "../spi/spiDefinitions.h"
#include "fsfw/returnvalues/HasReturnvaluesIF.h" #include "fsfw/returnvalues/HasReturnvaluesIF.h"
#include "stm32h7xx_hal.h"
#include "stm32h7xx_hal_spi.h"
#include <cstdint> enum class TransferStates { IDLE, WAIT, SUCCESS, FAILURE };
#include <array>
enum class TransferStates {
IDLE,
WAIT,
SUCCESS,
FAILURE
};
class GyroL3GD20H { class GyroL3GD20H {
public: public:
@ -27,7 +21,6 @@ public:
ReturnValue_t performOperation(); ReturnValue_t performOperation();
private: private:
const uint8_t WHO_AM_I_REG = 0b00001111; const uint8_t WHO_AM_I_REG = 0b00001111;
const uint8_t STM_READ_MASK = 0b10000000; const uint8_t STM_READ_MASK = 0b10000000;
const uint8_t STM_AUTO_INCREMENT_MASK = 0b01000000; const uint8_t STM_AUTO_INCREMENT_MASK = 0b01000000;
@ -57,11 +50,9 @@ private:
static void spiTransferCompleteCallback(SPI_HandleTypeDef* hspi, void* args); static void spiTransferCompleteCallback(SPI_HandleTypeDef* hspi, void* args);
static void spiTransferErrorCallback(SPI_HandleTypeDef* hspi, void* args); static void spiTransferErrorCallback(SPI_HandleTypeDef* hspi, void* args);
void prepareConfigRegs(uint8_t* configRegs); void prepareConfigRegs(uint8_t* configRegs);
void handleSensorReadout(); void handleSensorReadout();
DMA_HandleTypeDef* txDmaHandle = {}; DMA_HandleTypeDef* txDmaHandle = {};
DMA_HandleTypeDef* rxDmaHandle = {}; DMA_HandleTypeDef* rxDmaHandle = {};
spi::MspCfgBase* mspCfg = {}; spi::MspCfgBase* mspCfg = {};

View File

@ -1,7 +1,7 @@
#include <fsfw_hal/stm32h7/dma.h> #include <fsfw_hal/stm32h7/dma.h>
#include <cstdint>
#include <cstddef> #include <cstddef>
#include <cstdint>
user_handler_t DMA_1_USER_HANDLERS[8]; user_handler_t DMA_1_USER_HANDLERS[8];
user_args_t DMA_1_USER_ARGS[8]; user_args_t DMA_1_USER_ARGS[8];
@ -14,8 +14,7 @@ void dma::assignDmaUserHandler(DMAIndexes dma_idx, DMAStreams stream_idx,
if (dma_idx == DMA_1) { if (dma_idx == DMA_1) {
DMA_1_USER_HANDLERS[stream_idx] = user_handler; DMA_1_USER_HANDLERS[stream_idx] = user_handler;
DMA_1_USER_ARGS[stream_idx] = user_args; DMA_1_USER_ARGS[stream_idx] = user_args;
} } else if (dma_idx == DMA_2) {
else if(dma_idx == DMA_2) {
DMA_2_USER_HANDLERS[stream_idx] = user_handler; DMA_2_USER_HANDLERS[stream_idx] = user_handler;
DMA_2_USER_ARGS[stream_idx] = user_args; DMA_2_USER_ARGS[stream_idx] = user_args;
} }
@ -31,54 +30,22 @@ defined in the startup_stm32h743xx.s files! */
DMA_##DMA_IDX##_USER_HANDLERS[STREAM_IDX](DMA_##DMA_IDX##_USER_ARGS[STREAM_IDX]); \ DMA_##DMA_IDX##_USER_HANDLERS[STREAM_IDX](DMA_##DMA_IDX##_USER_ARGS[STREAM_IDX]); \
return; \ return; \
} \ } \
Default_Handler() \ Default_Handler()
extern"C" void DMA1_Stream0_IRQHandler() { extern "C" void DMA1_Stream0_IRQHandler() { GENERIC_DMA_IRQ_HANDLER(1, 0); }
GENERIC_DMA_IRQ_HANDLER(1, 0); extern "C" void DMA1_Stream1_IRQHandler() { GENERIC_DMA_IRQ_HANDLER(1, 1); }
} extern "C" void DMA1_Stream2_IRQHandler() { GENERIC_DMA_IRQ_HANDLER(1, 2); }
extern"C" void DMA1_Stream1_IRQHandler() { extern "C" void DMA1_Stream3_IRQHandler() { GENERIC_DMA_IRQ_HANDLER(1, 3); }
GENERIC_DMA_IRQ_HANDLER(1, 1); extern "C" void DMA1_Stream4_IRQHandler() { GENERIC_DMA_IRQ_HANDLER(1, 4); }
} extern "C" void DMA1_Stream5_IRQHandler() { GENERIC_DMA_IRQ_HANDLER(1, 5); }
extern"C" void DMA1_Stream2_IRQHandler() { extern "C" void DMA1_Stream6_IRQHandler() { GENERIC_DMA_IRQ_HANDLER(1, 6); }
GENERIC_DMA_IRQ_HANDLER(1, 2); extern "C" void DMA1_Stream7_IRQHandler() { GENERIC_DMA_IRQ_HANDLER(1, 7); }
}
extern"C" void DMA1_Stream3_IRQHandler() {
GENERIC_DMA_IRQ_HANDLER(1, 3);
}
extern"C" void DMA1_Stream4_IRQHandler() {
GENERIC_DMA_IRQ_HANDLER(1, 4);
}
extern"C" void DMA1_Stream5_IRQHandler() {
GENERIC_DMA_IRQ_HANDLER(1, 5);
}
extern"C" void DMA1_Stream6_IRQHandler() {
GENERIC_DMA_IRQ_HANDLER(1, 6);
}
extern"C" void DMA1_Stream7_IRQHandler() {
GENERIC_DMA_IRQ_HANDLER(1, 7);
}
extern"C" void DMA2_Stream0_IRQHandler() { extern "C" void DMA2_Stream0_IRQHandler() { GENERIC_DMA_IRQ_HANDLER(2, 0); }
GENERIC_DMA_IRQ_HANDLER(2, 0); extern "C" void DMA2_Stream1_IRQHandler() { GENERIC_DMA_IRQ_HANDLER(2, 1); }
} extern "C" void DMA2_Stream2_IRQHandler() { GENERIC_DMA_IRQ_HANDLER(2, 2); }
extern"C" void DMA2_Stream1_IRQHandler() { extern "C" void DMA2_Stream3_IRQHandler() { GENERIC_DMA_IRQ_HANDLER(2, 3); }
GENERIC_DMA_IRQ_HANDLER(2, 1); extern "C" void DMA2_Stream4_IRQHandler() { GENERIC_DMA_IRQ_HANDLER(2, 4); }
} extern "C" void DMA2_Stream5_IRQHandler() { GENERIC_DMA_IRQ_HANDLER(2, 5); }
extern"C" void DMA2_Stream2_IRQHandler() { extern "C" void DMA2_Stream6_IRQHandler() { GENERIC_DMA_IRQ_HANDLER(2, 6); }
GENERIC_DMA_IRQ_HANDLER(2, 2); extern "C" void DMA2_Stream7_IRQHandler() { GENERIC_DMA_IRQ_HANDLER(2, 7); }
}
extern"C" void DMA2_Stream3_IRQHandler() {
GENERIC_DMA_IRQ_HANDLER(2, 3);
}
extern"C" void DMA2_Stream4_IRQHandler() {
GENERIC_DMA_IRQ_HANDLER(2, 4);
}
extern"C" void DMA2_Stream5_IRQHandler() {
GENERIC_DMA_IRQ_HANDLER(2, 5);
}
extern"C" void DMA2_Stream6_IRQHandler() {
GENERIC_DMA_IRQ_HANDLER(2, 6);
}
extern"C" void DMA2_Stream7_IRQHandler() {
GENERIC_DMA_IRQ_HANDLER(2, 7);
}

View File

@ -5,20 +5,15 @@
extern "C" { extern "C" {
#endif #endif
#include "interrupts.h"
#include <cstdint> #include <cstdint>
#include "interrupts.h"
namespace dma { namespace dma {
enum DMAType { enum DMAType { TX = 0, RX = 1 };
TX = 0,
RX = 1
};
enum DMAIndexes: uint8_t { enum DMAIndexes : uint8_t { DMA_1 = 1, DMA_2 = 2 };
DMA_1 = 1,
DMA_2 = 2
};
enum DMAStreams { enum DMAStreams {
STREAM_0 = 0, STREAM_0 = 0,
@ -37,10 +32,10 @@ enum DMAStreams {
* @param user_handler * @param user_handler
* @param user_args * @param user_args
*/ */
void assignDmaUserHandler(DMAIndexes dma_idx, DMAStreams stream_idx, void assignDmaUserHandler(DMAIndexes dma_idx, DMAStreams stream_idx, user_handler_t user_handler,
user_handler_t user_handler, user_args_t user_args); user_args_t user_args);
} } // namespace dma
#ifdef __cplusplus #ifdef __cplusplus
} }

View File

@ -15,11 +15,7 @@ extern void Default_Handler();
typedef void (*user_handler_t)(void*); typedef void (*user_handler_t)(void*);
typedef void* user_args_t; typedef void* user_args_t;
enum IrqPriorities: uint8_t { enum IrqPriorities : uint8_t { HIGHEST = 0, HIGHEST_FREERTOS = 6, LOWEST = 15 };
HIGHEST = 0,
HIGHEST_FREERTOS = 6,
LOWEST = 15
};
#ifdef __cplusplus #ifdef __cplusplus
} }

View File

@ -1,11 +1,11 @@
#include "fsfw_hal/stm32h7/spi/SpiComIF.h" #include "fsfw_hal/stm32h7/spi/SpiComIF.h"
#include "fsfw_hal/stm32h7/spi/SpiCookie.h"
#include "fsfw/tasks/SemaphoreFactory.h" #include "fsfw/tasks/SemaphoreFactory.h"
#include "fsfw_hal/stm32h7/gpio/gpio.h"
#include "fsfw_hal/stm32h7/spi/SpiCookie.h"
#include "fsfw_hal/stm32h7/spi/mspInit.h"
#include "fsfw_hal/stm32h7/spi/spiCore.h" #include "fsfw_hal/stm32h7/spi/spiCore.h"
#include "fsfw_hal/stm32h7/spi/spiInterrupts.h" #include "fsfw_hal/stm32h7/spi/spiInterrupts.h"
#include "fsfw_hal/stm32h7/spi/mspInit.h"
#include "fsfw_hal/stm32h7/gpio/gpio.h"
// FreeRTOS required special Semaphore handling from an ISR. Therefore, we use the concrete // FreeRTOS required special Semaphore handling from an ISR. Therefore, we use the concrete
// instance here, because RTEMS and FreeRTOS are the only relevant OSALs currently // instance here, because RTEMS and FreeRTOS are the only relevant OSALs currently
@ -13,8 +13,8 @@
#if defined FSFW_OSAL_RTEMS #if defined FSFW_OSAL_RTEMS
#include "fsfw/osal/rtems/BinarySemaphore.h" #include "fsfw/osal/rtems/BinarySemaphore.h"
#elif defined FSFW_OSAL_FREERTOS #elif defined FSFW_OSAL_FREERTOS
#include "fsfw/osal/freertos/TaskManagement.h"
#include "fsfw/osal/freertos/BinarySemaphore.h" #include "fsfw/osal/freertos/BinarySemaphore.h"
#include "fsfw/osal/freertos/TaskManagement.h"
#endif #endif
#include "stm32h7xx_hal_gpio.h" #include "stm32h7xx_hal_gpio.h"
@ -35,9 +35,7 @@ void SpiComIF::addDmaHandles(DMA_HandleTypeDef *txHandle, DMA_HandleTypeDef *rxH
spi::setDmaHandles(txHandle, rxHandle); spi::setDmaHandles(txHandle, rxHandle);
} }
ReturnValue_t SpiComIF::initialize() { ReturnValue_t SpiComIF::initialize() { return HasReturnvaluesIF::RETURN_OK; }
return HasReturnvaluesIF::RETURN_OK;
}
ReturnValue_t SpiComIF::initializeInterface(CookieIF *cookie) { ReturnValue_t SpiComIF::initializeInterface(CookieIF *cookie) {
SpiCookie *spiCookie = dynamic_cast<SpiCookie *>(cookie); SpiCookie *spiCookie = dynamic_cast<SpiCookie *>(cookie);
@ -61,8 +59,8 @@ ReturnValue_t SpiComIF::initializeInterface(CookieIF *cookie) {
} }
} }
// This semaphore ensures thread-safety for a given bus // This semaphore ensures thread-safety for a given bus
spiSemaphore = dynamic_cast<BinarySemaphore*>( spiSemaphore =
SemaphoreFactory::instance()->createBinarySemaphore()); dynamic_cast<BinarySemaphore *>(SemaphoreFactory::instance()->createBinarySemaphore());
address_t spiAddress = spiCookie->getDeviceAddress(); address_t spiAddress = spiCookie->getDeviceAddress();
auto iter = spiDeviceMap.find(spiAddress); auto iter = spiDeviceMap.find(spiAddress);
@ -72,11 +70,13 @@ ReturnValue_t SpiComIF::initializeInterface(CookieIF *cookie) {
if (not statusPair.second) { if (not statusPair.second) {
#if FSFW_VERBOSE_LEVEL >= 1 #if FSFW_VERBOSE_LEVEL >= 1
#if FSFW_CPP_OSTREAM_ENABLED == 1 #if FSFW_CPP_OSTREAM_ENABLED == 1
sif::error << "SpiComIF::initializeInterface: Failed to insert device with address " << sif::error << "SpiComIF::initializeInterface: Failed to insert device with address "
spiAddress << "to SPI device map" << std::endl; << spiAddress << "to SPI device map" << std::endl;
#else #else
sif::printError("SpiComIF::initializeInterface: Failed to insert device with address " sif::printError(
"%lu to SPI device map\n", static_cast<unsigned long>(spiAddress)); "SpiComIF::initializeInterface: Failed to insert device with address "
"%lu to SPI device map\n",
static_cast<unsigned long>(spiAddress));
#endif /* FSFW_CPP_OSTREAM_ENABLED == 1 */ #endif /* FSFW_CPP_OSTREAM_ENABLED == 1 */
#endif /* FSFW_VERBOSE_LEVEL >= 1 */ #endif /* FSFW_VERBOSE_LEVEL >= 1 */
return HasReturnvaluesIF::RETURN_FAILED; return HasReturnvaluesIF::RETURN_FAILED;
@ -92,13 +92,11 @@ ReturnValue_t SpiComIF::initializeInterface(CookieIF *cookie) {
#ifdef SPI1 #ifdef SPI1
spiHandle.Instance = SPI1; spiHandle.Instance = SPI1;
#endif #endif
} } else if (spiIdx == spi::SpiBus::SPI_2) {
else if(spiIdx == spi::SpiBus::SPI_2) {
#ifdef SPI2 #ifdef SPI2
spiHandle.Instance = SPI2; spiHandle.Instance = SPI2;
#endif #endif
} } else {
else {
printCfgError("SPI Bus Index"); printCfgError("SPI Bus Index");
return HasReturnvaluesIF::RETURN_FAILED; return HasReturnvaluesIF::RETURN_FAILED;
} }
@ -112,16 +110,14 @@ ReturnValue_t SpiComIF::initializeInterface(CookieIF *cookie) {
return HasReturnvaluesIF::RETURN_FAILED; return HasReturnvaluesIF::RETURN_FAILED;
} }
spi::setSpiPollingMspFunctions(typedCfg); spi::setSpiPollingMspFunctions(typedCfg);
} } else if (transferMode == spi::TransferModes::INTERRUPT) {
else if(transferMode == spi::TransferModes::INTERRUPT) {
auto typedCfg = dynamic_cast<spi::MspIrqConfigStruct *>(mspCfg); auto typedCfg = dynamic_cast<spi::MspIrqConfigStruct *>(mspCfg);
if (typedCfg == nullptr) { if (typedCfg == nullptr) {
printCfgError("IRQ MSP"); printCfgError("IRQ MSP");
return HasReturnvaluesIF::RETURN_FAILED; return HasReturnvaluesIF::RETURN_FAILED;
} }
spi::setSpiIrqMspFunctions(typedCfg); spi::setSpiIrqMspFunctions(typedCfg);
} } else if (transferMode == spi::TransferModes::DMA) {
else if(transferMode == spi::TransferModes::DMA) {
auto typedCfg = dynamic_cast<spi::MspDmaConfigStruct *>(mspCfg); auto typedCfg = dynamic_cast<spi::MspDmaConfigStruct *>(mspCfg);
if (typedCfg == nullptr) { if (typedCfg == nullptr) {
printCfgError("DMA MSP"); printCfgError("DMA MSP");
@ -201,9 +197,7 @@ ReturnValue_t SpiComIF::sendMessage(CookieIF *cookie, const uint8_t *sendData, s
return HasReturnvaluesIF::RETURN_OK; return HasReturnvaluesIF::RETURN_OK;
} }
ReturnValue_t SpiComIF::getSendSuccess(CookieIF *cookie) { ReturnValue_t SpiComIF::getSendSuccess(CookieIF *cookie) { return HasReturnvaluesIF::RETURN_OK; }
return HasReturnvaluesIF::RETURN_OK;
}
ReturnValue_t SpiComIF::requestReceiveMessage(CookieIF *cookie, size_t requestLen) { ReturnValue_t SpiComIF::requestReceiveMessage(CookieIF *cookie, size_t requestLen) {
return HasReturnvaluesIF::RETURN_OK; return HasReturnvaluesIF::RETURN_OK;
@ -253,7 +247,8 @@ void SpiComIF::setDefaultPollingTimeout(dur_millis_t timeout) {
} }
ReturnValue_t SpiComIF::handlePollingSendOperation(uint8_t *recvPtr, SPI_HandleTypeDef &spiHandle, ReturnValue_t SpiComIF::handlePollingSendOperation(uint8_t *recvPtr, SPI_HandleTypeDef &spiHandle,
SpiCookie& spiCookie, const uint8_t *sendData, size_t sendLen) { SpiCookie &spiCookie, const uint8_t *sendData,
size_t sendLen) {
auto gpioPort = spiCookie.getChipSelectGpioPort(); auto gpioPort = spiCookie.getChipSelectGpioPort();
auto gpioPin = spiCookie.getChipSelectGpioPin(); auto gpioPin = spiCookie.getChipSelectGpioPin();
auto returnval = spiSemaphore->acquire(timeoutType, timeoutMs); auto returnval = spiSemaphore->acquire(timeoutType, timeoutMs);
@ -265,8 +260,8 @@ ReturnValue_t SpiComIF::handlePollingSendOperation(uint8_t* recvPtr, SPI_HandleT
HAL_GPIO_WritePin(gpioPort, gpioPin, GPIO_PIN_RESET); HAL_GPIO_WritePin(gpioPort, gpioPin, GPIO_PIN_RESET);
} }
auto result = HAL_SPI_TransmitReceive(&spiHandle, const_cast<uint8_t*>(sendData), auto result = HAL_SPI_TransmitReceive(&spiHandle, const_cast<uint8_t *>(sendData), recvPtr,
recvPtr, sendLen, defaultPollingTimeout); sendLen, defaultPollingTimeout);
if (gpioPort != nullptr) { if (gpioPort != nullptr) {
HAL_GPIO_WritePin(gpioPort, gpioPin, GPIO_PIN_SET); HAL_GPIO_WritePin(gpioPort, gpioPin, GPIO_PIN_SET);
} }
@ -279,8 +274,8 @@ ReturnValue_t SpiComIF::handlePollingSendOperation(uint8_t* recvPtr, SPI_HandleT
case (HAL_TIMEOUT): { case (HAL_TIMEOUT): {
#if FSFW_VERBOSE_LEVEL >= 1 #if FSFW_VERBOSE_LEVEL >= 1
#if FSFW_CPP_OSTREAM_ENABLED == 1 #if FSFW_CPP_OSTREAM_ENABLED == 1
sif::warning << "SpiComIF::sendMessage: Polling Mode | Timeout for SPI device" << sif::warning << "SpiComIF::sendMessage: Polling Mode | Timeout for SPI device"
spiCookie->getDeviceAddress() << std::endl; << spiCookie->getDeviceAddress() << std::endl;
#else #else
sif::printWarning("SpiComIF::sendMessage: Polling Mode | Timeout for SPI device %d\n", sif::printWarning("SpiComIF::sendMessage: Polling Mode | Timeout for SPI device %d\n",
spiCookie.getDeviceAddress()); spiCookie.getDeviceAddress());
@ -293,8 +288,8 @@ ReturnValue_t SpiComIF::handlePollingSendOperation(uint8_t* recvPtr, SPI_HandleT
default: { default: {
#if FSFW_VERBOSE_LEVEL >= 1 #if FSFW_VERBOSE_LEVEL >= 1
#if FSFW_CPP_OSTREAM_ENABLED == 1 #if FSFW_CPP_OSTREAM_ENABLED == 1
sif::warning << "SpiComIF::sendMessage: Polling Mode | HAL error for SPI device" << sif::warning << "SpiComIF::sendMessage: Polling Mode | HAL error for SPI device"
spiCookie->getDeviceAddress() << std::endl; << spiCookie->getDeviceAddress() << std::endl;
#else #else
sif::printWarning("SpiComIF::sendMessage: Polling Mode | HAL error for SPI device %d\n", sif::printWarning("SpiComIF::sendMessage: Polling Mode | HAL error for SPI device %d\n",
spiCookie.getDeviceAddress()); spiCookie.getDeviceAddress());
@ -308,17 +303,20 @@ ReturnValue_t SpiComIF::handlePollingSendOperation(uint8_t* recvPtr, SPI_HandleT
} }
ReturnValue_t SpiComIF::handleInterruptSendOperation(uint8_t *recvPtr, SPI_HandleTypeDef &spiHandle, ReturnValue_t SpiComIF::handleInterruptSendOperation(uint8_t *recvPtr, SPI_HandleTypeDef &spiHandle,
SpiCookie& spiCookie, const uint8_t * sendData, size_t sendLen) { SpiCookie &spiCookie, const uint8_t *sendData,
size_t sendLen) {
return handleIrqSendOperation(recvPtr, spiHandle, spiCookie, sendData, sendLen); return handleIrqSendOperation(recvPtr, spiHandle, spiCookie, sendData, sendLen);
} }
ReturnValue_t SpiComIF::handleDmaSendOperation(uint8_t *recvPtr, SPI_HandleTypeDef &spiHandle, ReturnValue_t SpiComIF::handleDmaSendOperation(uint8_t *recvPtr, SPI_HandleTypeDef &spiHandle,
SpiCookie& spiCookie, const uint8_t * sendData, size_t sendLen) { SpiCookie &spiCookie, const uint8_t *sendData,
size_t sendLen) {
return handleIrqSendOperation(recvPtr, spiHandle, spiCookie, sendData, sendLen); return handleIrqSendOperation(recvPtr, spiHandle, spiCookie, sendData, sendLen);
} }
ReturnValue_t SpiComIF::handleIrqSendOperation(uint8_t *recvPtr, SPI_HandleTypeDef &spiHandle, ReturnValue_t SpiComIF::handleIrqSendOperation(uint8_t *recvPtr, SPI_HandleTypeDef &spiHandle,
SpiCookie& spiCookie, const uint8_t *sendData, size_t sendLen) { SpiCookie &spiCookie, const uint8_t *sendData,
size_t sendLen) {
ReturnValue_t result = genericIrqSendSetup(recvPtr, spiHandle, spiCookie, sendData, sendLen); ReturnValue_t result = genericIrqSendSetup(recvPtr, spiHandle, spiCookie, sendData, sendLen);
if (result != HasReturnvaluesIF::RETURN_OK) { if (result != HasReturnvaluesIF::RETURN_OK) {
return result; return result;
@ -330,15 +328,13 @@ ReturnValue_t SpiComIF::handleIrqSendOperation(uint8_t *recvPtr, SPI_HandleTypeD
if (cacheMaintenanceOnTxBuffer) { if (cacheMaintenanceOnTxBuffer) {
/* Clean D-cache. Make sure the address is 32-byte aligned and add 32-bytes to length, /* Clean D-cache. Make sure the address is 32-byte aligned and add 32-bytes to length,
in case it overlaps cacheline */ in case it overlaps cacheline */
SCB_CleanDCache_by_Addr((uint32_t*)(((uint32_t) sendData ) & ~(uint32_t)0x1F), SCB_CleanDCache_by_Addr((uint32_t *)(((uint32_t)sendData) & ~(uint32_t)0x1F), sendLen + 32);
sendLen + 32);
} }
status = HAL_SPI_TransmitReceive_DMA(&spiHandle, const_cast<uint8_t *>(sendData), status = HAL_SPI_TransmitReceive_DMA(&spiHandle, const_cast<uint8_t *>(sendData),
currentRecvPtr, sendLen); currentRecvPtr, sendLen);
} } else {
else { status = HAL_SPI_TransmitReceive_IT(&spiHandle, const_cast<uint8_t *>(sendData), currentRecvPtr,
status = HAL_SPI_TransmitReceive_IT(&spiHandle, const_cast<uint8_t*>(sendData), sendLen);
currentRecvPtr, sendLen);
} }
switch (status) { switch (status) {
case (HAL_OK): { case (HAL_OK): {
@ -355,12 +351,10 @@ ReturnValue_t SpiComIF::halErrorHandler(HAL_StatusTypeDef status, spi::TransferM
char modeString[10]; char modeString[10];
if (transferMode == spi::TransferModes::DMA) { if (transferMode == spi::TransferModes::DMA) {
std::snprintf(modeString, sizeof(modeString), "Dma"); std::snprintf(modeString, sizeof(modeString), "Dma");
} } else {
else {
std::snprintf(modeString, sizeof(modeString), "Interrupt"); std::snprintf(modeString, sizeof(modeString), "Interrupt");
} }
sif::printWarning("SpiComIF::handle%sSendOperation: HAL error %d occured\n", modeString, sif::printWarning("SpiComIF::handle%sSendOperation: HAL error %d occured\n", modeString, status);
status);
switch (status) { switch (status) {
case (HAL_BUSY): { case (HAL_BUSY): {
return spi::HAL_BUSY_RETVAL; return spi::HAL_BUSY_RETVAL;
@ -377,9 +371,9 @@ ReturnValue_t SpiComIF::halErrorHandler(HAL_StatusTypeDef status, spi::TransferM
} }
} }
ReturnValue_t SpiComIF::genericIrqSendSetup(uint8_t *recvPtr, SPI_HandleTypeDef &spiHandle, ReturnValue_t SpiComIF::genericIrqSendSetup(uint8_t *recvPtr, SPI_HandleTypeDef &spiHandle,
SpiCookie& spiCookie, const uint8_t *sendData, size_t sendLen) { SpiCookie &spiCookie, const uint8_t *sendData,
size_t sendLen) {
currentRecvPtr = recvPtr; currentRecvPtr = recvPtr;
currentRecvBuffSize = sendLen; currentRecvBuffSize = sendLen;
@ -387,8 +381,10 @@ ReturnValue_t SpiComIF::genericIrqSendSetup(uint8_t *recvPtr, SPI_HandleTypeDef&
ReturnValue_t result = spiSemaphore->acquire(SemaphoreIF::TimeoutType::WAITING, timeoutMs); ReturnValue_t result = spiSemaphore->acquire(SemaphoreIF::TimeoutType::WAITING, timeoutMs);
if (result != HasReturnvaluesIF::RETURN_OK) { if (result != HasReturnvaluesIF::RETURN_OK) {
// Configuration error // Configuration error
sif::printWarning("SpiComIF::handleInterruptSendOperation: Semaphore " sif::printWarning(
"could not be acquired after %d ms\n", timeoutMs); "SpiComIF::handleInterruptSendOperation: Semaphore "
"could not be acquired after %d ms\n",
timeoutMs);
return result; return result;
} }
// Cache the current SPI handle in any case // Cache the current SPI handle in any case
@ -441,12 +437,11 @@ void SpiComIF::genericIrqHandler(void *irqArgsVoid, spi::TransferStates targetSt
GPIO_PIN_SET); GPIO_PIN_SET);
} }
#if defined FSFW_OSAL_FREERTOS #if defined FSFW_OSAL_FREERTOS
// Release the task semaphore // Release the task semaphore
BaseType_t taskWoken = pdFALSE; BaseType_t taskWoken = pdFALSE;
ReturnValue_t result = BinarySemaphore::releaseFromISR(comIF->spiSemaphore->getSemaphore(), ReturnValue_t result =
&taskWoken); BinarySemaphore::releaseFromISR(comIF->spiSemaphore->getSemaphore(), &taskWoken);
#elif defined FSFW_OSAL_RTEMS #elif defined FSFW_OSAL_RTEMS
ReturnValue_t result = comIF->spiSemaphore->release(); ReturnValue_t result = comIF->spiSemaphore->release();
#endif #endif
@ -458,8 +453,7 @@ void SpiComIF::genericIrqHandler(void *irqArgsVoid, spi::TransferStates targetSt
// Perform cache maintenance operation for DMA transfers // Perform cache maintenance operation for DMA transfers
if (spiCookie->getTransferMode() == spi::TransferModes::DMA) { if (spiCookie->getTransferMode() == spi::TransferModes::DMA) {
// Invalidate cache prior to access by CPU // Invalidate cache prior to access by CPU
SCB_InvalidateDCache_by_Addr ((uint32_t *) comIF->currentRecvPtr, SCB_InvalidateDCache_by_Addr((uint32_t *)comIF->currentRecvPtr, comIF->currentRecvBuffSize);
comIF->currentRecvBuffSize);
} }
#if defined FSFW_OSAL_FREERTOS #if defined FSFW_OSAL_FREERTOS
/* Request a context switch if the SPI ComIF task was woken up and has a higher priority /* Request a context switch if the SPI ComIF task was woken up and has a higher priority

View File

@ -1,16 +1,15 @@
#ifndef FSFW_HAL_STM32H7_SPI_SPICOMIF_H_ #ifndef FSFW_HAL_STM32H7_SPI_SPICOMIF_H_
#define FSFW_HAL_STM32H7_SPI_SPICOMIF_H_ #define FSFW_HAL_STM32H7_SPI_SPICOMIF_H_
#include "fsfw/tasks/SemaphoreIF.h" #include <map>
#include <vector>
#include "fsfw/devicehandlers/DeviceCommunicationIF.h" #include "fsfw/devicehandlers/DeviceCommunicationIF.h"
#include "fsfw/objectmanager/SystemObject.h" #include "fsfw/objectmanager/SystemObject.h"
#include "fsfw/tasks/SemaphoreIF.h"
#include "fsfw_hal/stm32h7/spi/spiDefinitions.h" #include "fsfw_hal/stm32h7/spi/spiDefinitions.h"
#include "stm32h7xx_hal_spi.h"
#include "stm32h743xx.h" #include "stm32h743xx.h"
#include "stm32h7xx_hal_spi.h"
#include <vector>
#include <map>
class SpiCookie; class SpiCookie;
class BinarySemaphore; class BinarySemaphore;
@ -28,9 +27,7 @@ class BinarySemaphore;
* implementation limits the transfer mode for a given SPI bus. * implementation limits the transfer mode for a given SPI bus.
* @author R. Mueller * @author R. Mueller
*/ */
class SpiComIF: class SpiComIF : public SystemObject, public DeviceCommunicationIF {
public SystemObject,
public DeviceCommunicationIF {
public: public:
/** /**
* Create a SPI communication interface for the given SPI peripheral (spiInstance) * Create a SPI communication interface for the given SPI peripheral (spiInstance)
@ -63,16 +60,14 @@ public:
// DeviceCommunicationIF overrides // DeviceCommunicationIF overrides
virtual ReturnValue_t initializeInterface(CookieIF* cookie) override; virtual ReturnValue_t initializeInterface(CookieIF* cookie) override;
virtual ReturnValue_t sendMessage(CookieIF *cookie, virtual ReturnValue_t sendMessage(CookieIF* cookie, const uint8_t* sendData,
const uint8_t * sendData, size_t sendLen) override; size_t sendLen) override;
virtual ReturnValue_t getSendSuccess(CookieIF* cookie) override; virtual ReturnValue_t getSendSuccess(CookieIF* cookie) override;
virtual ReturnValue_t requestReceiveMessage(CookieIF *cookie, virtual ReturnValue_t requestReceiveMessage(CookieIF* cookie, size_t requestLen) override;
size_t requestLen) override; virtual ReturnValue_t readReceivedMessage(CookieIF* cookie, uint8_t** buffer,
virtual ReturnValue_t readReceivedMessage(CookieIF *cookie, size_t* size) override;
uint8_t **buffer, size_t *size) override;
protected: protected:
struct SpiInstance { struct SpiInstance {
SpiInstance(size_t maxRecvSize) : replyBuffer(std::vector<uint8_t>(maxRecvSize)) {} SpiInstance(size_t maxRecvSize) : replyBuffer(std::vector<uint8_t>(maxRecvSize)) {}
std::vector<uint8_t> replyBuffer; std::vector<uint8_t> replyBuffer;
@ -103,13 +98,17 @@ protected:
SpiDeviceMap spiDeviceMap; SpiDeviceMap spiDeviceMap;
ReturnValue_t handlePollingSendOperation(uint8_t* recvPtr, SPI_HandleTypeDef& spiHandle, ReturnValue_t handlePollingSendOperation(uint8_t* recvPtr, SPI_HandleTypeDef& spiHandle,
SpiCookie& spiCookie, const uint8_t * sendData, size_t sendLen); SpiCookie& spiCookie, const uint8_t* sendData,
size_t sendLen);
ReturnValue_t handleInterruptSendOperation(uint8_t* recvPtr, SPI_HandleTypeDef& spiHandle, ReturnValue_t handleInterruptSendOperation(uint8_t* recvPtr, SPI_HandleTypeDef& spiHandle,
SpiCookie& spiCookie, const uint8_t * sendData, size_t sendLen); SpiCookie& spiCookie, const uint8_t* sendData,
size_t sendLen);
ReturnValue_t handleDmaSendOperation(uint8_t* recvPtr, SPI_HandleTypeDef& spiHandle, ReturnValue_t handleDmaSendOperation(uint8_t* recvPtr, SPI_HandleTypeDef& spiHandle,
SpiCookie& spiCookie, const uint8_t * sendData, size_t sendLen); SpiCookie& spiCookie, const uint8_t* sendData,
size_t sendLen);
ReturnValue_t handleIrqSendOperation(uint8_t* recvPtr, SPI_HandleTypeDef& spiHandle, ReturnValue_t handleIrqSendOperation(uint8_t* recvPtr, SPI_HandleTypeDef& spiHandle,
SpiCookie& spiCookie, const uint8_t * sendData, size_t sendLen); SpiCookie& spiCookie, const uint8_t* sendData,
size_t sendLen);
ReturnValue_t genericIrqSendSetup(uint8_t* recvPtr, SPI_HandleTypeDef& spiHandle, ReturnValue_t genericIrqSendSetup(uint8_t* recvPtr, SPI_HandleTypeDef& spiHandle,
SpiCookie& spiCookie, const uint8_t* sendData, size_t sendLen); SpiCookie& spiCookie, const uint8_t* sendData, size_t sendLen);
ReturnValue_t halErrorHandler(HAL_StatusTypeDef status, spi::TransferModes transferMode); ReturnValue_t halErrorHandler(HAL_StatusTypeDef status, spi::TransferModes transferMode);
@ -124,6 +123,4 @@ protected:
void printCfgError(const char* const type); void printCfgError(const char* const type);
}; };
#endif /* FSFW_HAL_STM32H7_SPI_SPICOMIF_H_ */ #endif /* FSFW_HAL_STM32H7_SPI_SPICOMIF_H_ */

View File

@ -1,12 +1,16 @@
#include "fsfw_hal/stm32h7/spi/SpiCookie.h" #include "fsfw_hal/stm32h7/spi/SpiCookie.h"
SpiCookie::SpiCookie(address_t deviceAddress, spi::SpiBus spiIdx, spi::TransferModes transferMode, SpiCookie::SpiCookie(address_t deviceAddress, spi::SpiBus spiIdx, spi::TransferModes transferMode,
spi::MspCfgBase* mspCfg, uint32_t spiSpeed, spi::SpiModes spiMode, spi::MspCfgBase* mspCfg, uint32_t spiSpeed, spi::SpiModes spiMode,
size_t maxRecvSize, stm32h7::GpioCfg csGpio): size_t maxRecvSize, stm32h7::GpioCfg csGpio)
deviceAddress(deviceAddress), spiIdx(spiIdx), spiSpeed(spiSpeed), spiMode(spiMode), : deviceAddress(deviceAddress),
transferMode(transferMode), csGpio(csGpio), spiIdx(spiIdx),
mspCfg(mspCfg), maxRecvSize(maxRecvSize) { spiSpeed(spiSpeed),
spiMode(spiMode),
transferMode(transferMode),
csGpio(csGpio),
mspCfg(mspCfg),
maxRecvSize(maxRecvSize) {
spiHandle.Init.DataSize = SPI_DATASIZE_8BIT; spiHandle.Init.DataSize = SPI_DATASIZE_8BIT;
spiHandle.Init.FirstBit = SPI_FIRSTBIT_MSB; spiHandle.Init.FirstBit = SPI_FIRSTBIT_MSB;
spiHandle.Init.TIMode = SPI_TIMODE_DISABLE; spiHandle.Init.TIMode = SPI_TIMODE_DISABLE;
@ -23,41 +27,23 @@ SpiCookie::SpiCookie(address_t deviceAddress, spi::SpiBus spiIdx, spi::TransferM
spiHandle.Init.BaudRatePrescaler = spi::getPrescaler(HAL_RCC_GetHCLKFreq(), spiSpeed); spiHandle.Init.BaudRatePrescaler = spi::getPrescaler(HAL_RCC_GetHCLKFreq(), spiSpeed);
} }
uint16_t SpiCookie::getChipSelectGpioPin() const { uint16_t SpiCookie::getChipSelectGpioPin() const { return csGpio.pin; }
return csGpio.pin;
}
GPIO_TypeDef* SpiCookie::getChipSelectGpioPort() { GPIO_TypeDef* SpiCookie::getChipSelectGpioPort() { return csGpio.port; }
return csGpio.port;
}
address_t SpiCookie::getDeviceAddress() const { address_t SpiCookie::getDeviceAddress() const { return deviceAddress; }
return deviceAddress;
}
spi::SpiBus SpiCookie::getSpiIdx() const { spi::SpiBus SpiCookie::getSpiIdx() const { return spiIdx; }
return spiIdx;
}
spi::SpiModes SpiCookie::getSpiMode() const { spi::SpiModes SpiCookie::getSpiMode() const { return spiMode; }
return spiMode;
}
uint32_t SpiCookie::getSpiSpeed() const { uint32_t SpiCookie::getSpiSpeed() const { return spiSpeed; }
return spiSpeed;
}
size_t SpiCookie::getMaxRecvSize() const { size_t SpiCookie::getMaxRecvSize() const { return maxRecvSize; }
return maxRecvSize;
}
SPI_HandleTypeDef& SpiCookie::getSpiHandle() { SPI_HandleTypeDef& SpiCookie::getSpiHandle() { return spiHandle; }
return spiHandle;
}
spi::MspCfgBase* SpiCookie::getMspCfg() { spi::MspCfgBase* SpiCookie::getMspCfg() { return mspCfg; }
return mspCfg;
}
void SpiCookie::deleteMspCfg() { void SpiCookie::deleteMspCfg() {
if (mspCfg != nullptr) { if (mspCfg != nullptr) {
@ -65,14 +51,10 @@ void SpiCookie::deleteMspCfg() {
} }
} }
spi::TransferModes SpiCookie::getTransferMode() const { spi::TransferModes SpiCookie::getTransferMode() const { return transferMode; }
return transferMode;
}
void SpiCookie::setTransferState(spi::TransferStates transferState) { void SpiCookie::setTransferState(spi::TransferStates transferState) {
this->transferState = transferState; this->transferState = transferState;
} }
spi::TransferStates SpiCookie::getTransferState() const { spi::TransferStates SpiCookie::getTransferState() const { return this->transferState; }
return this->transferState;
}

View File

@ -1,16 +1,14 @@
#ifndef FSFW_HAL_STM32H7_SPI_SPICOOKIE_H_ #ifndef FSFW_HAL_STM32H7_SPI_SPICOOKIE_H_
#define FSFW_HAL_STM32H7_SPI_SPICOOKIE_H_ #define FSFW_HAL_STM32H7_SPI_SPICOOKIE_H_
#include "spiDefinitions.h"
#include "mspInit.h"
#include "../definitions.h"
#include "fsfw/devicehandlers/CookieIF.h"
#include "stm32h743xx.h"
#include <utility> #include <utility>
#include "../definitions.h"
#include "fsfw/devicehandlers/CookieIF.h"
#include "mspInit.h"
#include "spiDefinitions.h"
#include "stm32h743xx.h"
/** /**
* @brief SPI cookie implementation for the STM32H7 device family * @brief SPI cookie implementation for the STM32H7 device family
* @details * @details
@ -20,8 +18,8 @@
*/ */
class SpiCookie : public CookieIF { class SpiCookie : public CookieIF {
friend class SpiComIF; friend class SpiComIF;
public:
public:
/** /**
* Allows construction of a SPI cookie for a connected SPI device * Allows construction of a SPI cookie for a connected SPI device
* @param deviceAddress * @param deviceAddress
@ -39,8 +37,8 @@ public:
* @param csGpio Optional CS GPIO definition. * @param csGpio Optional CS GPIO definition.
*/ */
SpiCookie(address_t deviceAddress, spi::SpiBus spiIdx, spi::TransferModes transferMode, SpiCookie(address_t deviceAddress, spi::SpiBus spiIdx, spi::TransferModes transferMode,
spi::MspCfgBase* mspCfg, uint32_t spiSpeed, spi::SpiModes spiMode, spi::MspCfgBase* mspCfg, uint32_t spiSpeed, spi::SpiModes spiMode, size_t maxRecvSize,
size_t maxRecvSize, stm32h7::GpioCfg csGpio = stm32h7::GpioCfg(nullptr, 0, 0)); stm32h7::GpioCfg csGpio = stm32h7::GpioCfg(nullptr, 0, 0));
uint16_t getChipSelectGpioPin() const; uint16_t getChipSelectGpioPin() const;
GPIO_TypeDef* getChipSelectGpioPort(); GPIO_TypeDef* getChipSelectGpioPort();
@ -75,6 +73,4 @@ private:
spi::TransferStates getTransferState() const; spi::TransferStates getTransferState() const;
}; };
#endif /* FSFW_HAL_STM32H7_SPI_SPICOOKIE_H_ */ #endif /* FSFW_HAL_STM32H7_SPI_SPICOOKIE_H_ */

View File

@ -1,15 +1,15 @@
#include "fsfw_hal/stm32h7/dma.h"
#include "fsfw_hal/stm32h7/spi/mspInit.h" #include "fsfw_hal/stm32h7/spi/mspInit.h"
#include "fsfw_hal/stm32h7/spi/spiCore.h"
#include "fsfw_hal/stm32h7/spi/spiInterrupts.h"
#include "stm32h743xx.h"
#include "stm32h7xx_hal_spi.h"
#include "stm32h7xx_hal_dma.h"
#include "stm32h7xx_hal_def.h"
#include <cstdio> #include <cstdio>
#include "fsfw_hal/stm32h7/dma.h"
#include "fsfw_hal/stm32h7/spi/spiCore.h"
#include "fsfw_hal/stm32h7/spi/spiInterrupts.h"
#include "stm32h743xx.h"
#include "stm32h7xx_hal_def.h"
#include "stm32h7xx_hal_dma.h"
#include "stm32h7xx_hal_spi.h"
spi::msp_func_t mspInitFunc = nullptr; spi::msp_func_t mspInitFunc = nullptr;
spi::MspCfgBase* mspInitArgs = nullptr; spi::MspCfgBase* mspInitArgs = nullptr;
@ -73,8 +73,7 @@ void spi::halMspInitDma(SPI_HandleTypeDef* hspi, MspCfgBase* cfgBase) {
/* NVIC configuration for DMA transfer complete interrupt (SPI1_TX) */ /* NVIC configuration for DMA transfer complete interrupt (SPI1_TX) */
// Assign the interrupt handler // Assign the interrupt handler
dma::assignDmaUserHandler(cfg->txDmaIndex, cfg->txDmaStream, dma::assignDmaUserHandler(cfg->txDmaIndex, cfg->txDmaStream, &spi::dmaTxIrqHandler, hdma_tx);
&spi::dmaTxIrqHandler, hdma_tx);
HAL_NVIC_SetPriority(cfg->txDmaIrqNumber, cfg->txPreEmptPriority, cfg->txSubpriority); HAL_NVIC_SetPriority(cfg->txDmaIrqNumber, cfg->txPreEmptPriority, cfg->txSubpriority);
HAL_NVIC_EnableIRQ(cfg->txDmaIrqNumber); HAL_NVIC_EnableIRQ(cfg->txDmaIrqNumber);
} }
@ -98,8 +97,7 @@ void spi::halMspDeinitDma(SPI_HandleTypeDef* hspi, MspCfgBase* cfgBase) {
spi::getDmaHandles(&hdma_tx, &hdma_rx); spi::getDmaHandles(&hdma_tx, &hdma_rx);
if (hdma_tx == NULL || hdma_rx == NULL) { if (hdma_tx == NULL || hdma_rx == NULL) {
printf("HAL_SPI_MspInit: Invalid DMA handles. Make sure to call setDmaHandles!\n"); printf("HAL_SPI_MspInit: Invalid DMA handles. Make sure to call setDmaHandles!\n");
} } else {
else {
// Disable the DMA // Disable the DMA
/* De-Initialize the DMA associated to transmission process */ /* De-Initialize the DMA associated to transmission process */
HAL_DMA_DeInit(hdma_tx); HAL_DMA_DeInit(hdma_tx);
@ -110,7 +108,6 @@ void spi::halMspDeinitDma(SPI_HandleTypeDef* hspi, MspCfgBase* cfgBase) {
// Disable the NVIC for DMA // Disable the NVIC for DMA
HAL_NVIC_DisableIRQ(cfg->txDmaIrqNumber); HAL_NVIC_DisableIRQ(cfg->txDmaIrqNumber);
HAL_NVIC_DisableIRQ(cfg->rxDmaIrqNumber); HAL_NVIC_DisableIRQ(cfg->rxDmaIrqNumber);
} }
void spi::halMspInitPolling(SPI_HandleTypeDef* hspi, MspCfgBase* cfgBase) { void spi::halMspInitPolling(SPI_HandleTypeDef* hspi, MspCfgBase* cfgBase) {
@ -188,8 +185,8 @@ void spi::getMspDeinitFunction(msp_func_t* deinit_func, MspCfgBase** args) {
} }
} }
void spi::setSpiDmaMspFunctions(MspDmaConfigStruct* cfg, void spi::setSpiDmaMspFunctions(MspDmaConfigStruct* cfg, msp_func_t initFunc,
msp_func_t initFunc, msp_func_t deinitFunc) { msp_func_t deinitFunc) {
mspInitFunc = initFunc; mspInitFunc = initFunc;
mspDeinitFunc = deinitFunc; mspDeinitFunc = deinitFunc;
mspInitArgs = cfg; mspInitArgs = cfg;
@ -225,8 +222,7 @@ void spi::setSpiPollingMspFunctions(MspPollingConfigStruct *cfg, msp_func_t init
extern "C" void HAL_SPI_MspInit(SPI_HandleTypeDef* hspi) { extern "C" void HAL_SPI_MspInit(SPI_HandleTypeDef* hspi) {
if (mspInitFunc != NULL) { if (mspInitFunc != NULL) {
mspInitFunc(hspi, mspInitArgs); mspInitFunc(hspi, mspInitArgs);
} } else {
else {
printf("HAL_SPI_MspInit: Please call set_msp_functions to assign SPI MSP functions\n"); printf("HAL_SPI_MspInit: Please call set_msp_functions to assign SPI MSP functions\n");
} }
} }
@ -242,8 +238,7 @@ extern "C" void HAL_SPI_MspInit(SPI_HandleTypeDef *hspi) {
extern "C" void HAL_SPI_MspDeInit(SPI_HandleTypeDef* hspi) { extern "C" void HAL_SPI_MspDeInit(SPI_HandleTypeDef* hspi) {
if (mspDeinitFunc != NULL) { if (mspDeinitFunc != NULL) {
mspDeinitFunc(hspi, mspDeinitArgs); mspDeinitFunc(hspi, mspDeinitArgs);
} } else {
else {
printf("HAL_SPI_MspDeInit: Please call set_msp_functions to assign SPI MSP functions\n"); printf("HAL_SPI_MspDeInit: Please call set_msp_functions to assign SPI MSP functions\n");
} }
} }

View File

@ -1,14 +1,13 @@
#ifndef FSFW_HAL_STM32H7_SPI_MSPINIT_H_ #ifndef FSFW_HAL_STM32H7_SPI_MSPINIT_H_
#define FSFW_HAL_STM32H7_SPI_MSPINIT_H_ #define FSFW_HAL_STM32H7_SPI_MSPINIT_H_
#include "spiDefinitions.h" #include <cstdint>
#include "../definitions.h" #include "../definitions.h"
#include "../dma.h" #include "../dma.h"
#include "spiDefinitions.h"
#include "stm32h7xx_hal_spi.h" #include "stm32h7xx_hal_spi.h"
#include <cstdint>
#ifdef __cplusplus #ifdef __cplusplus
extern "C" { extern "C" {
#endif #endif
@ -24,9 +23,8 @@ namespace spi {
struct MspCfgBase { struct MspCfgBase {
MspCfgBase(); MspCfgBase();
MspCfgBase(stm32h7::GpioCfg sck, stm32h7::GpioCfg mosi, stm32h7::GpioCfg miso, MspCfgBase(stm32h7::GpioCfg sck, stm32h7::GpioCfg mosi, stm32h7::GpioCfg miso,
mspCb cleanupCb = nullptr, mspCb setupCb = nullptr): mspCb cleanupCb = nullptr, mspCb setupCb = nullptr)
sck(sck), mosi(mosi), miso(miso), cleanupCb(cleanupCb), : sck(sck), mosi(mosi), miso(miso), cleanupCb(cleanupCb), setupCb(setupCb) {}
setupCb(setupCb) {}
virtual ~MspCfgBase() = default; virtual ~MspCfgBase() = default;
@ -41,8 +39,8 @@ struct MspCfgBase {
struct MspPollingConfigStruct : public MspCfgBase { struct MspPollingConfigStruct : public MspCfgBase {
MspPollingConfigStruct() : MspCfgBase(){}; MspPollingConfigStruct() : MspCfgBase(){};
MspPollingConfigStruct(stm32h7::GpioCfg sck, stm32h7::GpioCfg mosi, stm32h7::GpioCfg miso, MspPollingConfigStruct(stm32h7::GpioCfg sck, stm32h7::GpioCfg mosi, stm32h7::GpioCfg miso,
mspCb cleanupCb = nullptr, mspCb setupCb = nullptr): mspCb cleanupCb = nullptr, mspCb setupCb = nullptr)
MspCfgBase(sck, mosi, miso, cleanupCb, setupCb) {} : MspCfgBase(sck, mosi, miso, cleanupCb, setupCb) {}
}; };
/* A valid instance of this struct must be passed to the MSP initialization function as a void* /* A valid instance of this struct must be passed to the MSP initialization function as a void*
@ -50,8 +48,8 @@ argument */
struct MspIrqConfigStruct : public MspPollingConfigStruct { struct MspIrqConfigStruct : public MspPollingConfigStruct {
MspIrqConfigStruct() : MspPollingConfigStruct(){}; MspIrqConfigStruct() : MspPollingConfigStruct(){};
MspIrqConfigStruct(stm32h7::GpioCfg sck, stm32h7::GpioCfg mosi, stm32h7::GpioCfg miso, MspIrqConfigStruct(stm32h7::GpioCfg sck, stm32h7::GpioCfg mosi, stm32h7::GpioCfg miso,
mspCb cleanupCb = nullptr, mspCb setupCb = nullptr): mspCb cleanupCb = nullptr, mspCb setupCb = nullptr)
MspPollingConfigStruct(sck, mosi, miso, cleanupCb, setupCb) {} : MspPollingConfigStruct(sck, mosi, miso, cleanupCb, setupCb) {}
SpiBus spiBus = SpiBus::SPI_1; SpiBus spiBus = SpiBus::SPI_1;
user_handler_t spiIrqHandler = nullptr; user_handler_t spiIrqHandler = nullptr;
@ -68,8 +66,8 @@ argument */
struct MspDmaConfigStruct : public MspIrqConfigStruct { struct MspDmaConfigStruct : public MspIrqConfigStruct {
MspDmaConfigStruct() : MspIrqConfigStruct(){}; MspDmaConfigStruct() : MspIrqConfigStruct(){};
MspDmaConfigStruct(stm32h7::GpioCfg sck, stm32h7::GpioCfg mosi, stm32h7::GpioCfg miso, MspDmaConfigStruct(stm32h7::GpioCfg sck, stm32h7::GpioCfg mosi, stm32h7::GpioCfg miso,
mspCb cleanupCb = nullptr, mspCb setupCb = nullptr): mspCb cleanupCb = nullptr, mspCb setupCb = nullptr)
MspIrqConfigStruct(sck, mosi, miso, cleanupCb, setupCb) {} : MspIrqConfigStruct(sck, mosi, miso, cleanupCb, setupCb) {}
void (*dmaClkEnableWrapper)(void) = nullptr; void (*dmaClkEnableWrapper)(void) = nullptr;
dma::DMAIndexes txDmaIndex = dma::DMAIndexes::DMA_1; dma::DMAIndexes txDmaIndex = dma::DMAIndexes::DMA_1;
@ -87,7 +85,6 @@ struct MspDmaConfigStruct: public MspIrqConfigStruct {
using msp_func_t = void (*)(SPI_HandleTypeDef* hspi, MspCfgBase* cfg); using msp_func_t = void (*)(SPI_HandleTypeDef* hspi, MspCfgBase* cfg);
void getMspInitFunction(msp_func_t* init_func, MspCfgBase** args); void getMspInitFunction(msp_func_t* init_func, MspCfgBase** args);
void getMspDeinitFunction(msp_func_t* deinit_func, MspCfgBase** args); void getMspDeinitFunction(msp_func_t* deinit_func, MspCfgBase** args);
@ -107,23 +104,17 @@ void halMspDeinitPolling(SPI_HandleTypeDef* hspi, MspCfgBase* cfg);
* @param deinit_func * @param deinit_func
* @param deinit_args * @param deinit_args
*/ */
void setSpiDmaMspFunctions(MspDmaConfigStruct* cfg, void setSpiDmaMspFunctions(MspDmaConfigStruct* cfg, msp_func_t initFunc = &spi::halMspInitDma,
msp_func_t initFunc = &spi::halMspInitDma, msp_func_t deinitFunc = &spi::halMspDeinitDma);
msp_func_t deinitFunc= &spi::halMspDeinitDma void setSpiIrqMspFunctions(MspIrqConfigStruct* cfg, msp_func_t initFunc = &spi::halMspInitInterrupt,
); msp_func_t deinitFunc = &spi::halMspDeinitInterrupt);
void setSpiIrqMspFunctions(MspIrqConfigStruct* cfg,
msp_func_t initFunc = &spi::halMspInitInterrupt,
msp_func_t deinitFunc= &spi::halMspDeinitInterrupt
);
void setSpiPollingMspFunctions(MspPollingConfigStruct* cfg, void setSpiPollingMspFunctions(MspPollingConfigStruct* cfg,
msp_func_t initFunc = &spi::halMspInitPolling, msp_func_t initFunc = &spi::halMspInitPolling,
msp_func_t deinitFunc= &spi::halMspDeinitPolling msp_func_t deinitFunc = &spi::halMspDeinitPolling);
);
void mspErrorHandler(const char* const function, const char* const message); void mspErrorHandler(const char* const function, const char* const message);
} } // namespace spi
#ifdef __cplusplus #ifdef __cplusplus
} }

View File

@ -1,8 +1,9 @@
#include "fsfw_hal/stm32h7/spi/spiCore.h" #include "fsfw_hal/stm32h7/spi/spiCore.h"
#include "fsfw_hal/stm32h7/spi/spiDefinitions.h"
#include <cstdio> #include <cstdio>
#include "fsfw_hal/stm32h7/spi/spiDefinitions.h"
SPI_HandleTypeDef* spiHandle = nullptr; SPI_HandleTypeDef* spiHandle = nullptr;
DMA_HandleTypeDef* hdmaTx = nullptr; DMA_HandleTypeDef* hdmaTx = nullptr;
DMA_HandleTypeDef* hdmaRx = nullptr; DMA_HandleTypeDef* hdmaRx = nullptr;
@ -21,16 +22,15 @@ void mapIndexAndStream(DMA_HandleTypeDef* handle, dma::DMAType dmaType, dma::DMA
void mapSpiBus(DMA_HandleTypeDef* handle, dma::DMAType dmaType, spi::SpiBus spiBus); void mapSpiBus(DMA_HandleTypeDef* handle, dma::DMAType dmaType, spi::SpiBus spiBus);
void spi::configureDmaHandle(DMA_HandleTypeDef* handle, spi::SpiBus spiBus, dma::DMAType dmaType, void spi::configureDmaHandle(DMA_HandleTypeDef* handle, spi::SpiBus spiBus, dma::DMAType dmaType,
dma::DMAIndexes dmaIdx, dma::DMAStreams dmaStream, IRQn_Type* dmaIrqNumber, dma::DMAIndexes dmaIdx, dma::DMAStreams dmaStream,
uint32_t dmaMode, uint32_t dmaPriority) { IRQn_Type* dmaIrqNumber, uint32_t dmaMode, uint32_t dmaPriority) {
using namespace dma; using namespace dma;
mapIndexAndStream(handle, dmaType, dmaIdx, dmaStream, dmaIrqNumber); mapIndexAndStream(handle, dmaType, dmaIdx, dmaStream, dmaIrqNumber);
mapSpiBus(handle, dmaType, spiBus); mapSpiBus(handle, dmaType, spiBus);
if (dmaType == DMAType::TX) { if (dmaType == DMAType::TX) {
handle->Init.Direction = DMA_MEMORY_TO_PERIPH; handle->Init.Direction = DMA_MEMORY_TO_PERIPH;
} } else {
else {
handle->Init.Direction = DMA_PERIPH_TO_MEMORY; handle->Init.Direction = DMA_PERIPH_TO_MEMORY;
} }
@ -85,11 +85,7 @@ void spi::assignTransferErrorCallback(spi_transfer_cb_t callback, void *userArgs
errorArgs = userArgs; errorArgs = userArgs;
} }
SPI_HandleTypeDef* spi::getSpiHandle() { SPI_HandleTypeDef* spi::getSpiHandle() { return spiHandle; }
return spiHandle;
}
/** /**
* @brief TxRx Transfer completed callback. * @brief TxRx Transfer completed callback.
@ -98,8 +94,7 @@ SPI_HandleTypeDef* spi::getSpiHandle() {
extern "C" void HAL_SPI_TxRxCpltCallback(SPI_HandleTypeDef* hspi) { extern "C" void HAL_SPI_TxRxCpltCallback(SPI_HandleTypeDef* hspi) {
if (rxTxCb != NULL) { if (rxTxCb != NULL) {
rxTxCb(hspi, rxTxArgs); rxTxCb(hspi, rxTxArgs);
} } else {
else {
printf("HAL_SPI_TxRxCpltCallback: No user callback specified\n"); printf("HAL_SPI_TxRxCpltCallback: No user callback specified\n");
} }
} }
@ -111,8 +106,7 @@ extern "C" void HAL_SPI_TxRxCpltCallback(SPI_HandleTypeDef *hspi) {
extern "C" void HAL_SPI_TxCpltCallback(SPI_HandleTypeDef* hspi) { extern "C" void HAL_SPI_TxCpltCallback(SPI_HandleTypeDef* hspi) {
if (txCb != NULL) { if (txCb != NULL) {
txCb(hspi, txArgs); txCb(hspi, txArgs);
} } else {
else {
printf("HAL_SPI_TxCpltCallback: No user callback specified\n"); printf("HAL_SPI_TxCpltCallback: No user callback specified\n");
} }
} }
@ -124,8 +118,7 @@ extern "C" void HAL_SPI_TxCpltCallback(SPI_HandleTypeDef *hspi) {
extern "C" void HAL_SPI_RxCpltCallback(SPI_HandleTypeDef* hspi) { extern "C" void HAL_SPI_RxCpltCallback(SPI_HandleTypeDef* hspi) {
if (rxCb != nullptr) { if (rxCb != nullptr) {
rxCb(hspi, rxArgs); rxCb(hspi, rxArgs);
} } else {
else {
printf("HAL_SPI_RxCpltCallback: No user callback specified\n"); printf("HAL_SPI_RxCpltCallback: No user callback specified\n");
} }
} }
@ -140,8 +133,7 @@ extern "C" void HAL_SPI_RxCpltCallback(SPI_HandleTypeDef *hspi) {
extern "C" void HAL_SPI_ErrorCallback(SPI_HandleTypeDef* hspi) { extern "C" void HAL_SPI_ErrorCallback(SPI_HandleTypeDef* hspi) {
if (errorCb != nullptr) { if (errorCb != nullptr) {
errorCb(hspi, rxArgs); errorCb(hspi, rxArgs);
} } else {
else {
printf("HAL_SPI_ErrorCallback: No user callback specified\n"); printf("HAL_SPI_ErrorCallback: No user callback specified\n");
} }
} }
@ -227,8 +219,7 @@ void mapIndexAndStream(DMA_HandleTypeDef* handle, dma::DMAType dmaType, dma::DMA
} }
if (dmaType == DMAType::TX) { if (dmaType == DMAType::TX) {
handle->Init.Request = DMA_REQUEST_SPI1_TX; handle->Init.Request = DMA_REQUEST_SPI1_TX;
} } else {
else {
handle->Init.Request = DMA_REQUEST_SPI1_RX; handle->Init.Request = DMA_REQUEST_SPI1_RX;
} }
#endif /* DMA1 */ #endif /* DMA1 */
@ -319,20 +310,17 @@ void mapSpiBus(DMA_HandleTypeDef *handle, dma::DMAType dmaType, spi::SpiBus spiB
#ifdef DMA_REQUEST_SPI1_TX #ifdef DMA_REQUEST_SPI1_TX
handle->Init.Request = DMA_REQUEST_SPI1_TX; handle->Init.Request = DMA_REQUEST_SPI1_TX;
#endif #endif
} } else if (spiBus == spi::SpiBus::SPI_2) {
else if(spiBus == spi::SpiBus::SPI_2) {
#ifdef DMA_REQUEST_SPI2_TX #ifdef DMA_REQUEST_SPI2_TX
handle->Init.Request = DMA_REQUEST_SPI2_TX; handle->Init.Request = DMA_REQUEST_SPI2_TX;
#endif #endif
} }
} } else {
else {
if (spiBus == spi::SpiBus::SPI_1) { if (spiBus == spi::SpiBus::SPI_1) {
#ifdef DMA_REQUEST_SPI1_RX #ifdef DMA_REQUEST_SPI1_RX
handle->Init.Request = DMA_REQUEST_SPI1_RX; handle->Init.Request = DMA_REQUEST_SPI1_RX;
#endif #endif
} } else if (spiBus == spi::SpiBus::SPI_2) {
else if(spiBus == spi::SpiBus::SPI_2) {
#ifdef DMA_REQUEST_SPI2_RX #ifdef DMA_REQUEST_SPI2_RX
handle->Init.Request = DMA_REQUEST_SPI2_RX; handle->Init.Request = DMA_REQUEST_SPI2_RX;
#endif #endif

View File

@ -3,7 +3,6 @@
#include "fsfw_hal/stm32h7/dma.h" #include "fsfw_hal/stm32h7/dma.h"
#include "fsfw_hal/stm32h7/spi/spiDefinitions.h" #include "fsfw_hal/stm32h7/spi/spiDefinitions.h"
#include "stm32h7xx_hal.h" #include "stm32h7xx_hal.h"
#include "stm32h7xx_hal_dma.h" #include "stm32h7xx_hal_dma.h"
@ -15,10 +14,9 @@ using spi_transfer_cb_t = void (*) (SPI_HandleTypeDef *hspi, void* userArgs);
namespace spi { namespace spi {
void configureDmaHandle(DMA_HandleTypeDef* handle, spi::SpiBus spiBus, void configureDmaHandle(DMA_HandleTypeDef* handle, spi::SpiBus spiBus, dma::DMAType dmaType,
dma::DMAType dmaType, dma::DMAIndexes dmaIdx, dma::DMAIndexes dmaIdx, dma::DMAStreams dmaStream, IRQn_Type* dmaIrqNumber,
dma::DMAStreams dmaStream, IRQn_Type* dmaIrqNumber, uint32_t dmaMode = DMA_NORMAL, uint32_t dmaMode = DMA_NORMAL, uint32_t dmaPriority = DMA_PRIORITY_LOW);
uint32_t dmaPriority = DMA_PRIORITY_LOW);
/** /**
* Assign DMA handles. Required to use DMA for SPI transfers. * Assign DMA handles. Required to use DMA for SPI transfers.
@ -45,7 +43,7 @@ void assignTransferErrorCallback(spi_transfer_cb_t callback, void* userArgs);
*/ */
SPI_HandleTypeDef* getSpiHandle(); SPI_HandleTypeDef* getSpiHandle();
} } // namespace spi
#ifdef __cplusplus #ifdef __cplusplus
} }

View File

@ -30,20 +30,14 @@ uint32_t spi::getPrescaler(uint32_t clock_src_freq, uint32_t baudrate_mbps) {
uint32_t spi_clk = clock_src_freq; uint32_t spi_clk = clock_src_freq;
uint32_t presc = 0; uint32_t presc = 0;
static const uint32_t baudrate[] = { static const uint32_t baudrate[] = {
SPI_BAUDRATEPRESCALER_2, SPI_BAUDRATEPRESCALER_2, SPI_BAUDRATEPRESCALER_4, SPI_BAUDRATEPRESCALER_8,
SPI_BAUDRATEPRESCALER_4, SPI_BAUDRATEPRESCALER_16, SPI_BAUDRATEPRESCALER_32, SPI_BAUDRATEPRESCALER_64,
SPI_BAUDRATEPRESCALER_8, SPI_BAUDRATEPRESCALER_128, SPI_BAUDRATEPRESCALER_256,
SPI_BAUDRATEPRESCALER_16,
SPI_BAUDRATEPRESCALER_32,
SPI_BAUDRATEPRESCALER_64,
SPI_BAUDRATEPRESCALER_128,
SPI_BAUDRATEPRESCALER_256,
}; };
while (spi_clk > baudrate_mbps) { while (spi_clk > baudrate_mbps) {
presc = baudrate[divisor]; presc = baudrate[divisor];
if (++divisor > 7) if (++divisor > 7) break;
break;
spi_clk = (spi_clk >> 1); spi_clk = (spi_clk >> 1);
} }

View File

@ -2,37 +2,24 @@
#define FSFW_HAL_STM32H7_SPI_SPIDEFINITIONS_H_ #define FSFW_HAL_STM32H7_SPI_SPIDEFINITIONS_H_
#include "../../common/spi/spiCommon.h" #include "../../common/spi/spiCommon.h"
#include "fsfw/returnvalues/FwClassIds.h" #include "fsfw/returnvalues/FwClassIds.h"
#include "fsfw/returnvalues/HasReturnvaluesIF.h" #include "fsfw/returnvalues/HasReturnvaluesIF.h"
#include "stm32h7xx_hal.h" #include "stm32h7xx_hal.h"
#include "stm32h7xx_hal_spi.h" #include "stm32h7xx_hal_spi.h"
namespace spi { namespace spi {
static constexpr uint8_t HAL_SPI_ID = CLASS_ID::HAL_SPI; static constexpr uint8_t HAL_SPI_ID = CLASS_ID::HAL_SPI;
static constexpr ReturnValue_t HAL_TIMEOUT_RETVAL = HasReturnvaluesIF::makeReturnCode(HAL_SPI_ID, 0); static constexpr ReturnValue_t HAL_TIMEOUT_RETVAL =
HasReturnvaluesIF::makeReturnCode(HAL_SPI_ID, 0);
static constexpr ReturnValue_t HAL_BUSY_RETVAL = HasReturnvaluesIF::makeReturnCode(HAL_SPI_ID, 1); static constexpr ReturnValue_t HAL_BUSY_RETVAL = HasReturnvaluesIF::makeReturnCode(HAL_SPI_ID, 1);
static constexpr ReturnValue_t HAL_ERROR_RETVAL = HasReturnvaluesIF::makeReturnCode(HAL_SPI_ID, 2); static constexpr ReturnValue_t HAL_ERROR_RETVAL = HasReturnvaluesIF::makeReturnCode(HAL_SPI_ID, 2);
enum class TransferStates { enum class TransferStates { IDLE, WAIT, SUCCESS, FAILURE };
IDLE,
WAIT,
SUCCESS,
FAILURE
};
enum SpiBus { enum SpiBus { SPI_1, SPI_2 };
SPI_1,
SPI_2
};
enum TransferModes { enum TransferModes { POLLING, INTERRUPT, DMA };
POLLING,
INTERRUPT,
DMA
};
void assignSpiMode(SpiModes spiMode, SPI_HandleTypeDef& spiHandle); void assignSpiMode(SpiModes spiMode, SPI_HandleTypeDef& spiHandle);
@ -44,7 +31,6 @@ void assignSpiMode(SpiModes spiMode, SPI_HandleTypeDef& spiHandle);
*/ */
uint32_t getPrescaler(uint32_t clock_src_freq, uint32_t baudrate_mbps); uint32_t getPrescaler(uint32_t clock_src_freq, uint32_t baudrate_mbps);
} } // namespace spi
#endif /* FSFW_HAL_STM32H7_SPI_SPIDEFINITIONS_H_ */ #endif /* FSFW_HAL_STM32H7_SPI_SPIDEFINITIONS_H_ */

View File

@ -1,12 +1,12 @@
#include "fsfw_hal/stm32h7/spi/spiInterrupts.h" #include "fsfw_hal/stm32h7/spi/spiInterrupts.h"
#include "fsfw_hal/stm32h7/spi/spiCore.h"
#include <stddef.h>
#include "fsfw_hal/stm32h7/spi/spiCore.h"
#include "stm32h7xx_hal.h" #include "stm32h7xx_hal.h"
#include "stm32h7xx_hal_dma.h" #include "stm32h7xx_hal_dma.h"
#include "stm32h7xx_hal_spi.h" #include "stm32h7xx_hal_spi.h"
#include <stddef.h>
user_handler_t spi1UserHandler = &spi::spiIrqHandler; user_handler_t spi1UserHandler = &spi::spiIrqHandler;
user_args_t spi1UserArgs = nullptr; user_args_t spi1UserArgs = nullptr;
@ -55,8 +55,7 @@ void spi::assignSpiUserHandler(spi::SpiBus spiIdx, user_handler_t userHandler,
if (spiIdx == spi::SpiBus::SPI_1) { if (spiIdx == spi::SpiBus::SPI_1) {
spi1UserHandler = userHandler; spi1UserHandler = userHandler;
spi1UserArgs = userArgs; spi1UserArgs = userArgs;
} } else {
else {
spi2UserHandler = userHandler; spi2UserHandler = userHandler;
spi2UserArgs = userArgs; spi2UserArgs = userArgs;
} }
@ -70,8 +69,7 @@ void spi::getSpiUserHandler(spi::SpiBus spiBus, user_handler_t *userHandler,
if (spiBus == spi::SpiBus::SPI_1) { if (spiBus == spi::SpiBus::SPI_1) {
*userArgs = spi1UserArgs; *userArgs = spi1UserArgs;
*userHandler = spi1UserHandler; *userHandler = spi1UserHandler;
} } else {
else {
*userArgs = spi2UserArgs; *userArgs = spi2UserArgs;
*userHandler = spi2UserHandler; *userHandler = spi2UserHandler;
} }
@ -80,8 +78,7 @@ void spi::getSpiUserHandler(spi::SpiBus spiBus, user_handler_t *userHandler,
void spi::assignSpiUserArgs(spi::SpiBus spiBus, user_args_t userArgs) { void spi::assignSpiUserArgs(spi::SpiBus spiBus, user_args_t userArgs) {
if (spiBus == spi::SpiBus::SPI_1) { if (spiBus == spi::SpiBus::SPI_1) {
spi1UserArgs = userArgs; spi1UserArgs = userArgs;
} } else {
else {
spi2UserArgs = userArgs; spi2UserArgs = userArgs;
} }
} }

View File

@ -18,10 +18,8 @@ void assignSpiUserArgs(spi::SpiBus spiBus, user_args_t userArgs);
* @param user_handler * @param user_handler
* @param user_args * @param user_args
*/ */
void assignSpiUserHandler(spi::SpiBus spiBus, user_handler_t user_handler, void assignSpiUserHandler(spi::SpiBus spiBus, user_handler_t user_handler, user_args_t user_args);
user_args_t user_args); void getSpiUserHandler(spi::SpiBus spiBus, user_handler_t* user_handler, user_args_t* user_args);
void getSpiUserHandler(spi::SpiBus spiBus, user_handler_t* user_handler,
user_args_t* user_args);
/** /**
* Generic interrupt handlers supplied for convenience. Do not call these directly! Set them * Generic interrupt handlers supplied for convenience. Do not call these directly! Set them
@ -32,7 +30,7 @@ void dmaRxIrqHandler(void* dma_handle);
void dmaTxIrqHandler(void* dma_handle); void dmaTxIrqHandler(void* dma_handle);
void spiIrqHandler(void* spi_handle); void spiIrqHandler(void* spi_handle);
} } // namespace spi
#ifdef __cplusplus #ifdef __cplusplus
} }

View File

@ -1,12 +1,12 @@
#include "fsfw_hal/stm32h7/spi/stm32h743zi.h" #include "fsfw_hal/stm32h7/spi/stm32h743zi.h"
#include "fsfw_hal/stm32h7/spi/spiCore.h"
#include "fsfw_hal/stm32h7/spi/spiInterrupts.h"
#include "stm32h7xx_hal.h"
#include "stm32h7xx_hal_rcc.h"
#include <cstdio> #include <cstdio>
#include "fsfw_hal/stm32h7/spi/spiCore.h"
#include "fsfw_hal/stm32h7/spi/spiInterrupts.h"
#include "stm32h7xx_hal.h"
#include "stm32h7xx_hal_rcc.h"
void spiSetupWrapper() { void spiSetupWrapper() {
__HAL_RCC_GPIOA_CLK_ENABLE(); __HAL_RCC_GPIOA_CLK_ENABLE();
__HAL_RCC_GPIOB_CLK_ENABLE(); __HAL_RCC_GPIOB_CLK_ENABLE();
@ -18,9 +18,7 @@ void spiCleanUpWrapper() {
__HAL_RCC_SPI1_RELEASE_RESET(); __HAL_RCC_SPI1_RELEASE_RESET();
} }
void spiDmaClockEnableWrapper() { void spiDmaClockEnableWrapper() { __HAL_RCC_DMA2_CLK_ENABLE(); }
__HAL_RCC_DMA2_CLK_ENABLE();
}
void stm32h7::h743zi::standardPollingCfg(spi::MspPollingConfigStruct& cfg) { void stm32h7::h743zi::standardPollingCfg(spi::MspPollingConfigStruct& cfg) {
cfg.setupCb = &spiSetupWrapper; cfg.setupCb = &spiSetupWrapper;
@ -56,8 +54,9 @@ void stm32h7::h743zi::standardInterruptCfg(spi::MspIrqConfigStruct& cfg, IrqPrio
} }
void stm32h7::h743zi::standardDmaCfg(spi::MspDmaConfigStruct& cfg, IrqPriorities spiIrqPrio, void stm32h7::h743zi::standardDmaCfg(spi::MspDmaConfigStruct& cfg, IrqPriorities spiIrqPrio,
IrqPriorities txIrqPrio, IrqPriorities rxIrqPrio, IrqPriorities spiSubprio, IrqPriorities txIrqPrio, IrqPriorities rxIrqPrio,
IrqPriorities txSubprio, IrqPriorities rxSubprio) { IrqPriorities spiSubprio, IrqPriorities txSubprio,
IrqPriorities rxSubprio) {
cfg.dmaClkEnableWrapper = &spiDmaClockEnableWrapper; cfg.dmaClkEnableWrapper = &spiDmaClockEnableWrapper;
cfg.rxDmaIndex = dma::DMAIndexes::DMA_2; cfg.rxDmaIndex = dma::DMAIndexes::DMA_2;
cfg.txDmaIndex = dma::DMAIndexes::DMA_2; cfg.txDmaIndex = dma::DMAIndexes::DMA_2;

View File

@ -10,13 +10,11 @@ namespace h743zi {
void standardPollingCfg(spi::MspPollingConfigStruct& cfg); void standardPollingCfg(spi::MspPollingConfigStruct& cfg);
void standardInterruptCfg(spi::MspIrqConfigStruct& cfg, IrqPriorities spiIrqPrio, void standardInterruptCfg(spi::MspIrqConfigStruct& cfg, IrqPriorities spiIrqPrio,
IrqPriorities spiSubprio = HIGHEST); IrqPriorities spiSubprio = HIGHEST);
void standardDmaCfg(spi::MspDmaConfigStruct& cfg, IrqPriorities spiIrqPrio, void standardDmaCfg(spi::MspDmaConfigStruct& cfg, IrqPriorities spiIrqPrio, IrqPriorities txIrqPrio,
IrqPriorities txIrqPrio, IrqPriorities rxIrqPrio, IrqPriorities rxIrqPrio, IrqPriorities spiSubprio = HIGHEST,
IrqPriorities spiSubprio = HIGHEST, IrqPriorities txSubPrio = HIGHEST, IrqPriorities txSubPrio = HIGHEST, IrqPriorities rxSubprio = HIGHEST);
IrqPriorities rxSubprio = HIGHEST);
} // namespace h743zi
} } // namespace stm32h7
}
#endif /* FSFW_HAL_STM32H7_SPI_STM32H743ZISPI_H_ */ #endif /* FSFW_HAL_STM32H7_SPI_STM32H743ZISPI_H_ */

View File

@ -4,8 +4,8 @@
#include "fsfw/action/ActionHelper.h" #include "fsfw/action/ActionHelper.h"
#include "fsfw/action/ActionMessage.h" #include "fsfw/action/ActionMessage.h"
#include "fsfw/action/CommandActionHelper.h" #include "fsfw/action/CommandActionHelper.h"
#include "fsfw/action/HasActionsIF.h"
#include "fsfw/action/CommandsActionsIF.h" #include "fsfw/action/CommandsActionsIF.h"
#include "fsfw/action/HasActionsIF.h"
#include "fsfw/action/SimpleActionHelper.h" #include "fsfw/action/SimpleActionHelper.h"
#endif /* FSFW_INC_FSFW_ACTION_H_ */ #endif /* FSFW_INC_FSFW_ACTION_H_ */

View File

@ -1,22 +1,17 @@
#include "fsfw/action.h" #include "fsfw/action.h"
#include "fsfw/ipc/MessageQueueSenderIF.h" #include "fsfw/ipc/MessageQueueSenderIF.h"
#include "fsfw/objectmanager/ObjectManager.h" #include "fsfw/objectmanager/ObjectManager.h"
#include "fsfw/serviceinterface/ServiceInterface.h" #include "fsfw/serviceinterface/ServiceInterface.h"
ActionHelper::ActionHelper(HasActionsIF* setOwner, ActionHelper::ActionHelper(HasActionsIF* setOwner, MessageQueueIF* useThisQueue)
MessageQueueIF* useThisQueue) : : owner(setOwner), queueToUse(useThisQueue) {}
owner(setOwner), queueToUse(useThisQueue) {
}
ActionHelper::~ActionHelper() { ActionHelper::~ActionHelper() {}
}
ReturnValue_t ActionHelper::handleActionMessage(CommandMessage* command) { ReturnValue_t ActionHelper::handleActionMessage(CommandMessage* command) {
if (command->getCommand() == ActionMessage::EXECUTE_ACTION) { if (command->getCommand() == ActionMessage::EXECUTE_ACTION) {
ActionId_t currentAction = ActionMessage::getActionId(command); ActionId_t currentAction = ActionMessage::getActionId(command);
prepareExecution(command->getSender(), currentAction, prepareExecution(command->getSender(), currentAction, ActionMessage::getStoreId(command));
ActionMessage::getStoreId(command));
return HasReturnvaluesIF::RETURN_OK; return HasReturnvaluesIF::RETURN_OK;
} else { } else {
return CommandMessage::UNKNOWN_COMMAND; return CommandMessage::UNKNOWN_COMMAND;
@ -46,8 +41,8 @@ ReturnValue_t ActionHelper::initialize(MessageQueueIF* queueToUse_) {
return HasReturnvaluesIF::RETURN_OK; return HasReturnvaluesIF::RETURN_OK;
} }
void ActionHelper::step(uint8_t step, MessageQueueId_t reportTo, void ActionHelper::step(uint8_t step, MessageQueueId_t reportTo, ActionId_t commandId,
ActionId_t commandId, ReturnValue_t result) { ReturnValue_t result) {
CommandMessage reply; CommandMessage reply;
ActionMessage::setStepReply(&reply, commandId, step + STEP_OFFSET, result); ActionMessage::setStepReply(&reply, commandId, step + STEP_OFFSET, result);
queueToUse->sendMessage(reportTo, &reply); queueToUse->sendMessage(reportTo, &reply);
@ -60,12 +55,10 @@ void ActionHelper::finish(bool success, MessageQueueId_t reportTo, ActionId_t co
queueToUse->sendMessage(reportTo, &reply); queueToUse->sendMessage(reportTo, &reply);
} }
void ActionHelper::setQueueToUse(MessageQueueIF* queue) { void ActionHelper::setQueueToUse(MessageQueueIF* queue) { queueToUse = queue; }
queueToUse = queue;
}
void ActionHelper::prepareExecution(MessageQueueId_t commandedBy, void ActionHelper::prepareExecution(MessageQueueId_t commandedBy, ActionId_t actionId,
ActionId_t actionId, store_address_t dataAddress) { store_address_t dataAddress) {
const uint8_t* dataPtr = NULL; const uint8_t* dataPtr = NULL;
size_t size = 0; size_t size = 0;
ReturnValue_t result = ipcStore->getData(dataAddress, &dataPtr, &size); ReturnValue_t result = ipcStore->getData(dataAddress, &dataPtr, &size);
@ -90,8 +83,8 @@ void ActionHelper::prepareExecution(MessageQueueId_t commandedBy,
} }
} }
ReturnValue_t ActionHelper::reportData(MessageQueueId_t reportTo, ReturnValue_t ActionHelper::reportData(MessageQueueId_t reportTo, ActionId_t replyId,
ActionId_t replyId, SerializeIF* data, bool hideSender) { SerializeIF* data, bool hideSender) {
CommandMessage reply; CommandMessage reply;
store_address_t storeAddress; store_address_t storeAddress;
uint8_t* dataPtr; uint8_t* dataPtr;
@ -101,20 +94,19 @@ ReturnValue_t ActionHelper::reportData(MessageQueueId_t reportTo,
return HasReturnvaluesIF::RETURN_OK; return HasReturnvaluesIF::RETURN_OK;
} }
size_t size = 0; size_t size = 0;
ReturnValue_t result = ipcStore->getFreeElement(&storeAddress, maxSize, ReturnValue_t result = ipcStore->getFreeElement(&storeAddress, maxSize, &dataPtr);
&dataPtr);
if (result != HasReturnvaluesIF::RETURN_OK) { if (result != HasReturnvaluesIF::RETURN_OK) {
#if FSFW_CPP_OSTREAM_ENABLED == 1 #if FSFW_CPP_OSTREAM_ENABLED == 1
sif::warning << "ActionHelper::reportData: Getting free element from IPC store failed!" << sif::warning << "ActionHelper::reportData: Getting free element from IPC store failed!"
std::endl; << std::endl;
#else #else
sif::printWarning("ActionHelper::reportData: Getting free element from IPC " sif::printWarning(
"ActionHelper::reportData: Getting free element from IPC "
"store failed!\n"); "store failed!\n");
#endif #endif
return result; return result;
} }
result = data->serialize(&dataPtr, &size, maxSize, result = data->serialize(&dataPtr, &size, maxSize, SerializeIF::Endianness::BIG);
SerializeIF::Endianness::BIG);
if (result != HasReturnvaluesIF::RETURN_OK) { if (result != HasReturnvaluesIF::RETURN_OK) {
ipcStore->deleteData(storeAddress); ipcStore->deleteData(storeAddress);
return result; return result;
@ -128,8 +120,7 @@ ReturnValue_t ActionHelper::reportData(MessageQueueId_t reportTo,
as unrequested reply, this will be done here. */ as unrequested reply, this will be done here. */
if (hideSender) { if (hideSender) {
result = MessageQueueSenderIF::sendMessage(reportTo, &reply); result = MessageQueueSenderIF::sendMessage(reportTo, &reply);
} } else {
else {
result = queueToUse->sendMessage(reportTo, &reply); result = queueToUse->sendMessage(reportTo, &reply);
} }
@ -139,12 +130,10 @@ ReturnValue_t ActionHelper::reportData(MessageQueueId_t reportTo,
return result; return result;
} }
void ActionHelper::resetHelper() { void ActionHelper::resetHelper() {}
}
ReturnValue_t ActionHelper::reportData(MessageQueueId_t reportTo, ReturnValue_t ActionHelper::reportData(MessageQueueId_t reportTo, ActionId_t replyId,
ActionId_t replyId, const uint8_t *data, size_t dataSize, const uint8_t* data, size_t dataSize, bool hideSender) {
bool hideSender) {
CommandMessage reply; CommandMessage reply;
store_address_t storeAddress; store_address_t storeAddress;
ReturnValue_t result = ipcStore->addData(&storeAddress, data, dataSize); ReturnValue_t result = ipcStore->addData(&storeAddress, data, dataSize);
@ -165,8 +154,7 @@ ReturnValue_t ActionHelper::reportData(MessageQueueId_t reportTo,
as unrequested reply, this will be done here. */ as unrequested reply, this will be done here. */
if (hideSender) { if (hideSender) {
result = MessageQueueSenderIF::sendMessage(reportTo, &reply); result = MessageQueueSenderIF::sendMessage(reportTo, &reply);
} } else {
else {
result = queueToUse->sendMessage(reportTo, &reply); result = queueToUse->sendMessage(reportTo, &reply);
} }

View File

@ -1,9 +1,9 @@
#ifndef FSFW_ACTION_ACTIONHELPER_H_ #ifndef FSFW_ACTION_ACTIONHELPER_H_
#define FSFW_ACTION_ACTIONHELPER_H_ #define FSFW_ACTION_ACTIONHELPER_H_
#include "ActionMessage.h"
#include "../serialize/SerializeIF.h"
#include "../ipc/MessageQueueIF.h" #include "../ipc/MessageQueueIF.h"
#include "../serialize/SerializeIF.h"
#include "ActionMessage.h"
/** /**
* @brief Action Helper is a helper class which handles action messages * @brief Action Helper is a helper class which handles action messages
* *
@ -57,8 +57,7 @@ public:
* @param commandId ID of the executed command * @param commandId ID of the executed command
* @param result Result of the execution * @param result Result of the execution
*/ */
void step(uint8_t step, MessageQueueId_t reportTo, void step(uint8_t step, MessageQueueId_t reportTo, ActionId_t commandId,
ActionId_t commandId,
ReturnValue_t result = HasReturnvaluesIF::RETURN_OK); ReturnValue_t result = HasReturnvaluesIF::RETURN_OK);
/** /**
* Function to be called by the owner to send a action completion message * Function to be called by the owner to send a action completion message
@ -78,8 +77,8 @@ public:
* @param data Pointer to the data * @param data Pointer to the data
* @return Returns RETURN_OK if successful, otherwise failure code * @return Returns RETURN_OK if successful, otherwise failure code
*/ */
ReturnValue_t reportData(MessageQueueId_t reportTo, ActionId_t replyId, ReturnValue_t reportData(MessageQueueId_t reportTo, ActionId_t replyId, SerializeIF* data,
SerializeIF* data, bool hideSender = false); bool hideSender = false);
/** /**
* Function to be called by the owner if an action does report data. * Function to be called by the owner if an action does report data.
* Takes the raw data and writes it into the IPC store. * Takes the raw data and writes it into the IPC store.
@ -89,8 +88,8 @@ public:
* @param data Pointer to the data * @param data Pointer to the data
* @return Returns RETURN_OK if successful, otherwise failure code * @return Returns RETURN_OK if successful, otherwise failure code
*/ */
ReturnValue_t reportData(MessageQueueId_t reportTo, ActionId_t replyId, ReturnValue_t reportData(MessageQueueId_t reportTo, ActionId_t replyId, const uint8_t* data,
const uint8_t* data, size_t dataSize, bool hideSender = false); size_t dataSize, bool hideSender = false);
/** /**
* Function to setup the MessageQueueIF* of the helper. Can be used to * Function to setup the MessageQueueIF* of the helper. Can be used to
* set the MessageQueueIF* if message queue is unavailable at construction * set the MessageQueueIF* if message queue is unavailable at construction
@ -98,6 +97,7 @@ public:
* @param queue Queue to be used by the helper * @param queue Queue to be used by the helper
*/ */
void setQueueToUse(MessageQueueIF* queue); void setQueueToUse(MessageQueueIF* queue);
protected: protected:
//! Increase of value of this per step //! Increase of value of this per step
static const uint8_t STEP_OFFSET = 1; static const uint8_t STEP_OFFSET = 1;
@ -115,8 +115,8 @@ protected:
* @param actionId ID of action to be done * @param actionId ID of action to be done
* @param dataAddress Address of additional data in IPC Store * @param dataAddress Address of additional data in IPC Store
*/ */
virtual void prepareExecution(MessageQueueId_t commandedBy, virtual void prepareExecution(MessageQueueId_t commandedBy, ActionId_t actionId,
ActionId_t actionId, store_address_t dataAddress); store_address_t dataAddress);
/** /**
* @brief Default implementation is empty. * @brief Default implementation is empty.
*/ */

View File

@ -1,13 +1,10 @@
#include "fsfw/action.h" #include "fsfw/action.h"
#include "fsfw/objectmanager/ObjectManager.h" #include "fsfw/objectmanager/ObjectManager.h"
#include "fsfw/storagemanager/StorageManagerIF.h" #include "fsfw/storagemanager/StorageManagerIF.h"
ActionMessage::ActionMessage() { ActionMessage::ActionMessage() {}
}
ActionMessage::~ActionMessage() { ActionMessage::~ActionMessage() {}
}
void ActionMessage::setCommand(CommandMessage* message, ActionId_t fid, void ActionMessage::setCommand(CommandMessage* message, ActionId_t fid,
store_address_t parameters) { store_address_t parameters) {
@ -52,12 +49,11 @@ void ActionMessage::setDataReply(CommandMessage* message, ActionId_t actionId,
message->setParameter2(data.raw); message->setParameter2(data.raw);
} }
void ActionMessage::setCompletionReply(CommandMessage* message, void ActionMessage::setCompletionReply(CommandMessage* message, ActionId_t fid, bool success,
ActionId_t fid, bool success, ReturnValue_t result) { ReturnValue_t result) {
if (success) { if (success) {
message->setCommand(COMPLETION_SUCCESS); message->setCommand(COMPLETION_SUCCESS);
} } else {
else {
message->setCommand(COMPLETION_FAILED); message->setCommand(COMPLETION_FAILED);
} }
message->setParameter(fid); message->setParameter(fid);
@ -68,8 +64,8 @@ void ActionMessage::clear(CommandMessage* message) {
switch (message->getCommand()) { switch (message->getCommand()) {
case EXECUTE_ACTION: case EXECUTE_ACTION:
case DATA_REPLY: { case DATA_REPLY: {
StorageManagerIF *ipcStore = ObjectManager::instance()->get<StorageManagerIF>( StorageManagerIF* ipcStore =
objects::IPC_STORE); ObjectManager::instance()->get<StorageManagerIF>(objects::IPC_STORE);
if (ipcStore != NULL) { if (ipcStore != NULL) {
ipcStore->deleteData(getStoreId(message)); ipcStore->deleteData(getStoreId(message));
} }

View File

@ -16,6 +16,7 @@ using ActionId_t = uint32_t;
class ActionMessage { class ActionMessage {
private: private:
ActionMessage(); ActionMessage();
public: public:
static const uint8_t MESSAGE_ID = messagetypes::ACTION; static const uint8_t MESSAGE_ID = messagetypes::ACTION;
static const Command_t EXECUTE_ACTION = MAKE_COMMAND_ID(1); static const Command_t EXECUTE_ACTION = MAKE_COMMAND_ID(1);
@ -26,20 +27,18 @@ public:
static const Command_t COMPLETION_FAILED = MAKE_COMMAND_ID(6); static const Command_t COMPLETION_FAILED = MAKE_COMMAND_ID(6);
virtual ~ActionMessage(); virtual ~ActionMessage();
static void setCommand(CommandMessage* message, ActionId_t fid, static void setCommand(CommandMessage* message, ActionId_t fid, store_address_t parameters);
store_address_t parameters);
static ActionId_t getActionId(const CommandMessage* message); static ActionId_t getActionId(const CommandMessage* message);
static store_address_t getStoreId(const CommandMessage* message); static store_address_t getStoreId(const CommandMessage* message);
static void setStepReply(CommandMessage* message, ActionId_t fid, static void setStepReply(CommandMessage* message, ActionId_t fid, uint8_t step,
uint8_t step, ReturnValue_t result = HasReturnvaluesIF::RETURN_OK); ReturnValue_t result = HasReturnvaluesIF::RETURN_OK);
static uint8_t getStep(const CommandMessage* message); static uint8_t getStep(const CommandMessage* message);
static ReturnValue_t getReturnCode(const CommandMessage* message); static ReturnValue_t getReturnCode(const CommandMessage* message);
static void setDataReply(CommandMessage* message, ActionId_t actionId, static void setDataReply(CommandMessage* message, ActionId_t actionId, store_address_t data);
store_address_t data); static void setCompletionReply(CommandMessage* message, ActionId_t fid, bool success,
static void setCompletionReply(CommandMessage* message, ActionId_t fid, ReturnValue_t result = HasReturnvaluesIF::RETURN_OK);
bool success, ReturnValue_t result = HasReturnvaluesIF::RETURN_OK);
static void clear(CommandMessage* message); static void clear(CommandMessage* message);
}; };

View File

@ -1,17 +1,13 @@
#include "fsfw/action.h" #include "fsfw/action.h"
#include "fsfw/objectmanager/ObjectManager.h" #include "fsfw/objectmanager/ObjectManager.h"
CommandActionHelper::CommandActionHelper(CommandsActionsIF *setOwner) : CommandActionHelper::CommandActionHelper(CommandsActionsIF *setOwner)
owner(setOwner), queueToUse(NULL), ipcStore( : owner(setOwner), queueToUse(NULL), ipcStore(NULL), commandCount(0), lastTarget(0) {}
NULL), commandCount(0), lastTarget(0) {
}
CommandActionHelper::~CommandActionHelper() { CommandActionHelper::~CommandActionHelper() {}
}
ReturnValue_t CommandActionHelper::commandAction(object_id_t commandTo, ReturnValue_t CommandActionHelper::commandAction(object_id_t commandTo, ActionId_t actionId,
ActionId_t actionId, SerializeIF *data) { SerializeIF *data) {
HasActionsIF *receiver = ObjectManager::instance()->get<HasActionsIF>(commandTo); HasActionsIF *receiver = ObjectManager::instance()->get<HasActionsIF>(commandTo);
if (receiver == NULL) { if (receiver == NULL) {
return CommandsActionsIF::OBJECT_HAS_NO_FUNCTIONS; return CommandsActionsIF::OBJECT_HAS_NO_FUNCTIONS;
@ -19,22 +15,20 @@ ReturnValue_t CommandActionHelper::commandAction(object_id_t commandTo,
store_address_t storeId; store_address_t storeId;
uint8_t *storePointer; uint8_t *storePointer;
size_t maxSize = data->getSerializedSize(); size_t maxSize = data->getSerializedSize();
ReturnValue_t result = ipcStore->getFreeElement(&storeId, maxSize, ReturnValue_t result = ipcStore->getFreeElement(&storeId, maxSize, &storePointer);
&storePointer);
if (result != HasReturnvaluesIF::RETURN_OK) { if (result != HasReturnvaluesIF::RETURN_OK) {
return result; return result;
} }
size_t size = 0; size_t size = 0;
result = data->serialize(&storePointer, &size, maxSize, result = data->serialize(&storePointer, &size, maxSize, SerializeIF::Endianness::BIG);
SerializeIF::Endianness::BIG);
if (result != HasReturnvaluesIF::RETURN_OK) { if (result != HasReturnvaluesIF::RETURN_OK) {
return result; return result;
} }
return sendCommand(receiver->getCommandQueue(), actionId, storeId); return sendCommand(receiver->getCommandQueue(), actionId, storeId);
} }
ReturnValue_t CommandActionHelper::commandAction(object_id_t commandTo, ReturnValue_t CommandActionHelper::commandAction(object_id_t commandTo, ActionId_t actionId,
ActionId_t actionId, const uint8_t *data, uint32_t size) { const uint8_t *data, uint32_t size) {
// if (commandCount != 0) { // if (commandCount != 0) {
// return CommandsFunctionsIF::ALREADY_COMMANDING; // return CommandsFunctionsIF::ALREADY_COMMANDING;
// } // }
@ -50,8 +44,8 @@ ReturnValue_t CommandActionHelper::commandAction(object_id_t commandTo,
return sendCommand(receiver->getCommandQueue(), actionId, storeId); return sendCommand(receiver->getCommandQueue(), actionId, storeId);
} }
ReturnValue_t CommandActionHelper::sendCommand(MessageQueueId_t queueId, ReturnValue_t CommandActionHelper::sendCommand(MessageQueueId_t queueId, ActionId_t actionId,
ActionId_t actionId, store_address_t storeId) { store_address_t storeId) {
CommandMessage command; CommandMessage command;
ActionMessage::setCommand(&command, actionId, storeId); ActionMessage::setCommand(&command, actionId, storeId);
ReturnValue_t result = queueToUse->sendMessage(queueId, &command); ReturnValue_t result = queueToUse->sendMessage(queueId, &command);
@ -96,22 +90,18 @@ ReturnValue_t CommandActionHelper::handleReply(CommandMessage *reply) {
return HasReturnvaluesIF::RETURN_OK; return HasReturnvaluesIF::RETURN_OK;
case ActionMessage::STEP_FAILED: case ActionMessage::STEP_FAILED:
commandCount--; commandCount--;
owner->stepFailedReceived(ActionMessage::getActionId(reply), owner->stepFailedReceived(ActionMessage::getActionId(reply), ActionMessage::getStep(reply),
ActionMessage::getStep(reply),
ActionMessage::getReturnCode(reply)); ActionMessage::getReturnCode(reply));
return HasReturnvaluesIF::RETURN_OK; return HasReturnvaluesIF::RETURN_OK;
case ActionMessage::DATA_REPLY: case ActionMessage::DATA_REPLY:
extractDataForOwner(ActionMessage::getActionId(reply), extractDataForOwner(ActionMessage::getActionId(reply), ActionMessage::getStoreId(reply));
ActionMessage::getStoreId(reply));
return HasReturnvaluesIF::RETURN_OK; return HasReturnvaluesIF::RETURN_OK;
default: default:
return HasReturnvaluesIF::RETURN_FAILED; return HasReturnvaluesIF::RETURN_FAILED;
} }
} }
uint8_t CommandActionHelper::getCommandCount() const { uint8_t CommandActionHelper::getCommandCount() const { return commandCount; }
return commandCount;
}
void CommandActionHelper::extractDataForOwner(ActionId_t actionId, store_address_t storeId) { void CommandActionHelper::extractDataForOwner(ActionId_t actionId, store_address_t storeId) {
const uint8_t *data = NULL; const uint8_t *data = NULL;

View File

@ -2,26 +2,27 @@
#define COMMANDACTIONHELPER_H_ #define COMMANDACTIONHELPER_H_
#include "ActionMessage.h" #include "ActionMessage.h"
#include "fsfw/ipc/MessageQueueIF.h"
#include "fsfw/objectmanager/ObjectManagerIF.h" #include "fsfw/objectmanager/ObjectManagerIF.h"
#include "fsfw/returnvalues/HasReturnvaluesIF.h" #include "fsfw/returnvalues/HasReturnvaluesIF.h"
#include "fsfw/serialize/SerializeIF.h" #include "fsfw/serialize/SerializeIF.h"
#include "fsfw/storagemanager/StorageManagerIF.h" #include "fsfw/storagemanager/StorageManagerIF.h"
#include "fsfw/ipc/MessageQueueIF.h"
class CommandsActionsIF; class CommandsActionsIF;
class CommandActionHelper { class CommandActionHelper {
friend class CommandsActionsIF; friend class CommandsActionsIF;
public: public:
CommandActionHelper(CommandsActionsIF* owner); CommandActionHelper(CommandsActionsIF* owner);
virtual ~CommandActionHelper(); virtual ~CommandActionHelper();
ReturnValue_t commandAction(object_id_t commandTo, ReturnValue_t commandAction(object_id_t commandTo, ActionId_t actionId, const uint8_t* data,
ActionId_t actionId, const uint8_t* data, uint32_t size); uint32_t size);
ReturnValue_t commandAction(object_id_t commandTo, ReturnValue_t commandAction(object_id_t commandTo, ActionId_t actionId, SerializeIF* data);
ActionId_t actionId, SerializeIF* data);
ReturnValue_t initialize(); ReturnValue_t initialize();
ReturnValue_t handleReply(CommandMessage* reply); ReturnValue_t handleReply(CommandMessage* reply);
uint8_t getCommandCount() const; uint8_t getCommandCount() const;
private: private:
CommandsActionsIF* owner; CommandsActionsIF* owner;
MessageQueueIF* queueToUse; MessageQueueIF* queueToUse;
@ -29,8 +30,7 @@ private:
uint8_t commandCount; uint8_t commandCount;
MessageQueueId_t lastTarget; MessageQueueId_t lastTarget;
void extractDataForOwner(ActionId_t actionId, store_address_t storeId); void extractDataForOwner(ActionId_t actionId, store_address_t storeId);
ReturnValue_t sendCommand(MessageQueueId_t queueId, ActionId_t actionId, ReturnValue_t sendCommand(MessageQueueId_t queueId, ActionId_t actionId, store_address_t storeId);
store_address_t storeId);
}; };
#endif /* COMMANDACTIONHELPER_H_ */ #endif /* COMMANDACTIONHELPER_H_ */

View File

@ -1,9 +1,9 @@
#ifndef FSFW_ACTION_COMMANDSACTIONSIF_H_ #ifndef FSFW_ACTION_COMMANDSACTIONSIF_H_
#define FSFW_ACTION_COMMANDSACTIONSIF_H_ #define FSFW_ACTION_COMMANDSACTIONSIF_H_
#include "CommandActionHelper.h"
#include "../returnvalues/HasReturnvaluesIF.h"
#include "../ipc/MessageQueueIF.h" #include "../ipc/MessageQueueIF.h"
#include "../returnvalues/HasReturnvaluesIF.h"
#include "CommandActionHelper.h"
/** /**
* Interface to separate commanding actions of other objects. * Interface to separate commanding actions of other objects.
@ -16,22 +16,20 @@
*/ */
class CommandsActionsIF { class CommandsActionsIF {
friend class CommandActionHelper; friend class CommandActionHelper;
public: public:
static const uint8_t INTERFACE_ID = CLASS_ID::COMMANDS_ACTIONS_IF; static const uint8_t INTERFACE_ID = CLASS_ID::COMMANDS_ACTIONS_IF;
static const ReturnValue_t OBJECT_HAS_NO_FUNCTIONS = MAKE_RETURN_CODE(1); static const ReturnValue_t OBJECT_HAS_NO_FUNCTIONS = MAKE_RETURN_CODE(1);
static const ReturnValue_t ALREADY_COMMANDING = MAKE_RETURN_CODE(2); static const ReturnValue_t ALREADY_COMMANDING = MAKE_RETURN_CODE(2);
virtual ~CommandsActionsIF() {} virtual ~CommandsActionsIF() {}
virtual MessageQueueIF* getCommandQueuePtr() = 0; virtual MessageQueueIF* getCommandQueuePtr() = 0;
protected: protected:
virtual void stepSuccessfulReceived(ActionId_t actionId, uint8_t step) = 0; virtual void stepSuccessfulReceived(ActionId_t actionId, uint8_t step) = 0;
virtual void stepFailedReceived(ActionId_t actionId, uint8_t step, virtual void stepFailedReceived(ActionId_t actionId, uint8_t step, ReturnValue_t returnCode) = 0;
ReturnValue_t returnCode) = 0; virtual void dataReceived(ActionId_t actionId, const uint8_t* data, uint32_t size) = 0;
virtual void dataReceived(ActionId_t actionId, const uint8_t* data,
uint32_t size) = 0;
virtual void completionSuccessfulReceived(ActionId_t actionId) = 0; virtual void completionSuccessfulReceived(ActionId_t actionId) = 0;
virtual void completionFailedReceived(ActionId_t actionId, virtual void completionFailedReceived(ActionId_t actionId, ReturnValue_t returnCode) = 0;
ReturnValue_t returnCode) = 0;
}; };
#endif /* FSFW_ACTION_COMMANDSACTIONSIF_H_ */ #endif /* FSFW_ACTION_COMMANDSACTIONSIF_H_ */

View File

@ -1,11 +1,11 @@
#ifndef FSFW_ACTION_HASACTIONSIF_H_ #ifndef FSFW_ACTION_HASACTIONSIF_H_
#define FSFW_ACTION_HASACTIONSIF_H_ #define FSFW_ACTION_HASACTIONSIF_H_
#include "../ipc/MessageQueueIF.h"
#include "../returnvalues/HasReturnvaluesIF.h"
#include "ActionHelper.h" #include "ActionHelper.h"
#include "ActionMessage.h" #include "ActionMessage.h"
#include "SimpleActionHelper.h" #include "SimpleActionHelper.h"
#include "../returnvalues/HasReturnvaluesIF.h"
#include "../ipc/MessageQueueIF.h"
/** /**
* @brief * @brief
@ -55,9 +55,8 @@ public:
* -@c EXECUTION_FINISHED Finish reply will be generated * -@c EXECUTION_FINISHED Finish reply will be generated
* -@c Not RETURN_OK Step failure reply will be generated * -@c Not RETURN_OK Step failure reply will be generated
*/ */
virtual ReturnValue_t executeAction(ActionId_t actionId, virtual ReturnValue_t executeAction(ActionId_t actionId, MessageQueueId_t commandedBy,
MessageQueueId_t commandedBy, const uint8_t* data, size_t size) = 0; const uint8_t* data, size_t size) = 0;
}; };
#endif /* FSFW_ACTION_HASACTIONSIF_H_ */ #endif /* FSFW_ACTION_HASACTIONSIF_H_ */

View File

@ -1,18 +1,14 @@
#include "fsfw/action.h" #include "fsfw/action.h"
SimpleActionHelper::SimpleActionHelper(HasActionsIF* setOwner, SimpleActionHelper::SimpleActionHelper(HasActionsIF* setOwner, MessageQueueIF* useThisQueue)
MessageQueueIF* useThisQueue) : : ActionHelper(setOwner, useThisQueue), isExecuting(false) {}
ActionHelper(setOwner, useThisQueue), isExecuting(false) {
}
SimpleActionHelper::~SimpleActionHelper() { SimpleActionHelper::~SimpleActionHelper() {}
}
void SimpleActionHelper::step(ReturnValue_t result) { void SimpleActionHelper::step(ReturnValue_t result) {
// STEP_OFFESET is subtracted to compensate for adding offset in base // STEP_OFFESET is subtracted to compensate for adding offset in base
// method, which is not necessary here. // method, which is not necessary here.
ActionHelper::step(stepCount - STEP_OFFSET, lastCommander, lastAction, ActionHelper::step(stepCount - STEP_OFFSET, lastCommander, lastAction, result);
result);
if (result != HasReturnvaluesIF::RETURN_OK) { if (result != HasReturnvaluesIF::RETURN_OK) {
resetHelper(); resetHelper();
} }
@ -34,13 +30,12 @@ void SimpleActionHelper::resetHelper() {
lastCommander = 0; lastCommander = 0;
} }
void SimpleActionHelper::prepareExecution(MessageQueueId_t commandedBy, void SimpleActionHelper::prepareExecution(MessageQueueId_t commandedBy, ActionId_t actionId,
ActionId_t actionId, store_address_t dataAddress) { store_address_t dataAddress) {
CommandMessage reply; CommandMessage reply;
if (isExecuting) { if (isExecuting) {
ipcStore->deleteData(dataAddress); ipcStore->deleteData(dataAddress);
ActionMessage::setStepReply(&reply, actionId, 0, ActionMessage::setStepReply(&reply, actionId, 0, HasActionsIF::IS_BUSY);
HasActionsIF::IS_BUSY);
queueToUse->sendMessage(commandedBy, &reply); queueToUse->sendMessage(commandedBy, &reply);
} }
const uint8_t* dataPtr = NULL; const uint8_t* dataPtr = NULL;
@ -61,8 +56,7 @@ void SimpleActionHelper::prepareExecution(MessageQueueId_t commandedBy,
stepCount++; stepCount++;
break; break;
case HasActionsIF::EXECUTION_FINISHED: case HasActionsIF::EXECUTION_FINISHED:
ActionMessage::setCompletionReply(&reply, actionId, ActionMessage::setCompletionReply(&reply, actionId, true, HasReturnvaluesIF::RETURN_OK);
true, HasReturnvaluesIF::RETURN_OK);
queueToUse->sendMessage(commandedBy, &reply); queueToUse->sendMessage(commandedBy, &reply);
break; break;
default: default:
@ -70,5 +64,4 @@ void SimpleActionHelper::prepareExecution(MessageQueueId_t commandedBy,
queueToUse->sendMessage(commandedBy, &reply); queueToUse->sendMessage(commandedBy, &reply);
break; break;
} }
} }

View File

@ -20,6 +20,7 @@ protected:
void prepareExecution(MessageQueueId_t commandedBy, ActionId_t actionId, void prepareExecution(MessageQueueId_t commandedBy, ActionId_t actionId,
store_address_t dataAddress); store_address_t dataAddress);
virtual void resetHelper(); virtual void resetHelper();
private: private:
bool isExecuting; bool isExecuting;
MessageQueueId_t lastCommander = MessageQueueIF::NO_QUEUE; MessageQueueId_t lastCommander = MessageQueueIF::NO_QUEUE;

View File

@ -1,16 +1,17 @@
#include "fsfw/ipc/CommandMessage.h"
#include "fsfw/storagemanager/storeAddress.h"
#include "fsfw/cfdp/CFDPHandler.h" #include "fsfw/cfdp/CFDPHandler.h"
#include "fsfw/cfdp/CFDPMessage.h"
#include "fsfw/tmtcservices/AcceptsTelemetryIF.h" #include "fsfw/cfdp/CFDPMessage.h"
#include "fsfw/ipc/CommandMessage.h"
#include "fsfw/ipc/QueueFactory.h" #include "fsfw/ipc/QueueFactory.h"
#include "fsfw/objectmanager/ObjectManager.h" #include "fsfw/objectmanager/ObjectManager.h"
#include "fsfw/storagemanager/storeAddress.h"
#include "fsfw/tmtcservices/AcceptsTelemetryIF.h"
object_id_t CFDPHandler::packetSource = 0; object_id_t CFDPHandler::packetSource = 0;
object_id_t CFDPHandler::packetDestination = 0; object_id_t CFDPHandler::packetDestination = 0;
CFDPHandler::CFDPHandler(object_id_t setObjectId, CFDPDistributor* dist) : SystemObject(setObjectId) { CFDPHandler::CFDPHandler(object_id_t setObjectId, CFDPDistributor* dist)
: SystemObject(setObjectId) {
requestQueue = QueueFactory::instance()->createMessageQueue(CFDP_HANDLER_MAX_RECEPTION); requestQueue = QueueFactory::instance()->createMessageQueue(CFDP_HANDLER_MAX_RECEPTION);
distributor = dist; distributor = dist;
} }
@ -51,10 +52,6 @@ ReturnValue_t CFDPHandler::performOperation(uint8_t opCode) {
return RETURN_OK; return RETURN_OK;
} }
uint16_t CFDPHandler::getIdentifier() { uint16_t CFDPHandler::getIdentifier() { return 0; }
return 0;
}
MessageQueueId_t CFDPHandler::getRequestQueue() { MessageQueueId_t CFDPHandler::getRequestQueue() { return this->requestQueue->getId(); }
return this->requestQueue->getId();
}

View File

@ -1,24 +1,23 @@
#ifndef FSFW_CFDP_CFDPHANDLER_H_ #ifndef FSFW_CFDP_CFDPHANDLER_H_
#define FSFW_CFDP_CFDPHANDLER_H_ #define FSFW_CFDP_CFDPHANDLER_H_
#include "fsfw/tmtcservices/AcceptsTelecommandsIF.h" #include "fsfw/ipc/MessageQueueIF.h"
#include "fsfw/objectmanager/SystemObject.h" #include "fsfw/objectmanager/SystemObject.h"
#include "fsfw/returnvalues/HasReturnvaluesIF.h" #include "fsfw/returnvalues/HasReturnvaluesIF.h"
#include "fsfw/tasks/ExecutableObjectIF.h" #include "fsfw/tasks/ExecutableObjectIF.h"
#include "fsfw/tcdistribution/CFDPDistributor.h" #include "fsfw/tcdistribution/CFDPDistributor.h"
#include "fsfw/tmtcservices/AcceptsTelecommandsIF.h"
#include "fsfw/ipc/MessageQueueIF.h"
namespace Factory { namespace Factory {
void setStaticFrameworkObjectIds(); void setStaticFrameworkObjectIds();
} }
class CFDPHandler : class CFDPHandler : public ExecutableObjectIF,
public ExecutableObjectIF,
public AcceptsTelecommandsIF, public AcceptsTelecommandsIF,
public SystemObject, public SystemObject,
public HasReturnvaluesIF { public HasReturnvaluesIF {
friend void(Factory::setStaticFrameworkObjectIds)(); friend void(Factory::setStaticFrameworkObjectIds)();
public: public:
CFDPHandler(object_id_t setObjectId, CFDPDistributor* distributor); CFDPHandler(object_id_t setObjectId, CFDPDistributor* distributor);
/** /**
@ -32,6 +31,7 @@ public:
virtual uint16_t getIdentifier() override; virtual uint16_t getIdentifier() override;
MessageQueueId_t getRequestQueue() override; MessageQueueId_t getRequestQueue() override;
ReturnValue_t performOperation(uint8_t opCode) override; ReturnValue_t performOperation(uint8_t opCode) override;
protected: protected:
/** /**
* This is a complete instance of the telecommand reception queue * This is a complete instance of the telecommand reception queue
@ -50,6 +50,7 @@ public:
static object_id_t packetSource; static object_id_t packetSource;
static object_id_t packetDestination; static object_id_t packetDestination;
private: private:
/** /**
* This constant sets the maximum number of packets accepted per call. * This constant sets the maximum number of packets accepted per call.

View File

@ -1,13 +1,10 @@
#include "CFDPMessage.h" #include "CFDPMessage.h"
CFDPMessage::CFDPMessage() { CFDPMessage::CFDPMessage() {}
}
CFDPMessage::~CFDPMessage() { CFDPMessage::~CFDPMessage() {}
}
void CFDPMessage::setCommand(CommandMessage *message, void CFDPMessage::setCommand(CommandMessage *message, store_address_t cfdpPacket) {
store_address_t cfdpPacket) {
message->setParameter(cfdpPacket.raw); message->setParameter(cfdpPacket.raw);
} }
@ -17,5 +14,4 @@ store_address_t CFDPMessage::getStoreId(const CommandMessage *message) {
return storeAddressCFDPPacket; return storeAddressCFDPPacket;
} }
void CFDPMessage::clear(CommandMessage *message) { void CFDPMessage::clear(CommandMessage *message) {}
}

View File

@ -8,12 +8,12 @@
class CFDPMessage { class CFDPMessage {
private: private:
CFDPMessage(); CFDPMessage();
public: public:
static const uint8_t MESSAGE_ID = messagetypes::CFDP; static const uint8_t MESSAGE_ID = messagetypes::CFDP;
virtual ~CFDPMessage(); virtual ~CFDPMessage();
static void setCommand(CommandMessage* message, static void setCommand(CommandMessage* message, store_address_t cfdpPacket);
store_address_t cfdpPacket);
static store_address_t getStoreId(const CommandMessage* message); static store_address_t getStoreId(const CommandMessage* message);

View File

@ -10,9 +10,7 @@ struct FileSize: public SerializeIF {
public: public:
FileSize() : largeFile(false){}; FileSize() : largeFile(false){};
FileSize(uint64_t fileSize, bool isLarge = false) { FileSize(uint64_t fileSize, bool isLarge = false) { setFileSize(fileSize, isLarge); };
setFileSize(fileSize, isLarge);
};
ReturnValue_t serialize(bool isLarge, uint8_t **buffer, size_t *size, size_t maxSize, ReturnValue_t serialize(bool isLarge, uint8_t **buffer, size_t *size, size_t maxSize,
Endianness streamEndianness) { Endianness streamEndianness) {
@ -24,9 +22,7 @@ public:
Endianness streamEndianness) const override { Endianness streamEndianness) const override {
if (not largeFile) { if (not largeFile) {
uint32_t fileSizeTyped = fileSize; uint32_t fileSizeTyped = fileSize;
return SerializeAdapter::serialize(&fileSizeTyped, buffer, size, maxSize, return SerializeAdapter::serialize(&fileSizeTyped, buffer, size, maxSize, streamEndianness);
streamEndianness);
} }
return SerializeAdapter::serialize(&fileSize, buffer, size, maxSize, streamEndianness); return SerializeAdapter::serialize(&fileSize, buffer, size, maxSize, streamEndianness);
} }
@ -45,8 +41,8 @@ public:
return SerializeAdapter::deSerialize(&size, buffer, size, streamEndianness); return SerializeAdapter::deSerialize(&size, buffer, size, streamEndianness);
} else { } else {
uint32_t sizeTmp = 0; uint32_t sizeTmp = 0;
ReturnValue_t result = SerializeAdapter::deSerialize(&sizeTmp, buffer, size, ReturnValue_t result =
streamEndianness); SerializeAdapter::deSerialize(&sizeTmp, buffer, size, streamEndianness);
if (result == HasReturnvaluesIF::RETURN_OK) { if (result == HasReturnvaluesIF::RETURN_OK) {
fileSize = sizeTmp; fileSize = sizeTmp;
} }
@ -64,20 +60,19 @@ public:
return HasReturnvaluesIF::RETURN_OK; return HasReturnvaluesIF::RETURN_OK;
} }
bool isLargeFile() const { bool isLargeFile() const { return largeFile; }
return largeFile;
}
uint64_t getSize(bool *largeFile = nullptr) const { uint64_t getSize(bool *largeFile = nullptr) const {
if (largeFile != nullptr) { if (largeFile != nullptr) {
*largeFile = this->largeFile; *largeFile = this->largeFile;
} }
return fileSize; return fileSize;
} }
private: private:
uint64_t fileSize = 0; uint64_t fileSize = 0;
bool largeFile = false; bool largeFile = false;
}; };
} } // namespace cfdp
#endif /* FSFW_SRC_FSFW_CFDP_FILESIZE_H_ */ #endif /* FSFW_SRC_FSFW_CFDP_FILESIZE_H_ */

View File

@ -2,10 +2,12 @@
#define FSFW_SRC_FSFW_CFDP_PDU_DEFINITIONS_H_ #define FSFW_SRC_FSFW_CFDP_PDU_DEFINITIONS_H_
#include <fsfw/serialize/SerializeIF.h> #include <fsfw/serialize/SerializeIF.h>
#include <cstdint>
#include <cstddef> #include <cstddef>
#include "fsfw/returnvalues/HasReturnvaluesIF.h" #include <cstdint>
#include "fsfw/returnvalues/FwClassIds.h" #include "fsfw/returnvalues/FwClassIds.h"
#include "fsfw/returnvalues/HasReturnvaluesIF.h"
namespace cfdp { namespace cfdp {
@ -47,25 +49,13 @@ enum ChecksumType {
NULL_CHECKSUM = 15 NULL_CHECKSUM = 15
}; };
enum PduType: bool { enum PduType : bool { FILE_DIRECTIVE = 0, FILE_DATA = 1 };
FILE_DIRECTIVE = 0,
FILE_DATA = 1
};
enum TransmissionModes: bool { enum TransmissionModes : bool { ACKNOWLEDGED = 0, UNACKNOWLEDGED = 1 };
ACKNOWLEDGED = 0,
UNACKNOWLEDGED = 1
};
enum SegmentMetadataFlag: bool { enum SegmentMetadataFlag : bool { NOT_PRESENT = 0, PRESENT = 1 };
NOT_PRESENT = 0,
PRESENT = 1
};
enum Direction: bool { enum Direction : bool { TOWARDS_RECEIVER = 0, TOWARDS_SENDER = 1 };
TOWARDS_RECEIVER = 0,
TOWARDS_SENDER = 1
};
enum SegmentationControl : bool { enum SegmentationControl : bool {
NO_RECORD_BOUNDARIES_PRESERVATION = 0, NO_RECORD_BOUNDARIES_PRESERVATION = 0,
@ -114,10 +104,7 @@ enum AckTransactionStatus {
UNRECOGNIZED = 0b11 UNRECOGNIZED = 0b11
}; };
enum FinishedDeliveryCode { enum FinishedDeliveryCode { DATA_COMPLETE = 0, DATA_INCOMPLETE = 1 };
DATA_COMPLETE = 0,
DATA_INCOMPLETE = 1
};
enum FinishedFileStatus { enum FinishedFileStatus {
DISCARDED_DELIBERATELY = 0, DISCARDED_DELIBERATELY = 0,
@ -126,10 +113,7 @@ enum FinishedFileStatus {
FILE_STATUS_UNREPORTED = 3 FILE_STATUS_UNREPORTED = 3
}; };
enum PromptResponseRequired: bool { enum PromptResponseRequired : bool { PROMPT_NAK = 0, PROMPT_KEEP_ALIVE = 1 };
PROMPT_NAK = 0,
PROMPT_KEEP_ALIVE = 1
};
enum TlvTypes : uint8_t { enum TlvTypes : uint8_t {
FILESTORE_REQUEST = 0x00, FILESTORE_REQUEST = 0x00,
@ -148,6 +132,6 @@ enum RecordContinuationState {
CONTAINS_START_AND_END = 0b11 CONTAINS_START_AND_END = 0b11
}; };
} } // namespace cfdp
#endif /* FSFW_SRC_FSFW_CFDP_PDU_DEFINITIONS_H_ */ #endif /* FSFW_SRC_FSFW_CFDP_PDU_DEFINITIONS_H_ */

View File

@ -1,9 +1,11 @@
#include "AckInfo.h" #include "AckInfo.h"
AckInfo::AckInfo(cfdp::FileDirectives ackedDirective, cfdp::ConditionCode ackedConditionCode, AckInfo::AckInfo(cfdp::FileDirectives ackedDirective, cfdp::ConditionCode ackedConditionCode,
cfdp::AckTransactionStatus transactionStatus, uint8_t directiveSubtypeCode): cfdp::AckTransactionStatus transactionStatus, uint8_t directiveSubtypeCode)
ackedDirective(ackedDirective), ackedConditionCode(ackedConditionCode), : ackedDirective(ackedDirective),
transactionStatus(transactionStatus), directiveSubtypeCode(directiveSubtypeCode) { ackedConditionCode(ackedConditionCode),
transactionStatus(transactionStatus),
directiveSubtypeCode(directiveSubtypeCode) {
if (ackedDirective == cfdp::FileDirectives::FINISH) { if (ackedDirective == cfdp::FileDirectives::FINISH) {
this->directiveSubtypeCode = 0b0001; this->directiveSubtypeCode = 0b0001;
} else { } else {
@ -11,9 +13,7 @@ AckInfo::AckInfo(cfdp::FileDirectives ackedDirective, cfdp::ConditionCode ackedC
} }
} }
cfdp::ConditionCode AckInfo::getAckedConditionCode() const { cfdp::ConditionCode AckInfo::getAckedConditionCode() const { return ackedConditionCode; }
return ackedConditionCode;
}
void AckInfo::setAckedConditionCode(cfdp::ConditionCode ackedConditionCode) { void AckInfo::setAckedConditionCode(cfdp::ConditionCode ackedConditionCode) {
this->ackedConditionCode = ackedConditionCode; this->ackedConditionCode = ackedConditionCode;
@ -24,28 +24,21 @@ void AckInfo::setAckedConditionCode(cfdp::ConditionCode ackedConditionCode) {
} }
} }
cfdp::FileDirectives AckInfo::getAckedDirective() const { cfdp::FileDirectives AckInfo::getAckedDirective() const { return ackedDirective; }
return ackedDirective;
}
void AckInfo::setAckedDirective(cfdp::FileDirectives ackedDirective) { void AckInfo::setAckedDirective(cfdp::FileDirectives ackedDirective) {
this->ackedDirective = ackedDirective; this->ackedDirective = ackedDirective;
} }
uint8_t AckInfo::getDirectiveSubtypeCode() const { uint8_t AckInfo::getDirectiveSubtypeCode() const { return directiveSubtypeCode; }
return directiveSubtypeCode;
}
void AckInfo::setDirectiveSubtypeCode(uint8_t directiveSubtypeCode) { void AckInfo::setDirectiveSubtypeCode(uint8_t directiveSubtypeCode) {
this->directiveSubtypeCode = directiveSubtypeCode; this->directiveSubtypeCode = directiveSubtypeCode;
} }
cfdp::AckTransactionStatus AckInfo::getTransactionStatus() const { cfdp::AckTransactionStatus AckInfo::getTransactionStatus() const { return transactionStatus; }
return transactionStatus;
}
AckInfo::AckInfo() { AckInfo::AckInfo() {}
}
void AckInfo::setTransactionStatus(cfdp::AckTransactionStatus transactionStatus) { void AckInfo::setTransactionStatus(cfdp::AckTransactionStatus transactionStatus) {
this->transactionStatus = transactionStatus; this->transactionStatus = transactionStatus;

View File

@ -28,6 +28,4 @@ private:
uint8_t directiveSubtypeCode = 0; uint8_t directiveSubtypeCode = 0;
}; };
#endif /* FSFW_SRC_FSFW_CFDP_PDU_ACKINFO_H_ */ #endif /* FSFW_SRC_FSFW_CFDP_PDU_ACKINFO_H_ */

View File

@ -1,8 +1,7 @@
#include "AckPduDeserializer.h" #include "AckPduDeserializer.h"
AckPduDeserializer::AckPduDeserializer(const uint8_t *pduBuf, size_t maxSize, AckInfo& info): AckPduDeserializer::AckPduDeserializer(const uint8_t* pduBuf, size_t maxSize, AckInfo& info)
FileDirectiveDeserializer(pduBuf, maxSize), info(info) { : FileDirectiveDeserializer(pduBuf, maxSize), info(info) {}
}
ReturnValue_t AckPduDeserializer::parseData() { ReturnValue_t AckPduDeserializer::parseData() {
ReturnValue_t result = FileDirectiveDeserializer::parseData(); ReturnValue_t result = FileDirectiveDeserializer::parseData();

View File

@ -1,8 +1,8 @@
#ifndef FSFW_SRC_FSFW_CFDP_PDU_ACKPDUDESERIALIZER_H_ #ifndef FSFW_SRC_FSFW_CFDP_PDU_ACKPDUDESERIALIZER_H_
#define FSFW_SRC_FSFW_CFDP_PDU_ACKPDUDESERIALIZER_H_ #define FSFW_SRC_FSFW_CFDP_PDU_ACKPDUDESERIALIZER_H_
#include "fsfw/cfdp/pdu/FileDirectiveDeserializer.h"
#include "AckInfo.h" #include "AckInfo.h"
#include "fsfw/cfdp/pdu/FileDirectiveDeserializer.h"
class AckPduDeserializer : public FileDirectiveDeserializer { class AckPduDeserializer : public FileDirectiveDeserializer {
public: public:
@ -18,9 +18,6 @@ public:
private: private:
bool checkAndSetCodes(uint8_t rawAckedByte, uint8_t rawAckedConditionCode); bool checkAndSetCodes(uint8_t rawAckedByte, uint8_t rawAckedConditionCode);
AckInfo& info; AckInfo& info;
}; };
#endif /* FSFW_SRC_FSFW_CFDP_PDU_ACKPDUDESERIALIZER_H_ */ #endif /* FSFW_SRC_FSFW_CFDP_PDU_ACKPDUDESERIALIZER_H_ */

View File

@ -1,9 +1,7 @@
#include "AckPduSerializer.h" #include "AckPduSerializer.h"
AckPduSerializer::AckPduSerializer(AckInfo& ackInfo, PduConfig &pduConf): AckPduSerializer::AckPduSerializer(AckInfo &ackInfo, PduConfig &pduConf)
FileDirectiveSerializer(pduConf, cfdp::FileDirectives::ACK, 2), : FileDirectiveSerializer(pduConf, cfdp::FileDirectives::ACK, 2), ackInfo(ackInfo) {}
ackInfo(ackInfo) {
}
size_t AckPduSerializer::getSerializedSize() const { size_t AckPduSerializer::getSerializedSize() const {
return FileDirectiveSerializer::getWholePduSize(); return FileDirectiveSerializer::getWholePduSize();
@ -11,8 +9,8 @@ size_t AckPduSerializer::getSerializedSize() const {
ReturnValue_t AckPduSerializer::serialize(uint8_t **buffer, size_t *size, size_t maxSize, ReturnValue_t AckPduSerializer::serialize(uint8_t **buffer, size_t *size, size_t maxSize,
Endianness streamEndianness) const { Endianness streamEndianness) const {
ReturnValue_t result = FileDirectiveSerializer::serialize(buffer, size, maxSize, ReturnValue_t result =
streamEndianness); FileDirectiveSerializer::serialize(buffer, size, maxSize, streamEndianness);
if (result != HasReturnvaluesIF::RETURN_OK) { if (result != HasReturnvaluesIF::RETURN_OK) {
return result; return result;
} }

View File

@ -1,41 +1,30 @@
#include "EofInfo.h" #include "EofInfo.h"
EofInfo::EofInfo(cfdp::ConditionCode conditionCode, uint32_t checksum, cfdp::FileSize fileSize, EofInfo::EofInfo(cfdp::ConditionCode conditionCode, uint32_t checksum, cfdp::FileSize fileSize,
EntityIdTlv* faultLoc): conditionCode(conditionCode), checksum(checksum), EntityIdTlv* faultLoc)
fileSize(fileSize), faultLoc(faultLoc) { : conditionCode(conditionCode), checksum(checksum), fileSize(fileSize), faultLoc(faultLoc) {}
}
EofInfo::EofInfo(EntityIdTlv *faultLoc): conditionCode(cfdp::ConditionCode::NO_CONDITION_FIELD), EofInfo::EofInfo(EntityIdTlv* faultLoc)
checksum(0), fileSize(0), faultLoc(faultLoc) { : conditionCode(cfdp::ConditionCode::NO_CONDITION_FIELD),
} checksum(0),
fileSize(0),
faultLoc(faultLoc) {}
uint32_t EofInfo::getChecksum() const { uint32_t EofInfo::getChecksum() const { return checksum; }
return checksum;
}
cfdp::ConditionCode EofInfo::getConditionCode() const { cfdp::ConditionCode EofInfo::getConditionCode() const { return conditionCode; }
return conditionCode;
}
EntityIdTlv* EofInfo::getFaultLoc() const { EntityIdTlv* EofInfo::getFaultLoc() const { return faultLoc; }
return faultLoc;
}
cfdp::FileSize& EofInfo::getFileSize() { cfdp::FileSize& EofInfo::getFileSize() { return fileSize; }
return fileSize;
}
void EofInfo::setChecksum(uint32_t checksum) { void EofInfo::setChecksum(uint32_t checksum) { this->checksum = checksum; }
this->checksum = checksum;
}
void EofInfo::setConditionCode(cfdp::ConditionCode conditionCode) { void EofInfo::setConditionCode(cfdp::ConditionCode conditionCode) {
this->conditionCode = conditionCode; this->conditionCode = conditionCode;
} }
void EofInfo::setFaultLoc(EntityIdTlv *faultLoc) { void EofInfo::setFaultLoc(EntityIdTlv* faultLoc) { this->faultLoc = faultLoc; }
this->faultLoc = faultLoc;
}
size_t EofInfo::getSerializedSize(bool fssLarge) { size_t EofInfo::getSerializedSize(bool fssLarge) {
// Condition code + spare + 4 byte checksum // Condition code + spare + 4 byte checksum

View File

@ -1,9 +1,9 @@
#ifndef FSFW_SRC_FSFW_CFDP_PDU_EOFINFO_H_ #ifndef FSFW_SRC_FSFW_CFDP_PDU_EOFINFO_H_
#define FSFW_SRC_FSFW_CFDP_PDU_EOFINFO_H_ #define FSFW_SRC_FSFW_CFDP_PDU_EOFINFO_H_
#include "fsfw/cfdp/tlv/EntityIdTlv.h"
#include "../definitions.h"
#include "../FileSize.h" #include "../FileSize.h"
#include "../definitions.h"
#include "fsfw/cfdp/tlv/EntityIdTlv.h"
struct EofInfo { struct EofInfo {
public: public:
@ -22,8 +22,8 @@ public:
void setConditionCode(cfdp::ConditionCode conditionCode); void setConditionCode(cfdp::ConditionCode conditionCode);
void setFaultLoc(EntityIdTlv* faultLoc); void setFaultLoc(EntityIdTlv* faultLoc);
ReturnValue_t setFileSize(size_t size, bool isLarge); ReturnValue_t setFileSize(size_t size, bool isLarge);
private:
private:
cfdp::ConditionCode conditionCode; cfdp::ConditionCode conditionCode;
uint32_t checksum; uint32_t checksum;
cfdp::FileSize fileSize; cfdp::FileSize fileSize;

View File

@ -1,10 +1,10 @@
#include "EofPduDeserializer.h" #include "EofPduDeserializer.h"
#include "fsfw/FSFW.h" #include "fsfw/FSFW.h"
#include "fsfw/serviceinterface.h" #include "fsfw/serviceinterface.h"
EofPduDeserializer::EofPduDeserializer(const uint8_t *pduBuf, size_t maxSize, EofInfo& eofInfo): EofPduDeserializer::EofPduDeserializer(const uint8_t* pduBuf, size_t maxSize, EofInfo& eofInfo)
FileDirectiveDeserializer(pduBuf, maxSize), info(eofInfo) { : FileDirectiveDeserializer(pduBuf, maxSize), info(eofInfo) {}
}
ReturnValue_t EofPduDeserializer::parseData() { ReturnValue_t EofPduDeserializer::parseData() {
ReturnValue_t result = FileDirectiveDeserializer::parseData(); ReturnValue_t result = FileDirectiveDeserializer::parseData();
@ -39,8 +39,7 @@ ReturnValue_t EofPduDeserializer::parseData() {
uint64_t fileSizeValue = 0; uint64_t fileSizeValue = 0;
result = SerializeAdapter::deSerialize(&fileSizeValue, &bufPtr, &deserLen, endianness); result = SerializeAdapter::deSerialize(&fileSizeValue, &bufPtr, &deserLen, endianness);
info.setFileSize(fileSizeValue, true); info.setFileSize(fileSizeValue, true);
} } else {
else {
uint32_t fileSizeValue = 0; uint32_t fileSizeValue = 0;
result = SerializeAdapter::deSerialize(&fileSizeValue, &bufPtr, &deserLen, endianness); result = SerializeAdapter::deSerialize(&fileSizeValue, &bufPtr, &deserLen, endianness);
info.setFileSize(fileSizeValue, false); info.setFileSize(fileSizeValue, false);
@ -54,9 +53,11 @@ ReturnValue_t EofPduDeserializer::parseData() {
#if FSFW_VERBOSE_LEVEL >= 1 #if FSFW_VERBOSE_LEVEL >= 1
#if FSFW_CPP_OSTREAM_ENABLED == 1 #if FSFW_CPP_OSTREAM_ENABLED == 1
sif::warning << "EofPduDeserializer::parseData: Ca not deserialize fault location," sif::warning << "EofPduDeserializer::parseData: Ca not deserialize fault location,"
" given TLV pointer invalid" << std::endl; " given TLV pointer invalid"
<< std::endl;
#else #else
sif::printWarning("EofPduDeserializer::parseData: Ca not deserialize fault location," sif::printWarning(
"EofPduDeserializer::parseData: Ca not deserialize fault location,"
" given TLV pointer invalid"); " given TLV pointer invalid");
#endif #endif
#endif /* FSFW_VERBOSE_LEVEL >= 1 */ #endif /* FSFW_VERBOSE_LEVEL >= 1 */

View File

@ -1,18 +1,17 @@
#ifndef FSFW_SRC_FSFW_CFDP_PDU_EOFPDUDESERIALIZER_H_ #ifndef FSFW_SRC_FSFW_CFDP_PDU_EOFPDUDESERIALIZER_H_
#define FSFW_SRC_FSFW_CFDP_PDU_EOFPDUDESERIALIZER_H_ #define FSFW_SRC_FSFW_CFDP_PDU_EOFPDUDESERIALIZER_H_
#include "fsfw/cfdp/pdu/FileDirectiveDeserializer.h"
#include "EofInfo.h" #include "EofInfo.h"
#include "fsfw/cfdp/pdu/FileDirectiveDeserializer.h"
class EofPduDeserializer : public FileDirectiveDeserializer { class EofPduDeserializer : public FileDirectiveDeserializer {
public: public:
EofPduDeserializer(const uint8_t* pduBuf, size_t maxSize, EofInfo& eofInfo); EofPduDeserializer(const uint8_t* pduBuf, size_t maxSize, EofInfo& eofInfo);
virtual ReturnValue_t parseData() override; virtual ReturnValue_t parseData() override;
private: private:
EofInfo& info; EofInfo& info;
}; };
#endif /* FSFW_SRC_FSFW_CFDP_PDU_EOFPDUDESERIALIZER_H_ */ #endif /* FSFW_SRC_FSFW_CFDP_PDU_EOFPDUDESERIALIZER_H_ */

View File

@ -1,9 +1,10 @@
#include "fsfw/FSFW.h"
#include "fsfw/serviceinterface.h"
#include "EofPduSerializer.h" #include "EofPduSerializer.h"
EofPduSerializer::EofPduSerializer(PduConfig &conf, EofInfo& info): #include "fsfw/FSFW.h"
FileDirectiveSerializer(conf, cfdp::FileDirectives::EOF_DIRECTIVE, 9), info(info) { #include "fsfw/serviceinterface.h"
EofPduSerializer::EofPduSerializer(PduConfig &conf, EofInfo &info)
: FileDirectiveSerializer(conf, cfdp::FileDirectives::EOF_DIRECTIVE, 9), info(info) {
setDirectiveDataFieldLen(info.getSerializedSize(getLargeFileFlag())); setDirectiveDataFieldLen(info.getSerializedSize(getLargeFileFlag()));
} }
@ -13,8 +14,8 @@ size_t EofPduSerializer::getSerializedSize() const {
ReturnValue_t EofPduSerializer::serialize(uint8_t **buffer, size_t *size, size_t maxSize, ReturnValue_t EofPduSerializer::serialize(uint8_t **buffer, size_t *size, size_t maxSize,
Endianness streamEndianness) const { Endianness streamEndianness) const {
ReturnValue_t result = FileDirectiveSerializer::serialize(buffer, size, maxSize, ReturnValue_t result =
streamEndianness); FileDirectiveSerializer::serialize(buffer, size, maxSize, streamEndianness);
if (result != HasReturnvaluesIF::RETURN_OK) { if (result != HasReturnvaluesIF::RETURN_OK) {
return result; return result;
} }
@ -31,13 +32,10 @@ ReturnValue_t EofPduSerializer::serialize(uint8_t **buffer, size_t *size, size_t
} }
if (info.getFileSize().isLargeFile()) { if (info.getFileSize().isLargeFile()) {
uint64_t fileSizeValue = info.getFileSize().getSize(); uint64_t fileSizeValue = info.getFileSize().getSize();
result = SerializeAdapter::serialize(&fileSizeValue, buffer, size, result = SerializeAdapter::serialize(&fileSizeValue, buffer, size, maxSize, streamEndianness);
maxSize, streamEndianness); } else {
}
else {
uint32_t fileSizeValue = info.getFileSize().getSize(); uint32_t fileSizeValue = info.getFileSize().getSize();
result = SerializeAdapter::serialize(&fileSizeValue, buffer, size, result = SerializeAdapter::serialize(&fileSizeValue, buffer, size, maxSize, streamEndianness);
maxSize, streamEndianness);
} }
if (info.getFaultLoc() != nullptr and info.getConditionCode() != cfdp::ConditionCode::NO_ERROR) { if (info.getFaultLoc() != nullptr and info.getConditionCode() != cfdp::ConditionCode::NO_ERROR) {
result = info.getFaultLoc()->serialize(buffer, size, maxSize, streamEndianness); result = info.getFaultLoc()->serialize(buffer, size, maxSize, streamEndianness);

View File

@ -1,9 +1,9 @@
#ifndef FSFW_SRC_FSFW_CFDP_PDU_EOFPDUSERIALIZER_H_ #ifndef FSFW_SRC_FSFW_CFDP_PDU_EOFPDUSERIALIZER_H_
#define FSFW_SRC_FSFW_CFDP_PDU_EOFPDUSERIALIZER_H_ #define FSFW_SRC_FSFW_CFDP_PDU_EOFPDUSERIALIZER_H_
#include "EofInfo.h"
#include "fsfw/cfdp/pdu/FileDirectiveSerializer.h" #include "fsfw/cfdp/pdu/FileDirectiveSerializer.h"
#include "fsfw/cfdp/tlv/EntityIdTlv.h" #include "fsfw/cfdp/tlv/EntityIdTlv.h"
#include "EofInfo.h"
class EofPduSerializer : public FileDirectiveSerializer { class EofPduSerializer : public FileDirectiveSerializer {
public: public:
@ -13,10 +13,9 @@ public:
ReturnValue_t serialize(uint8_t** buffer, size_t* size, size_t maxSize, ReturnValue_t serialize(uint8_t** buffer, size_t* size, size_t maxSize,
Endianness streamEndianness) const override; Endianness streamEndianness) const override;
private: private:
EofInfo& info; EofInfo& info;
}; };
#endif /* FSFW_SRC_FSFW_CFDP_PDU_EOFPDUSERIALIZER_H_ */ #endif /* FSFW_SRC_FSFW_CFDP_PDU_EOFPDUSERIALIZER_H_ */

View File

@ -1,9 +1,8 @@
#include "FileDataDeserializer.h" #include "FileDataDeserializer.h"
FileDataDeserializer::FileDataDeserializer(const uint8_t* pduBuf, size_t maxSize, FileDataDeserializer::FileDataDeserializer(const uint8_t* pduBuf, size_t maxSize,
FileDataInfo& info): FileDataInfo& info)
HeaderDeserializer(pduBuf, maxSize), info(info) { : HeaderDeserializer(pduBuf, maxSize), info(info) {}
}
ReturnValue_t FileDataDeserializer::parseData() { ReturnValue_t FileDataDeserializer::parseData() {
ReturnValue_t result = HeaderDeserializer::parseData(); ReturnValue_t result = HeaderDeserializer::parseData();
@ -18,8 +17,7 @@ ReturnValue_t FileDataDeserializer::parseData() {
} }
if (hasSegmentMetadataFlag()) { if (hasSegmentMetadataFlag()) {
info.setSegmentMetadataFlag(true); info.setSegmentMetadataFlag(true);
info.setRecordContinuationState(static_cast<cfdp::RecordContinuationState>( info.setRecordContinuationState(static_cast<cfdp::RecordContinuationState>((*buf >> 6) & 0b11));
(*buf >> 6) & 0b11));
size_t segmentMetadataLen = *buf & 0b00111111; size_t segmentMetadataLen = *buf & 0b00111111;
info.setSegmentMetadataLen(segmentMetadataLen); info.setSegmentMetadataLen(segmentMetadataLen);
if (remSize < segmentMetadataLen + 1) { if (remSize < segmentMetadataLen + 1) {
@ -43,9 +41,7 @@ ReturnValue_t FileDataDeserializer::parseData() {
return HasReturnvaluesIF::RETURN_OK; return HasReturnvaluesIF::RETURN_OK;
} }
SerializeIF::Endianness FileDataDeserializer::getEndianness() const { SerializeIF::Endianness FileDataDeserializer::getEndianness() const { return endianness; }
return endianness;
}
void FileDataDeserializer::setEndianness(SerializeIF::Endianness endianness) { void FileDataDeserializer::setEndianness(SerializeIF::Endianness endianness) {
this->endianness = endianness; this->endianness = endianness;

View File

@ -1,9 +1,9 @@
#ifndef FSFW_SRC_FSFW_CFDP_PDU_FILEDATADESERIALIZER_H_ #ifndef FSFW_SRC_FSFW_CFDP_PDU_FILEDATADESERIALIZER_H_
#define FSFW_SRC_FSFW_CFDP_PDU_FILEDATADESERIALIZER_H_ #define FSFW_SRC_FSFW_CFDP_PDU_FILEDATADESERIALIZER_H_
#include "../definitions.h"
#include "FileDataInfo.h" #include "FileDataInfo.h"
#include "HeaderDeserializer.h" #include "HeaderDeserializer.h"
#include "../definitions.h"
class FileDataDeserializer : public HeaderDeserializer { class FileDataDeserializer : public HeaderDeserializer {
public: public:
@ -14,7 +14,6 @@ public:
void setEndianness(SerializeIF::Endianness endianness = SerializeIF::Endianness::NETWORK); void setEndianness(SerializeIF::Endianness endianness = SerializeIF::Endianness::NETWORK);
private: private:
SerializeIF::Endianness endianness = SerializeIF::Endianness::NETWORK; SerializeIF::Endianness endianness = SerializeIF::Endianness::NETWORK;
FileDataInfo& info; FileDataInfo& info;
}; };

View File

@ -1,11 +1,9 @@
#include "FileDataInfo.h" #include "FileDataInfo.h"
FileDataInfo::FileDataInfo(cfdp::FileSize &offset, const uint8_t *fileData, size_t fileSize): FileDataInfo::FileDataInfo(cfdp::FileSize &offset, const uint8_t *fileData, size_t fileSize)
offset(offset), fileData(fileData), fileSize(fileSize) { : offset(offset), fileData(fileData), fileSize(fileSize) {}
}
FileDataInfo::FileDataInfo(cfdp::FileSize &offset): offset(offset) { FileDataInfo::FileDataInfo(cfdp::FileSize &offset) : offset(offset) {}
}
void FileDataInfo::setSegmentMetadataFlag(bool enable) { void FileDataInfo::setSegmentMetadataFlag(bool enable) {
if (enable) { if (enable) {
@ -44,12 +42,11 @@ cfdp::RecordContinuationState FileDataInfo::getRecordContinuationState() const {
return this->recContState; return this->recContState;
} }
size_t FileDataInfo::getSegmentMetadataLen() const { size_t FileDataInfo::getSegmentMetadataLen() const { return segmentMetadataLen; }
return segmentMetadataLen;
}
ReturnValue_t FileDataInfo::addSegmentMetadataInfo(cfdp::RecordContinuationState recContState, ReturnValue_t FileDataInfo::addSegmentMetadataInfo(cfdp::RecordContinuationState recContState,
const uint8_t* segmentMetadata, size_t segmentMetadataLen) { const uint8_t *segmentMetadata,
size_t segmentMetadataLen) {
this->segmentMetadataFlag = cfdp::SegmentMetadataFlag::PRESENT; this->segmentMetadataFlag = cfdp::SegmentMetadataFlag::PRESENT;
this->recContState = recContState; this->recContState = recContState;
if (segmentMetadataLen > 63) { if (segmentMetadataLen > 63) {
@ -74,30 +71,22 @@ const uint8_t* FileDataInfo::getSegmentMetadata(size_t *segmentMetadataLen) {
return segmentMetadata; return segmentMetadata;
} }
cfdp::FileSize& FileDataInfo::getOffset() { cfdp::FileSize &FileDataInfo::getOffset() { return offset; }
return offset;
}
void FileDataInfo::setRecordContinuationState(cfdp::RecordContinuationState recContState) { void FileDataInfo::setRecordContinuationState(cfdp::RecordContinuationState recContState) {
this->recContState = recContState; this->recContState = recContState;
} }
void FileDataInfo::setSegmentMetadataLen(size_t len) { void FileDataInfo::setSegmentMetadataLen(size_t len) { this->segmentMetadataLen = len; }
this->segmentMetadataLen = len;
}
void FileDataInfo::setSegmentMetadata(const uint8_t *ptr) { void FileDataInfo::setSegmentMetadata(const uint8_t *ptr) { this->segmentMetadata = ptr; }
this->segmentMetadata = ptr;
}
void FileDataInfo::setFileData(const uint8_t *fileData, size_t fileSize) { void FileDataInfo::setFileData(const uint8_t *fileData, size_t fileSize) {
this->fileData = fileData; this->fileData = fileData;
this->fileSize = fileSize; this->fileSize = fileSize;
} }
cfdp::SegmentationControl FileDataInfo::getSegmentationControl() const { cfdp::SegmentationControl FileDataInfo::getSegmentationControl() const { return segCtrl; }
return segCtrl;
}
void FileDataInfo::setSegmentationControl(cfdp::SegmentationControl segCtrl) { void FileDataInfo::setSegmentationControl(cfdp::SegmentationControl segCtrl) {
this->segCtrl = segCtrl; this->segCtrl = segCtrl;

View File

@ -1,8 +1,8 @@
#ifndef FSFW_SRC_FSFW_CFDP_PDU_FILEDATAINFO_H_ #ifndef FSFW_SRC_FSFW_CFDP_PDU_FILEDATAINFO_H_
#define FSFW_SRC_FSFW_CFDP_PDU_FILEDATAINFO_H_ #define FSFW_SRC_FSFW_CFDP_PDU_FILEDATAINFO_H_
#include <fsfw/cfdp/definitions.h>
#include <fsfw/cfdp/FileSize.h> #include <fsfw/cfdp/FileSize.h>
#include <fsfw/cfdp/definitions.h>
class FileDataInfo { class FileDataInfo {
public: public:
@ -32,8 +32,7 @@ public:
private: private:
cfdp::SegmentMetadataFlag segmentMetadataFlag = cfdp::SegmentMetadataFlag::NOT_PRESENT; cfdp::SegmentMetadataFlag segmentMetadataFlag = cfdp::SegmentMetadataFlag::NOT_PRESENT;
cfdp::SegmentationControl segCtrl = cfdp::SegmentationControl segCtrl = cfdp::SegmentationControl::NO_RECORD_BOUNDARIES_PRESERVATION;
cfdp::SegmentationControl::NO_RECORD_BOUNDARIES_PRESERVATION;
cfdp::FileSize& offset; cfdp::FileSize& offset;
const uint8_t* fileData = nullptr; const uint8_t* fileData = nullptr;
size_t fileSize = 0; size_t fileSize = 0;

View File

@ -1,8 +1,9 @@
#include "FileDataSerializer.h" #include "FileDataSerializer.h"
#include <cstring> #include <cstring>
FileDataSerializer::FileDataSerializer(PduConfig& conf, FileDataInfo& info): FileDataSerializer::FileDataSerializer(PduConfig& conf, FileDataInfo& info)
HeaderSerializer(conf, cfdp::PduType::FILE_DATA, 0, info.getSegmentMetadataFlag()), : HeaderSerializer(conf, cfdp::PduType::FILE_DATA, 0, info.getSegmentMetadataFlag()),
info(info) { info(info) {
update(); update();
} }

View File

@ -1,8 +1,8 @@
#ifndef FSFW_SRC_FSFW_CFDP_PDU_FILEDATASERIALIZER_H_ #ifndef FSFW_SRC_FSFW_CFDP_PDU_FILEDATASERIALIZER_H_
#define FSFW_SRC_FSFW_CFDP_PDU_FILEDATASERIALIZER_H_ #define FSFW_SRC_FSFW_CFDP_PDU_FILEDATASERIALIZER_H_
#include "FileDataInfo.h"
#include "../definitions.h" #include "../definitions.h"
#include "FileDataInfo.h"
#include "HeaderSerializer.h" #include "HeaderSerializer.h"
class FileDataSerializer : public HeaderSerializer { class FileDataSerializer : public HeaderSerializer {

View File

@ -1,12 +1,9 @@
#include "FileDirectiveDeserializer.h" #include "FileDirectiveDeserializer.h"
FileDirectiveDeserializer::FileDirectiveDeserializer(const uint8_t *pduBuf, size_t maxSize): FileDirectiveDeserializer::FileDirectiveDeserializer(const uint8_t *pduBuf, size_t maxSize)
HeaderDeserializer(pduBuf, maxSize) { : HeaderDeserializer(pduBuf, maxSize) {}
}
cfdp::FileDirectives FileDirectiveDeserializer::getFileDirective() const { cfdp::FileDirectives FileDirectiveDeserializer::getFileDirective() const { return fileDirective; }
return fileDirective;
}
ReturnValue_t FileDirectiveDeserializer::parseData() { ReturnValue_t FileDirectiveDeserializer::parseData() {
ReturnValue_t result = HeaderDeserializer::parseData(); ReturnValue_t result = HeaderDeserializer::parseData();
@ -34,8 +31,7 @@ size_t FileDirectiveDeserializer::getHeaderSize() const {
bool FileDirectiveDeserializer::checkFileDirective(uint8_t rawByte) { bool FileDirectiveDeserializer::checkFileDirective(uint8_t rawByte) {
if (rawByte < cfdp::FileDirectives::EOF_DIRECTIVE or if (rawByte < cfdp::FileDirectives::EOF_DIRECTIVE or
(rawByte > cfdp::FileDirectives::PROMPT and (rawByte > cfdp::FileDirectives::PROMPT and rawByte != cfdp::FileDirectives::KEEP_ALIVE)) {
rawByte != cfdp::FileDirectives::KEEP_ALIVE)) {
// Invalid directive field. TODO: Custom returnvalue // Invalid directive field. TODO: Custom returnvalue
return false; return false;
} }
@ -50,6 +46,4 @@ void FileDirectiveDeserializer::setEndianness(SerializeIF::Endianness endianness
this->endianness = endianness; this->endianness = endianness;
} }
SerializeIF::Endianness FileDirectiveDeserializer::getEndianness() const { SerializeIF::Endianness FileDirectiveDeserializer::getEndianness() const { return endianness; }
return endianness;
}

View File

@ -36,6 +36,4 @@ private:
SerializeIF::Endianness endianness = SerializeIF::Endianness::NETWORK; SerializeIF::Endianness endianness = SerializeIF::Endianness::NETWORK;
}; };
#endif /* FSFW_SRC_FSFW_CFDP_PDU_FILEDIRECTIVEDESERIALIZER_H_ */ #endif /* FSFW_SRC_FSFW_CFDP_PDU_FILEDIRECTIVEDESERIALIZER_H_ */

View File

@ -1,11 +1,10 @@
#include "FileDirectiveSerializer.h" #include "FileDirectiveSerializer.h"
FileDirectiveSerializer::FileDirectiveSerializer(PduConfig &pduConf, FileDirectiveSerializer::FileDirectiveSerializer(PduConfig &pduConf,
cfdp::FileDirectives directiveCode, size_t directiveParamFieldLen): cfdp::FileDirectives directiveCode,
HeaderSerializer(pduConf, cfdp::PduType::FILE_DIRECTIVE, directiveParamFieldLen + 1), size_t directiveParamFieldLen)
directiveCode(directiveCode) { : HeaderSerializer(pduConf, cfdp::PduType::FILE_DIRECTIVE, directiveParamFieldLen + 1),
} directiveCode(directiveCode) {}
size_t FileDirectiveSerializer::getSerializedSize() const { size_t FileDirectiveSerializer::getSerializedSize() const {
return HeaderSerializer::getSerializedSize() + 1; return HeaderSerializer::getSerializedSize() + 1;

View File

@ -20,9 +20,9 @@ public:
Endianness streamEndianness) const override; Endianness streamEndianness) const override;
void setDirectiveDataFieldLen(size_t len); void setDirectiveDataFieldLen(size_t len);
private: private:
cfdp::FileDirectives directiveCode = cfdp::FileDirectives::INVALID_DIRECTIVE; cfdp::FileDirectives directiveCode = cfdp::FileDirectives::INVALID_DIRECTIVE;
}; };
#endif /* FSFW_SRC_FSFW_CFDP_PDU_FILEDIRECTIVESERIALIZER_H_ */ #endif /* FSFW_SRC_FSFW_CFDP_PDU_FILEDIRECTIVESERIALIZER_H_ */

View File

@ -1,13 +1,11 @@
#include "FinishedInfo.h" #include "FinishedInfo.h"
FinishedInfo::FinishedInfo() { FinishedInfo::FinishedInfo() {}
}
FinishedInfo::FinishedInfo(cfdp::ConditionCode conditionCode, FinishedInfo::FinishedInfo(cfdp::ConditionCode conditionCode,
cfdp::FinishedDeliveryCode deliveryCode, cfdp::FinishedFileStatus fileStatus): cfdp::FinishedDeliveryCode deliveryCode,
conditionCode(conditionCode), deliveryCode(deliveryCode), fileStatus(fileStatus) { cfdp::FinishedFileStatus fileStatus)
} : conditionCode(conditionCode), deliveryCode(deliveryCode), fileStatus(fileStatus) {}
size_t FinishedInfo::getSerializedSize() const { size_t FinishedInfo::getSerializedSize() const {
size_t size = 1; size_t size = 1;
@ -35,9 +33,9 @@ bool FinishedInfo::canHoldFsResponses() const {
return false; return false;
} }
ReturnValue_t FinishedInfo::setFilestoreResponsesArray(FilestoreResponseTlv** fsResponses, ReturnValue_t FinishedInfo::setFilestoreResponsesArray(FilestoreResponseTlv** fsResponses,
size_t* fsResponsesLen, const size_t* maxFsResponsesLen) { size_t* fsResponsesLen,
const size_t* maxFsResponsesLen) {
this->fsResponses = fsResponses; this->fsResponses = fsResponses;
if (fsResponsesLen != nullptr) { if (fsResponsesLen != nullptr) {
this->fsResponsesLen = *fsResponsesLen; this->fsResponsesLen = *fsResponsesLen;
@ -52,7 +50,8 @@ ReturnValue_t FinishedInfo::setFilestoreResponsesArray(FilestoreResponseTlv** fs
} }
ReturnValue_t FinishedInfo::getFilestoreResonses(FilestoreResponseTlv*** fsResponses, ReturnValue_t FinishedInfo::getFilestoreResonses(FilestoreResponseTlv*** fsResponses,
size_t *fsResponsesLen, size_t* fsResponsesMaxLen) { size_t* fsResponsesLen,
size_t* fsResponsesMaxLen) {
if (fsResponses == nullptr) { if (fsResponses == nullptr) {
return HasReturnvaluesIF::RETURN_FAILED; return HasReturnvaluesIF::RETURN_FAILED;
} }
@ -78,33 +77,25 @@ ReturnValue_t FinishedInfo::getFaultLocation(EntityIdTlv** faultLocation) {
return HasReturnvaluesIF::RETURN_OK; return HasReturnvaluesIF::RETURN_OK;
} }
cfdp::ConditionCode FinishedInfo::getConditionCode() const { cfdp::ConditionCode FinishedInfo::getConditionCode() const { return conditionCode; }
return conditionCode;
}
void FinishedInfo::setConditionCode(cfdp::ConditionCode conditionCode) { void FinishedInfo::setConditionCode(cfdp::ConditionCode conditionCode) {
this->conditionCode = conditionCode; this->conditionCode = conditionCode;
} }
cfdp::FinishedDeliveryCode FinishedInfo::getDeliveryCode() const { cfdp::FinishedDeliveryCode FinishedInfo::getDeliveryCode() const { return deliveryCode; }
return deliveryCode;
}
void FinishedInfo::setDeliveryCode(cfdp::FinishedDeliveryCode deliveryCode) { void FinishedInfo::setDeliveryCode(cfdp::FinishedDeliveryCode deliveryCode) {
this->deliveryCode = deliveryCode; this->deliveryCode = deliveryCode;
} }
cfdp::FinishedFileStatus FinishedInfo::getFileStatus() const { cfdp::FinishedFileStatus FinishedInfo::getFileStatus() const { return fileStatus; }
return fileStatus;
}
void FinishedInfo::setFilestoreResponsesArrayLen(size_t fsResponsesLen) { void FinishedInfo::setFilestoreResponsesArrayLen(size_t fsResponsesLen) {
this->fsResponsesLen = fsResponsesLen; this->fsResponsesLen = fsResponsesLen;
} }
size_t FinishedInfo::getFsResponsesLen() const { size_t FinishedInfo::getFsResponsesLen() const { return fsResponsesLen; }
return fsResponsesLen;
}
void FinishedInfo::setFileStatus(cfdp::FinishedFileStatus fileStatus) { void FinishedInfo::setFileStatus(cfdp::FinishedFileStatus fileStatus) {
this->fileStatus = fileStatus; this->fileStatus = fileStatus;

View File

@ -1,9 +1,9 @@
#ifndef FSFW_SRC_FSFW_CFDP_PDU_FINISHINFO_H_ #ifndef FSFW_SRC_FSFW_CFDP_PDU_FINISHINFO_H_
#define FSFW_SRC_FSFW_CFDP_PDU_FINISHINFO_H_ #define FSFW_SRC_FSFW_CFDP_PDU_FINISHINFO_H_
#include "../definitions.h"
#include "fsfw/cfdp/tlv/EntityIdTlv.h" #include "fsfw/cfdp/tlv/EntityIdTlv.h"
#include "fsfw/cfdp/tlv/FilestoreResponseTlv.h" #include "fsfw/cfdp/tlv/FilestoreResponseTlv.h"
#include "../definitions.h"
class FinishedInfo { class FinishedInfo {
public: public:
@ -20,8 +20,8 @@ public:
size_t* fsResponsesLen, const size_t* maxFsResponseLen); size_t* fsResponsesLen, const size_t* maxFsResponseLen);
void setFaultLocation(EntityIdTlv* entityId); void setFaultLocation(EntityIdTlv* entityId);
ReturnValue_t getFilestoreResonses(FilestoreResponseTlv ***fsResponses, ReturnValue_t getFilestoreResonses(FilestoreResponseTlv*** fsResponses, size_t* fsResponsesLen,
size_t *fsResponsesLen, size_t* fsResponsesMaxLen); size_t* fsResponsesMaxLen);
size_t getFsResponsesLen() const; size_t getFsResponsesLen() const;
void setFilestoreResponsesArrayLen(size_t fsResponsesLen); void setFilestoreResponsesArrayLen(size_t fsResponsesLen);
ReturnValue_t getFaultLocation(EntityIdTlv** entityId); ReturnValue_t getFaultLocation(EntityIdTlv** entityId);

View File

@ -1,8 +1,8 @@
#include "FinishedPduDeserializer.h" #include "FinishedPduDeserializer.h"
FinishPduDeserializer::FinishPduDeserializer(const uint8_t* pduBuf, size_t maxSize, FinishPduDeserializer::FinishPduDeserializer(const uint8_t* pduBuf, size_t maxSize,
FinishedInfo &info): FileDirectiveDeserializer(pduBuf, maxSize), finishedInfo(info) { FinishedInfo& info)
} : FileDirectiveDeserializer(pduBuf, maxSize), finishedInfo(info) {}
ReturnValue_t FinishPduDeserializer::parseData() { ReturnValue_t FinishPduDeserializer::parseData() {
ReturnValue_t result = FileDirectiveDeserializer::parseData(); ReturnValue_t result = FileDirectiveDeserializer::parseData();
@ -29,12 +29,10 @@ ReturnValue_t FinishPduDeserializer::parseData() {
return result; return result;
} }
FinishedInfo& FinishPduDeserializer::getInfo() { FinishedInfo& FinishPduDeserializer::getInfo() { return finishedInfo; }
return finishedInfo;
}
ReturnValue_t FinishPduDeserializer::parseTlvs(size_t remLen, size_t currentIdx, ReturnValue_t FinishPduDeserializer::parseTlvs(size_t remLen, size_t currentIdx, const uint8_t* buf,
const uint8_t* buf, cfdp::ConditionCode conditionCode) { cfdp::ConditionCode conditionCode) {
ReturnValue_t result = HasReturnvaluesIF::RETURN_OK; ReturnValue_t result = HasReturnvaluesIF::RETURN_OK;
size_t fsResponsesIdx = 0; size_t fsResponsesIdx = 0;
auto endianness = getEndianness(); auto endianness = getEndianness();
@ -55,8 +53,8 @@ ReturnValue_t FinishPduDeserializer::parseTlvs(size_t remLen, size_t currentIdx,
if (not finishedInfo.canHoldFsResponses()) { if (not finishedInfo.canHoldFsResponses()) {
return cfdp::FINISHED_CANT_PARSE_FS_RESPONSES; return cfdp::FINISHED_CANT_PARSE_FS_RESPONSES;
} }
result = finishedInfo.getFilestoreResonses(&fsResponseArray, nullptr, result =
&fsResponseMaxArrayLen); finishedInfo.getFilestoreResonses(&fsResponseArray, nullptr, &fsResponseMaxArrayLen);
} }
if (fsResponsesIdx == fsResponseMaxArrayLen) { if (fsResponsesIdx == fsResponseMaxArrayLen) {
return cfdp::FINISHED_CANT_PARSE_FS_RESPONSES; return cfdp::FINISHED_CANT_PARSE_FS_RESPONSES;

View File

@ -1,8 +1,8 @@
#ifndef FSFW_SRC_FSFW_CFDP_PDU_FINISHEDPDUDESERIALIZER_H_ #ifndef FSFW_SRC_FSFW_CFDP_PDU_FINISHEDPDUDESERIALIZER_H_
#define FSFW_SRC_FSFW_CFDP_PDU_FINISHEDPDUDESERIALIZER_H_ #define FSFW_SRC_FSFW_CFDP_PDU_FINISHEDPDUDESERIALIZER_H_
#include "fsfw/cfdp/pdu/FinishedInfo.h"
#include "fsfw/cfdp/pdu/FileDirectiveDeserializer.h" #include "fsfw/cfdp/pdu/FileDirectiveDeserializer.h"
#include "fsfw/cfdp/pdu/FinishedInfo.h"
class FinishPduDeserializer : public FileDirectiveDeserializer { class FinishPduDeserializer : public FileDirectiveDeserializer {
public: public:
@ -11,6 +11,7 @@ public:
ReturnValue_t parseData() override; ReturnValue_t parseData() override;
FinishedInfo& getInfo(); FinishedInfo& getInfo();
private: private:
FinishedInfo& finishedInfo; FinishedInfo& finishedInfo;

View File

@ -1,7 +1,7 @@
#include "FinishedPduSerializer.h" #include "FinishedPduSerializer.h"
FinishPduSerializer::FinishPduSerializer(PduConfig &conf, FinishedInfo &finishInfo): FinishPduSerializer::FinishPduSerializer(PduConfig &conf, FinishedInfo &finishInfo)
FileDirectiveSerializer(conf, cfdp::FileDirectives::FINISH, 0), finishInfo(finishInfo) { : FileDirectiveSerializer(conf, cfdp::FileDirectives::FINISH, 0), finishInfo(finishInfo) {
updateDirectiveFieldLen(); updateDirectiveFieldLen();
} }
@ -15,8 +15,8 @@ void FinishPduSerializer::updateDirectiveFieldLen() {
ReturnValue_t FinishPduSerializer::serialize(uint8_t **buffer, size_t *size, size_t maxSize, ReturnValue_t FinishPduSerializer::serialize(uint8_t **buffer, size_t *size, size_t maxSize,
Endianness streamEndianness) const { Endianness streamEndianness) const {
ReturnValue_t result = FileDirectiveSerializer::serialize(buffer, size, maxSize, ReturnValue_t result =
streamEndianness); FileDirectiveSerializer::serialize(buffer, size, maxSize, streamEndianness);
if (result != HasReturnvaluesIF::RETURN_OK) { if (result != HasReturnvaluesIF::RETURN_OK) {
return result; return result;
} }

View File

@ -1,9 +1,9 @@
#ifndef FSFW_SRC_FSFW_CFDP_PDU_FINISHEDPDUSERIALIZER_H_ #ifndef FSFW_SRC_FSFW_CFDP_PDU_FINISHEDPDUSERIALIZER_H_
#define FSFW_SRC_FSFW_CFDP_PDU_FINISHEDPDUSERIALIZER_H_ #define FSFW_SRC_FSFW_CFDP_PDU_FINISHEDPDUSERIALIZER_H_
#include "fsfw/cfdp/pdu/FileDirectiveSerializer.h"
#include "fsfw/cfdp/pdu/FileDataSerializer.h"
#include "FinishedInfo.h" #include "FinishedInfo.h"
#include "fsfw/cfdp/pdu/FileDataSerializer.h"
#include "fsfw/cfdp/pdu/FileDirectiveSerializer.h"
class FinishPduSerializer : public FileDirectiveSerializer { class FinishPduSerializer : public FileDirectiveSerializer {
public: public:
@ -15,6 +15,7 @@ public:
ReturnValue_t serialize(uint8_t** buffer, size_t* size, size_t maxSize, ReturnValue_t serialize(uint8_t** buffer, size_t* size, size_t maxSize,
Endianness streamEndianness) const override; Endianness streamEndianness) const override;
private: private:
FinishedInfo& finishInfo; FinishedInfo& finishInfo;
}; };

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