diff --git a/CHANGELOG.md b/CHANGELOG.md index 1c78318c..40bfd27f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,16 +8,30 @@ and this project adheres to [Semantic Versioning](http://semver.org/). # [unreleased] +# [v6.0.0] + +## Added + +- DHB TM handler `handleDeviceTM` renamed to `handleDeviceTm` and now takes + `util::DataWrapper` as the data input argument. This allows more flexibility in the possible + types of telemetry. + PR: https://egit.irs.uni-stuttgart.de/fsfw/fsfw/pulls/669 +- Add `util::DataWrapper` class inside the `util` module. This is a tagged union which allows + to specify raw data either as a classic C-style raw pointer and size or as a `SerializeIF` + pointer. + PR: https://egit.irs.uni-stuttgart.de/fsfw/fsfw/pulls/668 +- Add new `UnsignedByteField` class + PR: https://egit.irs.uni-stuttgart.de/fsfw/fsfw/pulls/660 + ## Changes - Removed `HasReturnvaluesIF` class in favor of `returnvalue` namespace with `OK` and `FAILED` constants. PR: https://egit.irs.uni-stuttgart.de/fsfw/fsfw/pulls/659 - -## Added - -- Add new `UnsignedByteField` class - PR: https://egit.irs.uni-stuttgart.de/fsfw/fsfw/pulls/660 +- Overhaul of the TMTC stack, including various changes and improvements + for other modules + PR: https://egit.irs.uni-stuttgart.de/fsfw/fsfw/pulls/655 + which also includes a migration guide # [v5.0.0] 25.07.2022 @@ -152,7 +166,6 @@ https://egit.irs.uni-stuttgart.de/fsfw/fsfw/pulls/593 - https://gitlab.kitware.com/cmake/cmake/-/issues/21696 Easiest solution for now: Keep this option OFF by default. PR: https://egit.irs.uni-stuttgart.de/fsfw/fsfw/pulls/616 -- Linux HAL: Add wiretapping option for I2C. Enabled with `FSFW_HAL_I2C_WIRETAPPING` defined to 1 - Dedicated Version class and constant `fsfw::FSFW_VERSION` containing version information inside `fsfw/version.h` PR: https://egit.irs.uni-stuttgart.de/fsfw/fsfw/pulls/559 @@ -167,6 +180,17 @@ https://egit.irs.uni-stuttgart.de/fsfw/fsfw/pulls/593 PR: https://egit.irs.uni-stuttgart.de/fsfw/fsfw/pulls/590 - `Subsystem`: New API to add table and sequence entries +## HAL + +- SPI: Cache the SPI device in the communication interface. Architecturally, this makes a + lot more sense because each ComIF should be responsible for one SPI bus. +- SPI: Move the empty transfer to update the line polarity to separate function. This means + it is not automatically called when calling the setter function for SPI speed and mode. + The user should call this function after locking the CS mutex if multiple SPI devices with + differing speeds and modes are attached to one bus. +- SPI: Getter functions for SPI speed and mode. +- I2C: Add wiretapping option for I2C. Enabled with `FSFW_HAL_I2C_WIRETAPPING` defined to 1. + ## Fixed - TCP TMTC Server: `MutexGuard` was not created properly in diff --git a/CMakeLists.txt b/CMakeLists.txt index 5351aeb4..9cbac419 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -195,7 +195,7 @@ message( ) # Check whether the user has already installed ETL first -find_package(${FSFW_ETL_LIB_NAME} ${FSFW_ETL_LIB_MAJOR_VERSION} QUIET) +find_package(${FSFW_ETL_LIB_NAME} ${FSFW_ETL_LIB_MAJOR_VERSION} CONFIG QUIET) # Not installed, so use FetchContent to download and provide etl if(NOT ${FSFW_ETL_LIB_NAME}_FOUND) message( diff --git a/automation/Jenkinsfile b/automation/Jenkinsfile index c5dcbe02..02340190 100644 --- a/automation/Jenkinsfile +++ b/automation/Jenkinsfile @@ -1,6 +1,6 @@ pipeline { environment { - BUILDDIR = 'build-tests' + BUILDDIR = 'cmake-build-tests' } agent { docker { image 'fsfw-ci:d3'} diff --git a/misc/defaultcfg/fsfwconfig/objects/FsfwFactory.cpp b/misc/defaultcfg/fsfwconfig/objects/FsfwFactory.cpp index 5aef4980..4d6e91f1 100644 --- a/misc/defaultcfg/fsfwconfig/objects/FsfwFactory.cpp +++ b/misc/defaultcfg/fsfwconfig/objects/FsfwFactory.cpp @@ -35,8 +35,8 @@ void Factory::produceFsfwObjects(void) { } void Factory::setStaticFrameworkObjectIds() { - PusServiceBase::packetSource = objects::NO_OBJECT; - PusServiceBase::packetDestination = objects::NO_OBJECT; + PusServiceBase::PUS_DISTRIBUTOR = objects::NO_OBJECT; + PusServiceBase::PACKET_DESTINATION = objects::NO_OBJECT; CommandingServiceBase::defaultPacketSource = objects::NO_OBJECT; CommandingServiceBase::defaultPacketDestination = objects::NO_OBJECT; diff --git a/scripts/helper.py b/scripts/helper.py index 0ac616b6..0ced7186 100755 --- a/scripts/helper.py +++ b/scripts/helper.py @@ -13,7 +13,7 @@ from shutil import which from typing import List -UNITTEST_FOLDER_NAME = "build-tests" +UNITTEST_FOLDER_NAME = "cmake-build-tests" DOCS_FOLDER_NAME = "build-docs" diff --git a/src/fsfw/action/CommandActionHelper.h b/src/fsfw/action/CommandActionHelper.h index 55176e09..ac8ed1ba 100644 --- a/src/fsfw/action/CommandActionHelper.h +++ b/src/fsfw/action/CommandActionHelper.h @@ -16,8 +16,8 @@ class CommandActionHelper { public: explicit CommandActionHelper(CommandsActionsIF* owner); virtual ~CommandActionHelper(); - ReturnValue_t commandAction(object_id_t commandTo, ActionId_t actionId, const uint8_t* data, - uint32_t size); + ReturnValue_t commandAction(object_id_t commandTo, ActionId_t actionId, + const uint8_t* data = nullptr, uint32_t size = 0); ReturnValue_t commandAction(object_id_t commandTo, ActionId_t actionId, SerializeIF* data); ReturnValue_t initialize(); ReturnValue_t handleReply(CommandMessage* reply); diff --git a/src/fsfw/cfdp/CFDPMessage.cpp b/src/fsfw/cfdp/CFDPMessage.cpp deleted file mode 100644 index fee55715..00000000 --- a/src/fsfw/cfdp/CFDPMessage.cpp +++ /dev/null @@ -1,17 +0,0 @@ -#include "CFDPMessage.h" - -CFDPMessage::CFDPMessage() {} - -CFDPMessage::~CFDPMessage() {} - -void CFDPMessage::setCommand(CommandMessage *message, store_address_t cfdpPacket) { - message->setParameter(cfdpPacket.raw); -} - -store_address_t CFDPMessage::getStoreId(const CommandMessage *message) { - store_address_t storeAddressCFDPPacket; - storeAddressCFDPPacket = message->getParameter(); - return storeAddressCFDPPacket; -} - -void CFDPMessage::clear(CommandMessage *message) {} diff --git a/src/fsfw/cfdp/CMakeLists.txt b/src/fsfw/cfdp/CMakeLists.txt index 0b926a9a..f2affbb4 100644 --- a/src/fsfw/cfdp/CMakeLists.txt +++ b/src/fsfw/cfdp/CMakeLists.txt @@ -1,4 +1,4 @@ -target_sources(${LIB_FSFW_NAME} PRIVATE CFDPHandler.cpp CFDPMessage.cpp) +target_sources(${LIB_FSFW_NAME} PRIVATE CfdpHandler.cpp CfdpMessage.cpp) add_subdirectory(pdu) add_subdirectory(tlv) diff --git a/src/fsfw/cfdp/CFDPHandler.cpp b/src/fsfw/cfdp/CfdpHandler.cpp similarity index 56% rename from src/fsfw/cfdp/CFDPHandler.cpp rename to src/fsfw/cfdp/CfdpHandler.cpp index d5cdbb46..707328c5 100644 --- a/src/fsfw/cfdp/CFDPHandler.cpp +++ b/src/fsfw/cfdp/CfdpHandler.cpp @@ -1,24 +1,25 @@ -#include "fsfw/cfdp/CFDPHandler.h" +#include "fsfw/cfdp/CfdpHandler.h" -#include "fsfw/cfdp/CFDPMessage.h" +#include "fsfw/cfdp/CfdpMessage.h" #include "fsfw/ipc/CommandMessage.h" #include "fsfw/ipc/QueueFactory.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::packetDestination = 0; +object_id_t CfdpHandler::packetSource = 0; +object_id_t CfdpHandler::packetDestination = 0; -CFDPHandler::CFDPHandler(object_id_t setObjectId, CFDPDistributor* dist) +CfdpHandler::CfdpHandler(object_id_t setObjectId, CFDPDistributor* dist) : SystemObject(setObjectId) { - requestQueue = QueueFactory::instance()->createMessageQueue(CFDP_HANDLER_MAX_RECEPTION); + auto mqArgs = MqArgs(setObjectId, static_cast(this)); + requestQueue = QueueFactory::instance()->createMessageQueue( + CFDP_HANDLER_MAX_RECEPTION, MessageQueueMessage::MAX_MESSAGE_SIZE, &mqArgs); distributor = dist; } -CFDPHandler::~CFDPHandler() {} +CfdpHandler::~CfdpHandler() = default; -ReturnValue_t CFDPHandler::initialize() { +ReturnValue_t CfdpHandler::initialize() { ReturnValue_t result = SystemObject::initialize(); if (result != returnvalue::OK) { return result; @@ -27,7 +28,7 @@ ReturnValue_t CFDPHandler::initialize() { return returnvalue::OK; } -ReturnValue_t CFDPHandler::handleRequest(store_address_t storeId) { +ReturnValue_t CfdpHandler::handleRequest(store_address_t storeId) { #if FSFW_VERBOSE_LEVEL >= 1 #if FSFW_CPP_OSTREAM_ENABLED == 1 sif::debug << "CFDPHandler::handleRequest" << std::endl; @@ -41,17 +42,17 @@ ReturnValue_t CFDPHandler::handleRequest(store_address_t storeId) { return returnvalue::OK; } -ReturnValue_t CFDPHandler::performOperation(uint8_t opCode) { +ReturnValue_t CfdpHandler::performOperation(uint8_t opCode) { ReturnValue_t status = returnvalue::OK; CommandMessage currentMessage; for (status = this->requestQueue->receiveMessage(¤tMessage); status == returnvalue::OK; status = this->requestQueue->receiveMessage(¤tMessage)) { - store_address_t storeId = CFDPMessage::getStoreId(¤tMessage); + store_address_t storeId = CfdpMessage::getStoreId(¤tMessage); this->handleRequest(storeId); } return returnvalue::OK; } -uint16_t CFDPHandler::getIdentifier() { return 0; } +uint16_t CfdpHandler::getIdentifier() { return 0; } -MessageQueueId_t CFDPHandler::getRequestQueue() { return this->requestQueue->getId(); } +MessageQueueId_t CfdpHandler::getRequestQueue() { return this->requestQueue->getId(); } diff --git a/src/fsfw/cfdp/CFDPHandler.h b/src/fsfw/cfdp/CfdpHandler.h similarity index 89% rename from src/fsfw/cfdp/CFDPHandler.h rename to src/fsfw/cfdp/CfdpHandler.h index 0078f748..94bb529e 100644 --- a/src/fsfw/cfdp/CFDPHandler.h +++ b/src/fsfw/cfdp/CfdpHandler.h @@ -12,15 +12,15 @@ namespace Factory { void setStaticFrameworkObjectIds(); } -class CFDPHandler : public ExecutableObjectIF, public AcceptsTelecommandsIF, public SystemObject { +class CfdpHandler : public ExecutableObjectIF, public AcceptsTelecommandsIF, public SystemObject { friend void(Factory::setStaticFrameworkObjectIds)(); public: - CFDPHandler(object_id_t setObjectId, CFDPDistributor* distributor); + CfdpHandler(object_id_t setObjectId, CFDPDistributor* distributor); /** * The destructor is empty. */ - virtual ~CFDPHandler(); + virtual ~CfdpHandler(); virtual ReturnValue_t handleRequest(store_address_t storeId); @@ -42,7 +42,7 @@ class CFDPHandler : public ExecutableObjectIF, public AcceptsTelecommandsIF, pub * The current CFDP packet to be processed. * It is deleted after handleRequest was executed. */ - CFDPPacketStored currentPacket; + CfdpPacketStored currentPacket; static object_id_t packetSource; diff --git a/src/fsfw/cfdp/CfdpMessage.cpp b/src/fsfw/cfdp/CfdpMessage.cpp new file mode 100644 index 00000000..ea4e2c98 --- /dev/null +++ b/src/fsfw/cfdp/CfdpMessage.cpp @@ -0,0 +1,17 @@ +#include "CfdpMessage.h" + +CfdpMessage::CfdpMessage() = default; + +CfdpMessage::~CfdpMessage() = default; + +void CfdpMessage::setCommand(CommandMessage *message, store_address_t cfdpPacket) { + message->setParameter(cfdpPacket.raw); +} + +store_address_t CfdpMessage::getStoreId(const CommandMessage *message) { + store_address_t storeId; + storeId = static_cast(message->getParameter()); + return storeId; +} + +void CfdpMessage::clear(CommandMessage *message) {} diff --git a/src/fsfw/cfdp/CFDPMessage.h b/src/fsfw/cfdp/CfdpMessage.h similarity index 89% rename from src/fsfw/cfdp/CFDPMessage.h rename to src/fsfw/cfdp/CfdpMessage.h index 3de723eb..a3ee9421 100644 --- a/src/fsfw/cfdp/CFDPMessage.h +++ b/src/fsfw/cfdp/CfdpMessage.h @@ -5,14 +5,14 @@ #include "fsfw/objectmanager/ObjectManagerIF.h" #include "fsfw/storagemanager/StorageManagerIF.h" -class CFDPMessage { +class CfdpMessage { private: - CFDPMessage(); + CfdpMessage(); public: static const uint8_t MESSAGE_ID = messagetypes::CFDP; - virtual ~CFDPMessage(); + virtual ~CfdpMessage(); static void setCommand(CommandMessage* message, store_address_t cfdpPacket); static store_address_t getStoreId(const CommandMessage* message); diff --git a/src/fsfw/controller/ControllerBase.cpp b/src/fsfw/controller/ControllerBase.cpp index a9d19ef2..80c08590 100644 --- a/src/fsfw/controller/ControllerBase.cpp +++ b/src/fsfw/controller/ControllerBase.cpp @@ -13,7 +13,9 @@ ControllerBase::ControllerBase(object_id_t setObjectId, object_id_t parentId, submode(SUBMODE_NONE), modeHelper(this), healthHelper(this, setObjectId) { - commandQueue = QueueFactory::instance()->createMessageQueue(commandQueueDepth); + auto mqArgs = MqArgs(setObjectId, static_cast(this)); + commandQueue = QueueFactory::instance()->createMessageQueue( + commandQueueDepth, MessageQueueMessage::MAX_MESSAGE_SIZE, &mqArgs); } ControllerBase::~ControllerBase() { QueueFactory::instance()->deleteMessageQueue(commandQueue); } diff --git a/src/fsfw/datalinklayer/MapPacketExtraction.cpp b/src/fsfw/datalinklayer/MapPacketExtraction.cpp index a2ee51e8..c074de73 100644 --- a/src/fsfw/datalinklayer/MapPacketExtraction.cpp +++ b/src/fsfw/datalinklayer/MapPacketExtraction.cpp @@ -6,7 +6,7 @@ #include "fsfw/objectmanager/ObjectManager.h" #include "fsfw/serviceinterface/ServiceInterface.h" #include "fsfw/storagemanager/StorageManagerIF.h" -#include "fsfw/tmtcpacket/SpacePacketBase.h" +#include "fsfw/tmtcpacket/ccsds/SpacePacketReader.h" #include "fsfw/tmtcservices/AcceptsTelecommandsIF.h" #include "fsfw/tmtcservices/TmTcMessage.h" diff --git a/src/fsfw/datapoollocal/HasLocalDataPoolIF.h b/src/fsfw/datapoollocal/HasLocalDataPoolIF.h index 2cf20e0b..8530fd77 100644 --- a/src/fsfw/datapoollocal/HasLocalDataPoolIF.h +++ b/src/fsfw/datapoollocal/HasLocalDataPoolIF.h @@ -79,8 +79,7 @@ class HasLocalDataPoolIF { * @param clearMessage If this is set to true, the pool manager will take care of * clearing the store automatically */ - virtual void handleChangedDataset(sid_t sid, - store_address_t storeId = storeId::INVALID_STORE_ADDRESS, + virtual void handleChangedDataset(sid_t sid, store_address_t storeId = store_address_t::invalid(), bool* clearMessage = nullptr) { if (clearMessage != nullptr) { *clearMessage = true; @@ -100,7 +99,7 @@ class HasLocalDataPoolIF { * after the callback. */ virtual void handleChangedPoolVariable(gp_id_t gpid, - store_address_t storeId = storeId::INVALID_STORE_ADDRESS, + store_address_t storeId = store_address_t::invalid(), bool* clearMessage = nullptr) { if (clearMessage != nullptr) { *clearMessage = true; diff --git a/src/fsfw/datapoollocal/LocalDataPoolManager.cpp b/src/fsfw/datapoollocal/LocalDataPoolManager.cpp index d25791a7..67c2b4b8 100644 --- a/src/fsfw/datapoollocal/LocalDataPoolManager.cpp +++ b/src/fsfw/datapoollocal/LocalDataPoolManager.cpp @@ -1,6 +1,5 @@ #include "fsfw/datapoollocal/LocalDataPoolManager.h" -#include #include #include "fsfw/datapoollocal.h" @@ -15,6 +14,7 @@ #include "internal/HasLocalDpIFManagerAttorney.h" #include "internal/LocalPoolDataSetAttorney.h" +// TODO: Get rid of this. This should be a constructor argument, not something hardcoded in any way object_id_t LocalDataPoolManager::defaultHkDestination = objects::PUS_SERVICE_3_HOUSEKEEPING; LocalDataPoolManager::LocalDataPoolManager(HasLocalDataPoolIF* owner, MessageQueueIF* queueToUse, @@ -57,7 +57,7 @@ ReturnValue_t LocalDataPoolManager::initialize(MessageQueueIF* queueToUse) { } if (defaultHkDestination != objects::NO_OBJECT) { - AcceptsHkPacketsIF* hkPacketReceiver = + auto* hkPacketReceiver = ObjectManager::instance()->get(defaultHkDestination); if (hkPacketReceiver != nullptr) { hkDestinationId = hkPacketReceiver->getHkQueue(); @@ -209,9 +209,9 @@ ReturnValue_t LocalDataPoolManager::handleNotificationSnapshot(HkReceiver& recei } /* Prepare and send update snapshot */ - timeval now; + timeval now{}; Clock::getClock_timeval(&now); - CCSDSTime::CDS_short cds; + CCSDSTime::CDS_short cds{}; CCSDSTime::convertToCcsds(&cds, &now); HousekeepingSnapshot updatePacket( reinterpret_cast(&cds), sizeof(cds), @@ -245,9 +245,9 @@ ReturnValue_t LocalDataPoolManager::handleNotificationSnapshot(HkReceiver& recei } /* Prepare and send update snapshot */ - timeval now; + timeval now{}; Clock::getClock_timeval(&now); - CCSDSTime::CDS_short cds; + CCSDSTime::CDS_short cds{}; CCSDSTime::convertToCcsds(&cds, &now); HousekeepingSnapshot updatePacket( reinterpret_cast(&cds), sizeof(cds), @@ -291,12 +291,7 @@ ReturnValue_t LocalDataPoolManager::addUpdateToStore(HousekeepingSnapshot& updat void LocalDataPoolManager::handleChangeResetLogic(DataType type, DataId dataId, MarkChangedIF* toReset) { - if (hkUpdateResetList == nullptr) { - /* Config error */ - return; - } - HkUpdateResetList& listRef = *hkUpdateResetList; - for (auto& changeInfo : listRef) { + for (auto& changeInfo : hkUpdateResetList) { if (changeInfo.dataType != type) { continue; } @@ -326,38 +321,37 @@ void LocalDataPoolManager::handleChangeResetLogic(DataType type, DataId dataId, } void LocalDataPoolManager::resetHkUpdateResetHelper() { - if (hkUpdateResetList == nullptr) { - return; - } - - for (auto& changeInfo : *hkUpdateResetList) { + for (auto& changeInfo : hkUpdateResetList) { changeInfo.currentUpdateCounter = changeInfo.updateCounter; } } -ReturnValue_t LocalDataPoolManager::subscribeForPeriodicPacket(sid_t sid, bool enableReporting, - float collectionInterval, - bool isDiagnostics, - object_id_t packetDestination) { - AcceptsHkPacketsIF* hkReceiverObject = - ObjectManager::instance()->get(packetDestination); - if (hkReceiverObject == nullptr) { - printWarningOrError(sif::OutputTypes::OUT_WARNING, "subscribeForPeriodicPacket", - QUEUE_OR_DESTINATION_INVALID); - return QUEUE_OR_DESTINATION_INVALID; - } +ReturnValue_t LocalDataPoolManager::subscribeForRegularPeriodicPacket( + subdp::RegularHkPeriodicParams params) { + return subscribeForPeriodicPacket(params); +} +ReturnValue_t LocalDataPoolManager::subscribeForDiagPeriodicPacket( + subdp::DiagnosticsHkPeriodicParams params) { + return subscribeForPeriodicPacket(params); +} + +ReturnValue_t LocalDataPoolManager::subscribeForPeriodicPacket(subdp::ParamsBase& params) { struct HkReceiver hkReceiver; - hkReceiver.dataId.sid = sid; + hkReceiver.dataId.sid = params.sid; hkReceiver.reportingType = ReportingType::PERIODIC; hkReceiver.dataType = DataType::DATA_SET; - hkReceiver.destinationQueue = hkReceiverObject->getHkQueue(); + if (params.receiver == MessageQueueIF::NO_QUEUE) { + hkReceiver.destinationQueue = hkDestinationId; + } else { + hkReceiver.destinationQueue = params.receiver; + } - LocalPoolDataSetBase* dataSet = HasLocalDpIFManagerAttorney::getDataSetHandle(owner, sid); + LocalPoolDataSetBase* dataSet = HasLocalDpIFManagerAttorney::getDataSetHandle(owner, params.sid); if (dataSet != nullptr) { - LocalPoolDataSetAttorney::setReportingEnabled(*dataSet, enableReporting); - LocalPoolDataSetAttorney::setDiagnostic(*dataSet, isDiagnostics); - LocalPoolDataSetAttorney::initializePeriodicHelper(*dataSet, collectionInterval, + LocalPoolDataSetAttorney::setReportingEnabled(*dataSet, params.enableReporting); + LocalPoolDataSetAttorney::setDiagnostic(*dataSet, params.isDiagnostics()); + LocalPoolDataSetAttorney::initializePeriodicHelper(*dataSet, params.collectionInterval, owner->getPeriodicOperationFrequency()); } @@ -365,27 +359,30 @@ ReturnValue_t LocalDataPoolManager::subscribeForPeriodicPacket(sid_t sid, bool e return returnvalue::OK; } -ReturnValue_t LocalDataPoolManager::subscribeForUpdatePacket(sid_t sid, bool isDiagnostics, - bool reportingEnabled, - object_id_t packetDestination) { - AcceptsHkPacketsIF* hkReceiverObject = - ObjectManager::instance()->get(packetDestination); - if (hkReceiverObject == nullptr) { - printWarningOrError(sif::OutputTypes::OUT_WARNING, "subscribeForPeriodicPacket", - QUEUE_OR_DESTINATION_INVALID); - return QUEUE_OR_DESTINATION_INVALID; - } +ReturnValue_t LocalDataPoolManager::subscribeForRegularUpdatePacket( + subdp::RegularHkUpdateParams params) { + return subscribeForUpdatePacket(params); +} +ReturnValue_t LocalDataPoolManager::subscribeForDiagUpdatePacket( + subdp::DiagnosticsHkUpdateParams params) { + return subscribeForUpdatePacket(params); +} +ReturnValue_t LocalDataPoolManager::subscribeForUpdatePacket(subdp::ParamsBase& params) { struct HkReceiver hkReceiver; - hkReceiver.dataId.sid = sid; + hkReceiver.dataId.sid = params.sid; hkReceiver.reportingType = ReportingType::UPDATE_HK; hkReceiver.dataType = DataType::DATA_SET; - hkReceiver.destinationQueue = hkReceiverObject->getHkQueue(); + if (params.receiver == MessageQueueIF::NO_QUEUE) { + hkReceiver.destinationQueue = hkDestinationId; + } else { + hkReceiver.destinationQueue = params.receiver; + } - LocalPoolDataSetBase* dataSet = HasLocalDpIFManagerAttorney::getDataSetHandle(owner, sid); + LocalPoolDataSetBase* dataSet = HasLocalDpIFManagerAttorney::getDataSetHandle(owner, params.sid); if (dataSet != nullptr) { LocalPoolDataSetAttorney::setReportingEnabled(*dataSet, true); - LocalPoolDataSetAttorney::setDiagnostic(*dataSet, isDiagnostics); + LocalPoolDataSetAttorney::setDiagnostic(*dataSet, params.isDiagnostics()); } hkReceivers.push_back(hkReceiver); @@ -436,11 +433,7 @@ ReturnValue_t LocalDataPoolManager::subscribeForVariableUpdateMessage( } void LocalDataPoolManager::handleHkUpdateResetListInsertion(DataType dataType, DataId dataId) { - if (hkUpdateResetList == nullptr) { - hkUpdateResetList = new std::vector(); - } - - for (auto& updateResetStruct : *hkUpdateResetList) { + for (auto& updateResetStruct : hkUpdateResetList) { if (dataType == DataType::DATA_SET) { if (updateResetStruct.dataId.sid == dataId.sid) { updateResetStruct.updateCounter++; @@ -464,7 +457,7 @@ void LocalDataPoolManager::handleHkUpdateResetListInsertion(DataType dataType, D } else { hkUpdateResetHelper.dataId.localPoolId = dataId.localPoolId; } - hkUpdateResetList->push_back(hkUpdateResetHelper); + hkUpdateResetList.push_back(hkUpdateResetHelper); } ReturnValue_t LocalDataPoolManager::handleHousekeepingMessage(CommandMessage* message) { @@ -577,6 +570,10 @@ ReturnValue_t LocalDataPoolManager::handleHousekeepingMessage(CommandMessage* me CommandMessage reply; if (result != returnvalue::OK) { + if (result == WRONG_HK_PACKET_TYPE) { + printWarningOrError(sif::OutputTypes::OUT_WARNING, "handleHousekeepingMessage", + WRONG_HK_PACKET_TYPE); + } HousekeepingMessage::setHkRequestFailureReply(&reply, sid, result); } else { HousekeepingMessage::setHkRequestSuccessReply(&reply, sid); @@ -639,6 +636,7 @@ ReturnValue_t LocalDataPoolManager::generateHousekeepingPacket(sid_t sid, /* Error, all destinations invalid */ printWarningOrError(sif::OutputTypes::OUT_WARNING, "generateHousekeepingPacket", QUEUE_OR_DESTINATION_INVALID); + return QUEUE_OR_DESTINATION_INVALID; } destination = hkDestinationId; } @@ -815,9 +813,7 @@ void LocalDataPoolManager::clearReceiversList() { /* Clear the vector completely and releases allocated memory. */ HkReceivers().swap(hkReceivers); /* Also clear the reset helper if it exists */ - if (hkUpdateResetList != nullptr) { - HkUpdateResetList().swap(*hkUpdateResetList); - } + HkUpdateResetList().swap(hkUpdateResetList); } MutexIF* LocalDataPoolManager::getLocalPoolMutex() { return this->mutex; } @@ -833,6 +829,8 @@ void LocalDataPoolManager::printWarningOrError(sif::OutputTypes outputType, errorPrint = "Dataset not found"; } else if (error == POOLOBJECT_NOT_FOUND) { errorPrint = "Pool Object not found"; + } else if (error == WRONG_HK_PACKET_TYPE) { + errorPrint = "Wrong Packet Type"; } else if (error == returnvalue::FAILED) { if (outputType == sif::OutputTypes::OUT_WARNING) { errorPrint = "Generic Warning"; @@ -877,3 +875,7 @@ void LocalDataPoolManager::printWarningOrError(sif::OutputTypes outputType, } LocalDataPoolManager* LocalDataPoolManager::getPoolManagerHandle() { return this; } + +void LocalDataPoolManager::setHkDestinationId(MessageQueueId_t hkDestId) { + hkDestinationId = hkDestId; +} diff --git a/src/fsfw/datapoollocal/LocalDataPoolManager.h b/src/fsfw/datapoollocal/LocalDataPoolManager.h index bb2ea564..8f369ea0 100644 --- a/src/fsfw/datapoollocal/LocalDataPoolManager.h +++ b/src/fsfw/datapoollocal/LocalDataPoolManager.h @@ -8,6 +8,7 @@ #include "ProvidesDataPoolSubscriptionIF.h" #include "fsfw/datapool/DataSetIF.h" #include "fsfw/datapool/PoolEntry.h" +#include "fsfw/housekeeping/AcceptsHkPacketsIF.h" #include "fsfw/housekeeping/HousekeepingMessage.h" #include "fsfw/housekeeping/HousekeepingPacketDownlink.h" #include "fsfw/housekeeping/PeriodicHousekeepingHelper.h" @@ -80,7 +81,9 @@ class LocalDataPoolManager : public ProvidesDataPoolSubscriptionIF, public Acces */ LocalDataPoolManager(HasLocalDataPoolIF* owner, MessageQueueIF* queueToUse, bool appendValidityBuffer = true); - virtual ~LocalDataPoolManager(); + ~LocalDataPoolManager() override; + + void setHkDestinationId(MessageQueueId_t hkDestId); /** * Assigns the queue to use. Make sure to call this in the #initialize @@ -112,31 +115,6 @@ class LocalDataPoolManager : public ProvidesDataPoolSubscriptionIF, public Acces */ virtual ReturnValue_t performHkOperation(); - /** - * @brief Subscribe for the generation of periodic packets. - * @details - * This subscription mechanism will generally be used by the data creator - * to generate housekeeping packets which are downlinked directly. - * @return - */ - ReturnValue_t subscribeForPeriodicPacket( - sid_t sid, bool enableReporting, float collectionInterval, bool isDiagnostics, - object_id_t packetDestination = defaultHkDestination) override; - - /** - * @brief Subscribe for the generation of packets if the dataset - * is marked as changed. - * @details - * This subscription mechanism will generally be used by the data creator. - * @param sid - * @param isDiagnostics - * @param packetDestination - * @return - */ - ReturnValue_t subscribeForUpdatePacket( - sid_t sid, bool reportingEnabled, bool isDiagnostics, - object_id_t packetDestination = defaultHkDestination) override; - /** * @brief Subscribe for a notification message which will be sent * if a dataset has changed. @@ -151,7 +129,7 @@ class LocalDataPoolManager : public ProvidesDataPoolSubscriptionIF, public Acces * Otherwise, only an notification message is sent. * @return */ - ReturnValue_t subscribeForSetUpdateMessage(const uint32_t setId, object_id_t destinationObject, + ReturnValue_t subscribeForSetUpdateMessage(uint32_t setId, object_id_t destinationObject, MessageQueueId_t targetQueueId, bool generateSnapshot) override; @@ -169,7 +147,7 @@ class LocalDataPoolManager : public ProvidesDataPoolSubscriptionIF, public Acces * Otherwise, only an notification message is sent. * @return */ - ReturnValue_t subscribeForVariableUpdateMessage(const lp_id_t localPoolId, + ReturnValue_t subscribeForVariableUpdateMessage(lp_id_t localPoolId, object_id_t destinationObject, MessageQueueId_t targetQueueId, bool generateSnapshot) override; @@ -252,7 +230,7 @@ class LocalDataPoolManager : public ProvidesDataPoolSubscriptionIF, public Acces */ void clearReceiversList(); - object_id_t getCreatorObjectId() const; + [[nodiscard]] object_id_t getCreatorObjectId() const; /** * Get the pointer to the mutex. Can be used to lock the data pool @@ -262,9 +240,17 @@ class LocalDataPoolManager : public ProvidesDataPoolSubscriptionIF, public Acces */ MutexIF* getMutexHandle(); - virtual LocalDataPoolManager* getPoolManagerHandle() override; + LocalDataPoolManager* getPoolManagerHandle() override; + ReturnValue_t subscribeForRegularPeriodicPacket(subdp::RegularHkPeriodicParams params) override; + ReturnValue_t subscribeForDiagPeriodicPacket(subdp::DiagnosticsHkPeriodicParams params) override; + + ReturnValue_t subscribeForRegularUpdatePacket(subdp::RegularHkUpdateParams params) override; + ReturnValue_t subscribeForDiagUpdatePacket(subdp::DiagnosticsHkUpdateParams params) override; protected: + ReturnValue_t subscribeForPeriodicPacket(subdp::ParamsBase& params); + ReturnValue_t subscribeForUpdatePacket(subdp::ParamsBase& params); + /** Core data structure for the actual pool data */ localpool::DataPool localPoolMap; /** Every housekeeping data manager has a mutex to protect access @@ -312,8 +298,8 @@ class LocalDataPoolManager : public ProvidesDataPoolSubscriptionIF, public Acces using HkUpdateResetList = std::vector; /** This list is used to manage creating multiple update packets and only resetting - the update flag if all of them were created. Will only be created when needed. */ - HkUpdateResetList* hkUpdateResetList = nullptr; + the update flag if all of them were created. */ + HkUpdateResetList hkUpdateResetList = HkUpdateResetList(); /** This is the map holding the actual data. Should only be initialized * once ! */ diff --git a/src/fsfw/datapoollocal/LocalPoolDataSetBase.h b/src/fsfw/datapoollocal/LocalPoolDataSetBase.h index 17cf8be2..9166cf34 100644 --- a/src/fsfw/datapoollocal/LocalPoolDataSetBase.h +++ b/src/fsfw/datapoollocal/LocalPoolDataSetBase.h @@ -162,6 +162,7 @@ class LocalPoolDataSetBase : public PoolDataSetBase, public MarkChangedIF { object_id_t getCreatorObjectId(); bool getReportingEnabled() const; + void setReportingEnabled(bool enabled); /** * Returns the current periodic HK generation interval this set @@ -189,7 +190,6 @@ class LocalPoolDataSetBase : public PoolDataSetBase, public MarkChangedIF { * Used for periodic generation. */ bool reportingEnabled = false; - void setReportingEnabled(bool enabled); void initializePeriodicHelper(float collectionInterval, dur_millis_t minimumPeriodicInterval, uint8_t nonDiagIntervalFactor = 5); diff --git a/src/fsfw/datapoollocal/ProvidesDataPoolSubscriptionIF.h b/src/fsfw/datapoollocal/ProvidesDataPoolSubscriptionIF.h index eb4e55b7..baf91796 100644 --- a/src/fsfw/datapoollocal/ProvidesDataPoolSubscriptionIF.h +++ b/src/fsfw/datapoollocal/ProvidesDataPoolSubscriptionIF.h @@ -1,24 +1,90 @@ #ifndef FSFW_DATAPOOLLOCAL_PROVIDESDATAPOOLSUBSCRIPTION_H_ #define FSFW_DATAPOOLLOCAL_PROVIDESDATAPOOLSUBSCRIPTION_H_ -#include "../ipc/messageQueueDefinitions.h" -#include "../returnvalues/returnvalue.h" +#include "fsfw/housekeeping/AcceptsHkPacketsIF.h" +#include "fsfw/ipc/MessageQueueIF.h" +#include "fsfw/ipc/messageQueueDefinitions.h" +#include "fsfw/returnvalues/returnvalue.h" #include "localPoolDefinitions.h" +namespace subdp { + +struct ParamsBase { + ParamsBase(sid_t sid, bool enableReporting, float collectionInterval, bool diagnostics) + : sid(sid), + enableReporting(enableReporting), + collectionInterval(collectionInterval), + diagnostics(diagnostics) {} + + [[nodiscard]] bool isDiagnostics() const { return diagnostics; } + + sid_t sid; + bool enableReporting; + float collectionInterval; + MessageQueueId_t receiver = MessageQueueIF::NO_QUEUE; + + protected: + bool diagnostics; +}; + +struct RegularHkPeriodicParams : public ParamsBase { + RegularHkPeriodicParams(sid_t sid, bool enableReporting, float collectionInterval) + : ParamsBase(sid, enableReporting, collectionInterval, false) {} +}; + +struct DiagnosticsHkPeriodicParams : public ParamsBase { + DiagnosticsHkPeriodicParams(sid_t sid, bool enableReporting, float collectionInterval) + : ParamsBase(sid, enableReporting, collectionInterval, true) {} +}; + +struct RegularHkUpdateParams : public ParamsBase { + RegularHkUpdateParams(sid_t sid, bool enableReporting) + : ParamsBase(sid, enableReporting, 0.0, false) {} +}; + +struct DiagnosticsHkUpdateParams : public ParamsBase { + DiagnosticsHkUpdateParams(sid_t sid, bool enableReporting) + : ParamsBase(sid, enableReporting, 0.0, true) {} +}; +} // namespace subdp + class ProvidesDataPoolSubscriptionIF { public: - virtual ~ProvidesDataPoolSubscriptionIF(){}; - + virtual ~ProvidesDataPoolSubscriptionIF() = default; /** - * @brief Subscribe for the generation of periodic packets. + * @brief Subscribe for the generation of periodic packets. Used for regular HK packets * @details * This subscription mechanism will generally be used by the data creator * to generate housekeeping packets which are downlinked directly. * @return */ - virtual ReturnValue_t subscribeForPeriodicPacket(sid_t sid, bool enableReporting, - float collectionInterval, bool isDiagnostics, - object_id_t packetDestination) = 0; + virtual ReturnValue_t subscribeForRegularPeriodicPacket( + subdp::RegularHkPeriodicParams params) = 0; + /** + * @brief Subscribe for the generation of periodic packets. Used for diagnostic packets + * @details + * This subscription mechanism will generally be used by the data creator + * to generate housekeeping packets which are downlinked directly. + * @return + */ + virtual ReturnValue_t subscribeForDiagPeriodicPacket( + subdp::DiagnosticsHkPeriodicParams params) = 0; + + [[deprecated( + "Please use the new API which takes all arguments as one wrapper " + "struct")]] virtual ReturnValue_t + subscribeForPeriodicPacket(sid_t sid, bool enableReporting, float collectionInterval, + bool isDiagnostics, + object_id_t packetDestination = objects::NO_OBJECT) { + if (isDiagnostics) { + subdp::DiagnosticsHkPeriodicParams params(sid, enableReporting, collectionInterval); + return subscribeForDiagPeriodicPacket(params); + } else { + subdp::RegularHkPeriodicParams params(sid, enableReporting, collectionInterval); + return subscribeForRegularPeriodicPacket(params); + } + } + /** * @brief Subscribe for the generation of packets if the dataset * is marked as changed. @@ -29,9 +95,28 @@ class ProvidesDataPoolSubscriptionIF { * @param packetDestination * @return */ - virtual ReturnValue_t subscribeForUpdatePacket(sid_t sid, bool reportingEnabled, - bool isDiagnostics, - object_id_t packetDestination) = 0; + virtual ReturnValue_t subscribeForRegularUpdatePacket(subdp::RegularHkUpdateParams params) = 0; + virtual ReturnValue_t subscribeForDiagUpdatePacket(subdp::DiagnosticsHkUpdateParams params) = 0; + + // virtual ReturnValue_t + // subscribeForUpdatePacket(sid_t sid, bool reportingEnabled, bool isDiagnostics) { + // return subscribeForUpdatePacket(sid, reportingEnabled, isDiagnostics, objects::NO_OBJECT); + // } + + [[deprecated( + "Please use the new API which takes all arguments as one wrapper " + "struct")]] virtual ReturnValue_t + subscribeForUpdatePacket(sid_t sid, bool reportingEnabled, bool isDiagnostics, + object_id_t packetDestination = objects::NO_OBJECT) { + if (isDiagnostics) { + subdp::DiagnosticsHkUpdateParams params(sid, reportingEnabled); + return subscribeForDiagUpdatePacket(params); + } else { + subdp::RegularHkUpdateParams params(sid, reportingEnabled); + return subscribeForRegularUpdatePacket(params); + } + } + /** * @brief Subscribe for a notification message which will be sent * if a dataset has changed. @@ -46,8 +131,7 @@ class ProvidesDataPoolSubscriptionIF { * Otherwise, only an notification message is sent. * @return */ - virtual ReturnValue_t subscribeForSetUpdateMessage(const uint32_t setId, - object_id_t destinationObject, + virtual ReturnValue_t subscribeForSetUpdateMessage(uint32_t setId, object_id_t destinationObject, MessageQueueId_t targetQueueId, bool generateSnapshot) = 0; /** @@ -64,7 +148,7 @@ class ProvidesDataPoolSubscriptionIF { * only an notification message is sent. * @return */ - virtual ReturnValue_t subscribeForVariableUpdateMessage(const lp_id_t localPoolId, + virtual ReturnValue_t subscribeForVariableUpdateMessage(lp_id_t localPoolId, object_id_t destinationObject, MessageQueueId_t targetQueueId, bool generateSnapshot) = 0; diff --git a/src/fsfw/devicehandlers/AssemblyBase.cpp b/src/fsfw/devicehandlers/AssemblyBase.cpp index 63178ab9..c943a4cf 100644 --- a/src/fsfw/devicehandlers/AssemblyBase.cpp +++ b/src/fsfw/devicehandlers/AssemblyBase.cpp @@ -26,11 +26,7 @@ void AssemblyBase::performChildOperation() { void AssemblyBase::startTransition(Mode_t mode, Submode_t submode) { doStartTransition(mode, submode); - if (modeHelper.isForced()) { - triggerEvent(FORCING_MODE, mode, submode); - } else { - triggerEvent(CHANGING_MODE, mode, submode); - } + triggerModeHelperEvents(mode, submode); } void AssemblyBase::doStartTransition(Mode_t mode, Submode_t submode) { @@ -77,9 +73,10 @@ bool AssemblyBase::handleChildrenChangedHealth() { } HealthState healthState = healthHelper.healthTable->getHealth(iter->first); if (healthState == HasHealthIF::NEEDS_RECOVERY) { - triggerEvent(TRYING_RECOVERY); + triggerEvent(TRYING_RECOVERY, iter->first, 0); recoveryState = RECOVERY_STARTED; recoveringDevice = iter; + // The user needs to take care of commanding the children off in commandChildren doStartTransition(targetMode, targetSubmode); } else { triggerEvent(CHILD_CHANGED_HEALTH); @@ -228,6 +225,9 @@ ReturnValue_t AssemblyBase::handleHealthReply(CommandMessage* message) { bool AssemblyBase::checkAndHandleRecovery() { switch (recoveryState) { case RECOVERY_STARTED: + // The recovery was already start in #handleChildrenChangedHealth and we just need + // to wait for an off time period. + // TODO: make time period configurable recoveryState = RECOVERY_WAIT; recoveryOffTimer.resetTimer(); return true; @@ -266,3 +266,11 @@ void AssemblyBase::overwriteDeviceHealth(object_id_t objectId, HasHealthIF::Heal modeHelper.setForced(true); sendHealthCommand(childrenMap[objectId].commandQueue, EXTERNAL_CONTROL); } + +void AssemblyBase::triggerModeHelperEvents(Mode_t mode, Submode_t submode) { + if (modeHelper.isForced()) { + triggerEvent(FORCING_MODE, mode, submode); + } else { + triggerEvent(CHANGING_MODE, mode, submode); + } +} diff --git a/src/fsfw/devicehandlers/AssemblyBase.h b/src/fsfw/devicehandlers/AssemblyBase.h index ec0847f1..fe1c4218 100644 --- a/src/fsfw/devicehandlers/AssemblyBase.h +++ b/src/fsfw/devicehandlers/AssemblyBase.h @@ -12,7 +12,8 @@ * Documentation: Dissertation Baetz p.156, 157. * * This class reduces the complexity of controller components which would - * otherwise be needed for the handling of redundant devices. + * otherwise be needed for the handling of redundant devices. However, it can also be used to + * manage the mode keeping and recovery of non-redundant devices * * The template class monitors mode and health state of its children * and checks availability of devices on every detected change. @@ -26,11 +27,9 @@ * * Important: * - * The implementation must call registerChild(object_id_t child) - * for all commanded children during initialization. + * The implementation must call #registerChild for all commanded children during initialization. * The implementation must call the initialization function of the base class. * (This will call the function in SubsystemBase) - * */ class AssemblyBase : public SubsystemBase { public: @@ -47,9 +46,10 @@ class AssemblyBase : public SubsystemBase { protected: /** - * Command children to reach [mode,submode] combination - * Can be done by setting #commandsOutstanding correctly, - * or using executeTable() + * Command children to reach [mode,submode] combination. Can be done by setting + * #commandsOutstanding correctly, or using #executeTable. In case of an FDIR recovery, + * the user needs to ensure that the target devices are healthy. If a device is not healthy, + * a recovery might be on-going and the device needs to be commanded to off first. * @param mode * @param submode * @return @@ -120,8 +120,19 @@ class AssemblyBase : public SubsystemBase { virtual ReturnValue_t handleHealthReply(CommandMessage *message); - virtual void performChildOperation(); + /** + * @brief Default periodic handler + * @details + * This is the default periodic handler which will be called by the SubsystemBase + * performOperation. It performs the child transitions or reacts to changed health/mode states + * of children objects + */ + virtual void performChildOperation() override; + /** + * This function handles changed mode or health states of children + * @return + */ bool handleChildrenChanged(); /** @@ -134,12 +145,37 @@ class AssemblyBase : public SubsystemBase { bool handleChildrenChangedHealth(); + /** + * Core transition handler. The default implementation will only do something if + * #commandsOutstanding is smaller or equal to zero, which means that all mode commands + * from the #doPerformTransition call were executed successfully. + * + * Unless a second step was requested, the function will then use #checkChildrenState to + * determine whether the target mode was reached. + * + * There is some special handling for certain (internal) modes: + * - A second step is necessary. #commandChildren will be performed again + * - The device health was overwritten. #commandChildren will be called + * - A recovery is ongoing. #checkAndHandleRecovery will be called. + */ virtual void handleChildrenTransition(); ReturnValue_t checkModeCommand(Mode_t mode, Submode_t submode, uint32_t *msToReachTheMode); + /** + * Calls #doStartTransition and triggers an informative event as well that the mode will + * change + * @param mode + * @param submode + */ virtual void startTransition(Mode_t mode, Submode_t submode); + /** + * This function starts the transition by setting the internal #targetSubmode and #targetMode + * variables and then calling the #commandChildren function. + * @param mode + * @param submode + */ virtual void doStartTransition(Mode_t mode, Submode_t submode); virtual bool isInTransition(); @@ -160,7 +196,7 @@ class AssemblyBase : public SubsystemBase { * Manages recovery of a device * @return true if recovery is still ongoing, false else. */ - bool checkAndHandleRecovery(); + virtual bool checkAndHandleRecovery(); /** * Helper method to overwrite health state of one of the children. @@ -168,6 +204,8 @@ class AssemblyBase : public SubsystemBase { * @param objectId Must be a registered child. */ void overwriteDeviceHealth(object_id_t objectId, HasHealthIF::HealthState oldHealth); + + void triggerModeHelperEvents(Mode_t mode, Submode_t submode); }; #endif /* FSFW_DEVICEHANDLERS_ASSEMBLYBASE_H_ */ diff --git a/src/fsfw/devicehandlers/DeviceHandlerBase.cpp b/src/fsfw/devicehandlers/DeviceHandlerBase.cpp index c4ce7781..cc6f99a8 100644 --- a/src/fsfw/devicehandlers/DeviceHandlerBase.cpp +++ b/src/fsfw/devicehandlers/DeviceHandlerBase.cpp @@ -8,6 +8,7 @@ #include "fsfw/ipc/MessageQueueMessage.h" #include "fsfw/ipc/QueueFactory.h" #include "fsfw/objectmanager/ObjectManager.h" +#include "fsfw/serialize/SerialBufferAdapter.h" #include "fsfw/serviceinterface/ServiceInterface.h" #include "fsfw/storagemanager/StorageManagerIF.h" #include "fsfw/subsystem/SubsystemBase.h" @@ -39,8 +40,9 @@ DeviceHandlerBase::DeviceHandlerBase(object_id_t setObjectId, object_id_t device childTransitionDelay(5000), transitionSourceMode(_MODE_POWER_DOWN), transitionSourceSubMode(SUBMODE_NONE) { + auto mqArgs = MqArgs(setObjectId, static_cast(this)); commandQueue = QueueFactory::instance()->createMessageQueue( - cmdQueueSize, MessageQueueMessage::MAX_MESSAGE_SIZE); + cmdQueueSize, MessageQueueMessage::MAX_MESSAGE_SIZE, &mqArgs); insertInCommandMap(RAW_COMMAND_ID); cookieInfo.state = COOKIE_UNUSED; cookieInfo.pendingCommand = deviceCommandMap.end(); @@ -48,9 +50,6 @@ DeviceHandlerBase::DeviceHandlerBase(object_id_t setObjectId, object_id_t device printWarningOrError(sif::OutputTypes::OUT_ERROR, "DeviceHandlerBase", returnvalue::FAILED, "Invalid cookie"); } - if (this->fdirInstance == nullptr) { - this->fdirInstance = new DeviceHandlerFailureIsolation(setObjectId, defaultFdirParentId); - } } void DeviceHandlerBase::setHkDestination(object_id_t hkDestination) { @@ -128,6 +127,18 @@ ReturnValue_t DeviceHandlerBase::initialize() { if (result != returnvalue::OK) { return result; } + if (this->fdirInstance == nullptr) { + this->fdirInstance = + new DeviceHandlerFailureIsolation(this->getObjectId(), defaultFdirParentId); + } + + if (this->parent != objects::NO_OBJECT) { + HasModesIF* modeIF = ObjectManager::instance()->get(this->parent); + HasHealthIF* healthIF = ObjectManager::instance()->get(this->parent); + if (modeIF != nullptr and healthIF != nullptr) { + setParentQueue(modeIF->getCommandQueue()); + } + } communicationInterface = ObjectManager::instance()->get(deviceCommunicationId); @@ -363,13 +374,12 @@ void DeviceHandlerBase::doStateMachine() { } } break; case _MODE_WAIT_OFF: { - uint32_t currentUptime; - Clock::getUptime(¤tUptime); - if (powerSwitcher == nullptr) { setMode(MODE_OFF); break; } + uint32_t currentUptime; + Clock::getUptime(¤tUptime); if (currentUptime - timeoutStart >= powerSwitcher->getSwitchDelayMs()) { triggerEvent(MODE_TRANSITION_FAILED, PowerSwitchIF::SWITCH_TIMEOUT, 0); setMode(MODE_ERROR_ON); @@ -570,6 +580,9 @@ void DeviceHandlerBase::setMode(Mode_t newMode, uint8_t newSubmode) { mode = newMode; modeChanged(); setNormalDatapoolEntriesInvalid(); + if (newMode == MODE_OFF) { + disableCommandsAndReplies(); + } if (!isTransitionalMode()) { modeHelper.modeChanged(newMode, newSubmode); announceMode(false); @@ -1257,28 +1270,31 @@ ReturnValue_t DeviceHandlerBase::letChildHandleMessage(CommandMessage* message) return returnvalue::FAILED; } -void DeviceHandlerBase::handleDeviceTM(SerializeIF* dataSet, DeviceCommandId_t replyId, - bool forceDirectTm) { - if (dataSet == nullptr) { - return; - } +void DeviceHandlerBase::handleDeviceTm(const uint8_t* rawData, size_t rawDataLen, + DeviceCommandId_t replyId, bool forceDirectTm) { + SerialBufferAdapter bufferWrapper(rawData, rawDataLen); + handleDeviceTm(bufferWrapper, replyId, forceDirectTm); +} - DeviceReplyMap::iterator iter = deviceReplyMap.find(replyId); +void DeviceHandlerBase::handleDeviceTm(const SerializeIF& dataSet, DeviceCommandId_t replyId, + bool forceDirectTm) { + auto iter = deviceReplyMap.find(replyId); if (iter == deviceReplyMap.end()) { triggerEvent(DEVICE_UNKNOWN_REPLY, replyId); return; } - /* Regular replies to a command */ + // Regular replies to a command if (iter->second.command != deviceCommandMap.end()) { MessageQueueId_t queueId = iter->second.command->second.sendReplyTo; + // This may fail, but we'll ignore the fault. if (queueId != NO_COMMANDER) { - /* This may fail, but we'll ignore the fault. */ - actionHelper.reportData(queueId, replyId, dataSet); + // This may fail, but we'll ignore the fault. + actionHelper.reportData(queueId, replyId, const_cast(&dataSet)); } - /* This check should make sure we get any TM but don't get anything doubled. */ + // This check should make sure we get any TM but don't get anything doubled. if (wiretappingMode == TM && (requestedRawTraffic != queueId)) { DeviceTmReportingWrapper wrapper(getObjectId(), replyId, dataSet); actionHelper.reportData(requestedRawTraffic, replyId, &wrapper); @@ -1289,22 +1305,17 @@ void DeviceHandlerBase::handleDeviceTM(SerializeIF* dataSet, DeviceCommandId_t r // hiding of sender needed so the service will handle it as // unexpected Data, no matter what state (progress or completed) // it is in - actionHelper.reportData(defaultRawReceiver, replyId, dataSet, true); + actionHelper.reportData(defaultRawReceiver, replyId, const_cast(&dataSet), + true); } } - /* Unrequested or aperiodic replies */ + // Unrequested or aperiodic replies else { DeviceTmReportingWrapper wrapper(getObjectId(), replyId, dataSet); if (wiretappingMode == TM) { actionHelper.reportData(requestedRawTraffic, replyId, &wrapper); } if (forceDirectTm and defaultRawReceiver != MessageQueueIF::NO_QUEUE) { - // sid_t setSid = sid_t(this->getObjectId(), replyId); - // LocalPoolDataSetBase* dataset = getDataSetHandle(setSid); - // if(dataset != nullptr) { - // poolManager.generateHousekeepingPacket(setSid, dataset, true); - // } - // hiding of sender needed so the service will handle it as // unexpected Data, no matter what state (progress or completed) // it is in @@ -1460,6 +1471,8 @@ void DeviceHandlerBase::setTaskIF(PeriodicTaskIF* task) { executingTask = task; void DeviceHandlerBase::debugInterface(uint8_t positionTracker, object_id_t objectId, uint32_t parameter) {} +Submode_t DeviceHandlerBase::getInitialSubmode() { return SUBMODE_NONE; } + void DeviceHandlerBase::performOperationHook() {} ReturnValue_t DeviceHandlerBase::initializeLocalDataPool(localpool::DataPool& localDataPoolMap, @@ -1482,7 +1495,7 @@ ReturnValue_t DeviceHandlerBase::initializeAfterTaskCreation() { this->poolManager.initializeAfterTaskCreation(); if (setStartupImmediately) { - startTransition(MODE_ON, SUBMODE_NONE); + startTransition(MODE_ON, getInitialSubmode()); } return returnvalue::OK; } @@ -1566,3 +1579,29 @@ MessageQueueId_t DeviceHandlerBase::getCommanderQueueId(DeviceCommandId_t replyI } return commandIter->second.sendReplyTo; } + +void DeviceHandlerBase::setCustomFdir(FailureIsolationBase* fdir) { this->fdirInstance = fdir; } + +void DeviceHandlerBase::setParent(object_id_t parent) { this->parent = parent; } + +void DeviceHandlerBase::setPowerSwitcher(PowerSwitchIF* switcher) { + this->powerSwitcher = switcher; +} + +void DeviceHandlerBase::disableCommandsAndReplies() { + for (auto& command : deviceCommandMap) { + if (command.second.isExecuting) { + command.second.isExecuting = false; + } + } + for (auto& reply : deviceReplyMap) { + if (!reply.second.periodic) { + if (reply.second.countdown != nullptr) { + reply.second.countdown->timeOut(); + } else { + reply.second.delayCycles = 0; + } + reply.second.active = false; + } + } +} diff --git a/src/fsfw/devicehandlers/DeviceHandlerBase.h b/src/fsfw/devicehandlers/DeviceHandlerBase.h index a20eae0c..209afaa6 100644 --- a/src/fsfw/devicehandlers/DeviceHandlerBase.h +++ b/src/fsfw/devicehandlers/DeviceHandlerBase.h @@ -23,6 +23,7 @@ #include "fsfw/serviceinterface/serviceInterfaceDefintions.h" #include "fsfw/tasks/ExecutableObjectIF.h" #include "fsfw/tasks/PeriodicTaskIF.h" +#include "fsfw/util/dataWrapper.h" namespace Factory { void setStaticFrameworkObjectIds(); @@ -102,6 +103,9 @@ class DeviceHandlerBase : public DeviceHandlerIF, DeviceHandlerBase(object_id_t setObjectId, object_id_t deviceCommunication, CookieIF *comCookie, FailureIsolationBase *fdirInstance = nullptr, size_t cmdQueueSize = 20); + void setCustomFdir(FailureIsolationBase *fdir); + void setParent(object_id_t parent); + void setPowerSwitcher(PowerSwitchIF *switcher); void setHkDestination(object_id_t hkDestination); /** @@ -463,14 +467,14 @@ class DeviceHandlerBase : public DeviceHandlerIF, * @brief This is a helper method to insert replies in the reply map. * @param deviceCommand Identifier of the reply to add. * @param maxDelayCycles The maximum number of delay cycles the reply waits - * until it times out. + * until it times out. * @param periodic Indicates if the command is periodic (i.e. it is sent - * by the device repeatedly without request) or not. Default is aperiodic (0). - * Please note that periodic replies are disabled by default. You can enable them with - * #updatePeriodicReply + * by the device repeatedly without request) or not. Default is aperiodic (0). + * Please note that periodic replies are disabled by default. You can enable them with + * #updatePeriodicReply * @param countdown Instead of using maxDelayCycles to timeout a device reply it is also possible - * to provide a pointer to a Countdown object which will signal the timeout - * when expired + * to provide a pointer to a Countdown object which will signal the timeout + * when expired * @return - @c returnvalue::OK when the command was successfully inserted, * - @c returnvalue::FAILED else. */ @@ -655,6 +659,12 @@ class DeviceHandlerBase : public DeviceHandlerIF, virtual void debugInterface(uint8_t positionTracker = 0, object_id_t objectId = 0, uint32_t parameter = 0); + /** + * @brief Can be overwritten by a child to specify the initial submode when device has been set + * to startup immediately. + */ + virtual Submode_t getInitialSubmode(); + protected: static const uint8_t INTERFACE_ID = CLASS_ID::DEVICE_HANDLER_BASE; @@ -773,11 +783,18 @@ class DeviceHandlerBase : public DeviceHandlerIF, * This is used to keep track of pending replies. */ struct DeviceReplyInfo { + //! For Command-Reply combinations: //! The maximum number of cycles the handler should wait for a reply //! to this command. + //! + //! Reply Only: + //! For periodic replies, this variable will be the number of delay cycles between the replies. + //! For the non-periodic variant, this variable is not used as there is no meaningful + //! definition for delay uint16_t maxDelayCycles; - //! The currently remaining cycles the handler should wait for a reply, - //! 0 means there is no reply expected + //! This variable will be set to #maxDelayCycles if a reply is expected. + //! For non-periodic replies without a command, this variable is unused. + //! A runtime value of 0 means there is no reply is currently expected. uint16_t delayCycles; size_t replyLen = 0; //!< Expected size of the reply. //! if this is !=0, the delayCycles will not be reset to 0 but to @@ -833,6 +850,7 @@ class DeviceHandlerBase : public DeviceHandlerIF, /** Pointer to the used FDIR instance. If not provided by child, * default class is instantiated. */ FailureIsolationBase *fdirInstance; + object_id_t parent = objects::NO_OBJECT; //! To correctly delete the default instance. bool defaultFDIRUsed; @@ -1052,9 +1070,10 @@ class DeviceHandlerBase : public DeviceHandlerIF, bool isAwaitingReply(); - void handleDeviceTM(SerializeIF *dataSet, DeviceCommandId_t replyId, bool forceDirectTm = false); - // void handleDeviceTM(uint8_t* data, size_t dataSize, DeviceCommandId_t replyId, - // bool forceDirectTm); + void handleDeviceTm(const uint8_t *rawData, size_t rawDataLen, DeviceCommandId_t replyId, + bool forceDirectTm = false); + void handleDeviceTm(const SerializeIF &dataSet, DeviceCommandId_t replyId, + bool forceDirectTm = false); virtual ReturnValue_t checkModeCommand(Mode_t mode, Submode_t submode, uint32_t *msToReachTheMode); @@ -1307,6 +1326,11 @@ class DeviceHandlerBase : public DeviceHandlerIF, void printWarningOrError(sif::OutputTypes errorType, const char *functionName, ReturnValue_t errorCode = returnvalue::FAILED, const char *errorPrint = nullptr); + + /** + * @brief Disables all commands and replies when device is set to MODE_OFF + */ + void disableCommandsAndReplies(); }; #endif /* FSFW_DEVICEHANDLERS_DEVICEHANDLERBASE_H_ */ diff --git a/src/fsfw/devicehandlers/DeviceHandlerFailureIsolation.cpp b/src/fsfw/devicehandlers/DeviceHandlerFailureIsolation.cpp index a3ac9ff7..20e141c3 100644 --- a/src/fsfw/devicehandlers/DeviceHandlerFailureIsolation.cpp +++ b/src/fsfw/devicehandlers/DeviceHandlerFailureIsolation.cpp @@ -29,6 +29,7 @@ ReturnValue_t DeviceHandlerFailureIsolation::eventReceived(EventMessage* event) switch (event->getEvent()) { case HasModesIF::MODE_TRANSITION_FAILED: case HasModesIF::OBJECT_IN_INVALID_MODE: + case DeviceHandlerIF::DEVICE_WANTS_HARD_REBOOT: // We'll try a recovery as long as defined in MAX_REBOOT. // Might cause some AssemblyBase cycles, so keep number low. handleRecovery(event->getEvent()); diff --git a/src/fsfw/devicehandlers/DeviceHandlerIF.h b/src/fsfw/devicehandlers/DeviceHandlerIF.h index 1fc63d3b..1ea742f7 100644 --- a/src/fsfw/devicehandlers/DeviceHandlerIF.h +++ b/src/fsfw/devicehandlers/DeviceHandlerIF.h @@ -109,6 +109,7 @@ class DeviceHandlerIF { static const Event INVALID_DEVICE_COMMAND = MAKE_EVENT(8, severity::LOW); static const Event MONITORING_LIMIT_EXCEEDED = MAKE_EVENT(9, severity::LOW); static const Event MONITORING_AMBIGUOUS = MAKE_EVENT(10, severity::HIGH); + static const Event DEVICE_WANTS_HARD_REBOOT = MAKE_EVENT(11, severity::HIGH); static const uint8_t INTERFACE_ID = CLASS_ID::DEVICE_HANDLER_IF; diff --git a/src/fsfw/devicehandlers/DeviceTmReportingWrapper.cpp b/src/fsfw/devicehandlers/DeviceTmReportingWrapper.cpp index dc987e6d..8fc0d368 100644 --- a/src/fsfw/devicehandlers/DeviceTmReportingWrapper.cpp +++ b/src/fsfw/devicehandlers/DeviceTmReportingWrapper.cpp @@ -3,10 +3,10 @@ #include "fsfw/serialize/SerializeAdapter.h" DeviceTmReportingWrapper::DeviceTmReportingWrapper(object_id_t objectId, ActionId_t actionId, - SerializeIF* data) + const SerializeIF& data) : objectId(objectId), actionId(actionId), data(data) {} -DeviceTmReportingWrapper::~DeviceTmReportingWrapper() {} +DeviceTmReportingWrapper::~DeviceTmReportingWrapper() = default; ReturnValue_t DeviceTmReportingWrapper::serialize(uint8_t** buffer, size_t* size, size_t maxSize, Endianness streamEndianness) const { @@ -19,22 +19,14 @@ ReturnValue_t DeviceTmReportingWrapper::serialize(uint8_t** buffer, size_t* size if (result != returnvalue::OK) { return result; } - return data->serialize(buffer, size, maxSize, streamEndianness); + return data.serialize(buffer, size, maxSize, streamEndianness); } size_t DeviceTmReportingWrapper::getSerializedSize() const { - return sizeof(objectId) + sizeof(ActionId_t) + data->getSerializedSize(); + return sizeof(objectId) + sizeof(ActionId_t) + data.getSerializedSize(); } ReturnValue_t DeviceTmReportingWrapper::deSerialize(const uint8_t** buffer, size_t* size, Endianness streamEndianness) { - ReturnValue_t result = SerializeAdapter::deSerialize(&objectId, buffer, size, streamEndianness); - if (result != returnvalue::OK) { - return result; - } - result = SerializeAdapter::deSerialize(&actionId, buffer, size, streamEndianness); - if (result != returnvalue::OK) { - return result; - } - return data->deSerialize(buffer, size, streamEndianness); + return returnvalue::FAILED; } diff --git a/src/fsfw/devicehandlers/DeviceTmReportingWrapper.h b/src/fsfw/devicehandlers/DeviceTmReportingWrapper.h index 71c64453..53f4b283 100644 --- a/src/fsfw/devicehandlers/DeviceTmReportingWrapper.h +++ b/src/fsfw/devicehandlers/DeviceTmReportingWrapper.h @@ -1,27 +1,29 @@ #ifndef FSFW_DEVICEHANDLERS_DEVICETMREPORTINGWRAPPER_H_ #define FSFW_DEVICEHANDLERS_DEVICETMREPORTINGWRAPPER_H_ -#include "../action/HasActionsIF.h" -#include "../objectmanager/SystemObjectIF.h" -#include "../serialize/SerializeIF.h" +#include "fsfw/action/HasActionsIF.h" +#include "fsfw/objectmanager/SystemObjectIF.h" +#include "fsfw/serialize/SerializeIF.h" +#include "fsfw/util/dataWrapper.h" class DeviceTmReportingWrapper : public SerializeIF { public: - DeviceTmReportingWrapper(object_id_t objectId, ActionId_t actionId, SerializeIF* data); - virtual ~DeviceTmReportingWrapper(); + DeviceTmReportingWrapper(object_id_t objectId, ActionId_t actionId, const SerializeIF& data); + ~DeviceTmReportingWrapper() override; - virtual ReturnValue_t serialize(uint8_t** buffer, size_t* size, size_t maxSize, - Endianness streamEndianness) const override; + ReturnValue_t serialize(uint8_t** buffer, size_t* size, size_t maxSize, + Endianness streamEndianness) const override; - virtual size_t getSerializedSize() const override; - - virtual ReturnValue_t deSerialize(const uint8_t** buffer, size_t* size, - Endianness streamEndianness) override; + [[nodiscard]] size_t getSerializedSize() const override; private: object_id_t objectId; ActionId_t actionId; - SerializeIF* data; + const SerializeIF& data; + + // Deserialization forbidden + ReturnValue_t deSerialize(const uint8_t** buffer, size_t* size, + Endianness streamEndianness) override; }; #endif /* FSFW_DEVICEHANDLERS_DEVICETMREPORTINGWRAPPER_H_ */ diff --git a/src/fsfw/devicehandlers/HealthDevice.cpp b/src/fsfw/devicehandlers/HealthDevice.cpp index 4c09964a..717fadd1 100644 --- a/src/fsfw/devicehandlers/HealthDevice.cpp +++ b/src/fsfw/devicehandlers/HealthDevice.cpp @@ -8,7 +8,9 @@ HealthDevice::HealthDevice(object_id_t setObjectId, MessageQueueId_t parentQueue parentQueue(parentQueue), commandQueue(), healthHelper(this, setObjectId) { - commandQueue = QueueFactory::instance()->createMessageQueue(3); + auto mqArgs = MqArgs(setObjectId, static_cast(this)); + commandQueue = QueueFactory::instance()->createMessageQueue( + 3, MessageQueueMessage::MAX_MESSAGE_SIZE, &mqArgs); } HealthDevice::~HealthDevice() { QueueFactory::instance()->deleteMessageQueue(commandQueue); } diff --git a/src/fsfw/events/EventManager.cpp b/src/fsfw/events/EventManager.cpp index f4466817..3cb80776 100644 --- a/src/fsfw/events/EventManager.cpp +++ b/src/fsfw/events/EventManager.cpp @@ -18,8 +18,9 @@ const LocalPool::LocalPoolConfig EventManager::poolConfig = { EventManager::EventManager(object_id_t setObjectId) : SystemObject(setObjectId), factoryBackend(0, poolConfig, false, true) { mutex = MutexFactory::instance()->createMutex(); - eventReportQueue = QueueFactory::instance()->createMessageQueue(MAX_EVENTS_PER_CYCLE, - EventMessage::EVENT_MESSAGE_SIZE); + auto mqArgs = MqArgs(setObjectId, static_cast(this)); + eventReportQueue = QueueFactory::instance()->createMessageQueue( + MAX_EVENTS_PER_CYCLE, EventMessage::EVENT_MESSAGE_SIZE, &mqArgs); } EventManager::~EventManager() { @@ -46,9 +47,20 @@ ReturnValue_t EventManager::performOperation(uint8_t opCode) { void EventManager::notifyListeners(EventMessage* message) { lockMutex(); - for (auto iter = listenerList.begin(); iter != listenerList.end(); ++iter) { - if (iter->second.match(message)) { - MessageQueueSenderIF::sendMessage(iter->first, message, message->getSender()); + for (auto& listener : listenerList) { + if (listener.second.match(message)) { + ReturnValue_t result = + MessageQueueSenderIF::sendMessage(listener.first, message, message->getSender()); + if (result != returnvalue::OK) { +#if FSFW_CPP_OSTREAM_ENABLED == 1 + sif::error << std::hex << "EventManager::notifyListeners: MSG to 0x" << std::setfill('0') + << std::setw(8) << listener.first << " failed with result 0x" << std::setw(4) + << result << std::setfill(' ') << std::endl; +#else + sif::printError("Sending message to listener 0x%08x failed with result %04x\n", + listener.first, result); +#endif + } } } unlockMutex(); @@ -194,4 +206,19 @@ void EventManager::printUtility(sif::OutputTypes printType, EventMessage* messag } } +void EventManager::printListeners() { +#if FSFW_CPP_OSTREAM_ENABLED == 1 + sif::info << "Event manager listener MQ IDs:" << std::setfill('0') << std::hex << std::endl; + for (auto& listener : listenerList) { + sif::info << "0x" << std::setw(8) << listener.first << std::endl; + } + sif::info << std::dec << std::setfill(' '); +#else + sif::printInfo("Event manager listener MQ IDs:\n"); + for (auto& listener : listenerList) { + sif::printInfo("0x%08x\n", listener.first); + } +#endif +} + #endif /* FSFW_OBJ_EVENT_TRANSLATION == 1 */ diff --git a/src/fsfw/events/EventManager.h b/src/fsfw/events/EventManager.h index 70245f5d..5d786358 100644 --- a/src/fsfw/events/EventManager.h +++ b/src/fsfw/events/EventManager.h @@ -43,6 +43,7 @@ class EventManager : public EventManagerIF, public ExecutableObjectIF, public Sy object_id_t reporterFrom = 0, object_id_t reporterTo = 0, bool reporterInverted = false); ReturnValue_t performOperation(uint8_t opCode); + void printListeners(); protected: MessageQueueIF* eventReportQueue = nullptr; diff --git a/src/fsfw/fdir/FailureIsolationBase.cpp b/src/fsfw/fdir/FailureIsolationBase.cpp index 28df16d8..1e8f1d18 100644 --- a/src/fsfw/fdir/FailureIsolationBase.cpp +++ b/src/fsfw/fdir/FailureIsolationBase.cpp @@ -9,8 +9,9 @@ FailureIsolationBase::FailureIsolationBase(object_id_t owner, object_id_t parent, uint8_t messageDepth, uint8_t parameterDomainBase) : ownerId(owner), faultTreeParent(parent), parameterDomainBase(parameterDomainBase) { - eventQueue = - QueueFactory::instance()->createMessageQueue(messageDepth, EventMessage::EVENT_MESSAGE_SIZE); + auto mqArgs = MqArgs(owner, static_cast(this)); + eventQueue = QueueFactory::instance()->createMessageQueue( + messageDepth, EventMessage::EVENT_MESSAGE_SIZE, &mqArgs); } FailureIsolationBase::~FailureIsolationBase() { @@ -61,11 +62,12 @@ ReturnValue_t FailureIsolationBase::initialize() { ObjectManager::instance()->get(faultTreeParent); if (parentIF == nullptr) { #if FSFW_CPP_OSTREAM_ENABLED == 1 - sif::error << "FailureIsolationBase::intialize: Parent object" - << "invalid." << std::endl; -#endif -#if FSFW_CPP_OSTREAM_ENABLED == 1 - sif::error << "Make sure it implements ConfirmsFailuresIF." << std::endl; + sif::error << "FailureIsolationBase::intialize: Parent object " + << "invalid" << std::endl; + sif::error << "Make sure it implements ConfirmsFailuresIF" << std::endl; +#else + sif::printError("FailureIsolationBase::intialize: Parent object invalid\n"); + sif::printError("Make sure it implements ConfirmsFailuresIF\n"); #endif return ObjectManagerIF::CHILD_INIT_FAILED; return returnvalue::FAILED; diff --git a/src/fsfw/fdir/FailureIsolationBase.h b/src/fsfw/fdir/FailureIsolationBase.h index 543ad6cc..42d82d76 100644 --- a/src/fsfw/fdir/FailureIsolationBase.h +++ b/src/fsfw/fdir/FailureIsolationBase.h @@ -12,13 +12,12 @@ class FailureIsolationBase : public ConfirmsFailuresIF, public HasParametersIF { public: static const uint8_t SUBSYSTEM_ID = SUBSYSTEM_ID::FDIR_1; - static const Event FDIR_CHANGED_STATE = - MAKE_EVENT(1, severity::INFO); //!< FDIR has an internal state, which changed from par2 - //!< (oldState) to par1 (newState). - static const Event FDIR_STARTS_RECOVERY = MAKE_EVENT( - 2, severity::MEDIUM); //!< FDIR tries to restart device. Par1: event that caused recovery. - static const Event FDIR_TURNS_OFF_DEVICE = MAKE_EVENT( - 3, severity::MEDIUM); //!< FDIR turns off device. Par1: event that caused recovery. + //! FDIR has an internal state, which changed from par2 (oldState) to par1 (newState). + static const Event FDIR_CHANGED_STATE = MAKE_EVENT(1, severity::INFO); + //! FDIR tries to restart device. Par1: event that caused recovery. + static const Event FDIR_STARTS_RECOVERY = MAKE_EVENT(2, severity::MEDIUM); + //! FDIR turns off device. Par1: event that caused recovery. + static const Event FDIR_TURNS_OFF_DEVICE = MAKE_EVENT(3, severity::MEDIUM); FailureIsolationBase(object_id_t owner, object_id_t parent = objects::NO_OBJECT, uint8_t messageDepth = 10, uint8_t parameterDomainBase = 0xF0); diff --git a/src/fsfw/globalfunctions/CMakeLists.txt b/src/fsfw/globalfunctions/CMakeLists.txt index cfa02696..cf8a25d5 100644 --- a/src/fsfw/globalfunctions/CMakeLists.txt +++ b/src/fsfw/globalfunctions/CMakeLists.txt @@ -4,6 +4,7 @@ target_sources( AsciiConverter.cpp CRC.cpp DleEncoder.cpp + DleParser.cpp PeriodicOperationDivider.cpp timevalOperations.cpp Type.cpp diff --git a/src/fsfw/globalfunctions/DleParser.cpp b/src/fsfw/globalfunctions/DleParser.cpp new file mode 100644 index 00000000..44c75bab --- /dev/null +++ b/src/fsfw/globalfunctions/DleParser.cpp @@ -0,0 +1,230 @@ +#include "DleParser.h" + +#include + +#include + +DleParser::DleParser(SimpleRingBuffer& decodeRingBuf, DleEncoder& decoder, BufPair encodedBuf, + BufPair decodedBuf, UserHandler handler, void* args) + : decodeRingBuf(decodeRingBuf), + decoder(decoder), + encodedBuf(encodedBuf), + decodedBuf(decodedBuf), + handler(handler), + ctx(args) { + if (handler == nullptr) { +#if FSFW_CPP_OSTREAM_ENABLED == 1 + sif::error << "DleParser::DleParser: Invalid user handler" << std::endl; +#else + sif::printError("DleParser::DleParser: Invalid user handler\n"); +#endif + } +} + +ReturnValue_t DleParser::passData(uint8_t* data, size_t len) { + if (data == nullptr or len == 0 or handler == nullptr) { + return returnvalue::FAILED; + } + size_t copyIntoRingBufFromHere = 0; + size_t copyAmount = len; + size_t startIdx = 0; + ReturnValue_t result = returnvalue::OK; + bool startFoundInThisPacket = false; + for (size_t idx = 0; idx < len; idx++) { + if (data[idx] == DleEncoder::STX_CHAR) { + if (not startFound and not startFoundInThisPacket) { + startIdx = idx; + copyIntoRingBufFromHere = idx; + copyAmount = len - idx; + } else { + // Maybe print warning, should not happen + decodeRingBuf.clear(); + ErrorInfo info; + info.len = idx; + prepareErrorContext(ErrorTypes::CONSECUTIVE_STX_CHARS, info); + handler(ctx); + copyIntoRingBufFromHere = idx; + copyAmount = len - idx; + } + startFound = true; + startFoundInThisPacket = true; + } else if (data[idx] == DleEncoder::ETX_CHAR) { + if (startFoundInThisPacket) { + size_t readLen = 0; + size_t decodedLen = 0; + result = decoder.decode(data + startIdx, idx + 1 - startIdx, &readLen, decodedBuf.first, + decodedBuf.second, &decodedLen); + if (result == returnvalue::OK) { + ctx.setType(ContextType::PACKET_FOUND); + ctx.decodedPacket.first = decodedBuf.first; + ctx.decodedPacket.second = decodedLen; + this->handler(ctx); + } else if (result == DleEncoder::STREAM_TOO_SHORT) { + ErrorInfo info; + info.res = result; + prepareErrorContext(ErrorTypes::DECODING_BUF_TOO_SMALL, info); + handler(ctx); + } else { + ErrorInfo info; + info.res = result; + prepareErrorContext(ErrorTypes::DECODING_BUF_TOO_SMALL, info); + handler(ctx); + } + decodeRingBuf.clear(); + if ((idx + 1) < len) { + copyIntoRingBufFromHere = idx + 1; + copyAmount = len - idx - 1; + } else { + copyAmount = 0; + } + } else if (startFound) { + // ETX found but STX was found in another mini packet. Reconstruct the full packet + // to decode it + result = decodeRingBuf.writeData(data, idx + 1); + if (result != returnvalue::OK) { + ErrorInfo info; + info.res = result; + prepareErrorContext(ErrorTypes::RING_BUF_ERROR, info); + handler(ctx); + } + size_t fullEncodedLen = decodeRingBuf.getAvailableReadData(); + if (fullEncodedLen > encodedBuf.second) { + ErrorInfo info; + info.len = fullEncodedLen; + prepareErrorContext(ErrorTypes::ENCODED_BUF_TOO_SMALL, info); + handler(ctx); + decodeRingBuf.clear(); + } else { + size_t decodedLen = 0; + size_t readLen = 0; + decodeRingBuf.readData(encodedBuf.first, fullEncodedLen, true); + result = decoder.decode(encodedBuf.first, fullEncodedLen, &readLen, decodedBuf.first, + decodedBuf.second, &decodedLen); + if (result == returnvalue::OK) { + if (this->handler != nullptr) { + ctx.setType(ContextType::PACKET_FOUND); + ctx.decodedPacket.first = decodedBuf.first; + ctx.decodedPacket.second = decodedLen; + this->handler(ctx); + } + } else if (result == DleEncoder::STREAM_TOO_SHORT) { + ErrorInfo info; + info.res = result; + prepareErrorContext(ErrorTypes::DECODING_BUF_TOO_SMALL, info); + handler(ctx); + } else { + ErrorInfo info; + info.res = result; + prepareErrorContext(ErrorTypes::DECODE_ERROR, info); + handler(ctx); + } + decodeRingBuf.clear(); + startFound = false; + startFoundInThisPacket = false; + if ((idx + 1) < len) { + copyIntoRingBufFromHere = idx + 1; + copyAmount = len - idx - 1; + } else { + copyAmount = 0; + } + } + } else { + // End data without preceeding STX + ErrorInfo info; + info.len = idx + 1; + prepareErrorContext(ErrorTypes::CONSECUTIVE_ETX_CHARS, info); + handler(ctx); + decodeRingBuf.clear(); + if ((idx + 1) < len) { + copyIntoRingBufFromHere = idx + 1; + copyAmount = len - idx - 1; + } else { + copyAmount = 0; + } + } + startFoundInThisPacket = false; + startFound = false; + } + } + if (copyAmount > 0) { + result = decodeRingBuf.writeData(data + copyIntoRingBufFromHere, copyAmount); + if (result != returnvalue::OK) { + ErrorInfo info; + info.res = result; + prepareErrorContext(ErrorTypes::RING_BUF_ERROR, info); + handler(ctx); + } + } + return returnvalue::OK; +} + +void DleParser::defaultFoundPacketHandler(uint8_t* packet, size_t len, void* args) { +#if FSFW_VERBOSE_LEVEL >= 1 +#if FSFW_CPP_OSTREAM_ENABLED == 1 + sif::info << "DleParserBase::handleFoundPacket: Detected DLE packet with " << len << " bytes" + << std::endl; +#else + sif::printInfo("DleParserBase::handleFoundPacket: Detected DLE packet with %d bytes\n", len); +#endif +#endif +} + +void DleParser::defaultErrorHandler(ErrorTypes err, ErrorInfo ctx) { + switch (err) { + case (ErrorTypes::NONE): { + errorPrinter("No error"); + break; + } + case (ErrorTypes::DECODE_ERROR): { + errorPrinter("Decode Error"); + break; + } + case (ErrorTypes::RING_BUF_ERROR): { + errorPrinter("Ring Buffer Error"); + break; + } + case (ErrorTypes::ENCODED_BUF_TOO_SMALL): + case (ErrorTypes::DECODING_BUF_TOO_SMALL): { + char opt[64]; + snprintf(opt, sizeof(opt), ": Too small for packet with length %zu", ctx.len); + if (err == ErrorTypes::ENCODED_BUF_TOO_SMALL) { + errorPrinter("Encoded buf too small", opt); + } else { + errorPrinter("Decoding buf too small", opt); + } + break; + } + case (ErrorTypes::CONSECUTIVE_STX_CHARS): { + errorPrinter("Consecutive STX chars detected"); + break; + } + case (ErrorTypes::CONSECUTIVE_ETX_CHARS): { + errorPrinter("Consecutive ETX chars detected"); + break; + } + } +} + +void DleParser::errorPrinter(const char* str, const char* opt) { + if (opt == nullptr) { + opt = ""; + } +#if FSFW_VERBOSE_LEVEL >= 1 +#if FSFW_CPP_OSTREAM_ENABLED == 1 + sif::info << "DleParserBase::handleParseError: " << str << opt << std::endl; +#else + sif::printInfo("DleParserBase::handleParseError: %s%s\n", str, opt); +#endif +#endif +} + +void DleParser::prepareErrorContext(ErrorTypes err, ErrorInfo info) { + ctx.setType(ContextType::ERROR); + ctx.error.first = err; + ctx.error.second = info; +} + +void DleParser::reset() { + startFound = false; + decodeRingBuf.clear(); +} diff --git a/src/fsfw/globalfunctions/DleParser.h b/src/fsfw/globalfunctions/DleParser.h new file mode 100644 index 00000000..f1a4f193 --- /dev/null +++ b/src/fsfw/globalfunctions/DleParser.h @@ -0,0 +1,124 @@ +#pragma once + +#include +#include +#include + +#include +#include + +/** + * @brief This base helper class can be used to extract DLE encoded packets from a data stream + * @details + * The core API of the parser takes received packets which can contains DLE packets. The parser + * can deal with DLE packets split across multiple packets. It does so by using a dedicated + * decoding ring buffer. The user can process received packets and detect errors by + * overriding two provided virtual methods. This also allows detecting multiple DLE packets + * inside one passed packet. + */ +class DleParser { + public: + using BufPair = std::pair; + + enum class ContextType { PACKET_FOUND, ERROR }; + + enum class ErrorTypes { + NONE, + ENCODED_BUF_TOO_SMALL, + DECODING_BUF_TOO_SMALL, + DECODE_ERROR, + RING_BUF_ERROR, + CONSECUTIVE_STX_CHARS, + CONSECUTIVE_ETX_CHARS + }; + + union ErrorInfo { + size_t len; + ReturnValue_t res; + }; + + using ErrorPair = std::pair; + + struct Context { + public: + Context(void* args) : userArgs(args) { setType(ContextType::PACKET_FOUND); } + + void setType(ContextType type) { + if (type == ContextType::PACKET_FOUND) { + error.first = ErrorTypes::NONE; + error.second.len = 0; + } else { + decodedPacket.first = nullptr; + decodedPacket.second = 0; + } + } + + ContextType getType() const { return type; } + + BufPair decodedPacket = {}; + ErrorPair error; + void* userArgs; + + private: + ContextType type; + }; + + using UserHandler = void (*)(const Context& ctx); + + /** + * Base class constructor + * @param decodeRingBuf Ring buffer used to store multiple packets to allow detecting DLE packets + * split across multiple packets + * @param decoder Decoder instance + * @param encodedBuf Buffer used to store encoded packets. It has to be large enough to hold + * the largest expected encoded DLE packet size + * @param decodedBuf Buffer used to store decoded packets. It has to be large enough to hold the + * largest expected decoded DLE packet size + * @param handler Function which will be called on a found packet + * @param args Arbitrary user argument + */ + DleParser(SimpleRingBuffer& decodeRingBuf, DleEncoder& decoder, BufPair encodedBuf, + BufPair decodedBuf, UserHandler handler, void* args); + + /** + * This function allows to pass new data into the parser. It then scans for DLE packets + * automatically and inserts (part of) the packet into a ring buffer if necessary. + * @param data + * @param len + * @return + */ + ReturnValue_t passData(uint8_t* data, size_t len); + + /** + * Example found packet handler + * function call + * @param packet Decoded packet + * @param len Length of detected packet + */ + void defaultFoundPacketHandler(uint8_t* packet, size_t len, void* args); + /** + * Will be called if an error occured in the #passData call + * @param err + * @param ctx Context information depending on the error type + * - For buffer length errors, will be set to the detected packet length which is too large + * - For decode or ring buffer errors, will be set to the result returned from the failed call + */ + static void defaultErrorHandler(ErrorTypes err, ErrorInfo ctx); + + static void errorPrinter(const char* str, const char* opt = nullptr); + + void prepareErrorContext(ErrorTypes err, ErrorInfo ctx); + /** + * Resets the parser by resetting the internal states and clearing the decoding ring buffer + */ + void reset(); + + private: + SimpleRingBuffer& decodeRingBuf; + DleEncoder& decoder; + BufPair encodedBuf; + BufPair decodedBuf; + UserHandler handler = nullptr; + Context ctx; + bool startFound = false; +}; diff --git a/src/fsfw/health/HasHealthIF.h b/src/fsfw/health/HasHealthIF.h index 77a1c12f..16666bbc 100644 --- a/src/fsfw/health/HasHealthIF.h +++ b/src/fsfw/health/HasHealthIF.h @@ -16,26 +16,24 @@ class HasHealthIF { }; static const uint8_t INTERFACE_ID = CLASS_ID::HAS_HEALTH_IF; - static const ReturnValue_t OBJECT_NOT_HEALTHY = MAKE_RETURN_CODE(1); - static const ReturnValue_t INVALID_HEALTH_STATE = MAKE_RETURN_CODE(2); + static constexpr ReturnValue_t OBJECT_NOT_HEALTHY = returnvalue::makeCode(INTERFACE_ID, 1); + static constexpr ReturnValue_t INVALID_HEALTH_STATE = returnvalue::makeCode(INTERFACE_ID, 2); + static constexpr ReturnValue_t IS_EXTERNALLY_CONTROLLED = returnvalue::makeCode(INTERFACE_ID, 3); static const uint8_t SUBSYSTEM_ID = SUBSYSTEM_ID::SYSTEM_MANAGER_1; + //! P1: New Health, P2: Old Health static const Event HEALTH_INFO = MAKE_EVENT(6, severity::INFO); static const Event CHILD_CHANGED_HEALTH = MAKE_EVENT(7, severity::INFO); static const Event CHILD_PROBLEMS = MAKE_EVENT(8, severity::LOW); - static const Event OVERWRITING_HEALTH = - MAKE_EVENT(9, severity::LOW); //!< Assembly overwrites health information of children to keep - //!< satellite alive. - static const Event TRYING_RECOVERY = - MAKE_EVENT(10, severity::MEDIUM); //!< Someone starts a recovery of a component (typically - //!< power-cycle). No parameters. - static const Event RECOVERY_STEP = - MAKE_EVENT(11, severity::MEDIUM); //!< Recovery is ongoing. Comes twice during recovery. P1: - //!< 0 for the first, 1 for the second event. P2: 0 - static const Event RECOVERY_DONE = MAKE_EVENT( - 12, - severity::MEDIUM); //!< Recovery was completed. Not necessarily successful. No parameters. - + //! Assembly overwrites health information of children to keep satellite alive. + static const Event OVERWRITING_HEALTH = MAKE_EVENT(9, severity::LOW); + //! Someone starts a recovery of a component (typically power-cycle). No parameters. + static const Event TRYING_RECOVERY = MAKE_EVENT(10, severity::MEDIUM); + //! Recovery is ongoing. Comes twice during recovery. + //! P1: 0 for the first, 1 for the second event. P2: 0 + static const Event RECOVERY_STEP = MAKE_EVENT(11, severity::MEDIUM); + //! Recovery was completed. Not necessarily successful. No parameters. + static const Event RECOVERY_DONE = MAKE_EVENT(12, severity::MEDIUM); virtual ~HasHealthIF() {} virtual MessageQueueId_t getCommandQueue() const = 0; diff --git a/src/fsfw/health/HealthTable.h b/src/fsfw/health/HealthTable.h index 60e00f92..076228c1 100644 --- a/src/fsfw/health/HealthTable.h +++ b/src/fsfw/health/HealthTable.h @@ -9,8 +9,8 @@ class HealthTable : public HealthTableIF, public SystemObject { public: - HealthTable(object_id_t objectid); - virtual ~HealthTable(); + explicit HealthTable(object_id_t objectid); + ~HealthTable() override; void setMutexTimeout(MutexIF::TimeoutType timeoutType, uint32_t timeoutMs); diff --git a/src/fsfw/housekeeping/AcceptsHkPacketsIF.h b/src/fsfw/housekeeping/AcceptsHkPacketsIF.h index 07882829..7648e7ed 100644 --- a/src/fsfw/housekeeping/AcceptsHkPacketsIF.h +++ b/src/fsfw/housekeeping/AcceptsHkPacketsIF.h @@ -1,12 +1,12 @@ #ifndef FRAMEWORK_HOUSEKEEPING_ACCEPTSHKPACKETSIF_H_ #define FRAMEWORK_HOUSEKEEPING_ACCEPTSHKPACKETSIF_H_ -#include "../ipc/MessageQueueMessageIF.h" +#include "fsfw/ipc/MessageQueueMessageIF.h" class AcceptsHkPacketsIF { public: - virtual ~AcceptsHkPacketsIF(){}; - virtual MessageQueueId_t getHkQueue() const = 0; + virtual ~AcceptsHkPacketsIF() = default; + [[nodiscard]] virtual MessageQueueId_t getHkQueue() const = 0; }; #endif /* FRAMEWORK_HOUSEKEEPING_ACCEPTSHKPACKETSIF_H_ */ diff --git a/src/fsfw/internalerror/InternalErrorReporter.cpp b/src/fsfw/internalerror/InternalErrorReporter.cpp index d0af62d8..96d12de4 100644 --- a/src/fsfw/internalerror/InternalErrorReporter.cpp +++ b/src/fsfw/internalerror/InternalErrorReporter.cpp @@ -7,11 +7,13 @@ InternalErrorReporter::InternalErrorReporter(object_id_t setObjectId, uint32_t messageQueueDepth) : SystemObject(setObjectId), - commandQueue(QueueFactory::instance()->createMessageQueue(messageQueueDepth)), poolManager(this, commandQueue), internalErrorSid(setObjectId, InternalErrorDataset::ERROR_SET_ID), internalErrorDataset(this) { mutex = MutexFactory::instance()->createMutex(); + auto mqArgs = MqArgs(setObjectId, static_cast(this)); + commandQueue = QueueFactory::instance()->createMessageQueue( + messageQueueDepth, MessageQueueMessage::MAX_MESSAGE_SIZE, &mqArgs); } InternalErrorReporter::~InternalErrorReporter() { MutexFactory::instance()->deleteMutex(mutex); } @@ -36,15 +38,14 @@ ReturnValue_t InternalErrorReporter::performOperation(uint8_t opCode) { if ((newQueueHits > 0) or (newTmHits > 0) or (newStoreHits > 0)) { #if FSFW_CPP_OSTREAM_ENABLED == 1 sif::debug << "InternalErrorReporter::performOperation: Errors " - << "occured!" << std::endl; - sif::debug << "Queue errors: " << newQueueHits << std::endl; - sif::debug << "TM errors: " << newTmHits << std::endl; - sif::debug << "Store errors: " << newStoreHits << std::endl; + << "occured: Queue | TM | Store : " << newQueueHits << " | " << newTmHits << " | " + << newStoreHits << std::endl; #else - sif::printDebug("InternalErrorReporter::performOperation: Errors occured!\n"); - sif::printDebug("Queue errors: %lu\n", static_cast(newQueueHits)); - sif::printDebug("TM errors: %lu\n", static_cast(newTmHits)); - sif::printDebug("Store errors: %lu\n", static_cast(newStoreHits)); + sif::printDebug( + "InternalErrorReporter::performOperation: Errors occured: Queue | TM | Store: %lu | %lu " + "| %lu\n", + static_cast(newQueueHits), static_cast(newTmHits), + static_cast(newStoreHits)); #endif } } @@ -126,11 +127,12 @@ MessageQueueId_t InternalErrorReporter::getCommandQueue() const { ReturnValue_t InternalErrorReporter::initializeLocalDataPool(localpool::DataPool &localDataPoolMap, LocalDataPoolManager &poolManager) { - localDataPoolMap.emplace(errorPoolIds::TM_HITS, new PoolEntry()); - localDataPoolMap.emplace(errorPoolIds::QUEUE_HITS, new PoolEntry()); - localDataPoolMap.emplace(errorPoolIds::STORE_HITS, new PoolEntry()); - poolManager.subscribeForPeriodicPacket(internalErrorSid, false, getPeriodicOperationFrequency(), - true); + localDataPoolMap.emplace(errorPoolIds::TM_HITS, &tmHitsEntry); + localDataPoolMap.emplace(errorPoolIds::QUEUE_HITS, &queueHitsEntry); + localDataPoolMap.emplace(errorPoolIds::STORE_HITS, &storeHitsEntry); + poolManager.subscribeForDiagPeriodicPacket(subdp::DiagnosticsHkPeriodicParams( + internalErrorSid, false, + static_cast(getPeriodicOperationFrequency()) / static_cast(1000.0))); internalErrorDataset.setValidity(true, true); return returnvalue::OK; } diff --git a/src/fsfw/internalerror/InternalErrorReporter.h b/src/fsfw/internalerror/InternalErrorReporter.h index 549be4bd..ca82d1a4 100644 --- a/src/fsfw/internalerror/InternalErrorReporter.h +++ b/src/fsfw/internalerror/InternalErrorReporter.h @@ -72,6 +72,9 @@ class InternalErrorReporter : public SystemObject, uint32_t queueHits = 0; uint32_t tmHits = 0; uint32_t storeHits = 0; + PoolEntry tmHitsEntry = PoolEntry(); + PoolEntry storeHitsEntry = PoolEntry(); + PoolEntry queueHitsEntry = PoolEntry(); uint32_t getAndResetQueueHits(); void incrementQueueHits(); diff --git a/src/fsfw/internalerror/InternalErrorReporterIF.h b/src/fsfw/internalerror/InternalErrorReporterIF.h index 61bb52e7..aa917d21 100644 --- a/src/fsfw/internalerror/InternalErrorReporterIF.h +++ b/src/fsfw/internalerror/InternalErrorReporterIF.h @@ -12,7 +12,7 @@ */ class InternalErrorReporterIF { public: - virtual ~InternalErrorReporterIF() {} + virtual ~InternalErrorReporterIF() = default; /** * @brief Function to be called if a message queue could not be sent. * @details OSAL Implementations should call this function to indicate that diff --git a/src/fsfw/ipc/CommandMessageIF.h b/src/fsfw/ipc/CommandMessageIF.h index dc8f7109..e714ca70 100644 --- a/src/fsfw/ipc/CommandMessageIF.h +++ b/src/fsfw/ipc/CommandMessageIF.h @@ -34,7 +34,7 @@ class CommandMessageIF { static const Command_t CMD_NONE = MAKE_COMMAND_ID(0); static const Command_t REPLY_COMMAND_OK = MAKE_COMMAND_ID(1); //! Reply indicating that the current command was rejected, - //! par1 should contain the error code + //! Parameter 1 should contain the error code static const Command_t REPLY_REJECTED = MAKE_COMMAND_ID(2); virtual ~CommandMessageIF(){}; diff --git a/src/fsfw/ipc/MessageQueueBase.cpp b/src/fsfw/ipc/MessageQueueBase.cpp index c43670ed..56041bee 100644 --- a/src/fsfw/ipc/MessageQueueBase.cpp +++ b/src/fsfw/ipc/MessageQueueBase.cpp @@ -8,7 +8,7 @@ MessageQueueBase::MessageQueueBase(MessageQueueId_t id, MessageQueueId_t default } } -MessageQueueBase::~MessageQueueBase() {} +MessageQueueBase::~MessageQueueBase() = default; ReturnValue_t MessageQueueBase::sendToDefault(MessageQueueMessageIF* message) { return sendToDefaultFrom(message, this->getId(), false); diff --git a/src/fsfw/ipc/MessageQueueBase.h b/src/fsfw/ipc/MessageQueueBase.h index 942b6121..c4de8eeb 100644 --- a/src/fsfw/ipc/MessageQueueBase.h +++ b/src/fsfw/ipc/MessageQueueBase.h @@ -7,28 +7,28 @@ class MessageQueueBase : public MessageQueueIF { public: MessageQueueBase(MessageQueueId_t id, MessageQueueId_t defaultDest, MqArgs* mqArgs); - virtual ~MessageQueueBase(); + ~MessageQueueBase() override; // Default implementations for MessageQueueIF where possible - virtual MessageQueueId_t getLastPartner() const override; - virtual MessageQueueId_t getId() const override; - virtual MqArgs& getMqArgs() override; - virtual void setDefaultDestination(MessageQueueId_t defaultDestination) override; - virtual MessageQueueId_t getDefaultDestination() const override; - virtual bool isDefaultDestinationSet() const override; - virtual ReturnValue_t sendMessage(MessageQueueId_t sendTo, MessageQueueMessageIF* message, - bool ignoreFault) override; - virtual ReturnValue_t sendToDefault(MessageQueueMessageIF* message) override; - virtual ReturnValue_t reply(MessageQueueMessageIF* message) override; - virtual ReturnValue_t receiveMessage(MessageQueueMessageIF* message, - MessageQueueId_t* receivedFrom) override; - virtual ReturnValue_t sendToDefaultFrom(MessageQueueMessageIF* message, MessageQueueId_t sentFrom, - bool ignoreFault = false) override; + [[nodiscard]] MessageQueueId_t getLastPartner() const override; + [[nodiscard]] MessageQueueId_t getId() const override; + MqArgs& getMqArgs() override; + void setDefaultDestination(MessageQueueId_t defaultDestination) override; + [[nodiscard]] MessageQueueId_t getDefaultDestination() const override; + [[nodiscard]] bool isDefaultDestinationSet() const override; + ReturnValue_t sendMessage(MessageQueueId_t sendTo, MessageQueueMessageIF* message, + bool ignoreFault) override; + ReturnValue_t sendToDefault(MessageQueueMessageIF* message) override; + ReturnValue_t reply(MessageQueueMessageIF* message) override; + ReturnValue_t receiveMessage(MessageQueueMessageIF* message, + MessageQueueId_t* receivedFrom) override; + ReturnValue_t sendToDefaultFrom(MessageQueueMessageIF* message, MessageQueueId_t sentFrom, + bool ignoreFault = false) override; // OSAL specific, forward the abstract function - virtual ReturnValue_t receiveMessage(MessageQueueMessageIF* message) = 0; - virtual ReturnValue_t sendMessageFrom(MessageQueueId_t sendTo, MessageQueueMessageIF* message, - MessageQueueId_t sentFrom, bool ignoreFault = false) = 0; + ReturnValue_t receiveMessage(MessageQueueMessageIF* message) override = 0; + ReturnValue_t sendMessageFrom(MessageQueueId_t sendTo, MessageQueueMessageIF* message, + MessageQueueId_t sentFrom, bool ignoreFault = false) override = 0; protected: MessageQueueId_t id = MessageQueueIF::NO_QUEUE; diff --git a/src/fsfw/ipc/MessageQueueIF.h b/src/fsfw/ipc/MessageQueueIF.h index 4fe8a63b..fcd7c329 100644 --- a/src/fsfw/ipc/MessageQueueIF.h +++ b/src/fsfw/ipc/MessageQueueIF.h @@ -30,7 +30,7 @@ class MessageQueueIF { //! [EXPORT] : [COMMENT] Returned if the target destination is invalid. static constexpr ReturnValue_t DESTINATION_INVALID = MAKE_RETURN_CODE(4); - virtual ~MessageQueueIF() {} + virtual ~MessageQueueIF() = default; /** * @brief This operation sends a message to the last communication partner. * @details @@ -82,11 +82,11 @@ class MessageQueueIF { /** * @brief This method returns the message queue ID of the last communication partner. */ - virtual MessageQueueId_t getLastPartner() const = 0; + [[nodiscard]] virtual MessageQueueId_t getLastPartner() const = 0; /** * @brief This method returns the message queue ID of this class's message queue. */ - virtual MessageQueueId_t getId() const = 0; + [[nodiscard]] virtual MessageQueueId_t getId() const = 0; /** * @brief With the sendMessage call, a queue message is sent to a receiving queue. @@ -159,9 +159,9 @@ class MessageQueueIF { /** * @brief This method is a simple getter for the default destination. */ - virtual MessageQueueId_t getDefaultDestination() const = 0; + [[nodiscard]] virtual MessageQueueId_t getDefaultDestination() const = 0; - virtual bool isDefaultDestinationSet() const = 0; + [[nodiscard]] virtual bool isDefaultDestinationSet() const = 0; virtual MqArgs& getMqArgs() = 0; }; diff --git a/src/fsfw/ipc/MessageQueueMessage.cpp b/src/fsfw/ipc/MessageQueueMessage.cpp index 6899915a..b0ce090f 100644 --- a/src/fsfw/ipc/MessageQueueMessage.cpp +++ b/src/fsfw/ipc/MessageQueueMessage.cpp @@ -10,10 +10,10 @@ MessageQueueMessage::MessageQueueMessage() : messageSize(getMinimumMessageSize() } MessageQueueMessage::MessageQueueMessage(uint8_t* data, size_t size) - : messageSize(this->HEADER_SIZE + size) { - if (size <= this->MAX_DATA_SIZE) { - memcpy(this->getData(), data, size); - this->messageSize = this->HEADER_SIZE + size; + : messageSize(MessageQueueMessage::HEADER_SIZE + size) { + if (size <= MessageQueueMessage::MAX_DATA_SIZE) { + std::memcpy(MessageQueueMessage::getData(), data, size); + this->messageSize = MessageQueueMessage::HEADER_SIZE + size; } else { #if FSFW_CPP_OSTREAM_ENABLED == 1 sif::warning << "MessageQueueMessage: Passed size larger than maximum" @@ -21,21 +21,23 @@ MessageQueueMessage::MessageQueueMessage(uint8_t* data, size_t size) << std::endl; #endif memset(this->internalBuffer, 0, sizeof(this->internalBuffer)); - this->messageSize = this->HEADER_SIZE; + this->messageSize = MessageQueueMessage::HEADER_SIZE; } } -MessageQueueMessage::~MessageQueueMessage() {} +MessageQueueMessage::~MessageQueueMessage() = default; const uint8_t* MessageQueueMessage::getBuffer() const { return this->internalBuffer; } uint8_t* MessageQueueMessage::getBuffer() { return this->internalBuffer; } const uint8_t* MessageQueueMessage::getData() const { - return this->internalBuffer + this->HEADER_SIZE; + return this->internalBuffer + MessageQueueMessage::HEADER_SIZE; } -uint8_t* MessageQueueMessage::getData() { return this->internalBuffer + this->HEADER_SIZE; } +uint8_t* MessageQueueMessage::getData() { + return this->internalBuffer + MessageQueueMessage::HEADER_SIZE; +} MessageQueueId_t MessageQueueMessage::getSender() const { MessageQueueId_t temp_id; @@ -58,14 +60,22 @@ void MessageQueueMessage::print(bool printWholeMessage) { } } -void MessageQueueMessage::clear() { memset(this->getBuffer(), 0, this->MAX_MESSAGE_SIZE); } +void MessageQueueMessage::clear() { + memset(this->getBuffer(), 0, MessageQueueMessage::MAX_MESSAGE_SIZE); +} size_t MessageQueueMessage::getMessageSize() const { return this->messageSize; } -void MessageQueueMessage::setMessageSize(size_t messageSize) { this->messageSize = messageSize; } +void MessageQueueMessage::setMessageSize(size_t messageSize_) { this->messageSize = messageSize_; } -size_t MessageQueueMessage::getMinimumMessageSize() const { return this->MIN_MESSAGE_SIZE; } +size_t MessageQueueMessage::getMinimumMessageSize() const { + return MessageQueueMessage::MIN_MESSAGE_SIZE; +} -size_t MessageQueueMessage::getMaximumMessageSize() const { return this->MAX_MESSAGE_SIZE; } +size_t MessageQueueMessage::getMaximumMessageSize() const { + return MessageQueueMessage::MAX_MESSAGE_SIZE; +} -size_t MessageQueueMessage::getMaximumDataSize() const { return this->MAX_DATA_SIZE; } +size_t MessageQueueMessage::getMaximumDataSize() const { + return MessageQueueMessage::MAX_DATA_SIZE; +} diff --git a/src/fsfw/ipc/MessageQueueMessage.h b/src/fsfw/ipc/MessageQueueMessage.h index 30e50ffe..a3d596f1 100644 --- a/src/fsfw/ipc/MessageQueueMessage.h +++ b/src/fsfw/ipc/MessageQueueMessage.h @@ -25,6 +25,30 @@ */ class MessageQueueMessage : public MessageQueueMessageIF { public: + /** + * @brief This constant defines the maximum size of the data content, + * excluding the header. + * @details + * It may be changed if necessary, but in general should be kept + * as small as possible. + */ + static const size_t MAX_DATA_SIZE = 24; + /** + * @brief This constant defines the maximum total size in bytes + * of a sent message. + * @details + * It is the sum of the maximum data and the header size. Be aware that + * this constant is used to define the buffer sizes for every message + * queue in the system. So, a change here may have significant impact on + * the required resources. + */ + static constexpr size_t MAX_MESSAGE_SIZE = MAX_DATA_SIZE + HEADER_SIZE; + /** + * @brief Defines the minimum size of a message where only the + * header is included + */ + static constexpr size_t MIN_MESSAGE_SIZE = HEADER_SIZE; + /** * @brief The class is initialized empty with this constructor. * @details @@ -50,59 +74,12 @@ class MessageQueueMessage : public MessageQueueMessageIF { * @brief As no memory is allocated in this class, * the destructor is empty. */ - virtual ~MessageQueueMessage(); + ~MessageQueueMessage() override; - /** - * @brief The size information of each message is stored in - * this attribute. - * @details - * It is public to simplify usage and to allow for passing the size - * address as a pointer. Care must be taken when inheriting from this class, - * as every child class is responsible for managing the size information by - * itself. When using the class to receive a message, the size information - * is updated automatically. - * - * Please note that the minimum size is limited by the size of the header - * while the maximum size is limited by the maximum allowed message size. - */ - size_t messageSize; - /** - * @brief This constant defines the maximum size of the data content, - * excluding the header. - * @details - * It may be changed if necessary, but in general should be kept - * as small as possible. - */ - static const size_t MAX_DATA_SIZE = 24; - - /** - * @brief This constant defines the maximum total size in bytes - * of a sent message. - * @details - * It is the sum of the maximum data and the header size. Be aware that - * this constant is used to define the buffer sizes for every message - * queue in the system. So, a change here may have significant impact on - * the required resources. - */ - static constexpr size_t MAX_MESSAGE_SIZE = MAX_DATA_SIZE + HEADER_SIZE; - /** - * @brief Defines the minimum size of a message where only the - * header is included - */ - static constexpr size_t MIN_MESSAGE_SIZE = HEADER_SIZE; - - private: - /** - * @brief This is the internal buffer that contains the - * actual message data. - */ - uint8_t internalBuffer[MAX_MESSAGE_SIZE]; - - public: /** * @brief This method is used to get the complete data of the message. */ - const uint8_t* getBuffer() const override; + [[nodiscard]] const uint8_t* getBuffer() const override; /** * @brief This method is used to get the complete data of the message. */ @@ -112,7 +89,7 @@ class MessageQueueMessage : public MessageQueueMessageIF { * @details * It shall be used by child classes to add data at the right position. */ - const uint8_t* getData() const override; + [[nodiscard]] const uint8_t* getData() const override; /** * @brief This method is used to fetch the data content of the message. * @details @@ -123,7 +100,7 @@ class MessageQueueMessage : public MessageQueueMessageIF { * @brief This method is used to extract the sender's message * queue id information from a received message. */ - MessageQueueId_t getSender() const override; + [[nodiscard]] MessageQueueId_t getSender() const override; /** * @brief With this method, the whole content * and the message size is set to zero. @@ -138,16 +115,40 @@ class MessageQueueMessage : public MessageQueueMessageIF { */ void setSender(MessageQueueId_t setId) override; - virtual size_t getMessageSize() const override; - virtual void setMessageSize(size_t messageSize) override; - virtual size_t getMinimumMessageSize() const override; - virtual size_t getMaximumMessageSize() const override; - virtual size_t getMaximumDataSize() const override; + [[nodiscard]] size_t getMessageSize() const override; + void setMessageSize(size_t messageSize) override; + [[nodiscard]] size_t getMinimumMessageSize() const override; + [[nodiscard]] size_t getMaximumMessageSize() const override; + [[nodiscard]] size_t getMaximumDataSize() const override; /** * @brief This is a debug method that prints the content. */ void print(bool printWholeMessage); + + /** + * TODO: This really should not be public. If it should be possible to pass size address as a + * pointer, add a getter function returning a const reference to the size + * @brief The size information of each message is stored in + * this attribute. + * @details + * It is public to simplify usage and to allow for passing the size + * address as a pointer. Care must be taken when inheriting from this class, + * as every child class is responsible for managing the size information by + * itself. When using the class to receive a message, the size information + * is updated automatically. + * + * Please note that the minimum size is limited by the size of the header + * while the maximum size is limited by the maximum allowed message size. + */ + size_t messageSize; + + private: + /** + * @brief This is the internal buffer that contains the + * actual message data. + */ + uint8_t internalBuffer[MAX_MESSAGE_SIZE] = {}; }; #endif /* FSFW_IPC_MESSAGEQUEUEMESSAGE_H_ */ diff --git a/src/fsfw/ipc/MessageQueueMessageIF.h b/src/fsfw/ipc/MessageQueueMessageIF.h index dae28926..300a90ab 100644 --- a/src/fsfw/ipc/MessageQueueMessageIF.h +++ b/src/fsfw/ipc/MessageQueueMessageIF.h @@ -14,7 +14,7 @@ class MessageQueueMessageIF { */ static const size_t HEADER_SIZE = sizeof(MessageQueueId_t); - virtual ~MessageQueueMessageIF(){}; + virtual ~MessageQueueMessageIF() = default; /** * @brief With this method, the whole content and the message @@ -29,7 +29,7 @@ class MessageQueueMessageIF { * @brief Get read-only pointer to the complete data of the message. * @return */ - virtual const uint8_t* getBuffer() const = 0; + [[nodiscard]] virtual const uint8_t* getBuffer() const = 0; /** * @brief This method is used to get the complete data of the message. @@ -48,14 +48,14 @@ class MessageQueueMessageIF { * @brief This method is used to extract the sender's message queue id * information from a received message. */ - virtual MessageQueueId_t getSender() const = 0; + [[nodiscard]] virtual MessageQueueId_t getSender() const = 0; /** * @brief This method is used to fetch the data content of the message. * @details * It shall be used by child classes to add data at the right position. */ - virtual const uint8_t* getData() const = 0; + [[nodiscard]] virtual const uint8_t* getData() const = 0; /** * @brief This method is used to fetch the data content of the message. * @details @@ -67,12 +67,28 @@ class MessageQueueMessageIF { * Get constant message size of current message implementation. * @return */ - virtual size_t getMessageSize() const = 0; + [[nodiscard]] virtual size_t getMessageSize() const = 0; + /** + * Sets the current message size of a given message + * @param messageSize + */ virtual void setMessageSize(size_t messageSize) = 0; - virtual size_t getMinimumMessageSize() const = 0; - virtual size_t getMaximumMessageSize() const = 0; - virtual size_t getMaximumDataSize() const = 0; + /** + * Returns the smallest possible message size, including any headers + * @return + */ + [[nodiscard]] virtual size_t getMinimumMessageSize() const = 0; + /** + * Returns the largest possible message size, including any headers + * @return + */ + [[nodiscard]] virtual size_t getMaximumMessageSize() const = 0; + /** + * Returns the largest possible data size without any headers + * @return + */ + [[nodiscard]] virtual size_t getMaximumDataSize() const = 0; }; #endif /* FRAMEWORK_IPC_MESSAGEQUEUEMESSAGEIF_H_ */ diff --git a/src/fsfw/ipc/MessageQueueSenderIF.h b/src/fsfw/ipc/MessageQueueSenderIF.h index a98862f6..83c7223a 100644 --- a/src/fsfw/ipc/MessageQueueSenderIF.h +++ b/src/fsfw/ipc/MessageQueueSenderIF.h @@ -1,14 +1,14 @@ #ifndef FSFW_IPC_MESSAGEQUEUESENDERIF_H_ #define FSFW_IPC_MESSAGEQUEUESENDERIF_H_ -#include "../objectmanager/ObjectManagerIF.h" #include "MessageQueueIF.h" #include "MessageQueueMessageIF.h" +#include "fsfw/objectmanager/ObjectManagerIF.h" class MessageQueueSenderIF { public: - virtual ~MessageQueueSenderIF() {} - + virtual ~MessageQueueSenderIF() = default; + MessageQueueSenderIF() = delete; /** * Allows sending messages without actually "owning" a message queue. * Not sure whether this is actually a good idea. @@ -16,9 +16,6 @@ class MessageQueueSenderIF { static ReturnValue_t sendMessage(MessageQueueId_t sendTo, MessageQueueMessageIF* message, MessageQueueId_t sentFrom = MessageQueueIF::NO_QUEUE, bool ignoreFault = false); - - private: - MessageQueueSenderIF() {} }; #endif /* FSFW_IPC_MESSAGEQUEUESENDERIF_H_ */ diff --git a/src/fsfw/modes/HasModesIF.h b/src/fsfw/modes/HasModesIF.h index 599975f8..ca207559 100644 --- a/src/fsfw/modes/HasModesIF.h +++ b/src/fsfw/modes/HasModesIF.h @@ -19,32 +19,33 @@ class HasModesIF { static const ReturnValue_t INVALID_SUBMODE = MAKE_RETURN_CODE(0x04); static const uint8_t SUBSYSTEM_ID = SUBSYSTEM_ID::SYSTEM_MANAGER; - static const Event CHANGING_MODE = - MAKE_EVENT(0, severity::INFO); //!< An object announces changing the mode. p1: target mode. - //!< p2: target submode - static const Event MODE_INFO = MAKE_EVENT( - 1, - severity::INFO); //!< An Object announces its mode; parameter1 is mode, parameter2 is submode + //! An object announces changing the mode. p1: target mode. p2: target submode + static const Event CHANGING_MODE = MAKE_EVENT(0, severity::INFO); + //! An Object announces its mode; parameter1 is mode, parameter2 is submode + static const Event MODE_INFO = MAKE_EVENT(1, severity::INFO); static const Event FALLBACK_FAILED = MAKE_EVENT(2, severity::HIGH); static const Event MODE_TRANSITION_FAILED = MAKE_EVENT(3, severity::LOW); static const Event CANT_KEEP_MODE = MAKE_EVENT(4, severity::HIGH); - static const Event OBJECT_IN_INVALID_MODE = - MAKE_EVENT(5, severity::LOW); //!< Indicates a bug or configuration failure: Object is in a - //!< mode it should never be in. - static const Event FORCING_MODE = MAKE_EVENT( - 6, severity::MEDIUM); //!< The mode is changed, but for some reason, the change is forced, - //!< i.e. EXTERNAL_CONTROL ignored. p1: target mode. p2: target submode - static const Event MODE_CMD_REJECTED = - MAKE_EVENT(7, severity::LOW); //!< A mode command was rejected by the called object. Par1: - //!< called object id, Par2: return code. + //! Indicates a bug or configuration failure: Object is in a mode it should never be in. + static const Event OBJECT_IN_INVALID_MODE = MAKE_EVENT(5, severity::LOW); + //! The mode is changed, but for some reason, the change is forced, i.e. EXTERNAL_CONTROL ignored. + //! p1: target mode. p2: target submode + static const Event FORCING_MODE = MAKE_EVENT(6, severity::MEDIUM); + //! A mode command was rejected by the called object. Par1: called object id, Par2: return code. + static const Event MODE_CMD_REJECTED = MAKE_EVENT(7, severity::LOW); - static const Mode_t MODE_ON = - 1; //!< The device is powered and ready to perform operations. In this mode, no commands are - //!< sent by the device handler itself, but direct commands van be commanded and will be - //!< interpreted - static const Mode_t MODE_OFF = 0; //!< The device is powered off. The only command accepted in - //!< this mode is a mode change to on. - static const Submode_t SUBMODE_NONE = 0; //!< To avoid checks against magic number "0". + //! The device is powered and ready to perform operations. In this mode, no commands are + //! sent by the device handler itself, but direct commands van be commanded and will be + //! interpreted + static constexpr Mode_t MODE_ON = 1; + //! The device is powered off. The only command accepted in this mode is a mode change to on. + static constexpr Mode_t MODE_OFF = 0; + + static constexpr Mode_t MODE_INVALID = -1; + static constexpr Mode_t MODE_UNDEFINED = -2; + + //! To avoid checks against magic number "0". + static const Submode_t SUBMODE_NONE = 0; virtual ~HasModesIF() {} virtual MessageQueueId_t getCommandQueue() const = 0; diff --git a/src/fsfw/monitoring/MonitoringMessageContent.h b/src/fsfw/monitoring/MonitoringMessageContent.h index fb3ace3d..aeadacdf 100644 --- a/src/fsfw/monitoring/MonitoringMessageContent.h +++ b/src/fsfw/monitoring/MonitoringMessageContent.h @@ -34,7 +34,7 @@ class MonitoringReportContent : public SerialLinkedListAdapter { SerializeElement limitValue; SerializeElement oldState; SerializeElement newState; - uint8_t rawTimestamp[TimeStamperIF::MISSION_TIMESTAMP_SIZE] = {}; + uint8_t rawTimestamp[TimeStamperIF::MAXIMUM_TIMESTAMP_LEN] = {}; SerializeElement> timestampSerializer; TimeStamperIF* timeStamper; MonitoringReportContent() @@ -47,7 +47,7 @@ class MonitoringReportContent : public SerialLinkedListAdapter { oldState(0), newState(0), timestampSerializer(rawTimestamp, sizeof(rawTimestamp)), - timeStamper(NULL) { + timeStamper(nullptr) { setAllNext(); } MonitoringReportContent(gp_id_t globalPoolId, T value, T limitValue, ReturnValue_t oldState, @@ -61,7 +61,7 @@ class MonitoringReportContent : public SerialLinkedListAdapter { oldState(oldState), newState(newState), timestampSerializer(rawTimestamp, sizeof(rawTimestamp)), - timeStamper(NULL) { + timeStamper(nullptr) { setAllNext(); if (checkAndSetStamper()) { timeStamper->addTimeStamp(rawTimestamp, sizeof(rawTimestamp)); diff --git a/src/fsfw/objectmanager/ObjectManager.cpp b/src/fsfw/objectmanager/ObjectManager.cpp index 7a32fcc6..e74d479e 100644 --- a/src/fsfw/objectmanager/ObjectManager.cpp +++ b/src/fsfw/objectmanager/ObjectManager.cpp @@ -21,7 +21,7 @@ void ObjectManager::setObjectFactoryFunction(produce_function_t objFactoryFunc, this->factoryArgs = factoryArgs; } -ObjectManager::ObjectManager() {} +ObjectManager::ObjectManager() = default; ObjectManager::~ObjectManager() { for (auto const& iter : objectList) { @@ -53,7 +53,7 @@ ReturnValue_t ObjectManager::insert(object_id_t id, SystemObjectIF* object) { } ReturnValue_t ObjectManager::remove(object_id_t id) { - if (this->getSystemObject(id) != NULL) { + if (this->getSystemObject(id) != nullptr) { this->objectList.erase(id); #if FSFW_CPP_OSTREAM_ENABLED == 1 // sif::debug << "ObjectManager::removeObject: Object " << std::hex @@ -95,13 +95,16 @@ void ObjectManager::initialize() { for (auto const& it : objectList) { result = it.second->initialize(); if (result != returnvalue::OK) { +#if FSFW_VERBOSE_LEVEL >= 1 #if FSFW_CPP_OSTREAM_ENABLED == 1 - object_id_t var = it.first; sif::error << "ObjectManager::initialize: Object 0x" << std::hex << std::setw(8) - << std::setfill('0') << var - << " failed to " - "initialize with code 0x" - << result << std::dec << std::setfill(' ') << std::endl; + << std::setfill('0') << it.first << " failed to initialize with code 0x" << result + << std::dec << std::setfill(' ') << std::endl; +#else + sif::printError( + "ObjectManager::initialize: Object 0x%08x failed to initialize with code 0x%04x\n", var, + it.first); +#endif #endif errorCount++; } diff --git a/src/fsfw/objectmanager/ObjectManager.h b/src/fsfw/objectmanager/ObjectManager.h index 50e4af00..e0e74792 100644 --- a/src/fsfw/objectmanager/ObjectManager.h +++ b/src/fsfw/objectmanager/ObjectManager.h @@ -38,7 +38,7 @@ class ObjectManager : public ObjectManagerIF { /** * @brief In the class's destructor, all objects in the list are deleted. */ - virtual ~ObjectManager(); + ~ObjectManager() override; ReturnValue_t insert(object_id_t id, SystemObjectIF* object) override; ReturnValue_t remove(object_id_t id) override; void initialize() override; diff --git a/src/fsfw/objectmanager/SystemObjectIF.h b/src/fsfw/objectmanager/SystemObjectIF.h index 490de20b..b9243de2 100644 --- a/src/fsfw/objectmanager/SystemObjectIF.h +++ b/src/fsfw/objectmanager/SystemObjectIF.h @@ -46,7 +46,7 @@ class SystemObjectIF : public EventReportingProxyIF { * Therefore, a two-step initialization resolves this problem and prevents * circular dependencies of not-fully initialized objects on start up. * @return - @c returnvalue::OK in case the initialization was successful - * - @c returnvalue::FAILED otherwise + * - @c returnvalue::FAILED otherwise */ virtual ReturnValue_t initialize() = 0; /** diff --git a/src/fsfw/objectmanager/frameworkObjects.h b/src/fsfw/objectmanager/frameworkObjects.h index cddc6ba2..9487147d 100644 --- a/src/fsfw/objectmanager/frameworkObjects.h +++ b/src/fsfw/objectmanager/frameworkObjects.h @@ -33,6 +33,7 @@ enum framework_objects : object_id_t { TC_STORE = 0x534f0100, TM_STORE = 0x534f0200, TIME_STAMPER = 0x53500010, + VERIFICATION_REPORTER = 0x53500020, FSFW_OBJECTS_END = 0x53ffffff, NO_OBJECT = 0xFFFFFFFF diff --git a/src/fsfw/osal/CMakeLists.txt b/src/fsfw/osal/CMakeLists.txt index 50fd6102..d0aea96a 100644 --- a/src/fsfw/osal/CMakeLists.txt +++ b/src/fsfw/osal/CMakeLists.txt @@ -16,7 +16,9 @@ elseif(FSFW_OSAL MATCHES "host") else() - message(WARNING "The OS_FSFW variable was not set. Assuming host OS..") + message( + WARNING + "${MSG_PREFIX} The FSFW_OSAL variable was not set. Assuming host OS..") # Not set. Assumuing this is a host build, try to determine host OS if(WIN32) add_subdirectory(host) diff --git a/src/fsfw/osal/host/Clock.cpp b/src/fsfw/osal/host/Clock.cpp index 8b6fc904..29c6c1a6 100644 --- a/src/fsfw/osal/host/Clock.cpp +++ b/src/fsfw/osal/host/Clock.cpp @@ -146,7 +146,7 @@ ReturnValue_t Clock::getDateAndTime(TimeOfDay_t* time) { } ReturnValue_t Clock::convertTimeOfDayToTimeval(const TimeOfDay_t* from, timeval* to) { - struct tm time_tm; + struct tm time_tm {}; time_tm.tm_year = from->year - 1900; time_tm.tm_mon = from->month - 1; diff --git a/src/fsfw/osal/host/MessageQueue.cpp b/src/fsfw/osal/host/MessageQueue.cpp index ced30f09..a4781cdb 100644 --- a/src/fsfw/osal/host/MessageQueue.cpp +++ b/src/fsfw/osal/host/MessageQueue.cpp @@ -65,11 +65,11 @@ ReturnValue_t MessageQueue::sendMessageFromMessageQueue(MessageQueueId_t sendTo, // But I will still return a failure here. return returnvalue::FAILED; } - MessageQueue* targetQueue = + auto* targetQueue = dynamic_cast(QueueMapManager::instance()->getMessageQueue(sendTo)); if (targetQueue == nullptr) { if (not ignoreFault) { - InternalErrorReporterIF* internalErrorReporter = + auto* internalErrorReporter = ObjectManager::instance()->get(objects::INTERNAL_ERROR_REPORTER); if (internalErrorReporter != nullptr) { internalErrorReporter->queueMessageNotSent(); @@ -84,7 +84,7 @@ ReturnValue_t MessageQueue::sendMessageFromMessageQueue(MessageQueueId_t sendTo, message->getMaximumMessageSize()); } else { if (not ignoreFault) { - InternalErrorReporterIF* internalErrorReporter = + auto* internalErrorReporter = ObjectManager::instance()->get(objects::INTERNAL_ERROR_REPORTER); if (internalErrorReporter != nullptr) { internalErrorReporter->queueMessageNotSent(); diff --git a/src/fsfw/osal/host/MessageQueue.h b/src/fsfw/osal/host/MessageQueue.h index 4020c6dc..7d60fb8e 100644 --- a/src/fsfw/osal/host/MessageQueue.h +++ b/src/fsfw/osal/host/MessageQueue.h @@ -68,7 +68,7 @@ class MessageQueue : public MessageQueueBase { * @details This is accomplished by using the delete call provided * by the operating system. */ - virtual ~MessageQueue(); + ~MessageQueue() override; // Implement non-generic MessageQueueIF functions not handled by MessageQueueBase virtual ReturnValue_t sendMessageFrom(MessageQueueId_t sendTo, MessageQueueMessageIF* message, @@ -111,8 +111,6 @@ class MessageQueue : public MessageQueueBase { size_t messageDepth = 0; MutexIF* queueLock; - - MessageQueueId_t defaultDestination = MessageQueueIF::NO_QUEUE; }; #endif /* FRAMEWORK_OSAL_HOST_MESSAGEQUEUE_H_ */ diff --git a/src/fsfw/osal/host/QueueFactory.cpp b/src/fsfw/osal/host/QueueFactory.cpp index c6605656..e2d83fd4 100644 --- a/src/fsfw/osal/host/QueueFactory.cpp +++ b/src/fsfw/osal/host/QueueFactory.cpp @@ -13,7 +13,6 @@ ReturnValue_t MessageQueueSenderIF::sendMessage(MessageQueueId_t sendTo, MessageQueueMessageIF* message, MessageQueueId_t sentFrom, bool ignoreFault) { return MessageQueue::sendMessageFromMessageQueue(sendTo, message, sentFrom, ignoreFault); - return returnvalue::OK; } QueueFactory* QueueFactory::instance() { @@ -23,9 +22,9 @@ QueueFactory* QueueFactory::instance() { return factoryInstance; } -QueueFactory::QueueFactory() {} +QueueFactory::QueueFactory() = default; -QueueFactory::~QueueFactory() {} +QueueFactory::~QueueFactory() = default; MessageQueueIF* QueueFactory::createMessageQueue(uint32_t messageDepth, size_t maxMessageSize, MqArgs* args) { diff --git a/src/fsfw/osal/host/QueueMapManager.cpp b/src/fsfw/osal/host/QueueMapManager.cpp index dc4eb1de..d7efb0dd 100644 --- a/src/fsfw/osal/host/QueueMapManager.cpp +++ b/src/fsfw/osal/host/QueueMapManager.cpp @@ -54,7 +54,7 @@ MessageQueueIF* QueueMapManager::getMessageQueue(MessageQueueId_t messageQueueId } else { #if FSFW_CPP_OSTREAM_ENABLED == 1 sif::warning << "QueueMapManager::getQueueHandle: The ID " << messageQueueId - << " does not exists in the map!" << std::endl; + << " does not exist in the map" << std::endl; #else sif::printWarning("QueueMapManager::getQueueHandle: The ID %d does not exist in the map!\n", messageQueueId); diff --git a/src/fsfw/osal/linux/Clock.cpp b/src/fsfw/osal/linux/Clock.cpp index a2b6f5bf..bfdcf4e2 100644 --- a/src/fsfw/osal/linux/Clock.cpp +++ b/src/fsfw/osal/linux/Clock.cpp @@ -2,23 +2,22 @@ #include #include -#include -#include #include +#include #include #include "fsfw/ipc/MutexGuard.h" #include "fsfw/serviceinterface/ServiceInterface.h" -uint32_t Clock::getTicksPerSecond(void) { +uint32_t Clock::getTicksPerSecond() { uint32_t ticks = sysconf(_SC_CLK_TCK); return ticks; } ReturnValue_t Clock::setClock(const TimeOfDay_t* time) { - timespec timeUnix; - timeval timeTimeval; + timespec timeUnix{}; + timeval timeTimeval{}; convertTimeOfDayToTimeval(time, &timeTimeval); timeUnix.tv_sec = timeTimeval.tv_sec; timeUnix.tv_nsec = (__syscall_slong_t)timeTimeval.tv_usec * 1000; @@ -32,7 +31,7 @@ ReturnValue_t Clock::setClock(const TimeOfDay_t* time) { } ReturnValue_t Clock::setClock(const timeval* time) { - timespec timeUnix; + timespec timeUnix{}; timeUnix.tv_sec = time->tv_sec; timeUnix.tv_nsec = (__syscall_slong_t)time->tv_usec * 1000; int status = clock_settime(CLOCK_REALTIME, &timeUnix); @@ -44,7 +43,7 @@ ReturnValue_t Clock::setClock(const timeval* time) { } ReturnValue_t Clock::getClock_timeval(timeval* time) { - timespec timeUnix; + timespec timeUnix{}; int status = clock_gettime(CLOCK_REALTIME, &timeUnix); if (status != 0) { return returnvalue::FAILED; @@ -55,18 +54,18 @@ ReturnValue_t Clock::getClock_timeval(timeval* time) { } ReturnValue_t Clock::getClock_usecs(uint64_t* time) { - timeval timeVal; + timeval timeVal{}; ReturnValue_t result = getClock_timeval(&timeVal); if (result != returnvalue::OK) { return result; } - *time = (uint64_t)timeVal.tv_sec * 1e6 + timeVal.tv_usec; + *time = static_cast(timeVal.tv_sec) * 1e6 + timeVal.tv_usec; return returnvalue::OK; } timeval Clock::getUptime() { - timeval uptime; + timeval uptime{}; auto result = getUptime(&uptime); if (result != returnvalue::OK) { #if FSFW_CPP_OSTREAM_ENABLED == 1 @@ -99,7 +98,7 @@ ReturnValue_t Clock::getUptime(timeval* uptime) { //} ReturnValue_t Clock::getUptime(uint32_t* uptimeMs) { - timeval uptime; + timeval uptime{}; ReturnValue_t result = getUptime(&uptime); if (result != returnvalue::OK) { return result; @@ -109,7 +108,7 @@ ReturnValue_t Clock::getUptime(uint32_t* uptimeMs) { } ReturnValue_t Clock::getDateAndTime(TimeOfDay_t* time) { - timespec timeUnix; + timespec timeUnix{}; int status = clock_gettime(CLOCK_REALTIME, &timeUnix); if (status != 0) { // TODO errno @@ -122,7 +121,7 @@ ReturnValue_t Clock::getDateAndTime(TimeOfDay_t* time) { MutexGuard helper(timeMutex); // gmtime writes its output in a global buffer which is not Thread Safe // Therefore we have to use a Mutex here - struct tm* timeInfo; + struct std::tm* timeInfo; timeInfo = gmtime(&timeUnix.tv_sec); time->year = timeInfo->tm_year + 1900; time->month = timeInfo->tm_mon + 1; @@ -136,7 +135,7 @@ ReturnValue_t Clock::getDateAndTime(TimeOfDay_t* time) { } ReturnValue_t Clock::convertTimeOfDayToTimeval(const TimeOfDay_t* from, timeval* to) { - tm fromTm; + std::tm fromTm{}; // Note: Fails for years before AD fromTm.tm_year = from->year - 1900; fromTm.tm_mon = from->month - 1; diff --git a/src/fsfw/parameters/HasParametersIF.h b/src/fsfw/parameters/HasParametersIF.h index d586ceba..8dc99644 100644 --- a/src/fsfw/parameters/HasParametersIF.h +++ b/src/fsfw/parameters/HasParametersIF.h @@ -66,7 +66,8 @@ class HasParametersIF { * @param newValues * @param startAtIndex Linear index, runs left to right, top to bottom for * matrix indexes. - * @return + * @return returnvalue::OK if parameter is valid and a set function of the parameter wrapper was + * called. */ virtual ReturnValue_t getParameter(uint8_t domainId, uint8_t uniqueIdentifier, ParameterWrapper *parameterWrapper, diff --git a/src/fsfw/parameters/ParameterMessage.cpp b/src/fsfw/parameters/ParameterMessage.cpp index 9dc58365..9a7b5288 100644 --- a/src/fsfw/parameters/ParameterMessage.cpp +++ b/src/fsfw/parameters/ParameterMessage.cpp @@ -44,7 +44,7 @@ store_address_t ParameterMessage::getParameterLoadCommand(const CommandMessage* *pfc = packedParamSettings >> 16 & 0xff; *rows = packedParamSettings >> 8 & 0xff; *columns = packedParamSettings & 0xff; - return message->getParameter2(); + return static_cast(message->getParameter2()); } void ParameterMessage::clear(CommandMessage* message) { diff --git a/src/fsfw/parameters/ParameterWrapper.cpp b/src/fsfw/parameters/ParameterWrapper.cpp index 522a68b1..ad1d2a51 100644 --- a/src/fsfw/parameters/ParameterWrapper.cpp +++ b/src/fsfw/parameters/ParameterWrapper.cpp @@ -211,9 +211,13 @@ ReturnValue_t ParameterWrapper::copyFrom(const ParameterWrapper *from, if (data == nullptr) { #if FSFW_VERBOSE_LEVEL >= 1 #if FSFW_CPP_OSTREAM_ENABLED == 1 - sif::warning << "ParameterWrapper::copyFrom: Called on read-only variable!" << std::endl; + sif::warning << "ParameterWrapper::copyFrom: Called on read-only variable or " + "data pointer not set" + << std::endl; #else - sif::printWarning("ParameterWrapper::copyFrom: Called on read-only variable!\n"); + sif::printWarning( + "ParameterWrapper::copyFrom: Called on read-only variable " + "or data pointer not set\n"); #endif #endif /* FSFW_VERBOSE_LEVEL >= 1 */ return READONLY; @@ -222,9 +226,9 @@ ReturnValue_t ParameterWrapper::copyFrom(const ParameterWrapper *from, if (from->readonlyData == nullptr) { #if FSFW_VERBOSE_LEVEL >= 1 #if FSFW_CPP_OSTREAM_ENABLED == 1 - sif::warning << "ParameterWrapper::copyFrom: Source not set!" << std::endl; + sif::warning << "ParameterWrapper::copyFrom: Source not set" << std::endl; #else - sif::printWarning("ParameterWrapper::copyFrom: Source not set!\n"); + sif::printWarning("ParameterWrapper::copyFrom: Source not set\n"); #endif #endif /* FSFW_VERBOSE_LEVEL >= 1 */ return SOURCE_NOT_SET; @@ -233,9 +237,9 @@ ReturnValue_t ParameterWrapper::copyFrom(const ParameterWrapper *from, if (type != from->type) { #if FSFW_VERBOSE_LEVEL >= 1 #if FSFW_CPP_OSTREAM_ENABLED == 1 - sif::warning << "ParameterWrapper::copyFrom: Datatype missmatch!" << std::endl; + sif::warning << "ParameterWrapper::copyFrom: Datatype missmatch" << std::endl; #else - sif::printWarning("ParameterWrapper::copyFrom: Datatype missmatch!\n"); + sif::printWarning("ParameterWrapper::copyFrom: Datatype missmatch\n"); #endif #endif /* FSFW_VERBOSE_LEVEL >= 1 */ return DATATYPE_MISSMATCH; @@ -245,9 +249,9 @@ ReturnValue_t ParameterWrapper::copyFrom(const ParameterWrapper *from, if (rows == 0 or columns == 0) { #if FSFW_VERBOSE_LEVEL >= 1 #if FSFW_CPP_OSTREAM_ENABLED == 1 - sif::warning << "ParameterWrapper::copyFrom: Columns or rows zero!" << std::endl; + sif::warning << "ParameterWrapper::copyFrom: Columns or rows zero" << std::endl; #else - sif::printWarning("ParameterWrapper::copyFrom: Columns or rows zero!\n"); + sif::printWarning("ParameterWrapper::copyFrom: Columns or rows zero\n"); #endif #endif /* FSFW_VERBOSE_LEVEL >= 1 */ return COLUMN_OR_ROWS_ZERO; diff --git a/src/fsfw/power/PowerSwitchIF.h b/src/fsfw/power/PowerSwitchIF.h index e8c9aff4..43746218 100644 --- a/src/fsfw/power/PowerSwitchIF.h +++ b/src/fsfw/power/PowerSwitchIF.h @@ -29,9 +29,9 @@ class PowerSwitchIF { static const ReturnValue_t FUSE_ON = MAKE_RETURN_CODE(3); static const ReturnValue_t FUSE_OFF = MAKE_RETURN_CODE(4); static const uint8_t SUBSYSTEM_ID = SUBSYSTEM_ID::PCDU_2; - static const Event SWITCH_WENT_OFF = MAKE_EVENT( - 0, severity::LOW); //!< Someone detected that a switch went off which shouldn't. Severity: - //!< Low, Parameter1: switchId1, Parameter2: switchId2 + //!< Someone detected that a switch went off which shouldn't. Severity: + //!< Low, Parameter1: switchId1, Parameter2: switchId2 + static const Event SWITCH_WENT_OFF = MAKE_EVENT(0, severity::LOW); /** * send a direct command to the Power Unit to enable/disable the specified switch. * diff --git a/src/fsfw/pus/CService200ModeCommanding.cpp b/src/fsfw/pus/CService200ModeCommanding.cpp index fedc4760..69c057ea 100644 --- a/src/fsfw/pus/CService200ModeCommanding.cpp +++ b/src/fsfw/pus/CService200ModeCommanding.cpp @@ -41,7 +41,7 @@ ReturnValue_t CService200ModeCommanding::getMessageQueueAndObject(uint8_t subser ReturnValue_t CService200ModeCommanding::checkInterfaceAndAcquireMessageQueue( MessageQueueId_t *messageQueueToSet, object_id_t *objectId) { - HasModesIF *destination = ObjectManager::instance()->get(*objectId); + auto *destination = ObjectManager::instance()->get(*objectId); if (destination == nullptr) { return CommandingServiceBase::INVALID_OBJECT; } @@ -96,13 +96,13 @@ ReturnValue_t CService200ModeCommanding::handleReply(const CommandMessage *reply ReturnValue_t CService200ModeCommanding::prepareModeReply(const CommandMessage *reply, object_id_t objectId) { ModePacket modeReplyPacket(objectId, ModeMessage::getMode(reply), ModeMessage::getSubmode(reply)); - return sendTmPacket(Subservice::REPLY_MODE_REPLY, &modeReplyPacket); + return sendTmPacket(Subservice::REPLY_MODE_REPLY, modeReplyPacket); } ReturnValue_t CService200ModeCommanding::prepareWrongModeReply(const CommandMessage *reply, object_id_t objectId) { ModePacket wrongModeReply(objectId, ModeMessage::getMode(reply), ModeMessage::getSubmode(reply)); - ReturnValue_t result = sendTmPacket(Subservice::REPLY_WRONG_MODE_REPLY, &wrongModeReply); + ReturnValue_t result = sendTmPacket(Subservice::REPLY_WRONG_MODE_REPLY, wrongModeReply); if (result == returnvalue::OK) { // We want to produce an error here in any case because the mode was not correct return returnvalue::FAILED; @@ -113,7 +113,7 @@ ReturnValue_t CService200ModeCommanding::prepareWrongModeReply(const CommandMess ReturnValue_t CService200ModeCommanding::prepareCantReachModeReply(const CommandMessage *reply, object_id_t objectId) { CantReachModePacket cantReachModePacket(objectId, ModeMessage::getCantReachModeReason(reply)); - ReturnValue_t result = sendTmPacket(Subservice::REPLY_CANT_REACH_MODE, &cantReachModePacket); + ReturnValue_t result = sendTmPacket(Subservice::REPLY_CANT_REACH_MODE, cantReachModePacket); if (result == returnvalue::OK) { // We want to produce an error here in any case because the mode was not reached return returnvalue::FAILED; diff --git a/src/fsfw/pus/CService201HealthCommanding.cpp b/src/fsfw/pus/CService201HealthCommanding.cpp index 45473581..c8458edb 100644 --- a/src/fsfw/pus/CService201HealthCommanding.cpp +++ b/src/fsfw/pus/CService201HealthCommanding.cpp @@ -102,5 +102,5 @@ ReturnValue_t CService201HealthCommanding::handleReply(const CommandMessage *rep auto health = static_cast(HealthMessage::getHealth(reply)); auto oldHealth = static_cast(HealthMessage::getOldHealth(reply)); HealthSetReply healthSetReply(health, oldHealth); - return sendTmPacket(Subservice::REPLY_HEALTH_SET, &healthSetReply); + return sendTmPacket(Subservice::REPLY_HEALTH_SET, healthSetReply); } diff --git a/src/fsfw/pus/Service11TelecommandScheduling.h b/src/fsfw/pus/Service11TelecommandScheduling.h index 2a14401b..aa958193 100644 --- a/src/fsfw/pus/Service11TelecommandScheduling.h +++ b/src/fsfw/pus/Service11TelecommandScheduling.h @@ -38,8 +38,9 @@ class Service11TelecommandScheduling final : public PusServiceBase { static constexpr uint8_t CLASS_ID = CLASS_ID::PUS_SERVICE_11; static constexpr ReturnValue_t INVALID_TYPE_TIME_WINDOW = returnvalue::makeCode(CLASS_ID, 1); - static constexpr ReturnValue_t TIMESHIFTING_NOT_POSSIBLE = returnvalue::makeCode(CLASS_ID, 2); - static constexpr ReturnValue_t INVALID_RELATIVE_TIME = returnvalue::makeCode(CLASS_ID, 3); + static constexpr ReturnValue_t INVALID_TIME_WINDOW = returnvalue::makeCode(CLASS_ID, 2); + static constexpr ReturnValue_t TIMESHIFTING_NOT_POSSIBLE = returnvalue::makeCode(CLASS_ID, 3); + static constexpr ReturnValue_t INVALID_RELATIVE_TIME = returnvalue::makeCode(CLASS_ID, 4); static constexpr uint8_t SUBSYSTEM_ID = SUBSYSTEM_ID::PUS_SERVICE_11; @@ -71,8 +72,7 @@ class Service11TelecommandScheduling final : public PusServiceBase { TO_TIMETAG = 3 }; - Service11TelecommandScheduling(object_id_t objectId, uint16_t apid, uint8_t serviceId, - AcceptsTelecommandsIF* tcRecipient, + Service11TelecommandScheduling(PsbParams params, AcceptsTelecommandsIF* tcRecipient, uint16_t releaseTimeMarginSeconds = DEFAULT_RELEASE_TIME_MARGIN, bool debugMode = false); @@ -156,7 +156,7 @@ class Service11TelecommandScheduling final : public PusServiceBase { * @param data The Application data of the TC (get via getApplicationData()). * @return requestId */ - uint64_t getRequestIdFromDataTC(const uint8_t* data) const; + [[nodiscard]] uint64_t getRequestIdFromTc() const; /** * @brief Extracts the Request ID from the Application Data directly, assuming it is packed diff --git a/src/fsfw/pus/Service11TelecommandScheduling.tpp b/src/fsfw/pus/Service11TelecommandScheduling.tpp index 7f60f7e8..315d8950 100644 --- a/src/fsfw/pus/Service11TelecommandScheduling.tpp +++ b/src/fsfw/pus/Service11TelecommandScheduling.tpp @@ -11,9 +11,9 @@ static constexpr auto DEF_END = SerializeIF::Endianness::BIG; template inline Service11TelecommandScheduling::Service11TelecommandScheduling( - object_id_t objectId, uint16_t apid, uint8_t serviceId, AcceptsTelecommandsIF *tcRecipient, - uint16_t releaseTimeMarginSeconds, bool debugMode) - : PusServiceBase(objectId, apid, serviceId), + PsbParams params, AcceptsTelecommandsIF *tcRecipient, uint16_t releaseTimeMarginSeconds, + bool debugMode) + : PusServiceBase(params), RELEASE_TIME_MARGIN_SECONDS(releaseTimeMarginSeconds), debugMode(debugMode), tcRecipient(tcRecipient) {} @@ -32,11 +32,8 @@ inline ReturnValue_t Service11TelecommandScheduling::handleRequest( #endif } // Get de-serialized Timestamp - const uint8_t *data = currentPacket.getApplicationData(); - size_t size = currentPacket.getApplicationDataSize(); - if (data == nullptr) { - return handleInvalidData("handleRequest"); - } + const uint8_t *data = currentPacket.getUserData(); + size_t size = currentPacket.getUserDataLen(); switch (subservice) { case Subservice::ENABLE_SCHEDULING: { schedulingEnabled = true; @@ -78,11 +75,11 @@ inline ReturnValue_t Service11TelecommandScheduling::performService // NOTE: The iterator is increased in the loop here. Increasing the iterator as for-loop arg // does not work in this case as we are deleting the current element here. for (auto it = telecommandMap.begin(); it != telecommandMap.end();) { - if (it->first <= tNow.tv_sec) { + if (it->first <= static_cast(tNow.tv_sec)) { if (schedulingEnabled) { // release tc TmTcMessage releaseMsg(it->second.storeAddr); - auto sendRet = this->requestQueue->sendMessage(recipientMsgQueueId, &releaseMsg, false); + auto sendRet = psbParams.reqQueue->sendMessage(recipientMsgQueueId, &releaseMsg, false); if (sendRet != returnvalue::OK) { return sendRet; @@ -175,7 +172,7 @@ inline ReturnValue_t Service11TelecommandScheduling::doInsertActivi // store currentPacket and receive the store address store_address_t addr{}; if (tcStore->addData(&addr, data, size) != returnvalue::OK || - addr.raw == storeId::INVALID_STORE_ADDRESS) { + addr.raw == store_address_t::INVALID_RAW) { #if FSFW_CPP_OSTREAM_ENABLED == 1 sif::error << "Service11TelecommandScheduling::doInsertActivity: Adding data to TC Store failed" << std::endl; @@ -190,8 +187,7 @@ inline ReturnValue_t Service11TelecommandScheduling::doInsertActivi TelecommandStruct tc; tc.seconds = timestamp; tc.storeAddr = addr; - tc.requestId = - getRequestIdFromDataTC(data); // TODO: Missing sanity check of the returned request id + tc.requestId = getRequestIdFromTc(); // TODO: Missing sanity check of the returned request id auto it = telecommandMap.insert(std::pair(timestamp, tc)); if (it == telecommandMap.end()) { @@ -455,13 +451,10 @@ inline ReturnValue_t Service11TelecommandScheduling::doFilterTimesh } template -inline uint64_t Service11TelecommandScheduling::getRequestIdFromDataTC( - const uint8_t *data) const { - TcPacketPus mask(data); - - uint32_t sourceId = mask.getSourceId(); - uint16_t apid = mask.getAPID(); - uint16_t sequenceCount = mask.getPacketSequenceCount(); +inline uint64_t Service11TelecommandScheduling::getRequestIdFromTc() const { + uint32_t sourceId = currentPacket.getSourceId(); + uint16_t apid = currentPacket.getApid(); + uint16_t sequenceCount = currentPacket.getSequenceCount(); return buildRequestId(sourceId, apid, sequenceCount); } @@ -571,6 +564,9 @@ inline ReturnValue_t Service11TelecommandScheduling::getMapFilterFr if (result != returnvalue::OK) { return result; } + if(fromTimestamp > toTimestamp) { + return INVALID_TIME_WINDOW; + } itBegin = telecommandMap.begin(); itEnd = telecommandMap.begin(); @@ -586,17 +582,6 @@ inline ReturnValue_t Service11TelecommandScheduling::getMapFilterFr default: return returnvalue::FAILED; } - - // additional security check, this should never be true - if (itBegin > itEnd) { -#if FSFW_CPP_OSTREAM_ENABLED == 1 - sif::error << "11::getMapFilterFromData: itBegin > itEnd\n" << std::endl; -#else - sif::printError("11::getMapFilterFromData: itBegin > itEnd\n"); -#endif - return returnvalue::FAILED; - } - // the map range should now be set according to the sent filter. return returnvalue::OK; } diff --git a/src/fsfw/pus/Service17Test.cpp b/src/fsfw/pus/Service17Test.cpp index acc48819..0a9db32f 100644 --- a/src/fsfw/pus/Service17Test.cpp +++ b/src/fsfw/pus/Service17Test.cpp @@ -1,39 +1,33 @@ #include "fsfw/pus/Service17Test.h" #include "fsfw/FSFW.h" +#include "fsfw/objectmanager/ObjectManager.h" #include "fsfw/objectmanager/SystemObject.h" -#include "fsfw/serviceinterface/ServiceInterface.h" -#include "fsfw/tmtcpacket/pus/tm/TmPacketStored.h" +#include "fsfw/tmtcservices/tmHelpers.h" -Service17Test::Service17Test(object_id_t objectId, uint16_t apid, uint8_t serviceId) - : PusServiceBase(objectId, apid, serviceId), packetSubCounter(0) {} +Service17Test::Service17Test(PsbParams params) + : PusServiceBase(params), + storeHelper(params.apid), + tmHelper(params.serviceId, storeHelper, sendHelper) {} -Service17Test::~Service17Test() {} +Service17Test::~Service17Test() = default; ReturnValue_t Service17Test::handleRequest(uint8_t subservice) { switch (subservice) { case Subservice::CONNECTION_TEST: { -#if FSFW_USE_PUS_C_TELEMETRY == 0 - TmPacketStoredPusA connectionPacket(apid, serviceId, Subservice::CONNECTION_TEST_REPORT, - packetSubCounter++); -#else - TmPacketStoredPusC connectionPacket(apid, serviceId, Subservice::CONNECTION_TEST_REPORT, - packetSubCounter++); -#endif - connectionPacket.sendPacket(requestQueue->getDefaultDestination(), requestQueue->getId()); - return returnvalue::OK; + ReturnValue_t result = tmHelper.prepareTmPacket(Subservice::CONNECTION_TEST_REPORT); + if (result != returnvalue::OK) { + return result; + } + return tmHelper.storeAndSendTmPacket(); } case Subservice::EVENT_TRIGGER_TEST: { -#if FSFW_USE_PUS_C_TELEMETRY == 0 - TmPacketStoredPusA connectionPacket(apid, serviceId, Subservice::CONNECTION_TEST_REPORT, - packetSubCounter++); -#else - TmPacketStoredPusC connectionPacket(apid, serviceId, Subservice::CONNECTION_TEST_REPORT, - packetSubCounter++); -#endif - connectionPacket.sendPacket(requestQueue->getDefaultDestination(), requestQueue->getId()); triggerEvent(TEST, 1234, 5678); - return returnvalue::OK; + ReturnValue_t result = tmHelper.prepareTmPacket(Subservice::EVENT_TRIGGER_TEST); + if (result != returnvalue::OK) { + return result; + } + return tmHelper.storeAndSendTmPacket(); } default: return AcceptsTelecommandsIF::INVALID_SUBSERVICE; @@ -41,3 +35,23 @@ ReturnValue_t Service17Test::handleRequest(uint8_t subservice) { } ReturnValue_t Service17Test::performService() { return returnvalue::OK; } + +ReturnValue_t Service17Test::initialize() { + ReturnValue_t result = PusServiceBase::initialize(); + if (result != returnvalue::OK) { + return result; + } + initializeTmHelpers(sendHelper, storeHelper); + if (storeHelper.getTmStore() == nullptr) { + auto* tmStore = ObjectManager::instance()->get(objects::TM_STORE); + if (tmStore == nullptr) { + return ObjectManagerIF::CHILD_INIT_FAILED; + } + storeHelper.setTmStore(*tmStore); + } + return result; +} + +void Service17Test::setCustomTmStore(StorageManagerIF& tmStore_) { + storeHelper.setTmStore(tmStore_); +} diff --git a/src/fsfw/pus/Service17Test.h b/src/fsfw/pus/Service17Test.h index c2248020..f2ec6e4f 100644 --- a/src/fsfw/pus/Service17Test.h +++ b/src/fsfw/pus/Service17Test.h @@ -3,6 +3,8 @@ #include "fsfw/objectmanager/SystemObject.h" #include "fsfw/tmtcservices/PusServiceBase.h" +#include "fsfw/tmtcservices/TmStoreAndSendHelper.h" +#include "fsfw/tmtcservices/TmStoreHelper.h" /** * @brief Test Service @@ -32,13 +34,19 @@ class Service17Test : public PusServiceBase { EVENT_TRIGGER_TEST = 128, }; - Service17Test(object_id_t objectId, uint16_t apid, uint8_t serviceId); - virtual ~Service17Test(); - virtual ReturnValue_t handleRequest(uint8_t subservice) override; - virtual ReturnValue_t performService() override; + explicit Service17Test(PsbParams params); + + void setCustomTmStore(StorageManagerIF& tmStore); + + ~Service17Test() override; + ReturnValue_t handleRequest(uint8_t subservice) override; + ReturnValue_t performService() override; + ReturnValue_t initialize() override; protected: - uint16_t packetSubCounter = 0; + TmStoreHelper storeHelper; + TmSendHelper sendHelper; + TmStoreAndSendWrapper tmHelper; }; #endif /* FSFW_PUS_SERVICE17TEST_H_ */ diff --git a/src/fsfw/pus/Service1TelecommandVerification.cpp b/src/fsfw/pus/Service1TelecommandVerification.cpp index 2e96a33a..adc00588 100644 --- a/src/fsfw/pus/Service1TelecommandVerification.cpp +++ b/src/fsfw/pus/Service1TelecommandVerification.cpp @@ -3,19 +3,21 @@ #include "fsfw/ipc/QueueFactory.h" #include "fsfw/objectmanager/ObjectManager.h" #include "fsfw/pus/servicepackets/Service1Packets.h" -#include "fsfw/serviceinterface/ServiceInterface.h" -#include "fsfw/tmtcpacket/pus/tm/TmPacketStored.h" #include "fsfw/tmtcservices/AcceptsTelemetryIF.h" #include "fsfw/tmtcservices/PusVerificationReport.h" +#include "fsfw/tmtcservices/tmHelpers.h" Service1TelecommandVerification::Service1TelecommandVerification(object_id_t objectId, uint16_t apid, uint8_t serviceId, object_id_t targetDestination, - uint16_t messageQueueDepth) + uint16_t messageQueueDepth, + TimeStamperIF* timeStamper) : SystemObject(objectId), apid(apid), serviceId(serviceId), - targetDestination(targetDestination) { + targetDestination(targetDestination), + storeHelper(apid), + tmHelper(serviceId, storeHelper, sendHelper) { tmQueue = QueueFactory::instance()->createMessageQueue(messageQueueDepth); } @@ -47,6 +49,19 @@ ReturnValue_t Service1TelecommandVerification::performOperation(uint8_t operatio ReturnValue_t Service1TelecommandVerification::sendVerificationReport( PusVerificationMessage* message) { ReturnValue_t result; + uint8_t reportId = message->getReportId(); + if (reportId == 0 or reportId > 8) { +#if FSFW_CPP_OSTREAM_ENABLED == 1 + sif::error << "Service1TelecommandVerification::sendVerificationReport: Invalid report ID " + << static_cast(reportId) << " detected" << std::endl; +#else + sif::printError( + "Service1TelecommandVerification::sendVerificationReport: Invalid report ID " + "%d detected\n", + reportId); +#endif + return returnvalue::FAILED; + } if (message->getReportId() % 2 == 0) { result = generateFailureReport(message); } else { @@ -67,32 +82,37 @@ ReturnValue_t Service1TelecommandVerification::generateFailureReport( FailureReport report(message->getReportId(), message->getTcPacketId(), message->getTcSequenceControl(), message->getStep(), message->getErrorCode(), message->getParameter1(), message->getParameter2()); -#if FSFW_USE_PUS_C_TELEMETRY == 0 - TmPacketStoredPusA tmPacket(apid, serviceId, message->getReportId(), packetSubCounter++, &report); -#else - TmPacketStoredPusC tmPacket(apid, serviceId, message->getReportId(), packetSubCounter++, &report); -#endif - ReturnValue_t result = tmPacket.sendPacket(tmQueue->getDefaultDestination(), tmQueue->getId()); - return result; + ReturnValue_t result = + storeHelper.preparePacket(serviceId, message->getReportId(), packetSubCounter++); + if (result != returnvalue::OK) { + return result; + } + result = storeHelper.setSourceDataSerializable(report); + if (result != returnvalue::OK) { + return result; + } + return tmHelper.storeAndSendTmPacket(); } ReturnValue_t Service1TelecommandVerification::generateSuccessReport( PusVerificationMessage* message) { SuccessReport report(message->getReportId(), message->getTcPacketId(), message->getTcSequenceControl(), message->getStep()); -#if FSFW_USE_PUS_C_TELEMETRY == 0 - TmPacketStoredPusA tmPacket(apid, serviceId, message->getReportId(), packetSubCounter++, &report); -#else - TmPacketStoredPusC tmPacket(apid, serviceId, message->getReportId(), packetSubCounter++, &report); -#endif - ReturnValue_t result = tmPacket.sendPacket(tmQueue->getDefaultDestination(), tmQueue->getId()); - return result; + ReturnValue_t result = + storeHelper.preparePacket(serviceId, message->getReportId(), packetSubCounter++); + if (result != returnvalue::OK) { + return result; + } + result = storeHelper.setSourceDataSerializable(report); + if (result != returnvalue::OK) { + return result; + } + return tmHelper.storeAndSendTmPacket(); } ReturnValue_t Service1TelecommandVerification::initialize() { // Get target object for TC verification messages - AcceptsTelemetryIF* funnel = - ObjectManager::instance()->get(targetDestination); + auto* funnel = ObjectManager::instance()->get(targetDestination); if (funnel == nullptr) { #if FSFW_CPP_OSTREAM_ENABLED == 1 sif::error << "Service1TelecommandVerification::initialize: Specified" @@ -102,6 +122,33 @@ ReturnValue_t Service1TelecommandVerification::initialize() { #endif return ObjectManagerIF::CHILD_INIT_FAILED; } + if (tmQueue == nullptr) { + return ObjectManagerIF::CHILD_INIT_FAILED; + } tmQueue->setDefaultDestination(funnel->getReportReceptionQueue()); + if (tmStore == nullptr) { + tmStore = ObjectManager::instance()->get(objects::TM_STORE); + if (tmStore == nullptr) { + return ObjectManager::CHILD_INIT_FAILED; + } + storeHelper.setTmStore(*tmStore); + } + if (timeStamper == nullptr) { + timeStamper = ObjectManager::instance()->get(objects::TIME_STAMPER); + if (timeStamper == nullptr) { + return ObjectManagerIF::CHILD_INIT_FAILED; + } + } else { + } + storeHelper.setTimeStamper(*timeStamper); + + sendHelper.setMsgQueue(*tmQueue); + if (errReporter == nullptr) { + errReporter = + ObjectManager::instance()->get(objects::INTERNAL_ERROR_REPORTER); + if (errReporter != nullptr) { + sendHelper.setInternalErrorReporter(*errReporter); + } + } return SystemObject::initialize(); } diff --git a/src/fsfw/pus/Service1TelecommandVerification.h b/src/fsfw/pus/Service1TelecommandVerification.h index d921b48c..fa4aba7c 100644 --- a/src/fsfw/pus/Service1TelecommandVerification.h +++ b/src/fsfw/pus/Service1TelecommandVerification.h @@ -7,6 +7,9 @@ #include "fsfw/tasks/ExecutableObjectIF.h" #include "fsfw/tmtcservices/AcceptsVerifyMessageIF.h" #include "fsfw/tmtcservices/PusVerificationReport.h" +#include "fsfw/tmtcservices/TmSendHelper.h" +#include "fsfw/tmtcservices/TmStoreAndSendHelper.h" +#include "fsfw/tmtcservices/TmStoreHelper.h" /** * @brief Verify TC acceptance, start, progress and execution. @@ -43,14 +46,15 @@ class Service1TelecommandVerification : public AcceptsVerifyMessageIF, static const uint8_t SUBSYSTEM_ID = SUBSYSTEM_ID::PUS_SERVICE_1; Service1TelecommandVerification(object_id_t objectId, uint16_t apid, uint8_t serviceId, - object_id_t targetDestination, uint16_t messageQueueDepth); - virtual ~Service1TelecommandVerification(); + object_id_t targetDestination, uint16_t messageQueueDepth, + TimeStamperIF* timeStamper = nullptr); + ~Service1TelecommandVerification() override; /** * * @return ID of Verification Queue */ - virtual MessageQueueId_t getVerificationQueue() override; + MessageQueueId_t getVerificationQueue() override; /** * Performs the service periodically as specified in init_mission(). @@ -58,7 +62,7 @@ class Service1TelecommandVerification : public AcceptsVerifyMessageIF, * @param operationCode * @return */ - ReturnValue_t performOperation(uint8_t operationCode = 0) override; + ReturnValue_t performOperation(uint8_t operationCode) override; /** * Initializes the destination for TC verification messages and initializes @@ -79,6 +83,12 @@ class Service1TelecommandVerification : public AcceptsVerifyMessageIF, uint16_t packetSubCounter = 0; + TmSendHelper sendHelper; + TmStoreHelper storeHelper; + TmStoreAndSendWrapper tmHelper; + InternalErrorReporterIF* errReporter = nullptr; + TimeStamperIF* timeStamper = nullptr; + StorageManagerIF* tmStore = nullptr; MessageQueueIF* tmQueue = nullptr; enum class Subservice : uint8_t { diff --git a/src/fsfw/pus/Service20ParameterManagement.cpp b/src/fsfw/pus/Service20ParameterManagement.cpp index 382aea00..f58a0d6c 100644 --- a/src/fsfw/pus/Service20ParameterManagement.cpp +++ b/src/fsfw/pus/Service20ParameterManagement.cpp @@ -14,7 +14,7 @@ Service20ParameterManagement::Service20ParameterManagement(object_id_t objectId, : CommandingServiceBase(objectId, apid, serviceId, numberOfParallelCommands, commandTimeoutSeconds) {} -Service20ParameterManagement::~Service20ParameterManagement() {} +Service20ParameterManagement::~Service20ParameterManagement() = default; ReturnValue_t Service20ParameterManagement::isValidSubservice(uint8_t subservice) { switch (static_cast(subservice)) { @@ -64,8 +64,7 @@ ReturnValue_t Service20ParameterManagement::checkAndAcquireTargetID(object_id_t* ReturnValue_t Service20ParameterManagement::checkInterfaceAndAcquireMessageQueue( MessageQueueId_t* messageQueueToSet, object_id_t* objectId) { // check ReceivesParameterMessagesIF property of target - ReceivesParameterMessagesIF* possibleTarget = - ObjectManager::instance()->get(*objectId); + auto* possibleTarget = ObjectManager::instance()->get(*objectId); if (possibleTarget == nullptr) { #if FSFW_CPP_OSTREAM_ENABLED == 1 sif::error << "Service20ParameterManagement::checkInterfaceAndAcquire" @@ -137,7 +136,7 @@ ReturnValue_t Service20ParameterManagement::prepareLoadCommand(CommandMessage* m if (parameterDataLen == 0) { return CommandingServiceBase::INVALID_TC; } - ReturnValue_t result = IPCStore->getFreeElement(&storeAddress, parameterDataLen, &storePointer); + ReturnValue_t result = ipcStore->getFreeElement(&storeAddress, parameterDataLen, &storePointer); if (result != returnvalue::OK) { return result; } @@ -169,7 +168,7 @@ ReturnValue_t Service20ParameterManagement::handleReply(const CommandMessage* re switch (replyId) { case ParameterMessage::REPLY_PARAMETER_DUMP: { - ConstAccessorPair parameterData = IPCStore->getData(ParameterMessage::getStoreId(reply)); + ConstAccessorPair parameterData = ipcStore->getData(ParameterMessage::getStoreId(reply)); if (parameterData.first != returnvalue::OK) { return returnvalue::FAILED; } @@ -177,8 +176,7 @@ ReturnValue_t Service20ParameterManagement::handleReply(const CommandMessage* re ParameterId_t parameterId = ParameterMessage::getParameterId(reply); ParameterDumpReply parameterReply(objectId, parameterId, parameterData.second.data(), parameterData.second.size()); - sendTmPacket(static_cast(Subservice::PARAMETER_DUMP_REPLY), ¶meterReply); - return returnvalue::OK; + return sendTmPacket(static_cast(Subservice::PARAMETER_DUMP_REPLY), parameterReply); } default: return CommandingServiceBase::INVALID_REPLY; diff --git a/src/fsfw/pus/Service2DeviceAccess.cpp b/src/fsfw/pus/Service2DeviceAccess.cpp index a1bf8121..6eea1807 100644 --- a/src/fsfw/pus/Service2DeviceAccess.cpp +++ b/src/fsfw/pus/Service2DeviceAccess.cpp @@ -75,7 +75,7 @@ ReturnValue_t Service2DeviceAccess::prepareRawCommand(CommandMessage* messageToS // store command into the Inter Process Communication Store store_address_t storeAddress; ReturnValue_t result = - IPCStore->addData(&storeAddress, RawCommand.getCommand(), RawCommand.getCommandSize()); + ipcStore->addData(&storeAddress, RawCommand.getCommand(), RawCommand.getCommandSize()); DeviceHandlerMessage::setDeviceHandlerRawCommandMessage(messageToSet, storeAddress); return result; } @@ -135,7 +135,7 @@ void Service2DeviceAccess::sendWiretappingTm(CommandMessage* reply, uint8_t subs store_address_t storeAddress = DeviceHandlerMessage::getStoreAddress(reply); const uint8_t* data = nullptr; size_t size = 0; - ReturnValue_t result = IPCStore->getData(storeAddress, &data, &size); + ReturnValue_t result = ipcStore->getData(storeAddress, &data, &size); if (result != returnvalue::OK) { #if FSFW_CPP_OSTREAM_ENABLED == 1 sif::error << "Service2DeviceAccess::sendWiretappingTm: Data Lost in " @@ -147,10 +147,12 @@ void Service2DeviceAccess::sendWiretappingTm(CommandMessage* reply, uint8_t subs // Init our dummy packet and correct endianness of object ID before // sending it back. - WiretappingPacket TmPacket(DeviceHandlerMessage::getDeviceObjectId(reply), data); - TmPacket.objectId = EndianConverter::convertBigEndian(TmPacket.objectId); - sendTmPacket(subservice, TmPacket.data, size, reinterpret_cast(&TmPacket.objectId), - sizeof(TmPacket.objectId)); + WiretappingPacket tmPacket(DeviceHandlerMessage::getDeviceObjectId(reply), data); + result = sendTmPacket(subservice, tmPacket.objectId, tmPacket.data, size); + if (result != returnvalue::OK) { + // TODO: Warning + return; + } } MessageQueueId_t Service2DeviceAccess::getDeviceQueue() { return commandQueue->getId(); } diff --git a/src/fsfw/pus/Service3Housekeeping.cpp b/src/fsfw/pus/Service3Housekeeping.cpp index 1a1c87ff..5c887572 100644 --- a/src/fsfw/pus/Service3Housekeeping.cpp +++ b/src/fsfw/pus/Service3Housekeeping.cpp @@ -208,17 +208,17 @@ ReturnValue_t Service3Housekeeping::handleReply(const CommandMessage* reply, ReturnValue_t error = returnvalue::FAILED; HousekeepingMessage::getHkRequestFailureReply(reply, &error); failureParameter2 = error; - return CommandingServiceBase::EXECUTION_COMPLETE; + return returnvalue::FAILED; } default: #if FSFW_CPP_OSTREAM_ENABLED == 1 sif::warning << "Service3Housekeeping::handleReply: Invalid reply with " - << "reply command " << command << "!" << std::endl; + << "reply command " << command << std::endl; #else sif::printWarning( "Service3Housekeeping::handleReply: Invalid reply with " - "reply command %hu!\n", + "reply command %hu\n", command); #endif return CommandingServiceBase::INVALID_REPLY; @@ -248,19 +248,28 @@ void Service3Housekeeping::handleUnrequestedReply(CommandMessage* reply) { case (HousekeepingMessage::HK_REQUEST_FAILURE): { break; } + case (CommandMessage::REPLY_REJECTED): { +#if FSFW_CPP_OSTREAM_ENABLED == 1 + sif::warning << "Service3Housekeeping::handleUnrequestedReply: Unexpected reply " + "rejected with error code" + << reply->getParameter() << std::endl; +#else +#endif + break; + } default: { #if FSFW_CPP_OSTREAM_ENABLED == 1 sif::warning << "Service3Housekeeping::handleUnrequestedReply: Invalid reply with reply " "command " - << command << "!" << std::endl; + << command << "" << std::endl; #else sif::printWarning( "Service3Housekeeping::handleUnrequestedReply: Invalid reply with " - "reply command %hu!\n", + "reply command %hu\n", command); #endif - return; + break; } } @@ -275,6 +284,7 @@ void Service3Housekeeping::handleUnrequestedReply(CommandMessage* reply) { "Could not generate reply!\n"); #endif } + CommandingServiceBase::handleUnrequestedReply(reply); } MessageQueueId_t Service3Housekeeping::getHkQueue() const { return commandQueue->getId(); } @@ -284,14 +294,13 @@ ReturnValue_t Service3Housekeeping::generateHkReply(const CommandMessage* hkMess store_address_t storeId; sid_t sid = HousekeepingMessage::getHkDataReply(hkMessage, &storeId); - auto resultPair = IPCStore->getData(storeId); + auto resultPair = ipcStore->getData(storeId); if (resultPair.first != returnvalue::OK) { return resultPair.first; } HkPacket hkPacket(sid, resultPair.second.data(), resultPair.second.size()); - return sendTmPacket(static_cast(subserviceId), hkPacket.hkData, hkPacket.hkSize, nullptr, - 0); + return sendTmPacket(static_cast(subserviceId), hkPacket.hkData, hkPacket.hkSize); } sid_t Service3Housekeeping::buildSid(object_id_t objectId, const uint8_t** tcData, diff --git a/src/fsfw/pus/Service5EventReporting.cpp b/src/fsfw/pus/Service5EventReporting.cpp index d267c803..d927bc3e 100644 --- a/src/fsfw/pus/Service5EventReporting.cpp +++ b/src/fsfw/pus/Service5EventReporting.cpp @@ -5,14 +5,17 @@ #include "fsfw/objectmanager/ObjectManager.h" #include "fsfw/pus/servicepackets/Service5Packets.h" #include "fsfw/serviceinterface/ServiceInterface.h" -#include "fsfw/tmtcpacket/pus/tm/TmPacketStored.h" +#include "fsfw/tmtcservices/tmHelpers.h" -Service5EventReporting::Service5EventReporting(object_id_t objectId, uint16_t apid, - uint8_t serviceId, size_t maxNumberReportsPerCycle, +Service5EventReporting::Service5EventReporting(PsbParams params, size_t maxNumberReportsPerCycle, uint32_t messageQueueDepth) - : PusServiceBase(objectId, apid, serviceId), + : PusServiceBase(params), + storeHelper(params.apid), + tmHelper(params.serviceId, storeHelper, sendHelper), maxNumberReportsPerCycle(maxNumberReportsPerCycle) { - eventQueue = QueueFactory::instance()->createMessageQueue(messageQueueDepth); + auto mqArgs = MqArgs(getObjectId(), static_cast(this)); + eventQueue = QueueFactory::instance()->createMessageQueue( + messageQueueDepth, MessageQueueMessage::MAX_MESSAGE_SIZE, &mqArgs); } Service5EventReporting::~Service5EventReporting() { @@ -36,24 +39,15 @@ ReturnValue_t Service5EventReporting::performService() { } } } -#if FSFW_CPP_OSTREAM_ENABLED == 1 - sif::warning << "Service5EventReporting::generateEventReport: Too many events" << std::endl; -#endif return returnvalue::OK; } ReturnValue_t Service5EventReporting::generateEventReport(EventMessage message) { EventReport report(message.getEventId(), message.getReporter(), message.getParameter1(), message.getParameter2()); -#if FSFW_USE_PUS_C_TELEMETRY == 0 - TmPacketStoredPusA tmPacket(PusServiceBase::apid, PusServiceBase::serviceId, - message.getSeverity(), packetSubCounter++, &report); -#else - TmPacketStoredPusC tmPacket(PusServiceBase::apid, PusServiceBase::serviceId, - message.getSeverity(), packetSubCounter++, &report); -#endif - ReturnValue_t result = - tmPacket.sendPacket(requestQueue->getDefaultDestination(), requestQueue->getId()); + storeHelper.preparePacket(psbParams.serviceId, message.getSeverity(), tmHelper.sendCounter); + storeHelper.setSourceDataSerializable(report); + ReturnValue_t result = tmHelper.storeAndSendTmPacket(); if (result != returnvalue::OK) { #if FSFW_CPP_OSTREAM_ENABLED == 1 sif::warning << "Service5EventReporting::generateEventReport: " @@ -86,14 +80,19 @@ ReturnValue_t Service5EventReporting::handleRequest(uint8_t subservice) { // In addition to the default PUSServiceBase initialization, this service needs // to be registered to the event manager to listen for events. ReturnValue_t Service5EventReporting::initialize() { + ReturnValue_t result = PusServiceBase::initialize(); + if (result != returnvalue::OK) { + return result; + } auto* manager = ObjectManager::instance()->get(objects::EVENT_MANAGER); if (manager == nullptr) { return returnvalue::FAILED; } // register Service 5 as listener for events - ReturnValue_t result = manager->registerListener(eventQueue->getId(), true); + result = manager->registerListener(eventQueue->getId(), true); if (result != returnvalue::OK) { return result; } - return PusServiceBase::initialize(); + initializeTmHelpers(sendHelper, storeHelper); + return result; } diff --git a/src/fsfw/pus/Service5EventReporting.h b/src/fsfw/pus/Service5EventReporting.h index 74264130..1f4e5a3a 100644 --- a/src/fsfw/pus/Service5EventReporting.h +++ b/src/fsfw/pus/Service5EventReporting.h @@ -3,6 +3,7 @@ #include "fsfw/events/EventMessage.h" #include "fsfw/tmtcservices/PusServiceBase.h" +#include "fsfw/tmtcservices/TmStoreAndSendHelper.h" /** * @brief Report on-board events like information or errors @@ -40,9 +41,9 @@ */ class Service5EventReporting : public PusServiceBase { public: - Service5EventReporting(object_id_t objectId, uint16_t apid, uint8_t serviceId, - size_t maxNumberReportsPerCycle = 10, uint32_t messageQueueDepth = 10); - virtual ~Service5EventReporting(); + Service5EventReporting(PsbParams params, size_t maxNumberReportsPerCycle = 10, + uint32_t messageQueueDepth = 10); + ~Service5EventReporting() override; /*** * Check for events and generate event reports if required. @@ -74,9 +75,11 @@ class Service5EventReporting : public PusServiceBase { }; private: - uint16_t packetSubCounter = 0; MessageQueueIF* eventQueue = nullptr; bool enableEventReport = true; + TmSendHelper sendHelper; + TmStoreHelper storeHelper; + TmStoreAndSendWrapper tmHelper; const uint8_t maxNumberReportsPerCycle; ReturnValue_t generateEventReport(EventMessage message); diff --git a/src/fsfw/pus/Service8FunctionManagement.cpp b/src/fsfw/pus/Service8FunctionManagement.cpp index 4f552ec8..b9ef6c4d 100644 --- a/src/fsfw/pus/Service8FunctionManagement.cpp +++ b/src/fsfw/pus/Service8FunctionManagement.cpp @@ -78,7 +78,7 @@ ReturnValue_t Service8FunctionManagement::prepareDirectCommand(CommandMessage* m // store additional parameters into the IPC Store store_address_t parameterAddress; ReturnValue_t result = - IPCStore->addData(¶meterAddress, command.getParameters(), command.getParametersSize()); + ipcStore->addData(¶meterAddress, command.getParameters(), command.getParametersSize()); // setCommand expects a Command Message, an Action ID and a store adress // pointing to additional parameters @@ -130,7 +130,7 @@ ReturnValue_t Service8FunctionManagement::handleDataReply(const CommandMessage* store_address_t storeId = ActionMessage::getStoreId(reply); size_t size = 0; const uint8_t* buffer = nullptr; - ReturnValue_t result = IPCStore->getData(storeId, &buffer, &size); + ReturnValue_t result = ipcStore->getData(storeId, &buffer, &size); if (result != returnvalue::OK) { #if FSFW_CPP_OSTREAM_ENABLED == 1 sif::error << "Service 8: Could not retrieve data for data reply" << std::endl; @@ -138,9 +138,9 @@ ReturnValue_t Service8FunctionManagement::handleDataReply(const CommandMessage* return result; } DataReply dataReply(objectId, actionId, buffer, size); - result = sendTmPacket(static_cast(Subservice::REPLY_DIRECT_COMMANDING_DATA), &dataReply); + result = sendTmPacket(static_cast(Subservice::REPLY_DIRECT_COMMANDING_DATA), dataReply); - auto deletionResult = IPCStore->deleteData(storeId); + auto deletionResult = ipcStore->deleteData(storeId); if (deletionResult != returnvalue::OK) { #if FSFW_CPP_OSTREAM_ENABLED == 1 sif::warning << "Service8FunctionManagement::handleReply: Deletion" diff --git a/src/fsfw/pus/Service8FunctionManagement.h b/src/fsfw/pus/Service8FunctionManagement.h index 649b3257..38aaf4f4 100644 --- a/src/fsfw/pus/Service8FunctionManagement.h +++ b/src/fsfw/pus/Service8FunctionManagement.h @@ -32,7 +32,7 @@ class Service8FunctionManagement : public CommandingServiceBase { public: Service8FunctionManagement(object_id_t objectId, uint16_t apid, uint8_t serviceId, uint8_t numParallelCommands = 4, uint16_t commandTimeoutSeconds = 60); - virtual ~Service8FunctionManagement(); + ~Service8FunctionManagement() override; protected: /* CSB abstract functions implementation . See CSB documentation. */ diff --git a/src/fsfw/pus/Service9TimeManagement.cpp b/src/fsfw/pus/Service9TimeManagement.cpp index ea852f28..698290c9 100644 --- a/src/fsfw/pus/Service9TimeManagement.cpp +++ b/src/fsfw/pus/Service9TimeManagement.cpp @@ -5,11 +5,9 @@ #include "fsfw/serviceinterface/ServiceInterface.h" #include "fsfw/timemanager/CCSDSTime.h" -Service9TimeManagement::Service9TimeManagement(object_id_t objectId, uint16_t apid, - uint8_t serviceId) - : PusServiceBase(objectId, apid, serviceId) {} +Service9TimeManagement::Service9TimeManagement(PsbParams params) : PusServiceBase(params) {} -Service9TimeManagement::~Service9TimeManagement() {} +Service9TimeManagement::~Service9TimeManagement() = default; ReturnValue_t Service9TimeManagement::performService() { return returnvalue::OK; } @@ -25,7 +23,7 @@ ReturnValue_t Service9TimeManagement::handleRequest(uint8_t subservice) { ReturnValue_t Service9TimeManagement::setTime() { Clock::TimeOfDay_t timeToSet; - TimePacket timePacket(currentPacket.getApplicationData(), currentPacket.getApplicationDataSize()); + TimePacket timePacket(currentPacket.getUserData(), currentPacket.getUserDataLen()); ReturnValue_t result = CCSDSTime::convertFromCcsds(&timeToSet, timePacket.getTime(), timePacket.getTimeSize()); if (result != returnvalue::OK) { diff --git a/src/fsfw/pus/Service9TimeManagement.h b/src/fsfw/pus/Service9TimeManagement.h index 9369e207..97284d32 100644 --- a/src/fsfw/pus/Service9TimeManagement.h +++ b/src/fsfw/pus/Service9TimeManagement.h @@ -6,26 +6,26 @@ class Service9TimeManagement : public PusServiceBase { public: static constexpr uint8_t SUBSYSTEM_ID = SUBSYSTEM_ID::PUS_SERVICE_9; - static constexpr Event CLOCK_SET = - MAKE_EVENT(0, severity::INFO); //!< Clock has been set. P1: New Uptime. P2: Old Uptime - static constexpr Event CLOCK_SET_FAILURE = - MAKE_EVENT(1, severity::LOW); //!< Clock could not be set. P1: Returncode. + //!< Clock has been set. P1: New Uptime. P2: Old Uptime + static constexpr Event CLOCK_SET = MAKE_EVENT(0, severity::INFO); + //!< Clock could not be set. P1: Returncode. + static constexpr Event CLOCK_SET_FAILURE = MAKE_EVENT(1, severity::LOW); static constexpr uint8_t CLASS_ID = CLASS_ID::PUS_SERVICE_9; /** * @brief This service provides the capability to set the on-board time. */ - Service9TimeManagement(object_id_t objectId, uint16_t apid, uint8_t serviceId); + explicit Service9TimeManagement(PsbParams params); - virtual ~Service9TimeManagement(); + ~Service9TimeManagement() override; - virtual ReturnValue_t performService() override; + ReturnValue_t performService() override; /** * @brief Sets the onboard-time by retrieving the time to set from TC[9,128]. */ - virtual ReturnValue_t handleRequest(uint8_t subservice) override; + ReturnValue_t handleRequest(uint8_t subservice) override; virtual ReturnValue_t setTime(); diff --git a/src/fsfw/pus/servicepackets/Service1Packets.h b/src/fsfw/pus/servicepackets/Service1Packets.h index 1878f722..70bf167e 100644 --- a/src/fsfw/pus/servicepackets/Service1Packets.h +++ b/src/fsfw/pus/servicepackets/Service1Packets.h @@ -50,7 +50,7 @@ class FailureReport : public SerializeIF { //!< [EXPORT] : [SUBSERVICE] 2, 4, 6 if (result != returnvalue::OK) { return result; } - if (failureSubtype == tc_verification::PROGRESS_FAILURE) { + if (failureSubtype == tcverif::PROGRESS_FAILURE) { result = SerializeAdapter::serialize(&stepNumber, buffer, size, maxSize, streamEndianness); if (result != returnvalue::OK) { return result; @@ -73,7 +73,7 @@ class FailureReport : public SerializeIF { //!< [EXPORT] : [SUBSERVICE] 2, 4, 6 size_t size = 0; size += SerializeAdapter::getSerializedSize(&packetId); size += sizeof(packetSequenceControl); - if (failureSubtype == tc_verification::PROGRESS_FAILURE) { + if (failureSubtype == tcverif::PROGRESS_FAILURE) { size += SerializeAdapter::getSerializedSize(&stepNumber); } size += SerializeAdapter::getSerializedSize(&errorCode); @@ -130,7 +130,7 @@ class SuccessReport : public SerializeIF { //!< [EXPORT] : [SUBSERVICE] 1, 3, 5 if (result != returnvalue::OK) { return result; } - if (subtype == tc_verification::PROGRESS_SUCCESS) { + if (subtype == tcverif::PROGRESS_SUCCESS) { result = SerializeAdapter::serialize(&stepNumber, buffer, size, maxSize, streamEndianness); if (result != returnvalue::OK) { return result; @@ -143,7 +143,7 @@ class SuccessReport : public SerializeIF { //!< [EXPORT] : [SUBSERVICE] 1, 3, 5 size_t size = 0; size += SerializeAdapter::getSerializedSize(&packetId); size += sizeof(packetSequenceControl); - if (subtype == tc_verification::PROGRESS_SUCCESS) { + if (subtype == tcverif::PROGRESS_SUCCESS) { size += SerializeAdapter::getSerializedSize(&stepNumber); } return size; diff --git a/src/fsfw/pus/servicepackets/Service9Packets.h b/src/fsfw/pus/servicepackets/Service9Packets.h index 076536e8..082a65fa 100644 --- a/src/fsfw/pus/servicepackets/Service9Packets.h +++ b/src/fsfw/pus/servicepackets/Service9Packets.h @@ -1,7 +1,7 @@ #ifndef FSFW_PUS_SERVICEPACKETS_SERVICE9PACKETS_H_ #define FSFW_PUS_SERVICEPACKETS_SERVICE9PACKETS_H_ -#include "../../serialize/SerialLinkedListAdapter.h" +#include "fsfw/serialize/SerialLinkedListAdapter.h" /** * @brief Subservice 128 @@ -11,16 +11,16 @@ */ class TimePacket : SerialLinkedListAdapter { //!< [EXPORT] : [SUBSERVICE] 128 public: + TimePacket(const TimePacket& command) = delete; TimePacket(const uint8_t* timeBuffer_, uint32_t timeSize_) { timeBuffer = timeBuffer_; timeSize = timeSize_; } const uint8_t* getTime() { return timeBuffer; } - uint32_t getTimeSize() const { return timeSize; } + [[nodiscard]] uint32_t getTimeSize() const { return timeSize; } private: - TimePacket(const TimePacket& command); const uint8_t* timeBuffer; uint32_t timeSize; //!< [EXPORT] : [IGNORE] }; diff --git a/src/fsfw/returnvalues/FwClassIds.h b/src/fsfw/returnvalues/FwClassIds.h index f5f57276..1dfe1cc8 100644 --- a/src/fsfw/returnvalues/FwClassIds.h +++ b/src/fsfw/returnvalues/FwClassIds.h @@ -34,9 +34,10 @@ enum : uint8_t { FIFO_CLASS, // FF MESSAGE_PROXY, // MQP TRIPLE_REDUNDACY_CHECK, // TRC - TC_PACKET_CHECK, // TCC + PACKET_CHECK, // TCC PACKET_DISTRIBUTION, // TCD - ACCEPTS_TELECOMMANDS_IF, // PUS + ACCEPTS_TELECOMMANDS_IF, // ATC + PUS_IF, // PUS DEVICE_SERVICE_BASE, // DSB COMMAND_SERVICE_BASE, // CSB TM_STORE_BACKEND_IF, // TMB diff --git a/src/fsfw/returnvalues/HasReturnvaluesIF.h b/src/fsfw/returnvalues/HasReturnvaluesIF.h new file mode 100644 index 00000000..325b07e9 --- /dev/null +++ b/src/fsfw/returnvalues/HasReturnvaluesIF.h @@ -0,0 +1,8 @@ +#ifndef FSFW_RETURNVALUES_HASRETURNVALUES_IF_H_ +#define FSFW_RETURNVALUES_HASRETURNVALUES_IF_H_ + +#warning "This header is deprecated, please include returnvalue.h" + +#include "returnvalue.h" + +#endif /* FSFW_RETURNVALUES_HASRETURNVALUES_IF_H_ */ diff --git a/src/fsfw/retval.h b/src/fsfw/retval.h new file mode 100644 index 00000000..1ef15ab3 --- /dev/null +++ b/src/fsfw/retval.h @@ -0,0 +1,6 @@ +#ifndef FSFW_RETVAL_H +#define FSFW_RETVAL_H + +#include "fsfw/returnvalues/returnvalue.h" + +#endif // FSFW_RETVAL_H diff --git a/src/fsfw/serialize.h b/src/fsfw/serialize.h index 514e1e0c..b74c3c32 100644 --- a/src/fsfw/serialize.h +++ b/src/fsfw/serialize.h @@ -1,10 +1,10 @@ -#ifndef FSFW_INC_FSFW_SERIALIZE_H_ -#define FSFW_INC_FSFW_SERIALIZE_H_ +#ifndef FSFW_SERIALIZE_H_ +#define FSFW_SERIALIZE_H_ -#include "fsfw/serialize/EndianConverter.h" -#include "fsfw/serialize/SerialArrayListAdapter.h" -#include "fsfw/serialize/SerialBufferAdapter.h" -#include "fsfw/serialize/SerialLinkedListAdapter.h" -#include "fsfw/serialize/SerializeElement.h" +#include "serialize/EndianConverter.h" +#include "serialize/SerialArrayListAdapter.h" +#include "serialize/SerialBufferAdapter.h" +#include "serialize/SerialLinkedListAdapter.h" +#include "serialize/SerializeElement.h" -#endif /* FSFW_INC_FSFW_SERIALIZE_H_ */ +#endif /* FSFW_SERIALIZE_H_ */ diff --git a/src/fsfw/serialize/SerializeAdapter.h b/src/fsfw/serialize/SerializeAdapter.h index bca0e637..3c478271 100644 --- a/src/fsfw/serialize/SerializeAdapter.h +++ b/src/fsfw/serialize/SerializeAdapter.h @@ -74,7 +74,7 @@ class SerializeAdapter { return returnvalue::FAILED; } InternalSerializeAdapter::value> adapter; - uint8_t **tempPtr = const_cast(&buffer); + auto **tempPtr = const_cast(&buffer); size_t tmpSize = 0; ReturnValue_t result = adapter.serialize(object, tempPtr, &tmpSize, maxSize, streamEndianness); if (serSize != nullptr) { @@ -232,7 +232,7 @@ class SerializeAdapter { } } - uint32_t getSerializedSize(const T *object) { return sizeof(T); } + uint32_t getSerializedSize(const T *) { return sizeof(T); } }; /** diff --git a/src/fsfw/storagemanager/LocalPool.cpp b/src/fsfw/storagemanager/LocalPool.cpp index b0376d2c..d907a9b3 100644 --- a/src/fsfw/storagemanager/LocalPool.cpp +++ b/src/fsfw/storagemanager/LocalPool.cpp @@ -194,8 +194,6 @@ void LocalPool::clearStore() { for (auto& size : sizeList) { size = STORAGE_FREE; } - // std::memset(sizeList[index], 0xff, - // numberOfElements[index] * sizeof(size_type)); } } @@ -338,3 +336,16 @@ void LocalPool::clearSubPool(max_subpools_t subpoolIndex) { } LocalPool::max_subpools_t LocalPool::getNumberOfSubPools() const { return NUMBER_OF_SUBPOOLS; } + +bool LocalPool::hasDataAtId(store_address_t storeId) const { + if (storeId.poolIndex >= NUMBER_OF_SUBPOOLS) { + return false; + } + if ((storeId.packetIndex >= numberOfElements[storeId.poolIndex])) { + return false; + } + if (sizeLists[storeId.poolIndex][storeId.packetIndex] != STORAGE_FREE) { + return true; + } + return false; +} diff --git a/src/fsfw/storagemanager/LocalPool.h b/src/fsfw/storagemanager/LocalPool.h index ebdcba9f..a82da971 100644 --- a/src/fsfw/storagemanager/LocalPool.h +++ b/src/fsfw/storagemanager/LocalPool.h @@ -81,7 +81,7 @@ class LocalPool : public SystemObject, public StorageManagerIF { /** * @brief In the LocalPool's destructor all allocated memory is freed. */ - virtual ~LocalPool(void); + ~LocalPool() override; /** * Documentation: See StorageManagerIF.h @@ -132,6 +132,7 @@ class LocalPool : public SystemObject, public StorageManagerIF { * @return */ max_subpools_t getNumberOfSubPools() const override; + bool hasDataAtId(store_address_t storeId) const override; protected: /** diff --git a/src/fsfw/storagemanager/PoolManager.cpp b/src/fsfw/storagemanager/PoolManager.cpp index 92de1dfe..41e140b2 100644 --- a/src/fsfw/storagemanager/PoolManager.cpp +++ b/src/fsfw/storagemanager/PoolManager.cpp @@ -7,7 +7,7 @@ PoolManager::PoolManager(object_id_t setObjectId, const LocalPoolConfig& localPo mutex = MutexFactory::instance()->createMutex(); } -PoolManager::~PoolManager(void) { MutexFactory::instance()->deleteMutex(mutex); } +PoolManager::~PoolManager() { MutexFactory::instance()->deleteMutex(mutex); } ReturnValue_t PoolManager::reserveSpace(const size_t size, store_address_t* address, bool ignoreFault) { @@ -17,7 +17,7 @@ ReturnValue_t PoolManager::reserveSpace(const size_t size, store_address_t* addr } ReturnValue_t PoolManager::deleteData(store_address_t storeId) { -#if FSFW_VERBOSE_LEVEL >= 2 +#if FSFW_VERBOSE_LEVEL >= 2 && FSFW_OBJ_EVENT_TRANSLATION == 1 #if FSFW_CPP_OSTREAM_ENABLED == 1 sif::debug << "PoolManager( " << translateObject(getObjectId()) << " )::deleteData from store " << storeId.poolIndex << ". id is " << storeId.packetIndex << std::endl; diff --git a/src/fsfw/storagemanager/StorageManagerIF.h b/src/fsfw/storagemanager/StorageManagerIF.h index 4041c84b..228d380b 100644 --- a/src/fsfw/storagemanager/StorageManagerIF.h +++ b/src/fsfw/storagemanager/StorageManagerIF.h @@ -55,7 +55,7 @@ class StorageManagerIF { /** * @brief This is the empty virtual destructor as required for C++ interfaces. */ - virtual ~StorageManagerIF(){}; + ~StorageManagerIF() = default; /** * @brief With addData, a free storage position is allocated and data * stored there. @@ -63,9 +63,8 @@ class StorageManagerIF { * @param storageId A pointer to the storageId to retrieve. * @param data The data to be stored in the StorageManager. * @param size The amount of data to be stored. - * @return Returns @li returnvalue::OK if data was added. - * @li returnvalue::FAILED if data could not be added. - * storageId is unchanged then. + * @return Returns @returnvalue::OK if data was added. + * @returnvalue::FAILED if data could not be added, storageId is unchanged then. */ virtual ReturnValue_t addData(store_address_t* storageId, const uint8_t* data, size_t size, bool ignoreFault = false) = 0; @@ -116,8 +115,8 @@ class StorageManagerIF { * @param packet_ptr The passed pointer address is set to the the memory * position * @param size The exact size of the stored data is returned here. - * @return @li returnvalue::OK on success. - * @li returnvalue::FAILED if fetching data did not work + * @return @returnvalue::OK on success. + * @returnvalue::FAILED if fetching data did not work * (e.g. an illegal packet_id was passed). */ virtual ReturnValue_t getData(store_address_t packet_id, const uint8_t** packet_ptr, @@ -157,11 +156,12 @@ class StorageManagerIF { * @param size The size of the space to be reserved. * @param p_data A pointer to the element data is returned here. * @return Returns @li returnvalue::OK if data was added. - * @li returnvalue::FAILED if data could not be added. - * storageId is unchanged then. + * @returnvalue::FAILED if data could not be added, storageId is unchanged then. */ - virtual ReturnValue_t getFreeElement(store_address_t* storageId, const size_t size, - uint8_t** p_data, bool ignoreFault = false) = 0; + virtual ReturnValue_t getFreeElement(store_address_t* storageId, size_t size, uint8_t** p_data, + bool ignoreFault = false) = 0; + + [[nodiscard]] virtual bool hasDataAtId(store_address_t storeId) const = 0; /** * Clears the whole store. @@ -192,7 +192,7 @@ class StorageManagerIF { * Get number of pools. * @return */ - virtual max_subpools_t getNumberOfSubPools() const = 0; + [[nodiscard]] virtual max_subpools_t getNumberOfSubPools() const = 0; }; #endif /* FSFW_STORAGEMANAGER_STORAGEMANAGERIF_H_ */ diff --git a/src/fsfw/storagemanager/storeAddress.h b/src/fsfw/storagemanager/storeAddress.h index 41f70573..a656cfe1 100644 --- a/src/fsfw/storagemanager/storeAddress.h +++ b/src/fsfw/storagemanager/storeAddress.h @@ -3,26 +3,26 @@ #include -namespace storeId { -static constexpr uint32_t INVALID_STORE_ADDRESS = 0xffffffff; -} - /** * This union defines the type that identifies where a data packet is * stored in the store. It comprises of a raw part to read it as raw value and * a structured part to use it in pool-like stores. */ union store_address_t { + public: + static constexpr uint32_t INVALID_RAW = 0xffffffff; /** * Default Constructor, initializing to INVALID_ADDRESS */ - store_address_t() : raw(storeId::INVALID_STORE_ADDRESS) {} + store_address_t() : raw(INVALID_RAW) {} /** * Constructor to create an address object using the raw address * * @param rawAddress */ - store_address_t(uint32_t rawAddress) : raw(rawAddress) {} + explicit store_address_t(uint32_t rawAddress) : raw(rawAddress) {} + + static store_address_t invalid() { return {}; }; /** * Constructor to create an address object using pool @@ -52,6 +52,12 @@ union store_address_t { uint32_t raw; bool operator==(const store_address_t& other) const { return raw == other.raw; } + bool operator!=(const store_address_t& other) const { return raw != other.raw; } + + store_address_t& operator=(const uint32_t rawAddr) { + raw = rawAddr; + return *this; + } }; #endif /* FSFW_STORAGEMANAGER_STOREADDRESS_H_ */ diff --git a/src/fsfw/subsystem/Subsystem.h b/src/fsfw/subsystem/Subsystem.h index 855c8f7a..f4e73117 100644 --- a/src/fsfw/subsystem/Subsystem.h +++ b/src/fsfw/subsystem/Subsystem.h @@ -33,8 +33,12 @@ struct SequenceEntry : public TableSequenceBase { }; /** - * @brief TODO: documentation missing + * @brief This class extends the SubsystemBase to perform the management of mode tables + * and mode sequences * @details + * This class is able to use mode tables and sequences to command all its children into the + * right mode. Fallback sequences can be used to handle failed transitions or have a fallback + * in case a component can't keep its current mode. */ class Subsystem : public SubsystemBase, public HasModeSequenceIF { public: diff --git a/src/fsfw/subsystem/SubsystemBase.cpp b/src/fsfw/subsystem/SubsystemBase.cpp index 86ee251a..2ae2cb77 100644 --- a/src/fsfw/subsystem/SubsystemBase.cpp +++ b/src/fsfw/subsystem/SubsystemBase.cpp @@ -8,11 +8,13 @@ SubsystemBase::SubsystemBase(object_id_t setObjectId, object_id_t parent, Mode_t uint16_t commandQueueDepth) : SystemObject(setObjectId), mode(initialMode), - commandQueue(QueueFactory::instance()->createMessageQueue(commandQueueDepth, - CommandMessage::MAX_MESSAGE_SIZE)), healthHelper(this, setObjectId), modeHelper(this), - parentId(parent) {} + parentId(parent) { + auto mqArgs = MqArgs(setObjectId, static_cast(this)); + commandQueue = QueueFactory::instance()->createMessageQueue( + commandQueueDepth, CommandMessage::MAX_MESSAGE_SIZE, &mqArgs); +} SubsystemBase::~SubsystemBase() { QueueFactory::instance()->deleteMessageQueue(commandQueue); } @@ -31,8 +33,9 @@ ReturnValue_t SubsystemBase::registerChild(object_id_t objectId) { info.mode = MODE_OFF; } } else { + // intentional to force an initial command during system startup info.commandQueue = child->getCommandQueue(); - info.mode = -1; // intentional to force an initial command during system startup + info.mode = HasModesIF::MODE_UNDEFINED; } info.submode = SUBMODE_NONE; diff --git a/src/fsfw/subsystem/SubsystemBase.h b/src/fsfw/subsystem/SubsystemBase.h index 6db9efa5..69bdfd37 100644 --- a/src/fsfw/subsystem/SubsystemBase.h +++ b/src/fsfw/subsystem/SubsystemBase.h @@ -15,7 +15,14 @@ /** * @defgroup subsystems Subsystem Objects - * Contains all Subsystem and Assemblies + * All Subsystem and Assemblies can derive from this class. It contains helper classes to + * perform mode and health handling, which allows OBSW developers to build a mode tree for + * the whole satellite. + * + * Aside from setting up a mode tree and being able to executing mode tables, this class does not + * provide an implementation on what to do with the features. To build a mode tree, helper classes + * like the #AssemblyBase or the #Subsystem class extend and use the functionality of the base + * class. */ class SubsystemBase : public SystemObject, public HasModesIF, @@ -95,6 +102,7 @@ class SubsystemBase : public SystemObject, Submode_t targetSubmode); /** + * This function takes care of sending all according mode commands specified inside a mode table. * We need to know the target Submode, as children are able to inherit the submode * Still, we have a default for all child implementations which do not use submode inheritance */ diff --git a/src/fsfw/tcdistribution/CCSDSDistributor.cpp b/src/fsfw/tcdistribution/CCSDSDistributor.cpp index 6202ca78..db408e6d 100644 --- a/src/fsfw/tcdistribution/CCSDSDistributor.cpp +++ b/src/fsfw/tcdistribution/CCSDSDistributor.cpp @@ -2,12 +2,13 @@ #include "fsfw/objectmanager/ObjectManager.h" #include "fsfw/serviceinterface/ServiceInterface.h" -#include "fsfw/tmtcpacket/SpacePacketBase.h" +#include "fsfw/tmtcpacket/ccsds/SpacePacketReader.h" #define CCSDS_DISTRIBUTOR_DEBUGGING 0 -CCSDSDistributor::CCSDSDistributor(uint16_t setDefaultApid, object_id_t setObjectId) - : TcDistributor(setObjectId), defaultApid(setDefaultApid) {} +CCSDSDistributor::CCSDSDistributor(uint16_t setDefaultApid, object_id_t setObjectId, + CcsdsPacketCheckIF* packetChecker) + : TcDistributor(setObjectId), defaultApid(setDefaultApid), packetChecker(packetChecker) {} CCSDSDistributor::~CCSDSDistributor() = default; @@ -25,7 +26,7 @@ TcDistributor::TcMqMapIter CCSDSDistributor::selectDestination() { #endif const uint8_t* packet = nullptr; size_t size = 0; - ReturnValue_t result = this->tcStore->getData(currentMessage.getStorageId(), &packet, &size); + ReturnValue_t result = tcStore->getData(currentMessage.getStorageId(), &packet, &size); if (result != returnvalue::OK) { #if FSFW_VERBOSE_LEVEL >= 1 #if FSFW_CPP_OSTREAM_ENABLED == 1 @@ -40,19 +41,21 @@ TcDistributor::TcMqMapIter CCSDSDistributor::selectDestination() { #endif return queueMap.end(); } - SpacePacketBase currentPacket(packet); - + SpacePacketReader currentPacket(packet, size); + result = packetChecker->checkPacket(currentPacket, size); + if (result != returnvalue::OK) { + } #if FSFW_CPP_OSTREAM_ENABLED == 1 && CCSDS_DISTRIBUTOR_DEBUGGING == 1 - sif::info << "CCSDSDistributor::selectDestination has packet with APID " << std::hex - << currentPacket.getAPID() << std::dec << std::endl; + sif::info << "CCSDSDistributor::selectDestination has packet with APID 0x" << std::hex + << currentPacket.getApid() << std::dec << std::endl; #endif - auto position = this->queueMap.find(currentPacket.getAPID()); + auto position = this->queueMap.find(currentPacket.getApid()); if (position != this->queueMap.end()) { return position; } else { // The APID was not found. Forward packet to main SW-APID anyway to // create acceptance failure report. - return this->queueMap.find(this->defaultApid); + return queueMap.find(this->defaultApid); } } @@ -80,6 +83,9 @@ ReturnValue_t CCSDSDistributor::registerApplication(uint16_t apid, MessageQueueI uint16_t CCSDSDistributor::getIdentifier() { return 0; } ReturnValue_t CCSDSDistributor::initialize() { + if (packetChecker == nullptr) { + packetChecker = new CcsdsPacketChecker(ccsds::PacketType::TC); + } ReturnValue_t status = this->TcDistributor::initialize(); this->tcStore = ObjectManager::instance()->get(objects::TC_STORE); if (this->tcStore == nullptr) { diff --git a/src/fsfw/tcdistribution/CCSDSDistributor.h b/src/fsfw/tcdistribution/CCSDSDistributor.h index 2d9b1fbd..d6e4f0e7 100644 --- a/src/fsfw/tcdistribution/CCSDSDistributor.h +++ b/src/fsfw/tcdistribution/CCSDSDistributor.h @@ -1,11 +1,12 @@ #ifndef FRAMEWORK_TCDISTRIBUTION_CCSDSDISTRIBUTOR_H_ #define FRAMEWORK_TCDISTRIBUTION_CCSDSDISTRIBUTOR_H_ -#include "../objectmanager/ObjectManagerIF.h" -#include "../storagemanager/StorageManagerIF.h" -#include "../tcdistribution/CCSDSDistributorIF.h" -#include "../tcdistribution/TcDistributor.h" -#include "../tmtcservices/AcceptsTelecommandsIF.h" +#include "fsfw/objectmanager/ObjectManagerIF.h" +#include "fsfw/storagemanager/StorageManagerIF.h" +#include "fsfw/tcdistribution/CCSDSDistributorIF.h" +#include "fsfw/tcdistribution/CcsdsPacketChecker.h" +#include "fsfw/tcdistribution/TcDistributor.h" +#include "fsfw/tmtcservices/AcceptsTelecommandsIF.h" /** * @brief An instantiation of the CCSDSDistributorIF. @@ -24,14 +25,15 @@ class CCSDSDistributor : public TcDistributor, * TcDistributor ctor with a certain object id. * @details * @c tcStore is set in the @c initialize method. - * @param setDefaultApid The default APID, where packets with unknown + * @param unknownApid The default APID, where packets with unknown * destination are sent to. */ - CCSDSDistributor(uint16_t setDefaultApid, object_id_t setObjectId); + CCSDSDistributor(uint16_t unknownApid, object_id_t setObjectId, + CcsdsPacketCheckIF* packetChecker = nullptr); /** * The destructor is empty. */ - virtual ~CCSDSDistributor(); + ~CCSDSDistributor() override; MessageQueueId_t getRequestQueue() override; ReturnValue_t registerApplication(uint16_t apid, MessageQueueId_t id) override; @@ -63,6 +65,8 @@ class CCSDSDistributor : public TcDistributor, * pure Space Packets and there exists no SpacePacketStored class. */ StorageManagerIF* tcStore = nullptr; + + CcsdsPacketCheckIF* packetChecker = nullptr; }; #endif /* FRAMEWORK_TCDISTRIBUTION_CCSDSDISTRIBUTOR_H_ */ diff --git a/src/fsfw/tcdistribution/CCSDSDistributorIF.h b/src/fsfw/tcdistribution/CCSDSDistributorIF.h index 9d512549..2ad012a0 100644 --- a/src/fsfw/tcdistribution/CCSDSDistributorIF.h +++ b/src/fsfw/tcdistribution/CCSDSDistributorIF.h @@ -18,7 +18,7 @@ class CCSDSDistributorIF { * at the distributor. * @param application A pointer to the Application to register. * @return - @c returnvalue::OK on success, - * - @c returnvalue::FAILED on failure. + * - @c returnvalue::FAILED on failure. */ virtual ReturnValue_t registerApplication(AcceptsTelecommandsIF* application) = 0; /** @@ -28,13 +28,13 @@ class CCSDSDistributorIF { * @param id The MessageQueueId of the message queue to send the * TC Packets to. * @return - @c returnvalue::OK on success, - * - @c returnvalue::FAILED on failure. + * - @c returnvalue::FAILED on failure. */ virtual ReturnValue_t registerApplication(uint16_t apid, MessageQueueId_t id) = 0; /** * The empty virtual destructor. */ - virtual ~CCSDSDistributorIF() {} + virtual ~CCSDSDistributorIF() = default; }; #endif /* FSFW_TCDISTRIBUTION_CCSDSDISTRIBUTORIF_H_ */ diff --git a/src/fsfw/tcdistribution/CFDPDistributor.cpp b/src/fsfw/tcdistribution/CFDPDistributor.cpp index 5f5f3904..1aa4adf9 100644 --- a/src/fsfw/tcdistribution/CFDPDistributor.cpp +++ b/src/fsfw/tcdistribution/CFDPDistributor.cpp @@ -2,7 +2,7 @@ #include "fsfw/objectmanager/ObjectManager.h" #include "fsfw/tcdistribution/CCSDSDistributorIF.h" -#include "fsfw/tmtcpacket/cfdp/CFDPPacketStored.h" +#include "fsfw/tmtcpacket/cfdp/CfdpPacketStored.h" #ifndef FSFW_CFDP_DISTRIBUTOR_DEBUGGING #define FSFW_CFDP_DISTRIBUTOR_DEBUGGING 1 @@ -16,7 +16,7 @@ CFDPDistributor::CFDPDistributor(uint16_t setApid, object_id_t setObjectId, tcStatus(returnvalue::FAILED), packetSource(setPacketSource) {} -CFDPDistributor::~CFDPDistributor() {} +CFDPDistributor::~CFDPDistributor() = default; CFDPDistributor::TcMqMapIter CFDPDistributor::selectDestination() { #if FSFW_CFDP_DISTRIBUTOR_DEBUGGING == 1 @@ -29,13 +29,13 @@ CFDPDistributor::TcMqMapIter CFDPDistributor::selectDestination() { storeId.packetIndex); #endif #endif - TcMqMapIter queueMapIt = this->queueMap.end(); + auto queueMapIt = this->queueMap.end(); if (this->currentPacket == nullptr) { return queueMapIt; } this->currentPacket->setStoreAddress(this->currentMessage.getStorageId()); - if (currentPacket->getWholeData() != nullptr) { - tcStatus = checker.checkPacket(currentPacket); + if (currentPacket->getFullData() != nullptr) { + tcStatus = checker.checkPacket(*currentPacket, currentPacket->getFullPacketLen()); if (tcStatus != returnvalue::OK) { #if FSFW_VERBOSE_LEVEL >= 1 #if FSFW_CPP_OSTREAM_ENABLED == 1 @@ -72,7 +72,7 @@ CFDPDistributor::TcMqMapIter CFDPDistributor::selectDestination() { ReturnValue_t CFDPDistributor::registerHandler(AcceptsTelecommandsIF* handler) { uint16_t handlerId = - handler->getIdentifier(); // should be 0, because CFDPHandler does not set a set a service-ID + handler->getIdentifier(); // should be 0, because CfdpHandler does not set a set a service-ID #if FSFW_CFDP_DISTRIBUTOR_DEBUGGING == 1 #if FSFW_CPP_OSTREAM_ENABLED == 1 sif::info << "CFDPDistributor::registerHandler: Handler ID: " << static_cast(handlerId) @@ -121,14 +121,13 @@ MessageQueueId_t CFDPDistributor::getRequestQueue() { return tcQueue->getId(); } uint16_t CFDPDistributor::getIdentifier() { return this->apid; } ReturnValue_t CFDPDistributor::initialize() { - currentPacket = new CFDPPacketStored(); + currentPacket = new CfdpPacketStored(); if (currentPacket == nullptr) { // Should not happen, memory allocation failed! return ObjectManagerIF::CHILD_INIT_FAILED; } - CCSDSDistributorIF* ccsdsDistributor = - ObjectManager::instance()->get(packetSource); + auto* ccsdsDistributor = ObjectManager::instance()->get(packetSource); if (ccsdsDistributor == nullptr) { #if FSFW_CPP_OSTREAM_ENABLED == 1 sif::error << "CFDPDistributor::initialize: Packet source invalid" << std::endl; diff --git a/src/fsfw/tcdistribution/CFDPDistributor.h b/src/fsfw/tcdistribution/CFDPDistributor.h index 18c139ff..17e79ff3 100644 --- a/src/fsfw/tcdistribution/CFDPDistributor.h +++ b/src/fsfw/tcdistribution/CFDPDistributor.h @@ -1,10 +1,10 @@ #ifndef FSFW_TCDISTRIBUTION_CFDPDISTRIBUTOR_H_ #define FSFW_TCDISTRIBUTION_CFDPDISTRIBUTOR_H_ -#include +#include #include "../returnvalues/returnvalue.h" -#include "../tmtcpacket/cfdp/CFDPPacketStored.h" +#include "../tmtcpacket/cfdp/CfdpPacketStored.h" #include "../tmtcservices/AcceptsTelecommandsIF.h" #include "../tmtcservices/VerificationReporter.h" #include "CFDPDistributorIF.h" @@ -31,7 +31,7 @@ class CFDPDistributor : public TcDistributor, /** * The destructor is empty. */ - virtual ~CFDPDistributor(); + ~CFDPDistributor() override; ReturnValue_t registerHandler(AcceptsTelecommandsIF* handler) override; MessageQueueId_t getRequestQueue() override; ReturnValue_t initialize() override; @@ -42,8 +42,8 @@ class CFDPDistributor : public TcDistributor, /** * The currently handled packet is stored here. */ - CFDPPacketStored* currentPacket = nullptr; - TcPacketCheckCFDP checker; + CfdpPacketStored* currentPacket = nullptr; + CfdpPacketChecker checker; /** * With this variable, the current check status is stored to generate * acceptance messages later. diff --git a/src/fsfw/tcdistribution/CFDPDistributorIF.h b/src/fsfw/tcdistribution/CFDPDistributorIF.h index 8ee5568f..101ffa15 100644 --- a/src/fsfw/tcdistribution/CFDPDistributorIF.h +++ b/src/fsfw/tcdistribution/CFDPDistributorIF.h @@ -13,12 +13,12 @@ class CFDPDistributorIF { /** * The empty virtual destructor. */ - virtual ~CFDPDistributorIF() {} + virtual ~CFDPDistributorIF() = default; /** * With this method, Handlers can register themselves at the CFDP Distributor. * @param handler A pointer to the registering Handler. * @return - @c returnvalue::OK on success, - * - @c returnvalue::FAILED on failure. + * - @c returnvalue::FAILED on failure. */ virtual ReturnValue_t registerHandler(AcceptsTelecommandsIF* handler) = 0; }; diff --git a/src/fsfw/tcdistribution/CMakeLists.txt b/src/fsfw/tcdistribution/CMakeLists.txt index ab32c509..532ba2ca 100644 --- a/src/fsfw/tcdistribution/CMakeLists.txt +++ b/src/fsfw/tcdistribution/CMakeLists.txt @@ -1,4 +1,9 @@ target_sources( ${LIB_FSFW_NAME} - PRIVATE CCSDSDistributor.cpp PUSDistributor.cpp TcDistributor.cpp - TcPacketCheckPUS.cpp TcPacketCheckCFDP.cpp CFDPDistributor.cpp) + PRIVATE CCSDSDistributor.cpp + PusDistributor.cpp + TcDistributor.cpp + PusPacketChecker.cpp + TcPacketCheckCFDP.cpp + CFDPDistributor.cpp + CcsdsPacketChecker.cpp) diff --git a/src/fsfw/tcdistribution/TcPacketCheckIF.h b/src/fsfw/tcdistribution/CcsdsPacketCheckIF.h similarity index 60% rename from src/fsfw/tcdistribution/TcPacketCheckIF.h rename to src/fsfw/tcdistribution/CcsdsPacketCheckIF.h index e583cb0f..251203d4 100644 --- a/src/fsfw/tcdistribution/TcPacketCheckIF.h +++ b/src/fsfw/tcdistribution/CcsdsPacketCheckIF.h @@ -1,30 +1,32 @@ #ifndef FSFW_TCDISTRIBUTION_TCPACKETCHECKIF_H_ #define FSFW_TCDISTRIBUTION_TCPACKETCHECKIF_H_ -#include "../returnvalues/returnvalue.h" +#include -class SpacePacketBase; +#include "fsfw/returnvalues/returnvalue.h" + +class SpacePacketReader; /** * This interface is used by PacketCheckers for PUS packets and CFDP packets . * @ingroup tc_distribution */ -class TcPacketCheckIF { +class CcsdsPacketCheckIF { public: /** * The empty virtual destructor. */ - virtual ~TcPacketCheckIF() {} + virtual ~CcsdsPacketCheckIF() = default; /** * This is the actual method to formally check a certain Packet. * The packet's Application Data can not be checked here. * @param current_packet The packet to check * @return - @c returnvalue::OK on success. - * - @c INCORRECT_CHECKSUM if checksum is invalid. - * - @c ILLEGAL_APID if APID does not match. + * - @c INCORRECT_CHECKSUM if checksum is invalid. + * - @c ILLEGAL_APID if APID does not match. */ - virtual ReturnValue_t checkPacket(SpacePacketBase* currentPacket) = 0; + virtual ReturnValue_t checkPacket(const SpacePacketReader& currentPacket, size_t packetLen) = 0; }; #endif /* FSFW_TCDISTRIBUTION_TCPACKETCHECKIF_H_ */ diff --git a/src/fsfw/tcdistribution/CcsdsPacketChecker.cpp b/src/fsfw/tcdistribution/CcsdsPacketChecker.cpp new file mode 100644 index 00000000..08ec1811 --- /dev/null +++ b/src/fsfw/tcdistribution/CcsdsPacketChecker.cpp @@ -0,0 +1,33 @@ +#include "CcsdsPacketChecker.h" + +#include "fsfw/tcdistribution/definitions.h" +#include "fsfw/tmtcpacket/ccsds/SpacePacketReader.h" + +CcsdsPacketChecker::CcsdsPacketChecker(ccsds::PacketType packetType_, uint8_t ccsdsVersion_) + : packetType(packetType_), ccsdsVersion(ccsdsVersion_) {} + +ReturnValue_t CcsdsPacketChecker::checkPacket(const SpacePacketReader& currentPacket, + size_t packetLen) { + if (checkApid) { + if (currentPacket.getApid() != apid) { + return tcdistrib::INVALID_APID; + } + } + + if (currentPacket.getVersion() != ccsdsVersion) { + return tcdistrib::INVALID_CCSDS_VERSION; + } + if (currentPacket.getPacketType() != packetType) { + return tcdistrib::INVALID_PACKET_TYPE; + } + // This assumes that the getFullPacketLen version uses the space packet data length field + if (currentPacket.getFullPacketLen() != packetLen) { + return tcdistrib::INCOMPLETE_PACKET; + } + return returnvalue::OK; +} + +void CcsdsPacketChecker::setApidToCheck(uint16_t apid_) { + apid = apid_; + checkApid = true; +} diff --git a/src/fsfw/tcdistribution/CcsdsPacketChecker.h b/src/fsfw/tcdistribution/CcsdsPacketChecker.h new file mode 100644 index 00000000..7def030d --- /dev/null +++ b/src/fsfw/tcdistribution/CcsdsPacketChecker.h @@ -0,0 +1,20 @@ +#ifndef FSFW_TESTS_CCSDSPACKETCHECKERBASE_H +#define FSFW_TESTS_CCSDSPACKETCHECKERBASE_H + +#include "CcsdsPacketCheckIF.h" +#include "fsfw/tmtcpacket/ccsds/SpacePacketIF.h" + +class CcsdsPacketChecker : public CcsdsPacketCheckIF { + public: + CcsdsPacketChecker(ccsds::PacketType packetType, uint8_t ccsdsVersion = 0b000); + + void setApidToCheck(uint16_t apid); + ReturnValue_t checkPacket(const SpacePacketReader& currentPacket, size_t packetLen) override; + + protected: + bool checkApid = false; + uint16_t apid = 0; + ccsds::PacketType packetType; + uint8_t ccsdsVersion; +}; +#endif // FSFW_TESTS_CCSDSPACKETCHECKERBASE_H diff --git a/src/fsfw/tcdistribution/TcPacketCheckCFDP.h b/src/fsfw/tcdistribution/CfdpPacketChecker.h similarity index 65% rename from src/fsfw/tcdistribution/TcPacketCheckCFDP.h rename to src/fsfw/tcdistribution/CfdpPacketChecker.h index 8946c7a7..b1d46ae4 100644 --- a/src/fsfw/tcdistribution/TcPacketCheckCFDP.h +++ b/src/fsfw/tcdistribution/CfdpPacketChecker.h @@ -1,16 +1,16 @@ #ifndef FSFW_TCDISTRIBUTION_TCPACKETCHECKCFDP_H_ #define FSFW_TCDISTRIBUTION_TCPACKETCHECKCFDP_H_ -#include "TcPacketCheckIF.h" +#include "CcsdsPacketCheckIF.h" #include "fsfw/FSFW.h" -class CFDPPacketStored; +class CfdpPacketStored; /** * This class performs a formal packet check for incoming CFDP Packets. * @ingroup tc_distribution */ -class TcPacketCheckCFDP : public TcPacketCheckIF { +class CfdpPacketChecker : public CcsdsPacketCheckIF { protected: /** * The packet id each correct packet should have. @@ -23,11 +23,11 @@ class TcPacketCheckCFDP : public TcPacketCheckIF { * The constructor only sets the APID attribute. * @param set_apid The APID to set. */ - TcPacketCheckCFDP(uint16_t setApid); + explicit CfdpPacketChecker(uint16_t setApid); - ReturnValue_t checkPacket(SpacePacketBase* currentPacket) override; + ReturnValue_t checkPacket(const SpacePacketReader& currentPacket, size_t packetLen) override; - uint16_t getApid() const; + [[nodiscard]] uint16_t getApid() const; }; #endif /* FSFW_TCDISTRIBUTION_TCPACKETCHECKCFDP_H_ */ diff --git a/src/fsfw/tcdistribution/PUSDistributor.cpp b/src/fsfw/tcdistribution/PUSDistributor.cpp deleted file mode 100644 index a32a210f..00000000 --- a/src/fsfw/tcdistribution/PUSDistributor.cpp +++ /dev/null @@ -1,146 +0,0 @@ -#include "fsfw/tcdistribution/PUSDistributor.h" - -#include "fsfw/objectmanager/ObjectManager.h" -#include "fsfw/serviceinterface/ServiceInterface.h" -#include "fsfw/tcdistribution/CCSDSDistributorIF.h" -#include "fsfw/tmtcservices/PusVerificationReport.h" - -#define PUS_DISTRIBUTOR_DEBUGGING 0 - -PUSDistributor::PUSDistributor(uint16_t setApid, object_id_t setObjectId, - object_id_t setPacketSource) - : TcDistributor(setObjectId), - checker(setApid), - verifyChannel(), - tcStatus(returnvalue::FAILED), - packetSource(setPacketSource) {} - -PUSDistributor::~PUSDistributor() = default; - -PUSDistributor::TcMqMapIter PUSDistributor::selectDestination() { -#if FSFW_CPP_OSTREAM_ENABLED == 1 && PUS_DISTRIBUTOR_DEBUGGING == 1 - store_address_t storeId = this->currentMessage.getStorageId()); - sif::debug << "PUSDistributor::handlePacket received: " << storeId.poolIndex << ", " - << storeId.packetIndex << std::endl; -#endif - auto queueMapIt = this->queueMap.end(); - if (this->currentPacket == nullptr) { - return queueMapIt; - } - this->currentPacket->setStoreAddress(this->currentMessage.getStorageId(), currentPacket); - if (currentPacket->getWholeData() != nullptr) { - tcStatus = checker.checkPacket(currentPacket); - if (tcStatus != returnvalue::OK) { -#if FSFW_VERBOSE_LEVEL >= 1 - const char* keyword = "unnamed error"; - if (tcStatus == TcPacketCheckPUS::INCORRECT_CHECKSUM) { - keyword = "checksum"; - } else if (tcStatus == TcPacketCheckPUS::INCORRECT_PRIMARY_HEADER) { - keyword = "incorrect primary header"; - } else if (tcStatus == TcPacketCheckPUS::ILLEGAL_APID) { - keyword = "illegal APID"; - } else if (tcStatus == TcPacketCheckPUS::INCORRECT_SECONDARY_HEADER) { - keyword = "incorrect secondary header"; - } else if (tcStatus == TcPacketCheckPUS::INCOMPLETE_PACKET) { - keyword = "incomplete packet"; - } -#if FSFW_CPP_OSTREAM_ENABLED == 1 - sif::warning << "PUSDistributor::handlePacket: Packet format invalid, " << keyword - << " error" << std::endl; -#else - sif::printWarning("PUSDistributor::handlePacket: Packet format invalid, %s error\n", - keyword); -#endif -#endif - } - uint32_t queue_id = currentPacket->getService(); - queueMapIt = this->queueMap.find(queue_id); - } else { - tcStatus = PACKET_LOST; - } - - if (queueMapIt == this->queueMap.end()) { - tcStatus = DESTINATION_NOT_FOUND; -#if FSFW_VERBOSE_LEVEL >= 1 -#if FSFW_CPP_OSTREAM_ENABLED == 1 - sif::debug << "PUSDistributor::handlePacket: Destination not found" << std::endl; -#else - sif::printDebug("PUSDistributor::handlePacket: Destination not found\n"); -#endif /* !FSFW_CPP_OSTREAM_ENABLED == 1 */ -#endif - } - - if (tcStatus != returnvalue::OK) { - return this->queueMap.end(); - } else { - return queueMapIt; - } -} - -ReturnValue_t PUSDistributor::registerService(AcceptsTelecommandsIF* service) { - uint16_t serviceId = service->getIdentifier(); -#if PUS_DISTRIBUTOR_DEBUGGING == 1 -#if FSFW_CPP_OSTREAM_ENABLED == 1 - sif::info << "Service ID: " << static_cast(serviceId) << std::endl; -#else - sif::printInfo("Service ID: %d\n", static_cast(serviceId)); -#endif -#endif - MessageQueueId_t queue = service->getRequestQueue(); - auto returnPair = queueMap.emplace(serviceId, queue); - if (not returnPair.second) { -#if FSFW_VERBOSE_LEVEL >= 1 -#if FSFW_CPP_OSTREAM_ENABLED == 1 - sif::error << "PUSDistributor::registerService: Service ID already" - " exists in map" - << std::endl; -#else - sif::printError("PUSDistributor::registerService: Service ID already exists in map\n"); -#endif -#endif - return SERVICE_ID_ALREADY_EXISTS; - } - return returnvalue::OK; -} - -MessageQueueId_t PUSDistributor::getRequestQueue() { return tcQueue->getId(); } - -ReturnValue_t PUSDistributor::callbackAfterSending(ReturnValue_t queueStatus) { - if (queueStatus != returnvalue::OK) { - tcStatus = queueStatus; - } - if (tcStatus != returnvalue::OK) { - this->verifyChannel.sendFailureReport(tc_verification::ACCEPTANCE_FAILURE, currentPacket, - tcStatus); - // A failed packet is deleted immediately after reporting, - // otherwise it will block memory. - currentPacket->deletePacket(); - return returnvalue::FAILED; - } else { - this->verifyChannel.sendSuccessReport(tc_verification::ACCEPTANCE_SUCCESS, currentPacket); - return returnvalue::OK; - } -} - -uint16_t PUSDistributor::getIdentifier() { return checker.getApid(); } - -ReturnValue_t PUSDistributor::initialize() { - currentPacket = new TcPacketStoredPus(); - if (currentPacket == nullptr) { - // Should not happen, memory allocation failed! - return ObjectManagerIF::CHILD_INIT_FAILED; - } - - auto* ccsdsDistributor = ObjectManager::instance()->get(packetSource); - if (ccsdsDistributor == nullptr) { -#if FSFW_CPP_OSTREAM_ENABLED == 1 - sif::error << "PUSDistributor::initialize: Packet source invalid" << std::endl; - sif::error << " Make sure it exists and implements CCSDSDistributorIF!" << std::endl; -#else - sif::printError("PUSDistributor::initialize: Packet source invalid\n"); - sif::printError("Make sure it exists and implements CCSDSDistributorIF\n"); -#endif - return returnvalue::FAILED; - } - return ccsdsDistributor->registerApplication(this); -} diff --git a/src/fsfw/tcdistribution/PUSDistributorIF.h b/src/fsfw/tcdistribution/PUSDistributorIF.h index e3bff93f..85a80b46 100644 --- a/src/fsfw/tcdistribution/PUSDistributorIF.h +++ b/src/fsfw/tcdistribution/PUSDistributorIF.h @@ -18,7 +18,7 @@ class PUSDistributorIF { * With this method, Services can register themselves at the PUS Distributor. * @param service A pointer to the registering Service. * @return - @c returnvalue::OK on success, - * - @c returnvalue::FAILED on failure. + * - @c returnvalue::FAILED on failure. */ virtual ReturnValue_t registerService(AcceptsTelecommandsIF* service) = 0; }; diff --git a/src/fsfw/tcdistribution/PusDistributor.cpp b/src/fsfw/tcdistribution/PusDistributor.cpp new file mode 100644 index 00000000..c94d5736 --- /dev/null +++ b/src/fsfw/tcdistribution/PusDistributor.cpp @@ -0,0 +1,168 @@ +#include "fsfw/tcdistribution/PusDistributor.h" + +#include "definitions.h" +#include "fsfw/objectmanager/ObjectManager.h" +#include "fsfw/serviceinterface/ServiceInterface.h" +#include "fsfw/tcdistribution/CCSDSDistributorIF.h" +#include "fsfw/tmtcservices/PusVerificationReport.h" + +#define PUS_DISTRIBUTOR_DEBUGGING 0 + +PusDistributor::PusDistributor(uint16_t setApid, object_id_t setObjectId, + CCSDSDistributorIF* distributor, StorageManagerIF* store_) + : TcDistributor(setObjectId), + store(store_), + checker(setApid, ccsds::PacketType::TC), + ccsdsDistributor(distributor), + tcStatus(returnvalue::FAILED) {} + +PusDistributor::~PusDistributor() = default; + +PusDistributor::TcMqMapIter PusDistributor::selectDestination() { +#if FSFW_CPP_OSTREAM_ENABLED == 1 && PUS_DISTRIBUTOR_DEBUGGING == 1 + store_address_t storeId = currentMessage.getStorageId(); + sif::debug << "PUSDistributor::handlePacket received: " << storeId.poolIndex << ", " + << storeId.packetIndex << std::endl; +#endif + auto queueMapIt = queueMap.end(); + // TODO: Need to set the data + const uint8_t* packetPtr = nullptr; + size_t packetLen = 0; + if (store->getData(currentMessage.getStorageId(), &packetPtr, &packetLen) != returnvalue::OK) { + return queueMapIt; + } + ReturnValue_t result = reader.setReadOnlyData(packetPtr, packetLen); + if (result != returnvalue::OK) { + tcStatus = PACKET_LOST; + return queueMapIt; + } + // CRC check done by checker + result = reader.parseDataWithoutCrcCheck(); + if (result != returnvalue::OK) { + tcStatus = PACKET_LOST; + return queueMapIt; + } + if (reader.getFullData() != nullptr) { + tcStatus = checker.checkPacket(reader, reader.getFullPacketLen()); + if (tcStatus != returnvalue::OK) { + checkerFailurePrinter(); + } + uint32_t queue_id = reader.getService(); + queueMapIt = queueMap.find(queue_id); + } else { + tcStatus = PACKET_LOST; + } + + if (queueMapIt == this->queueMap.end()) { + tcStatus = DESTINATION_NOT_FOUND; +#if FSFW_VERBOSE_LEVEL >= 1 +#if FSFW_CPP_OSTREAM_ENABLED == 1 + sif::debug << "PUSDistributor::handlePacket: Destination not found" << std::endl; +#else + sif::printDebug("PUSDistributor::handlePacket: Destination not found\n"); +#endif /* !FSFW_CPP_OSTREAM_ENABLED == 1 */ +#endif + } + + if (tcStatus != returnvalue::OK) { + return this->queueMap.end(); + } else { + return queueMapIt; + } +} + +ReturnValue_t PusDistributor::registerService(AcceptsTelecommandsIF* service) { + uint16_t serviceId = service->getIdentifier(); +#if PUS_DISTRIBUTOR_DEBUGGING == 1 +#if FSFW_CPP_OSTREAM_ENABLED == 1 + sif::info << "Service ID: " << static_cast(serviceId) << std::endl; +#else + sif::printInfo("Service ID: %d\n", static_cast(serviceId)); +#endif +#endif + MessageQueueId_t queue = service->getRequestQueue(); + auto returnPair = queueMap.emplace(serviceId, queue); + if (not returnPair.second) { +#if FSFW_VERBOSE_LEVEL >= 1 +#if FSFW_CPP_OSTREAM_ENABLED == 1 + sif::error << "PUSDistributor::registerService: Service ID already" + " exists in map" + << std::endl; +#else + sif::printError("PUSDistributor::registerService: Service ID already exists in map\n"); +#endif +#endif + return SERVICE_ID_ALREADY_EXISTS; + } + return returnvalue::OK; +} + +MessageQueueId_t PusDistributor::getRequestQueue() { return tcQueue->getId(); } + +ReturnValue_t PusDistributor::callbackAfterSending(ReturnValue_t queueStatus) { + if (queueStatus != returnvalue::OK) { + tcStatus = queueStatus; + } + if (tcStatus != returnvalue::OK) { + verifyChannel->sendFailureReport({tcverif::ACCEPTANCE_FAILURE, reader, tcStatus}); + // A failed packet is deleted immediately after reporting, + // otherwise it will block memory. + store->deleteData(currentMessage.getStorageId()); + return returnvalue::FAILED; + } else { + verifyChannel->sendSuccessReport({tcverif::ACCEPTANCE_SUCCESS, reader}); + return returnvalue::OK; + } +} + +uint16_t PusDistributor::getIdentifier() { return checker.getApid(); } + +ReturnValue_t PusDistributor::initialize() { + if (store == nullptr) { + store = ObjectManager::instance()->get(objects::TC_STORE); + if (store == nullptr) { + return ObjectManagerIF::CHILD_INIT_FAILED; + } + } + if (ccsdsDistributor == nullptr) { +#if FSFW_CPP_OSTREAM_ENABLED == 1 + sif::error << "PUSDistributor::initialize: Packet source invalid" << std::endl; + sif::error << " Make sure it exists and implements CCSDSDistributorIF!" << std::endl; +#else + sif::printError("PusDistributor::initialize: Packet source invalid\n"); + sif::printError("Make sure it exists and implements CCSDSDistributorIF\n"); +#endif + return ObjectManagerIF::CHILD_INIT_FAILED; + } + if (verifyChannel == nullptr) { + verifyChannel = + ObjectManager::instance()->get(objects::VERIFICATION_REPORTER); + if (verifyChannel == nullptr) { + return ObjectManagerIF::CHILD_INIT_FAILED; + } + } + return ccsdsDistributor->registerApplication(this); +} + +void PusDistributor::checkerFailurePrinter() const { +#if FSFW_VERBOSE_LEVEL >= 1 + const char* keyword = "unnamed error"; + if (tcStatus == tcdistrib::INCORRECT_CHECKSUM) { + keyword = "checksum"; + } else if (tcStatus == tcdistrib::INCORRECT_PRIMARY_HEADER) { + keyword = "incorrect primary header"; + } else if (tcStatus == tcdistrib::INVALID_APID) { + keyword = "illegal APID"; + } else if (tcStatus == tcdistrib::INCORRECT_SECONDARY_HEADER) { + keyword = "incorrect secondary header"; + } else if (tcStatus == tcdistrib::INCOMPLETE_PACKET) { + keyword = "incomplete packet"; + } +#if FSFW_CPP_OSTREAM_ENABLED == 1 + sif::warning << "PUSDistributor::handlePacket: Packet format invalid, " << keyword << " error" + << std::endl; +#else + sif::printWarning("PUSDistributor::handlePacket: Packet format invalid, %s error\n", keyword); +#endif +#endif +} diff --git a/src/fsfw/tcdistribution/PUSDistributor.h b/src/fsfw/tcdistribution/PusDistributor.h similarity index 79% rename from src/fsfw/tcdistribution/PUSDistributor.h rename to src/fsfw/tcdistribution/PusDistributor.h index 8cef0f46..d2265f95 100644 --- a/src/fsfw/tcdistribution/PUSDistributor.h +++ b/src/fsfw/tcdistribution/PusDistributor.h @@ -2,20 +2,22 @@ #define FSFW_TCDISTRIBUTION_PUSDISTRIBUTOR_H_ #include "PUSDistributorIF.h" +#include "PusPacketChecker.h" #include "TcDistributor.h" -#include "TcPacketCheckPUS.h" #include "fsfw/returnvalues/returnvalue.h" #include "fsfw/tmtcpacket/pus/tc.h" #include "fsfw/tmtcservices/AcceptsTelecommandsIF.h" #include "fsfw/tmtcservices/VerificationReporter.h" +class CCSDSDistributorIF; + /** * This class accepts PUS Telecommands and forwards them to Application * services. In addition, the class performs a formal packet check and * sends acceptance success or failure messages. * @ingroup tc_distribution */ -class PUSDistributor : public TcDistributor, public PUSDistributorIF, public AcceptsTelecommandsIF { +class PusDistributor : public TcDistributor, public PUSDistributorIF, public AcceptsTelecommandsIF { public: /** * The ctor passes @c set_apid to the checker class and calls the @@ -25,30 +27,31 @@ class PUSDistributor : public TcDistributor, public PUSDistributorIF, public Acc * @param setPacketSource Object ID of the source of TC packets. * Must implement CCSDSDistributorIF. */ - PUSDistributor(uint16_t setApid, object_id_t setObjectId, object_id_t setPacketSource); + PusDistributor(uint16_t setApid, object_id_t setObjectId, CCSDSDistributorIF* packetSource, + StorageManagerIF* store = nullptr); /** * The destructor is empty. */ - virtual ~PUSDistributor(); + ~PusDistributor() override; ReturnValue_t registerService(AcceptsTelecommandsIF* service) override; MessageQueueId_t getRequestQueue() override; ReturnValue_t initialize() override; uint16_t getIdentifier() override; protected: + StorageManagerIF* store; /** * This attribute contains the class, that performs a formal packet check. */ - TcPacketCheckPUS checker; + PusPacketChecker checker; /** * With this class, verification messages are sent to the * TC Verification service. */ - VerificationReporter verifyChannel; - /** - * The currently handled packet is stored here. - */ - TcPacketStoredPus* currentPacket = nullptr; + VerificationReporterIF* verifyChannel = nullptr; + //! Cached for initialization + CCSDSDistributorIF* ccsdsDistributor = nullptr; + PusTcReader reader; /** * With this variable, the current check status is stored to generate @@ -56,8 +59,6 @@ class PUSDistributor : public TcDistributor, public PUSDistributorIF, public Acc */ ReturnValue_t tcStatus; - const object_id_t packetSource; - /** * This method reads the packet service, checks if such a service is * registered and forwards the packet to the destination. @@ -72,6 +73,8 @@ class PUSDistributor : public TcDistributor, public PUSDistributorIF, public Acc * success/failure messages. */ ReturnValue_t callbackAfterSending(ReturnValue_t queueStatus) override; + + void checkerFailurePrinter() const; }; #endif /* FSFW_TCDISTRIBUTION_PUSDISTRIBUTOR_H_ */ diff --git a/src/fsfw/tcdistribution/PusPacketChecker.cpp b/src/fsfw/tcdistribution/PusPacketChecker.cpp new file mode 100644 index 00000000..dc5b9ab9 --- /dev/null +++ b/src/fsfw/tcdistribution/PusPacketChecker.cpp @@ -0,0 +1,30 @@ +#include "fsfw/tcdistribution/PusPacketChecker.h" + +#include "fsfw/globalfunctions/CRC.h" +#include "fsfw/serviceinterface/ServiceInterface.h" +#include "fsfw/tcdistribution/definitions.h" +#include "fsfw/tmtcpacket/pus/tc/PusTcReader.h" + +PusPacketChecker::PusPacketChecker(uint16_t apid, ccsds::PacketType packetType_, + ecss::PusVersion pusVersion_) + : pusVersion(pusVersion_), apid(apid) {} + +ReturnValue_t PusPacketChecker::checkPacket(const PusTcReader& pusPacket, size_t packetLen) { + // Other primary header fields are checked by base class + if (not pusPacket.hasSecHeader()) { + return tcdistrib::INVALID_SEC_HEADER_FIELD; + } + uint16_t calculated_crc = CRC::crc16ccitt(pusPacket.getFullData(), pusPacket.getFullPacketLen()); + if (calculated_crc != 0) { + return tcdistrib::INCORRECT_CHECKSUM; + } + if (pusPacket.getApid() != apid) { + return tcdistrib::INVALID_APID; + } + if (pusPacket.getPusVersion() != pusVersion) { + return tcdistrib::INVALID_PUS_VERSION; + } + return returnvalue::OK; +} + +uint16_t PusPacketChecker::getApid() const { return apid; } diff --git a/src/fsfw/tcdistribution/PusPacketChecker.h b/src/fsfw/tcdistribution/PusPacketChecker.h new file mode 100644 index 00000000..249221bb --- /dev/null +++ b/src/fsfw/tcdistribution/PusPacketChecker.h @@ -0,0 +1,34 @@ +#ifndef FSFW_TCDISTRIBUTION_TCPACKETCHECKPUS_H_ +#define FSFW_TCDISTRIBUTION_TCPACKETCHECKPUS_H_ + +#include "fsfw/FSFW.h" +#include "fsfw/returnvalues/returnvalue.h" +#include "fsfw/tmtcpacket/pus/defs.h" +#include "fsfw/tmtcservices/PusVerificationReport.h" + +/** + * This class performs a formal packet check for incoming PUS Telecommand Packets. + * Currently, it only checks if the APID and CRC are correct. + * @ingroup tc_distribution + */ +class PusPacketChecker { + public: + /** + * The constructor only sets the APID attribute. + * @param set_apid The APID to set. + */ + explicit PusPacketChecker(uint16_t apid, ccsds::PacketType packetType, + ecss::PusVersion = ecss::PusVersion::PUS_C); + + ReturnValue_t checkPacket(const PusTcReader& currentPacket, size_t packetLen); + + [[nodiscard]] uint16_t getApid() const; + + protected: + ecss::PusVersion pusVersion; + uint16_t apid; + + private: +}; + +#endif /* FSFW_TCDISTRIBUTION_TCPACKETCHECKPUS_H_ */ diff --git a/src/fsfw/tcdistribution/TcDistributor.cpp b/src/fsfw/tcdistribution/TcDistributor.cpp index e26ba2ff..f76df208 100644 --- a/src/fsfw/tcdistribution/TcDistributor.cpp +++ b/src/fsfw/tcdistribution/TcDistributor.cpp @@ -5,31 +5,32 @@ #include "fsfw/tmtcservices/TmTcMessage.h" TcDistributor::TcDistributor(object_id_t objectId) : SystemObject(objectId) { - tcQueue = QueueFactory::instance()->createMessageQueue(DISTRIBUTER_MAX_PACKETS); + auto mqArgs = MqArgs(objectId); + tcQueue = QueueFactory::instance()->createMessageQueue( + DISTRIBUTER_MAX_PACKETS, MessageQueueMessage::MAX_MESSAGE_SIZE, &mqArgs); } TcDistributor::~TcDistributor() { QueueFactory::instance()->deleteMessageQueue(tcQueue); } ReturnValue_t TcDistributor::performOperation(uint8_t opCode) { - ReturnValue_t status = returnvalue::OK; + ReturnValue_t status; for (status = tcQueue->receiveMessage(¤tMessage); status == returnvalue::OK; status = tcQueue->receiveMessage(¤tMessage)) { status = handlePacket(); } if (status == MessageQueueIF::EMPTY) { return returnvalue::OK; - } else { - return status; } + return status; } ReturnValue_t TcDistributor::handlePacket() { - TcMqMapIter queueMapIt = this->selectDestination(); - ReturnValue_t returnValue = returnvalue::FAILED; - if (queueMapIt != this->queueMap.end()) { - returnValue = this->tcQueue->sendMessage(queueMapIt->second, &this->currentMessage); + auto queueMapIt = selectDestination(); + ReturnValue_t result = returnvalue::FAILED; + if (queueMapIt != queueMap.end()) { + result = tcQueue->sendMessage(queueMapIt->second, ¤tMessage); } - return this->callbackAfterSending(returnValue); + return callbackAfterSending(result); } void TcDistributor::print() { diff --git a/src/fsfw/tcdistribution/TcDistributor.h b/src/fsfw/tcdistribution/TcDistributor.h index d018cad4..bc1534a6 100644 --- a/src/fsfw/tcdistribution/TcDistributor.h +++ b/src/fsfw/tcdistribution/TcDistributor.h @@ -105,7 +105,7 @@ class TcDistributor : public SystemObject, public ExecutableObjectIF { * @param queueStatus The status of the message queue after an attempt * to send the TC. * @return - @c returnvalue::OK on success - * - @c returnvalue::FAILED on failure + * - @c returnvalue::FAILED on failure */ virtual ReturnValue_t callbackAfterSending(ReturnValue_t queueStatus); diff --git a/src/fsfw/tcdistribution/TcPacketCheckCFDP.cpp b/src/fsfw/tcdistribution/TcPacketCheckCFDP.cpp index 3d6899a5..8171a392 100644 --- a/src/fsfw/tcdistribution/TcPacketCheckCFDP.cpp +++ b/src/fsfw/tcdistribution/TcPacketCheckCFDP.cpp @@ -1,11 +1,11 @@ -#include "fsfw/tcdistribution/TcPacketCheckCFDP.h" +#include "fsfw/tcdistribution/CfdpPacketChecker.h" +#include "fsfw/tmtcpacket/cfdp/CfdpPacketStored.h" -#include "fsfw/tmtcpacket/cfdp/CFDPPacketStored.h" +CfdpPacketChecker::CfdpPacketChecker(uint16_t setApid) : apid(setApid) {} -TcPacketCheckCFDP::TcPacketCheckCFDP(uint16_t setApid) : apid(setApid) {} - -ReturnValue_t TcPacketCheckCFDP::checkPacket(SpacePacketBase* currentPacket) { +ReturnValue_t CfdpPacketChecker::checkPacket(const SpacePacketReader& currentPacket, + size_t packetLen) { return returnvalue::OK; } -uint16_t TcPacketCheckCFDP::getApid() const { return apid; } +uint16_t CfdpPacketChecker::getApid() const { return apid; } diff --git a/src/fsfw/tcdistribution/TcPacketCheckPUS.cpp b/src/fsfw/tcdistribution/TcPacketCheckPUS.cpp deleted file mode 100644 index 8ae29ae1..00000000 --- a/src/fsfw/tcdistribution/TcPacketCheckPUS.cpp +++ /dev/null @@ -1,44 +0,0 @@ -#include "fsfw/tcdistribution/TcPacketCheckPUS.h" - -#include "fsfw/globalfunctions/CRC.h" -#include "fsfw/serviceinterface/ServiceInterface.h" -#include "fsfw/storagemanager/StorageManagerIF.h" -#include "fsfw/tmtcpacket/pus/tc/TcPacketPusBase.h" -#include "fsfw/tmtcpacket/pus/tc/TcPacketStoredBase.h" -#include "fsfw/tmtcpacket/pus/tc/TcPacketStoredPus.h" -#include "fsfw/tmtcservices/VerificationCodes.h" - -TcPacketCheckPUS::TcPacketCheckPUS(uint16_t setApid) : apid(setApid) {} - -ReturnValue_t TcPacketCheckPUS::checkPacket(SpacePacketBase* currentPacket) { - TcPacketStoredBase* storedPacket = dynamic_cast(currentPacket); - TcPacketPusBase* tcPacketBase = dynamic_cast(currentPacket); - if (tcPacketBase == nullptr or storedPacket == nullptr) { - return returnvalue::FAILED; - } - uint16_t calculated_crc = - CRC::crc16ccitt(tcPacketBase->getWholeData(), tcPacketBase->getFullSize()); - if (calculated_crc != 0) { - return INCORRECT_CHECKSUM; - } - bool condition = (not tcPacketBase->hasSecondaryHeader()) or - (tcPacketBase->getPacketVersionNumber() != CCSDS_VERSION_NUMBER) or - (not tcPacketBase->isTelecommand()); - if (condition) { - return INCORRECT_PRIMARY_HEADER; - } - if (tcPacketBase->getAPID() != this->apid) return ILLEGAL_APID; - - if (not storedPacket->isSizeCorrect()) { - return INCOMPLETE_PACKET; - } - - condition = (tcPacketBase->getSecondaryHeaderFlag() != CCSDS_SECONDARY_HEADER_FLAG) || - (tcPacketBase->getPusVersionNumber() != PUS_VERSION_NUMBER); - if (condition) { - return INCORRECT_SECONDARY_HEADER; - } - return returnvalue::OK; -} - -uint16_t TcPacketCheckPUS::getApid() const { return apid; } diff --git a/src/fsfw/tcdistribution/TcPacketCheckPUS.h b/src/fsfw/tcdistribution/TcPacketCheckPUS.h deleted file mode 100644 index 1ecd1007..00000000 --- a/src/fsfw/tcdistribution/TcPacketCheckPUS.h +++ /dev/null @@ -1,61 +0,0 @@ -#ifndef FSFW_TCDISTRIBUTION_TCPACKETCHECKPUS_H_ -#define FSFW_TCDISTRIBUTION_TCPACKETCHECKPUS_H_ - -#include "TcPacketCheckIF.h" -#include "fsfw/FSFW.h" -#include "fsfw/returnvalues/returnvalue.h" -#include "fsfw/tmtcservices/PusVerificationReport.h" - -class TcPacketStoredBase; - -/** - * This class performs a formal packet check for incoming PUS Telecommand Packets. - * Currently, it only checks if the APID and CRC are correct. - * @ingroup tc_distribution - */ -class TcPacketCheckPUS : public TcPacketCheckIF { - protected: - /** - * Describes the version number a packet must have to pass. - */ - static constexpr uint8_t CCSDS_VERSION_NUMBER = 0; - /** - * Describes the secondary header a packet must have to pass. - */ - static constexpr uint8_t CCSDS_SECONDARY_HEADER_FLAG = 0; - /** - * Describes the TC Packet PUS Version Number a packet must have to pass. - */ -#if FSFW_USE_PUS_C_TELECOMMANDS == 1 - static constexpr uint8_t PUS_VERSION_NUMBER = 2; -#else - static constexpr uint8_t PUS_VERSION_NUMBER = 1; -#endif - - /** - * The packet id each correct packet should have. - * It is composed of the APID and some static fields. - */ - uint16_t apid; - - public: - static const uint8_t INTERFACE_ID = CLASS_ID::TC_PACKET_CHECK; - static const ReturnValue_t ILLEGAL_APID = MAKE_RETURN_CODE(0); - static const ReturnValue_t INCOMPLETE_PACKET = MAKE_RETURN_CODE(1); - static const ReturnValue_t INCORRECT_CHECKSUM = MAKE_RETURN_CODE(2); - static const ReturnValue_t ILLEGAL_PACKET_TYPE = MAKE_RETURN_CODE(3); - static const ReturnValue_t ILLEGAL_PACKET_SUBTYPE = MAKE_RETURN_CODE(4); - static const ReturnValue_t INCORRECT_PRIMARY_HEADER = MAKE_RETURN_CODE(5); - static const ReturnValue_t INCORRECT_SECONDARY_HEADER = MAKE_RETURN_CODE(6); - /** - * The constructor only sets the APID attribute. - * @param set_apid The APID to set. - */ - TcPacketCheckPUS(uint16_t setApid); - - ReturnValue_t checkPacket(SpacePacketBase* currentPacket) override; - - uint16_t getApid() const; -}; - -#endif /* FSFW_TCDISTRIBUTION_TCPACKETCHECKPUS_H_ */ diff --git a/src/fsfw/tcdistribution/definitions.h b/src/fsfw/tcdistribution/definitions.h new file mode 100644 index 00000000..3d455077 --- /dev/null +++ b/src/fsfw/tcdistribution/definitions.h @@ -0,0 +1,24 @@ +#ifndef FSFW_TMTCPACKET_DEFINITIONS_H +#define FSFW_TMTCPACKET_DEFINITIONS_H + +#include + +#include "fsfw/returnvalues/FwClassIds.h" +#include "fsfw/returnvalues/returnvalue.h" + +namespace tcdistrib { +static const uint8_t INTERFACE_ID = CLASS_ID::PACKET_CHECK; +static constexpr ReturnValue_t INVALID_CCSDS_VERSION = MAKE_RETURN_CODE(0); +static constexpr ReturnValue_t INVALID_APID = MAKE_RETURN_CODE(1); +static constexpr ReturnValue_t INVALID_PACKET_TYPE = MAKE_RETURN_CODE(2); +static constexpr ReturnValue_t INVALID_SEC_HEADER_FIELD = MAKE_RETURN_CODE(3); +static constexpr ReturnValue_t INCORRECT_PRIMARY_HEADER = MAKE_RETURN_CODE(4); + +static constexpr ReturnValue_t INCOMPLETE_PACKET = MAKE_RETURN_CODE(5); +static constexpr ReturnValue_t INVALID_PUS_VERSION = MAKE_RETURN_CODE(6); +static constexpr ReturnValue_t INCORRECT_CHECKSUM = MAKE_RETURN_CODE(7); +static constexpr ReturnValue_t ILLEGAL_PACKET_SUBTYPE = MAKE_RETURN_CODE(8); +static constexpr ReturnValue_t INCORRECT_SECONDARY_HEADER = MAKE_RETURN_CODE(9); + +}; // namespace tcdistrib +#endif // FSFW_TMTCPACKET_DEFINITIONS_H diff --git a/src/fsfw/thermal/AbstractTemperatureSensor.cpp b/src/fsfw/thermal/AbstractTemperatureSensor.cpp index fc182bf1..7687bd38 100644 --- a/src/fsfw/thermal/AbstractTemperatureSensor.cpp +++ b/src/fsfw/thermal/AbstractTemperatureSensor.cpp @@ -4,14 +4,13 @@ AbstractTemperatureSensor::AbstractTemperatureSensor(object_id_t setObjectid, ThermalModuleIF *thermalModule) - : SystemObject(setObjectid), - commandQueue(NULL), - healthHelper(this, setObjectid), - parameterHelper(this) { - if (thermalModule != NULL) { + : SystemObject(setObjectid), healthHelper(this, setObjectid), parameterHelper(this) { + if (thermalModule != nullptr) { thermalModule->registerSensor(this); } - commandQueue = QueueFactory::instance()->createMessageQueue(); + auto mqArgs = MqArgs(setObjectid, static_cast(this)); + commandQueue = QueueFactory::instance()->createMessageQueue( + 3, MessageQueueMessage::MAX_MESSAGE_SIZE, &mqArgs); } AbstractTemperatureSensor::~AbstractTemperatureSensor() { diff --git a/src/fsfw/thermal/AbstractTemperatureSensor.h b/src/fsfw/thermal/AbstractTemperatureSensor.h index 0c6493fe..b790b0ca 100644 --- a/src/fsfw/thermal/AbstractTemperatureSensor.h +++ b/src/fsfw/thermal/AbstractTemperatureSensor.h @@ -51,7 +51,7 @@ class AbstractTemperatureSensor : public HasHealthIF, HasHealthIF::HealthState getHealth(); protected: - MessageQueueIF* commandQueue; + MessageQueueIF* commandQueue = nullptr; HealthHelper healthHelper; ParameterHelper parameterHelper; diff --git a/src/fsfw/thermal/Heater.cpp b/src/fsfw/thermal/Heater.cpp index 64348106..04abadc7 100644 --- a/src/fsfw/thermal/Heater.cpp +++ b/src/fsfw/thermal/Heater.cpp @@ -12,7 +12,9 @@ Heater::Heater(uint32_t objectId, uint8_t switch0, uint8_t switch1) switch1(switch1), heaterOnCountdown(10800000) /*about two orbits*/, parameterHelper(this) { - eventQueue = QueueFactory::instance()->createMessageQueue(); + auto mqArgs = MqArgs(objectId, static_cast(this)); + eventQueue = QueueFactory::instance()->createMessageQueue( + 3, MessageQueueMessage::MAX_MESSAGE_SIZE, &mqArgs); } Heater::~Heater() { QueueFactory::instance()->deleteMessageQueue(eventQueue); } diff --git a/src/fsfw/thermal/ThermalComponentIF.h b/src/fsfw/thermal/ThermalComponentIF.h index 0ab22d85..023d7758 100644 --- a/src/fsfw/thermal/ThermalComponentIF.h +++ b/src/fsfw/thermal/ThermalComponentIF.h @@ -13,9 +13,9 @@ class ThermalComponentIF : public HasParametersIF { static const Event COMPONENT_TEMP_HIGH = MAKE_EVENT(2, severity::LOW); static const Event COMPONENT_TEMP_OOL_LOW = MAKE_EVENT(3, severity::LOW); static const Event COMPONENT_TEMP_OOL_HIGH = MAKE_EVENT(4, severity::LOW); - static const Event TEMP_NOT_IN_OP_RANGE = MAKE_EVENT( - 5, severity::LOW); //!< Is thrown when a device should start-up, but the temperature is out - //!< of OP range. P1: thermalState of the component, P2: 0 + //!< Is thrown when a device should start-up, but the temperature is out + //!< of OP range. P1: thermalState of the component, P2: 0 + static const Event TEMP_NOT_IN_OP_RANGE = MAKE_EVENT(5, severity::LOW); static const uint8_t INTERFACE_ID = CLASS_ID::THERMAL_COMPONENT_IF; static const ReturnValue_t INVALID_TARGET_STATE = MAKE_RETURN_CODE(1); diff --git a/src/fsfw/timemanager/CCSDSTime.cpp b/src/fsfw/timemanager/CCSDSTime.cpp index 5e035d67..cb0d5758 100644 --- a/src/fsfw/timemanager/CCSDSTime.cpp +++ b/src/fsfw/timemanager/CCSDSTime.cpp @@ -504,7 +504,7 @@ ReturnValue_t CCSDSTime::convertFromCDS(timeval* to, const uint8_t* from, size_t } else if ((pField & 0b11) == 0b10) { expectedLength += 4; } - if (foundLength != NULL) { + if (foundLength != nullptr) { *foundLength = expectedLength; } if (expectedLength > maxLength) { diff --git a/src/fsfw/timemanager/CCSDSTime.h b/src/fsfw/timemanager/CCSDSTime.h index c52d7e87..77801cec 100644 --- a/src/fsfw/timemanager/CCSDSTime.h +++ b/src/fsfw/timemanager/CCSDSTime.h @@ -6,9 +6,9 @@ #include #include -#include "../returnvalues/returnvalue.h" #include "Clock.h" #include "clockDefinitions.h" +#include "fsfw/returnvalues/returnvalue.h" bool operator<(const timeval &lhs, const timeval &rhs); bool operator<=(const timeval &lhs, const timeval &rhs); @@ -39,13 +39,13 @@ class CCSDSTime { * Struct for CDS day-segmented format. */ struct CDS_short { - uint8_t pField; - uint8_t dayMSB; - uint8_t dayLSB; - uint8_t msDay_hh; - uint8_t msDay_h; - uint8_t msDay_l; - uint8_t msDay_ll; + uint8_t pField = P_FIELD_CDS_SHORT; + uint8_t dayMSB = 0; + uint8_t dayLSB = 0; + uint8_t msDay_hh = 0; + uint8_t msDay_h = 0; + uint8_t msDay_l = 0; + uint8_t msDay_ll = 0; }; /** * Struct for the CCS fromat in day of month variation with max resolution diff --git a/src/fsfw/timemanager/CMakeLists.txt b/src/fsfw/timemanager/CMakeLists.txt index c4f77395..7e38cc6a 100644 --- a/src/fsfw/timemanager/CMakeLists.txt +++ b/src/fsfw/timemanager/CMakeLists.txt @@ -1,3 +1,4 @@ target_sources( - ${LIB_FSFW_NAME} PRIVATE CCSDSTime.cpp Countdown.cpp Stopwatch.cpp - TimeMessage.cpp TimeStamper.cpp ClockCommon.cpp) + ${LIB_FSFW_NAME} + PRIVATE CCSDSTime.cpp Countdown.cpp Stopwatch.cpp TimeMessage.cpp + CdsShortTimeStamper.cpp ClockCommon.cpp) diff --git a/src/fsfw/timemanager/CcsdsTimeStampReader.cpp b/src/fsfw/timemanager/CcsdsTimeStampReader.cpp new file mode 100644 index 00000000..d23d0387 --- /dev/null +++ b/src/fsfw/timemanager/CcsdsTimeStampReader.cpp @@ -0,0 +1,14 @@ +#include "CcsdsTimeStampReader.h" + +#include "CCSDSTime.h" + +ReturnValue_t CcsdsTimestampReader::readTimeStamp(const uint8_t* buffer, uint8_t maxSize) { + ReturnValue_t result = CCSDSTime::convertFromCcsds(&time, buffer, ×tampLen, maxSize); + if (result != HasReturnvaluesIF::RETURN_OK) { + return result; + } + return result; +} + +timeval& CcsdsTimestampReader::getTime() { return time; } +size_t CcsdsTimestampReader::getTimestampLen() { return timestampLen; } diff --git a/src/fsfw/timemanager/CcsdsTimeStampReader.h b/src/fsfw/timemanager/CcsdsTimeStampReader.h new file mode 100644 index 00000000..0bec2553 --- /dev/null +++ b/src/fsfw/timemanager/CcsdsTimeStampReader.h @@ -0,0 +1,17 @@ +#ifndef FSFW_TIMEMANAGER_CCSDSTIMESTAMPREADER_H +#define FSFW_TIMEMANAGER_CCSDSTIMESTAMPREADER_H + +#include + +#include "TimeReaderIF.h" + +class CcsdsTimestampReader : public TimeReaderIF { + public: + timeval& getTime() override; + + private: + timeval time{}; + size_t timestampLen = 0; +}; + +#endif // FSFW_TIMEMANAGER_CCSDSTIMESTAMPREADER_H diff --git a/src/fsfw/timemanager/CdsShortTimeStamper.cpp b/src/fsfw/timemanager/CdsShortTimeStamper.cpp new file mode 100644 index 00000000..8095e28d --- /dev/null +++ b/src/fsfw/timemanager/CdsShortTimeStamper.cpp @@ -0,0 +1,49 @@ +#include "fsfw/timemanager/CdsShortTimeStamper.h" + +#include + +#include "fsfw/timemanager/Clock.h" + +CdsShortTimeStamper::CdsShortTimeStamper(object_id_t objectId) : SystemObject(objectId) {} + +ReturnValue_t CdsShortTimeStamper::addTimeStamp(uint8_t *buffer, const uint8_t maxSize) { + size_t serLen = 0; + return serialize(&buffer, &serLen, maxSize, SerializeIF::Endianness::NETWORK); +} + +ReturnValue_t CdsShortTimeStamper::serialize(uint8_t **buffer, size_t *size, size_t maxSize, + SerializeIF::Endianness streamEndianness) const { + if (*size + getSerializedSize() > maxSize) { + return SerializeIF::BUFFER_TOO_SHORT; + } + timeval now{}; + Clock::getClock_timeval(&now); + CCSDSTime::CDS_short cds{}; + ReturnValue_t result = CCSDSTime::convertToCcsds(&cds, &now); + if (result != returnvalue::OK) { + return result; + } + std::memcpy(*buffer, &cds, sizeof(cds)); + *buffer += getSerializedSize(); + *size += getSerializedSize(); + return result; +} + +size_t CdsShortTimeStamper::getSerializedSize() const { return getTimestampSize(); } + +ReturnValue_t CdsShortTimeStamper::deSerialize(const uint8_t **buffer, size_t *size, + SerializeIF::Endianness streamEndianness) { + return returnvalue::FAILED; +} + +ReturnValue_t CdsShortTimeStamper::readTimeStamp(const uint8_t *buffer, size_t maxSize) { + if (maxSize < getTimestampSize()) { + return SerializeIF::STREAM_TOO_SHORT; + } + size_t foundLen = 0; + return CCSDSTime::convertFromCcsds(&readTime, buffer, &foundLen, maxSize); +} + +timeval &CdsShortTimeStamper::getTime() { return readTime; } + +size_t CdsShortTimeStamper::getTimestampSize() const { return TIMESTAMP_LEN; } diff --git a/src/fsfw/timemanager/TimeStamper.h b/src/fsfw/timemanager/CdsShortTimeStamper.h similarity index 50% rename from src/fsfw/timemanager/TimeStamper.h rename to src/fsfw/timemanager/CdsShortTimeStamper.h index aa311ec4..4b1f6c28 100644 --- a/src/fsfw/timemanager/TimeStamper.h +++ b/src/fsfw/timemanager/CdsShortTimeStamper.h @@ -1,9 +1,10 @@ #ifndef FSFW_TIMEMANAGER_TIMESTAMPER_H_ #define FSFW_TIMEMANAGER_TIMESTAMPER_H_ -#include "../objectmanager/SystemObject.h" #include "CCSDSTime.h" +#include "TimeReaderIF.h" #include "TimeStamperIF.h" +#include "fsfw/objectmanager/SystemObject.h" /** * @brief Time stamper which can be used to add any timestamp to a @@ -14,14 +15,15 @@ * overriding the #addTimeStamp function. * @ingroup utility */ -class TimeStamper : public TimeStamperIF, public SystemObject { +class CdsShortTimeStamper : public TimeStamperIF, public TimeReaderIF, public SystemObject { public: + static constexpr size_t TIMESTAMP_LEN = 7; /** * @brief Default constructor which also registers the time stamper as a * system object so it can be found with the #objectManager. * @param objectId */ - TimeStamper(object_id_t objectId); + explicit CdsShortTimeStamper(object_id_t objectId); /** * Adds a CCSDS CDC short 8 byte timestamp to the given buffer. @@ -30,7 +32,18 @@ class TimeStamper : public TimeStamperIF, public SystemObject { * @param maxSize * @return */ - virtual ReturnValue_t addTimeStamp(uint8_t* buffer, const uint8_t maxSize); + ReturnValue_t addTimeStamp(uint8_t *buffer, uint8_t maxSize) override; + ReturnValue_t serialize(uint8_t **buffer, size_t *size, size_t maxSize, + Endianness streamEndianness) const override; + [[nodiscard]] size_t getSerializedSize() const override; + ReturnValue_t deSerialize(const uint8_t **buffer, size_t *size, + Endianness streamEndianness) override; + ReturnValue_t readTimeStamp(const uint8_t *buffer, size_t maxSize) override; + timeval &getTime() override; + [[nodiscard]] size_t getTimestampSize() const override; + + private: + timeval readTime{}; }; #endif /* FSFW_TIMEMANAGER_TIMESTAMPER_H_ */ diff --git a/src/fsfw/timemanager/Clock.h b/src/fsfw/timemanager/Clock.h index 88436b8b..83bc3d9f 100644 --- a/src/fsfw/timemanager/Clock.h +++ b/src/fsfw/timemanager/Clock.h @@ -11,7 +11,7 @@ #ifdef WIN32 #include #else -#include +#include #endif class Clock { @@ -33,7 +33,7 @@ class Clock { * * @deprecated, we should not worry about ticks, but only time */ - static uint32_t getTicksPerSecond(void); + static uint32_t getTicksPerSecond(); /** * This system call sets the system time. * To set the time, it uses a TimeOfDay_t struct. @@ -148,7 +148,7 @@ class Clock { * @return * - @c returnvalue::OK on success. */ - static ReturnValue_t setLeapSeconds(const uint16_t leapSeconds_); + static ReturnValue_t setLeapSeconds(uint16_t leapSeconds_); /** * Get the Leap Seconds since 1972 diff --git a/src/fsfw/timemanager/Countdown.cpp b/src/fsfw/timemanager/Countdown.cpp index a8ba78cb..334883ae 100644 --- a/src/fsfw/timemanager/Countdown.cpp +++ b/src/fsfw/timemanager/Countdown.cpp @@ -1,7 +1,11 @@ #include "fsfw/timemanager/Countdown.h" -Countdown::Countdown(uint32_t initialTimeout) : timeout(initialTimeout) { - setTimeout(initialTimeout); +Countdown::Countdown(uint32_t initialTimeout, bool startImmediately) : timeout(initialTimeout) { + if (startImmediately) { + setTimeout(initialTimeout); + } else { + timeout = initialTimeout; + } } Countdown::~Countdown() {} diff --git a/src/fsfw/timemanager/Countdown.h b/src/fsfw/timemanager/Countdown.h index 44be2b1a..26534789 100644 --- a/src/fsfw/timemanager/Countdown.h +++ b/src/fsfw/timemanager/Countdown.h @@ -26,8 +26,9 @@ class Countdown { * Otherwise a call to hasTimedOut might return True. * * @param initialTimeout Countdown duration in milliseconds + * @param startImmediately Set to false if countdown should not be started immediately */ - Countdown(uint32_t initialTimeout = 0); + Countdown(uint32_t initialTimeout = 0, bool startImmediately = true); ~Countdown(); /** * Call to set a new countdown duration. diff --git a/src/fsfw/timemanager/ReceivesTimeInfoIF.h b/src/fsfw/timemanager/ReceivesTimeInfoIF.h index 5fb915ae..a6067a33 100644 --- a/src/fsfw/timemanager/ReceivesTimeInfoIF.h +++ b/src/fsfw/timemanager/ReceivesTimeInfoIF.h @@ -1,7 +1,7 @@ #ifndef FSFW_TIMEMANAGER_RECEIVESTIMEINFOIF_H_ #define FSFW_TIMEMANAGER_RECEIVESTIMEINFOIF_H_ -#include "../ipc/MessageQueueSenderIF.h" +#include "fsfw/ipc/MessageQueueSenderIF.h" /** * This is a Interface for classes that receive timing information @@ -13,11 +13,11 @@ class ReceivesTimeInfoIF { * Returns the id of the queue which receives the timing information. * @return Queue id of the timing queue. */ - virtual MessageQueueId_t getTimeReceptionQueue() const = 0; + [[nodiscard]] virtual MessageQueueId_t getTimeReceptionQueue() const = 0; /** * Empty virtual destructor. */ - virtual ~ReceivesTimeInfoIF() {} + virtual ~ReceivesTimeInfoIF() = default; }; #endif /* FSFW_TIMEMANAGER_RECEIVESTIMEINFOIF_H_ */ diff --git a/src/fsfw/timemanager/TimeMessage.h b/src/fsfw/timemanager/TimeMessage.h index ae4a9caf..62833036 100644 --- a/src/fsfw/timemanager/TimeMessage.h +++ b/src/fsfw/timemanager/TimeMessage.h @@ -3,8 +3,8 @@ #include -#include "../ipc/MessageQueueMessage.h" #include "Clock.h" +#include "fsfw/ipc/MessageQueueMessage.h" class TimeMessage : public MessageQueueMessage { protected: diff --git a/src/fsfw/timemanager/TimeReaderIF.h b/src/fsfw/timemanager/TimeReaderIF.h new file mode 100644 index 00000000..a3343e1c --- /dev/null +++ b/src/fsfw/timemanager/TimeReaderIF.h @@ -0,0 +1,16 @@ +#ifndef FSFW_TIMEMANAGER_TIMEREADERIF_H +#define FSFW_TIMEMANAGER_TIMEREADERIF_H + +#include + +#include "TimeStampIF.h" +#include "fsfw/returnvalues/returnvalue.h" + +class TimeReaderIF : public TimeStampIF { + public: + ~TimeReaderIF() override = default; + virtual ReturnValue_t readTimeStamp(const uint8_t* buffer, size_t maxSize) = 0; + virtual timeval& getTime() = 0; +}; + +#endif // FSFW_TIMEMANAGER_TIMEREADERIF_H diff --git a/src/fsfw/timemanager/TimeStampIF.h b/src/fsfw/timemanager/TimeStampIF.h new file mode 100644 index 00000000..805cf3b1 --- /dev/null +++ b/src/fsfw/timemanager/TimeStampIF.h @@ -0,0 +1,20 @@ +#ifndef FSFW_TIMEMANAGER_TIMESTAMPIF_H +#define FSFW_TIMEMANAGER_TIMESTAMPIF_H + +#include + +#include "fsfw/retval.h" + +class TimeStampIF { + public: + static const uint8_t INTERFACE_ID = CLASS_ID::TIME_STAMPER_IF; + static const ReturnValue_t BAD_TIMESTAMP = MAKE_RETURN_CODE(1); + + // I am going to assume there are no larger timestamps + static constexpr size_t MAXIMUM_TIMESTAMP_LEN = 16; + + virtual ~TimeStampIF() = default; + [[nodiscard]] virtual size_t getTimestampSize() const = 0; +}; + +#endif // FSFW_TIMEMANAGER_TIMESTAMPIF_H diff --git a/src/fsfw/timemanager/TimeStamper.cpp b/src/fsfw/timemanager/TimeStamper.cpp deleted file mode 100644 index 99cbdd70..00000000 --- a/src/fsfw/timemanager/TimeStamper.cpp +++ /dev/null @@ -1,23 +0,0 @@ -#include "fsfw/timemanager/TimeStamper.h" - -#include - -#include "fsfw/timemanager/Clock.h" - -TimeStamper::TimeStamper(object_id_t objectId) : SystemObject(objectId) {} - -ReturnValue_t TimeStamper::addTimeStamp(uint8_t* buffer, const uint8_t maxSize) { - if (maxSize < TimeStamperIF::MISSION_TIMESTAMP_SIZE) { - return returnvalue::FAILED; - } - - timeval now; - Clock::getClock_timeval(&now); - CCSDSTime::CDS_short cds; - ReturnValue_t result = CCSDSTime::convertToCcsds(&cds, &now); - if (result != returnvalue::OK) { - return result; - } - std::memcpy(buffer, &cds, sizeof(cds)); - return result; -} diff --git a/src/fsfw/timemanager/TimeStamperIF.h b/src/fsfw/timemanager/TimeStamperIF.h index 92577943..9085c067 100644 --- a/src/fsfw/timemanager/TimeStamperIF.h +++ b/src/fsfw/timemanager/TimeStamperIF.h @@ -1,9 +1,9 @@ #ifndef FSFW_TIMEMANAGER_TIMESTAMPERIF_H_ #define FSFW_TIMEMANAGER_TIMESTAMPERIF_H_ -#include - -#include "../returnvalues/returnvalue.h" +#include "TimeStampIF.h" +#include "fsfw/returnvalues/returnvalue.h" +#include "fsfw/serialize/SerializeIF.h" /** * A class implementing this IF provides facilities to add a time stamp to the @@ -11,17 +11,13 @@ * Implementors need to ensure that calling the method is thread-safe, i.e. * addTimeStamp may be called in parallel from a different context. */ -class TimeStamperIF { +class TimeStamperIF : public SerializeIF, public TimeStampIF { public: - static const uint8_t INTERFACE_ID = CLASS_ID::TIME_STAMPER_IF; - static const ReturnValue_t BAD_TIMESTAMP = MAKE_RETURN_CODE(1); + virtual ReturnValue_t addTimeStamp(uint8_t* buffer, uint8_t maxSize) = 0; + ~TimeStamperIF() override = default; + size_t getTimestampSize() const override { return getSerializedSize(); } - //! This is a mission-specific constant and determines the total - //! size reserved for timestamps. - static const uint8_t MISSION_TIMESTAMP_SIZE = fsfwconfig::FSFW_MISSION_TIMESTAMP_SIZE; - - virtual ReturnValue_t addTimeStamp(uint8_t* buffer, const uint8_t maxSize) = 0; - virtual ~TimeStamperIF() {} + protected: }; #endif /* FSFW_TIMEMANAGER_TIMESTAMPERIF_H_ */ diff --git a/src/fsfw/tmstorage/TmStoreBackendIF.h b/src/fsfw/tmstorage/TmStoreBackendIF.h index 84c94f77..cd0149c5 100644 --- a/src/fsfw/tmstorage/TmStoreBackendIF.h +++ b/src/fsfw/tmstorage/TmStoreBackendIF.h @@ -33,50 +33,47 @@ class TmStoreBackendIF : public HasParametersIF { static const ReturnValue_t INVALID_REQUEST = MAKE_RETURN_CODE(15); static const uint8_t SUBSYSTEM_ID = SUBSYSTEM_ID::MEMORY; - static const Event STORE_SEND_WRITE_FAILED = - MAKE_EVENT(0, severity::LOW); //!< Initiating sending data to store failed. Low, par1: - //!< returnCode, par2: integer (debug info) - static const Event STORE_WRITE_FAILED = MAKE_EVENT( - 1, severity::LOW); //!< Data was sent, but writing failed. Low, par1: returnCode, par2: 0 - static const Event STORE_SEND_READ_FAILED = - MAKE_EVENT(2, severity::LOW); //!< Initiating reading data from store failed. Low, par1: - //!< returnCode, par2: 0 - static const Event STORE_READ_FAILED = MAKE_EVENT( - 3, severity::LOW); //!< Data was requested, but access failed. Low, par1: returnCode, par2: 0 - static const Event UNEXPECTED_MSG = - MAKE_EVENT(4, severity::LOW); //!< An unexpected TM packet or data message occurred. Low, - //!< par1: 0, par2: integer (debug info) - static const Event STORING_FAILED = MAKE_EVENT( - 5, severity::LOW); //!< Storing data failed. May simply be a full store. Low, par1: - //!< returnCode, par2: integer (sequence count of failed packet). - static const Event TM_DUMP_FAILED = - MAKE_EVENT(6, severity::LOW); //!< Dumping retrieved data failed. Low, par1: returnCode, - //!< par2: integer (sequence count of failed packet). - static const Event STORE_INIT_FAILED = - MAKE_EVENT(7, severity::LOW); //!< Corrupted init data or read error. Low, par1: returnCode, - //!< par2: integer (debug info) - static const Event STORE_INIT_EMPTY = MAKE_EVENT( - 8, severity::INFO); //!< Store was not initialized. Starts empty. Info, parameters both zero. - static const Event STORE_CONTENT_CORRUPTED = - MAKE_EVENT(9, severity::LOW); //!< Data was read out, but it is inconsistent. Low par1: - //!< Memory address of corruption, par2: integer (debug info) - static const Event STORE_INITIALIZE = - MAKE_EVENT(10, severity::INFO); //!< Info event indicating the store will be initialized, - //!< either at boot or after IOB switch. Info. pars: 0 - static const Event INIT_DONE = MAKE_EVENT( - 11, severity::INFO); //!< Info event indicating the store was successfully initialized, - //!< either at boot or after IOB switch. Info. pars: 0 - static const Event DUMP_FINISHED = MAKE_EVENT( - 12, severity::INFO); //!< Info event indicating that dumping finished successfully. par1: - //!< Number of dumped packets. par2: APID/SSC (16bits each) - static const Event DELETION_FINISHED = MAKE_EVENT( - 13, severity::INFO); //!< Info event indicating that deletion finished successfully. par1: - //!< Number of deleted packets. par2: APID/SSC (16bits each) - static const Event DELETION_FAILED = MAKE_EVENT( - 14, - severity::LOW); //!< Info event indicating that something went wrong during deletion. pars: 0 - static const Event AUTO_CATALOGS_SENDING_FAILED = - MAKE_EVENT(15, severity::INFO); //!< Info that the a auto catalog report failed + //! Initiating sending data to store failed. Low, par1: + //! returnCode, par2: integer (debug info) + static const Event STORE_SEND_WRITE_FAILED = MAKE_EVENT(0, severity::LOW); + //! Data was sent, but writing failed. Low, par1: returnCode, par2: 0 + static const Event STORE_WRITE_FAILED = MAKE_EVENT(1, severity::LOW); + //! Initiating reading data from store failed. Low, par1: returnCode, par2: 0 + static const Event STORE_SEND_READ_FAILED = MAKE_EVENT(2, severity::LOW); + //! Data was requested, but access failed. Low, par1: returnCode, par2: 0 + static const Event STORE_READ_FAILED = MAKE_EVENT(3, severity::LOW); + //! An unexpected TM packet or data message occurred. Low, par1: 0, par2: integer (debug info) + static const Event UNEXPECTED_MSG = MAKE_EVENT(4, severity::LOW); + //! Storing data failed. May simply be a full store. Low, par1: returnCode, + //! par2: integer (sequence count of failed packet). + static const Event STORING_FAILED = MAKE_EVENT(5, severity::LOW); + //! Dumping retrieved data failed. Low, par1: returnCode, + //! par2: integer (sequence count of failed packet). + static const Event TM_DUMP_FAILED = MAKE_EVENT(6, severity::LOW); + //! Corrupted init data or read error. Low, par1: returnCode, par2: integer (debug info) + //! Store was not initialized. Starts empty. Info, parameters both zero. + static const Event STORE_INIT_FAILED = MAKE_EVENT(7, severity::LOW); + //! Data was read out, but it is inconsistent. Low par1: + //! Memory address of corruption, par2: integer (debug info) + static const Event STORE_INIT_EMPTY = MAKE_EVENT(8, severity::INFO); + + static const Event STORE_CONTENT_CORRUPTED = MAKE_EVENT(9, severity::LOW); + //! Info event indicating the store will be initialized, either at boot or after IOB switch. + //! Info. pars: 0 + static const Event STORE_INITIALIZE = MAKE_EVENT(10, severity::INFO); + //! Info event indicating the store was successfully initialized, either at boot or after + //! IOB switch. Info. pars: 0 + static const Event INIT_DONE = MAKE_EVENT(11, severity::INFO); + //! Info event indicating that dumping finished successfully. + //! par1: Number of dumped packets. par2: APID/SSC (16bits each) + static const Event DUMP_FINISHED = MAKE_EVENT(12, severity::INFO); + //! Info event indicating that deletion finished successfully. + //! par1:Number of deleted packets. par2: APID/SSC (16bits each) + static const Event DELETION_FINISHED = MAKE_EVENT(13, severity::INFO); + //! Info event indicating that something went wrong during deletion. pars: 0 + static const Event DELETION_FAILED = MAKE_EVENT(14, severity::LOW); + //! Info that the a auto catalog report failed + static const Event AUTO_CATALOGS_SENDING_FAILED = MAKE_EVENT(15, severity::INFO); virtual ~TmStoreBackendIF() {} diff --git a/src/fsfw/tmstorage/TmStorePackets.h b/src/fsfw/tmstorage/TmStorePackets.h index 8a2dfaf3..a5d2f5a0 100644 --- a/src/fsfw/tmstorage/TmStorePackets.h +++ b/src/fsfw/tmstorage/TmStorePackets.h @@ -8,7 +8,7 @@ #include "fsfw/serialize/SerializeElement.h" #include "fsfw/timemanager/CCSDSTime.h" #include "fsfw/timemanager/TimeStamperIF.h" -#include "fsfw/tmtcpacket/pus/tm/TmPacketMinimal.h" +#include "fsfw/tmtcpacket/pus/tm/PusTmMinimal.h" #include "tmStorageConf.h" class ServiceSubservice : public SerialLinkedListAdapter { diff --git a/src/fsfw/tmtcpacket/CMakeLists.txt b/src/fsfw/tmtcpacket/CMakeLists.txt index 196ba752..e1b54efe 100644 --- a/src/fsfw/tmtcpacket/CMakeLists.txt +++ b/src/fsfw/tmtcpacket/CMakeLists.txt @@ -1,5 +1,4 @@ -target_sources(${LIB_FSFW_NAME} PRIVATE SpacePacket.cpp SpacePacketBase.cpp) - +add_subdirectory(ccsds) +add_subdirectory(pus) add_subdirectory(cfdp) add_subdirectory(packetmatcher) -add_subdirectory(pus) diff --git a/src/fsfw/tmtcpacket/ReadablePacketIF.h b/src/fsfw/tmtcpacket/ReadablePacketIF.h new file mode 100644 index 00000000..4f2f09e8 --- /dev/null +++ b/src/fsfw/tmtcpacket/ReadablePacketIF.h @@ -0,0 +1,15 @@ +#ifndef FSFW_TMTCPACKET_SPACEPACKETREADERIF_H +#define FSFW_TMTCPACKET_SPACEPACKETREADERIF_H + +#include "fsfw/tmtcpacket/ccsds/SpacePacketIF.h" + +class ReadablePacketIF { + public: + virtual ~ReadablePacketIF() = default; + + /** + * This method returns a raw uint8_t pointer to the readable data + */ + [[nodiscard]] virtual const uint8_t* getFullData() const = 0; +}; +#endif // FSFW_TMTCPACKET_SPACEPACKETREADERIF_H diff --git a/src/fsfw/tmtcpacket/RedirectableDataPointerIF.h b/src/fsfw/tmtcpacket/RedirectableDataPointerIF.h index 13eec711..52b3df0a 100644 --- a/src/fsfw/tmtcpacket/RedirectableDataPointerIF.h +++ b/src/fsfw/tmtcpacket/RedirectableDataPointerIF.h @@ -11,7 +11,7 @@ */ class RedirectableDataPointerIF { public: - virtual ~RedirectableDataPointerIF(){}; + virtual ~RedirectableDataPointerIF() = default; /** * Redirect the data pointer, but allow an implementation to change the data. @@ -25,9 +25,12 @@ class RedirectableDataPointerIF { * - returnvalue::OK if the pointer was set successfully * - returnvalue::FAILED on general error of if the maximum size is too small */ - virtual ReturnValue_t setData(uint8_t* dataPtr, size_t maxSize, void* args = nullptr) = 0; + virtual ReturnValue_t setData(uint8_t* dataPtr, size_t size, void* args) = 0; + virtual ReturnValue_t setData(uint8_t* dataPtr, size_t size) { + return setData(dataPtr, size, nullptr); + } private: }; -#endif /* FSFW_SRC_FSFW_TMTCPACKET_PUS_TC_SETTABLEDATAPOINTERIF_H_ */ +#endif /* TMTCPACKET_PUS_TC_SETTABLEDATAPOINTERIF_H_ */ diff --git a/src/fsfw/tmtcpacket/SpacePacket.cpp b/src/fsfw/tmtcpacket/SpacePacket.cpp deleted file mode 100644 index 16d968fb..00000000 --- a/src/fsfw/tmtcpacket/SpacePacket.cpp +++ /dev/null @@ -1,28 +0,0 @@ -#include "fsfw/tmtcpacket/SpacePacket.h" - -#include - -#include "fsfw/tmtcpacket/ccsds_header.h" - -SpacePacket::SpacePacket(uint16_t packetDataLength, bool isTelecommand, uint16_t apid, - uint16_t sequenceCount) - : SpacePacketBase((uint8_t*)&this->localData) { - initSpacePacketHeader(isTelecommand, false, apid, sequenceCount); - this->setPacketSequenceCount(sequenceCount); - if (packetDataLength <= sizeof(this->localData.fields.buffer)) { - this->setPacketDataLength(packetDataLength); - } else { - this->setPacketDataLength(sizeof(this->localData.fields.buffer)); - } -} - -SpacePacket::~SpacePacket(void) {} - -bool SpacePacket::addWholeData(const uint8_t* p_Data, uint32_t packet_size) { - if (packet_size <= sizeof(this->localData)) { - memcpy(this->localData.byteStream, p_Data, packet_size); - return true; - } else { - return false; - } -} diff --git a/src/fsfw/tmtcpacket/SpacePacket.h b/src/fsfw/tmtcpacket/SpacePacket.h deleted file mode 100644 index 10140db1..00000000 --- a/src/fsfw/tmtcpacket/SpacePacket.h +++ /dev/null @@ -1,89 +0,0 @@ -#ifndef SPACEPACKET_H_ -#define SPACEPACKET_H_ - -#include "SpacePacketBase.h" - -/** - * The SpacePacket class is a representation of a simple CCSDS Space Packet - * without (control over) a secondary header. - * It can be instantiated with a size smaller than \c PACKET_MAX_SIZE. Its - * main use is to serve as an idle packet in case no other packets are sent. - * For the ECSS PUS part the TcPacket and TmPacket classes are used. - * A pointer to \c local_data is passed to the \c SpacePacketBase parent class, - * so the parent's methods are reachable. - * @ingroup tmtcpackets - */ -class SpacePacket : public SpacePacketBase { - public: - static const uint16_t PACKET_MAX_SIZE = 1024; - /** - * The constructor initializes the packet and sets all header information - * according to the passed parameters. - * @param packetDataLength Sets the packet data length field and therefore specifies - * the size of the packet. - * @param isTelecommand Sets the packet type field to either TC (true) or TM (false). - * @param apid Sets the packet's APID field. The default value describes an idle packet. - * @param sequenceCount ets the packet's Source Sequence Count field. - */ - SpacePacket(uint16_t packetDataLength, bool isTelecommand = false, - uint16_t apid = APID_IDLE_PACKET, uint16_t sequenceCount = 0); - /** - * The class's default destructor. - */ - virtual ~SpacePacket(); - /** - * With this call, the complete data content (including the CCSDS Primary - * Header) is overwritten with the byte stream given. - * @param p_data Pointer to data to overwrite the content with - * @param packet_size Size of the data - * @return @li \c true if packet_size is smaller than \c MAX_PACKET_SIZE. - * @li \c false else. - */ - bool addWholeData(const uint8_t* p_data, uint32_t packet_size); - - protected: - /** - * This structure defines the data structure of a Space Packet as local data. - * There's a buffer which corresponds to the Space Packet Data Field with a - * maximum size of \c PACKET_MAX_SIZE. - */ - struct PacketStructured { - CCSDSPrimaryHeader header; - uint8_t buffer[PACKET_MAX_SIZE]; - }; - /** - * This union simplifies accessing the full data content of the Space Packet. - * This is achieved by putting the \c PacketStructured struct in a union with - * a plain buffer. - */ - union SpacePacketData { - PacketStructured fields; - uint8_t byteStream[PACKET_MAX_SIZE + sizeof(CCSDSPrimaryHeader)]; - }; - /** - * This is the data representation of the class. - * It is a struct of CCSDS Primary Header and a data field, which again is - * packed in an union, so the data can be accessed as a byte stream without - * a cast. - */ - SpacePacketData localData; -}; - -namespace spacepacket { - -constexpr uint16_t getSpacePacketIdFromApid(bool isTc, uint16_t apid, - bool secondaryHeaderFlag = true) { - return ((isTc << 4) | (secondaryHeaderFlag << 3) | ((apid >> 8) & 0x07)) << 8 | (apid & 0x00ff); -} - -constexpr uint16_t getTcSpacePacketIdFromApid(uint16_t apid, bool secondaryHeaderFlag = true) { - return getSpacePacketIdFromApid(true, apid, secondaryHeaderFlag); -} - -constexpr uint16_t getTmSpacePacketIdFromApid(uint16_t apid, bool secondaryHeaderFlag = true) { - return getSpacePacketIdFromApid(false, apid, secondaryHeaderFlag); -} - -} // namespace spacepacket - -#endif /* SPACEPACKET_H_ */ diff --git a/src/fsfw/tmtcpacket/SpacePacketBase.cpp b/src/fsfw/tmtcpacket/SpacePacketBase.cpp deleted file mode 100644 index e02417d8..00000000 --- a/src/fsfw/tmtcpacket/SpacePacketBase.cpp +++ /dev/null @@ -1,118 +0,0 @@ -#include "fsfw/tmtcpacket/SpacePacketBase.h" - -#include - -#include "fsfw/serviceinterface/ServiceInterface.h" - -SpacePacketBase::SpacePacketBase(const uint8_t* setAddress) { - this->data = reinterpret_cast(const_cast(setAddress)); -} - -SpacePacketBase::~SpacePacketBase(){}; - -// CCSDS Methods: -uint8_t SpacePacketBase::getPacketVersionNumber(void) { - return (this->data->header.packet_id_h & 0b11100000) >> 5; -} - -ReturnValue_t SpacePacketBase::initSpacePacketHeader(bool isTelecommand, bool hasSecondaryHeader, - uint16_t apid, uint16_t sequenceCount) { - if (data == nullptr) { -#if FSFW_VERBOSE_LEVEL >= 1 -#if FSFW_CPP_OSTREAM_ENABLED == 1 - sif::warning << "SpacePacketBase::initSpacePacketHeader: Data pointer is invalid" << std::endl; -#else - sif::printWarning("SpacePacketBase::initSpacePacketHeader: Data pointer is invalid!\n"); -#endif -#endif - return returnvalue::FAILED; - } - // reset header to zero: - memset(data, 0, sizeof(this->data->header)); - // Set TC/TM bit. - data->header.packet_id_h = ((isTelecommand ? 1 : 0)) << 4; - // Set secondaryHeader bit - data->header.packet_id_h |= ((hasSecondaryHeader ? 1 : 0)) << 3; - this->setAPID(apid); - // Always initialize as standalone packets. - data->header.sequence_control_h = 0b11000000; - setPacketSequenceCount(sequenceCount); - return returnvalue::OK; -} - -bool SpacePacketBase::isTelecommand(void) { - return (this->data->header.packet_id_h & 0b00010000) >> 4; -} - -bool SpacePacketBase::hasSecondaryHeader(void) { - return (this->data->header.packet_id_h & 0b00001000) >> 3; -} - -uint16_t SpacePacketBase::getPacketId() { - return ((this->data->header.packet_id_h) << 8) + this->data->header.packet_id_l; -} - -uint16_t SpacePacketBase::getAPID(void) const { - return ((this->data->header.packet_id_h & 0b00000111) << 8) + this->data->header.packet_id_l; -} - -void SpacePacketBase::setAPID(uint16_t new_apid) { - // Use first three bits of new APID, but keep rest of packet id as it was (see specification). - this->data->header.packet_id_h = - (this->data->header.packet_id_h & 0b11111000) | ((new_apid & 0x0700) >> 8); - this->data->header.packet_id_l = (new_apid & 0x00FF); -} - -void SpacePacketBase::setSequenceFlags(uint8_t sequenceflags) { - this->data->header.sequence_control_h &= 0x3F; - this->data->header.sequence_control_h |= sequenceflags << 6; -} - -uint16_t SpacePacketBase::getPacketSequenceControl(void) { - return ((this->data->header.sequence_control_h) << 8) + this->data->header.sequence_control_l; -} - -uint8_t SpacePacketBase::getSequenceFlags(void) { - return (this->data->header.sequence_control_h & 0b11000000) >> 6; -} - -uint16_t SpacePacketBase::getPacketSequenceCount(void) const { - return ((this->data->header.sequence_control_h & 0b00111111) << 8) + - this->data->header.sequence_control_l; -} - -void SpacePacketBase::setPacketSequenceCount(uint16_t new_count) { - this->data->header.sequence_control_h = (this->data->header.sequence_control_h & 0b11000000) | - (((new_count % LIMIT_SEQUENCE_COUNT) & 0x3F00) >> 8); - this->data->header.sequence_control_l = ((new_count % LIMIT_SEQUENCE_COUNT) & 0x00FF); -} - -uint16_t SpacePacketBase::getPacketDataLength() const { - return ((this->data->header.packet_length_h) << 8) + this->data->header.packet_length_l; -} - -void SpacePacketBase::setPacketDataLength(uint16_t new_length) { - this->data->header.packet_length_h = ((new_length & 0xFF00) >> 8); - this->data->header.packet_length_l = (new_length & 0x00FF); -} - -size_t SpacePacketBase::getFullSize() { - // +1 is done because size in packet data length field is: size of data field -1 - return this->getPacketDataLength() + sizeof(this->data->header) + 1; -} - -uint8_t* SpacePacketBase::getWholeData() { return (uint8_t*)this->data; } - -uint32_t SpacePacketBase::getApidAndSequenceCount() const { - return (getAPID() << 16) + getPacketSequenceCount(); -} - -uint8_t* SpacePacketBase::getPacketData() { return &(data->packet_data); } - -ReturnValue_t SpacePacketBase::setData(uint8_t* pData, size_t maxSize, void* args) { - if (maxSize < 6) { - return returnvalue::FAILED; - } - this->data = reinterpret_cast(const_cast(pData)); - return returnvalue::OK; -} diff --git a/src/fsfw/tmtcpacket/SpacePacketBase.h b/src/fsfw/tmtcpacket/SpacePacketBase.h deleted file mode 100644 index f3d3dbc6..00000000 --- a/src/fsfw/tmtcpacket/SpacePacketBase.h +++ /dev/null @@ -1,192 +0,0 @@ -#ifndef FSFW_TMTCPACKET_SPACEPACKETBASE_H_ -#define FSFW_TMTCPACKET_SPACEPACKETBASE_H_ - -#include - -#include - -#include "ccsds_header.h" -#include "fsfw/returnvalues/returnvalue.h" - -/** - * @defgroup tmtcpackets Space Packets - * This is the group, where all classes associated with Telecommand and - * Telemetry packets belong to. - * The class hierarchy resembles the dependency between the different standards - * applied, namely the CCSDS Space Packet standard and the ECCSS Packet - * Utilization Standard. Most field and structure names are taken from these - * standards. - */ - -/** - * This struct defines the data structure of a Space Packet when accessed - * via a pointer. - * @ingroup tmtcpackets - */ -struct SpacePacketPointer { - CCSDSPrimaryHeader header; - uint8_t packet_data; -}; - -/** - * This class is the basic data handler for any CCSDS Space Packet - * compatible Telecommand and Telemetry packet. - * It does not contain the packet data itself but a pointer to the - * data must be set on instantiation. An invalid pointer may cause - * damage, as no getter method checks data validity. Anyway, a NULL - * check can be performed by making use of the getWholeData method. - * Remark: All bit numbers in this documentation are counted from - * the most significant bit (from left). - * @ingroup tmtcpackets - */ -class SpacePacketBase : virtual public RedirectableDataPointerIF { - protected: - /** - * A pointer to a structure which defines the data structure of - * the packet header. - * To be hardware-safe, all elements are of byte size. - */ - SpacePacketPointer* data; - - public: - static const uint16_t LIMIT_APID = 2048; // 2^1 - static const uint16_t LIMIT_SEQUENCE_COUNT = 16384; // 2^14 - static const uint16_t APID_IDLE_PACKET = 0x7FF; - static const uint8_t TELECOMMAND_PACKET = 1; - static const uint8_t TELEMETRY_PACKET = 0; - /** - * This definition defines the CRC size in byte. - */ - static const uint8_t CRC_SIZE = 2; - /** - * This is the minimum size of a SpacePacket. - */ - static const uint16_t MINIMUM_SIZE = sizeof(CCSDSPrimaryHeader) + CRC_SIZE; - /** - * This is the default constructor. - * It sets its internal data pointer to the address passed. - * @param set_address The position where the packet data lies. - */ - SpacePacketBase(const uint8_t* set_address); - /** - * No data is allocated, so the destructor is empty. - */ - virtual ~SpacePacketBase(); - - // CCSDS Methods: - /** - * Getter for the packet version number field. - * @return Returns the highest three bit of the packet in one byte. - */ - uint8_t getPacketVersionNumber(void); - /** - * This method checks the type field in the header. - * This bit specifies, if the command is interpreted as Telecommand of - * as Telemetry. For a Telecommand, the bit is set. - * @return Returns true if the bit is set and false if not. - */ - bool isTelecommand(void); - - ReturnValue_t initSpacePacketHeader(bool isTelecommand, bool hasSecondaryHeader, uint16_t apid, - uint16_t sequenceCount = 0); - /** - * The CCSDS header provides a secondary header flag (the fifth-highest bit), - * which is checked with this method. - * @return Returns true if the bit is set and false if not. - */ - bool hasSecondaryHeader(void); - /** - * Returns the complete first two bytes of the packet, which together form - * the CCSDS packet id. - * @return The CCSDS packet id. - */ - uint16_t getPacketId(void); - /** - * Returns the APID of a packet, which are the lowest 11 bit of the packet - * id. - * @return The CCSDS APID. - */ - uint16_t getAPID(void) const; - /** - * Sets the APID of a packet, which are the lowest 11 bit of the packet - * id. - * @param The APID to set. The highest five bits of the parameter are - * ignored. - */ - void setAPID(uint16_t setAPID); - - /** - * Sets the sequence flags of a packet, which are bit 17 and 18 in the space packet header. - * @param The sequence flags to set - */ - void setSequenceFlags(uint8_t sequenceflags); - - /** - * Returns the CCSDS packet sequence control field, which are the third and - * the fourth byte of the CCSDS primary header. - * @return The CCSDS packet sequence control field. - */ - uint16_t getPacketSequenceControl(void); - /** - * Returns the SequenceFlags, which are the highest two bit of the packet - * sequence control field. - * @return The CCSDS sequence flags. - */ - uint8_t getSequenceFlags(void); - /** - * Returns the packet sequence count, which are the lowest 14 bit of the - * packet sequence control field. - * @return The CCSDS sequence count. - */ - uint16_t getPacketSequenceCount(void) const; - /** - * Sets the packet sequence count, which are the lowest 14 bit of the - * packet sequence control field. - * setCount is modulo-divided by \c LIMIT_SEQUENCE_COUNT to avoid overflows. - * @param setCount The value to set the count to. - */ - void setPacketSequenceCount(uint16_t setCount); - /** - * Returns the packet data length, which is the fifth and sixth byte of the - * CCSDS Primary Header. The packet data length is the size of every kind - * of data \b after the CCSDS Primary Header \b -1. - * @return - * The CCSDS packet data length. uint16_t is sufficient, - * because this is limit in CCSDS standard - */ - uint16_t getPacketDataLength(void) const; - /** - * Sets the packet data length, which is the fifth and sixth byte of the - * CCSDS Primary Header. - * @param setLength The value of the length to set. It must fit the true - * CCSDS packet data length . The packet data length is - * the size of every kind of data \b after the CCSDS - * Primary Header \b -1. - */ - void setPacketDataLength(uint16_t setLength); - - // Helper methods: - /** - * This method returns a raw uint8_t pointer to the packet. - * @return A \c uint8_t pointer to the first byte of the CCSDS primary header. - */ - virtual uint8_t* getWholeData(void); - - uint8_t* getPacketData(); - - /** - * With this method, the packet data pointer can be redirected to another - * location. - * @param p_Data A pointer to another raw Space Packet. - */ - virtual ReturnValue_t setData(uint8_t* p_Data, size_t maxSize, void* args = nullptr) override; - /** - * This method returns the full raw packet size. - * @return The full size of the packet in bytes. - */ - size_t getFullSize(); - - uint32_t getApidAndSequenceCount() const; -}; - -#endif /* FSFW_TMTCPACKET_SPACEPACKETBASE_H_ */ diff --git a/src/fsfw/tmtcpacket/ccsds/CMakeLists.txt b/src/fsfw/tmtcpacket/ccsds/CMakeLists.txt new file mode 100644 index 00000000..68efe09c --- /dev/null +++ b/src/fsfw/tmtcpacket/ccsds/CMakeLists.txt @@ -0,0 +1,2 @@ +target_sources(${LIB_FSFW_NAME} PRIVATE SpacePacketReader.cpp + SpacePacketCreator.cpp header.cpp) diff --git a/src/fsfw/tmtcpacket/ccsds/PacketId.h b/src/fsfw/tmtcpacket/ccsds/PacketId.h new file mode 100644 index 00000000..5b61db7d --- /dev/null +++ b/src/fsfw/tmtcpacket/ccsds/PacketId.h @@ -0,0 +1,87 @@ +#ifndef FSFW_TMTCPACKET_PACKETID_H +#define FSFW_TMTCPACKET_PACKETID_H + +#include + +#include "defs.h" +#include "fsfw/serialize/SerializeAdapter.h" +#include "fsfw/serialize/SerializeIF.h" + +struct PacketId : public SerializeIF { + public: + PacketId() = default; + /** + * Simple wrapper for Space Packet IDs. Does not check the APID for validity + * @param packetType_ + * @param secHeaderFlag_ + * @param apid_ + */ + PacketId(ccsds::PacketType packetType_, bool secHeaderFlag_, uint16_t apid_) + : packetType(packetType_), secHeaderFlag(secHeaderFlag_), apid(apid_) {} + + bool operator==(const PacketId &other) const { + return packetType == other.packetType and secHeaderFlag == other.secHeaderFlag and + apid == other.apid; + } + /** + * NOTE: If the APID has an invalid value, the invalid bits will be cut off + * @return + */ + [[nodiscard]] uint16_t raw() const { + return (static_cast(packetType) << 12) | + (static_cast(secHeaderFlag) << 11) | (apid & 0x7ff); + } + + static PacketId fromRaw(uint16_t raw) { + uint8_t highByte = (raw >> 8) & 0xff; + uint8_t lowByte = raw & 0xff; + return {static_cast((highByte >> 4) & 0b1), + static_cast((highByte >> 3) & 0b1), + static_cast((highByte & 0b111) << 8 | lowByte)}; + } + + ReturnValue_t serialize(uint8_t **buffer, size_t *size, size_t maxSize, + Endianness streamEndianness) const override { + if (*size + getSerializedSize() > maxSize) { + return SerializeIF::BUFFER_TOO_SHORT; + } + uint16_t idRaw = raw(); + // Leave the first three bits untouched, they could generally contain the CCSDS version, + // or more generally, the packet ID is a 13 bit field + **buffer &= ~0x1f; + **buffer |= (idRaw >> 8) & 0x1f; + *size += 1; + *buffer += 1; + **buffer = idRaw & 0xff; + *size += 1; + *buffer += 1; + return returnvalue::OK; + } + + [[nodiscard]] size_t getSerializedSize() const override { return 2; } + + ReturnValue_t deSerialize(const uint8_t **buffer, size_t *size, + Endianness streamEndianness) override { + if (*size < 2) { + return SerializeIF::STREAM_TOO_SHORT; + } + uint8_t highByte = **buffer; + *buffer += 1; + uint8_t lowByte = **buffer; + *buffer += 1; + *size -= 2; + packetType = static_cast((highByte >> 4) & 0b1); + secHeaderFlag = (highByte >> 3) & 0b1; + apid = static_cast((highByte & 0b111) << 8 | lowByte); + return returnvalue::OK; + } + + ccsds::PacketType packetType = ccsds::PacketType::TM; + bool secHeaderFlag = false; + uint16_t apid = 0; + + using SerializeIF::deSerialize; + using SerializeIF::serialize; +}; + +#endif // FSFW_TMTCPACKET_PACKETID_H diff --git a/src/fsfw/tmtcpacket/ccsds/PacketSeqCtrl.h b/src/fsfw/tmtcpacket/ccsds/PacketSeqCtrl.h new file mode 100644 index 00000000..1944e8c2 --- /dev/null +++ b/src/fsfw/tmtcpacket/ccsds/PacketSeqCtrl.h @@ -0,0 +1,63 @@ +#ifndef FSFW_TMTCPACKET_PACKETSEQCTRL_H +#define FSFW_TMTCPACKET_PACKETSEQCTRL_H + +#include "defs.h" +#include "fsfw/serialize/SerializeAdapter.h" +#include "fsfw/serialize/SerializeIF.h" + +struct PacketSeqCtrl : public SerializeIF { + public: + PacketSeqCtrl() = default; + + PacketSeqCtrl(ccsds::SequenceFlags seqFlags, uint16_t seqCount) + : seqFlags(seqFlags), seqCount(seqCount) {} + + bool operator==(const PacketSeqCtrl &other) const { + return seqCount == other.seqCount and seqFlags == other.seqFlags; + } + + /** + * NOTE: If the sequence control has an invalid value, the invalid bits will be cut off + * @return + */ + [[nodiscard]] uint16_t raw() const { + return (static_cast(seqFlags) << 14) | (seqCount & 0x3FFF); + } + + static PacketSeqCtrl fromRaw(uint16_t raw) { + uint8_t highByte = (raw >> 8) & 0xff; + uint8_t lowByte = raw & 0xff; + return {static_cast((highByte >> 6) & 0b11), + static_cast(((highByte << 8) | lowByte) & 0x3FFF)}; + } + + ReturnValue_t serialize(uint8_t **buffer, size_t *size, size_t maxSize, + Endianness streamEndianness) const override { + uint16_t packetIdRaw = raw(); + return SerializeAdapter::serialize(&packetIdRaw, buffer, size, maxSize, streamEndianness); + } + [[nodiscard]] size_t getSerializedSize() const override { return 2; } + + ReturnValue_t deSerialize(const uint8_t **buffer, size_t *size, + Endianness streamEndianness) override { + if (*size < 2) { + return SerializeIF::STREAM_TOO_SHORT; + } + uint8_t highByte = **buffer; + *buffer += 1; + uint8_t lowByte = **buffer; + *buffer += 1; + *size -= 2; + seqFlags = static_cast((highByte >> 6) & 0b11); + seqCount = ((highByte << 8) | lowByte) & 0x3FFF; + return returnvalue::OK; + } + + ccsds::SequenceFlags seqFlags = ccsds::SequenceFlags::CONTINUATION; + uint16_t seqCount = 0; + + using SerializeIF::deSerialize; + using SerializeIF::serialize; +}; + +#endif // FSFW_TMTCPACKET_PACKETSEQCTRL_H diff --git a/src/fsfw/tmtcpacket/ccsds/SpacePacketCreator.cpp b/src/fsfw/tmtcpacket/ccsds/SpacePacketCreator.cpp new file mode 100644 index 00000000..8c4822cd --- /dev/null +++ b/src/fsfw/tmtcpacket/ccsds/SpacePacketCreator.cpp @@ -0,0 +1,87 @@ +#include "SpacePacketCreator.h" + +#include + +#include "fsfw/serialize/SerializeAdapter.h" + +SpacePacketCreator::SpacePacketCreator(SpacePacketParams params_) : params(std::move(params_)) { + checkFieldValidity(); +} + +SpacePacketCreator::SpacePacketCreator(ccsds::PacketType packetType, bool secHeaderFlag, + uint16_t apid, ccsds::SequenceFlags seqFlags, + uint16_t seqCount, uint16_t dataLen, uint8_t version) + : params(SpacePacketParams(PacketId(packetType, secHeaderFlag, apid), + PacketSeqCtrl(seqFlags, seqCount), dataLen)) { + params.version = version; +} + +uint16_t SpacePacketCreator::getPacketIdRaw() const { return params.packetId.raw(); } +uint16_t SpacePacketCreator::getPacketSeqCtrlRaw() const { return params.packetSeqCtrl.raw(); } +uint16_t SpacePacketCreator::getPacketDataLen() const { return params.dataLen; } + +ReturnValue_t SpacePacketCreator::serialize(uint8_t **buffer, size_t *size, size_t maxSize, + SerializeIF::Endianness streamEndianness) const { + if (not isValid()) { + return returnvalue::FAILED; + } + uint16_t packetIdAndVersion = + (static_cast(params.version) << 13) | params.packetId.raw(); + ReturnValue_t result = + SerializeAdapter::serialize(&packetIdAndVersion, buffer, size, maxSize, streamEndianness); + if (result != returnvalue::OK) { + return result; + } + uint16_t pscRaw = params.packetSeqCtrl.raw(); + result = SerializeAdapter::serialize(&pscRaw, buffer, size, maxSize, streamEndianness); + if (result != returnvalue::OK) { + return result; + } + return SerializeAdapter::serialize(¶ms.dataLen, buffer, size, maxSize, streamEndianness); +} + +size_t SpacePacketCreator::getSerializedSize() const { return 6; } + +ReturnValue_t SpacePacketCreator::deSerialize(const uint8_t **buffer, size_t *size, + SerializeIF::Endianness streamEndianness) { + return returnvalue::FAILED; +} +bool SpacePacketCreator::isValid() const { return valid; } + +void SpacePacketCreator::setApid(uint16_t apid) { + if (apid < ccsds::LIMIT_APID) { + params.packetId.apid = apid; + } + checkFieldValidity(); +} + +void SpacePacketCreator::setSeqCount(uint16_t seqCount) { + if (seqCount < ccsds::LIMIT_SEQUENCE_COUNT) { + params.packetSeqCtrl.seqCount = seqCount; + } + checkFieldValidity(); +} +void SpacePacketCreator::setSeqFlags(ccsds::SequenceFlags flags) { + params.packetSeqCtrl.seqFlags = flags; +} +void SpacePacketCreator::setDataLen(uint16_t dataLen_) { params.dataLen = dataLen_; } +void SpacePacketCreator::checkFieldValidity() { + valid = true; + if (params.packetId.apid > ccsds::LIMIT_APID or + params.packetSeqCtrl.seqCount > ccsds::LIMIT_SEQUENCE_COUNT) { + valid = false; + } +} + +void SpacePacketCreator::setParams(SpacePacketParams params_) { params = std::move(params_); } + +SpacePacketParams &SpacePacketCreator::getParams() { return params; } + +void SpacePacketCreator::setPacketType(ccsds::PacketType type) { + params.packetId.packetType = type; +} +bool SpacePacketCreator::operator==(const SpacePacketCreator &other) const { return false; } + +SpacePacketCreator::operator bool() const { return isValid(); } + +void SpacePacketCreator::setSecHeaderFlag() { params.packetId.secHeaderFlag = true; } diff --git a/src/fsfw/tmtcpacket/ccsds/SpacePacketCreator.h b/src/fsfw/tmtcpacket/ccsds/SpacePacketCreator.h new file mode 100644 index 00000000..5869560d --- /dev/null +++ b/src/fsfw/tmtcpacket/ccsds/SpacePacketCreator.h @@ -0,0 +1,61 @@ +#ifndef FSFW_TMTCPACKET_SPACEPACKETCREATOR_H +#define FSFW_TMTCPACKET_SPACEPACKETCREATOR_H + +#include + +#include "PacketId.h" +#include "PacketSeqCtrl.h" +#include "SpacePacketIF.h" +#include "fsfw/serialize/SerializeIF.h" + +struct SpacePacketParams { + SpacePacketParams() = default; + + SpacePacketParams(PacketId packetId, PacketSeqCtrl psc, uint16_t dataLen) + : packetId(std::move(packetId)), packetSeqCtrl(std::move(psc)), dataLen(dataLen) {} + + PacketId packetId{}; + PacketSeqCtrl packetSeqCtrl{}; + uint16_t dataLen = 0; + uint8_t version = 0b000; +}; + +class SpacePacketCreator : public SpacePacketIF, public SerializeIF { + public: + SpacePacketCreator() = default; + explicit SpacePacketCreator(SpacePacketParams params); + + bool operator==(const SpacePacketCreator &other) const; + explicit operator bool() const; + + SpacePacketCreator(ccsds::PacketType packetType, bool secHeaderFlag, uint16_t apid, + ccsds::SequenceFlags seqFlags, uint16_t seqCount, uint16_t dataLen, + uint8_t version = 0); + + [[nodiscard]] bool isValid() const; + [[nodiscard]] uint16_t getPacketIdRaw() const override; + [[nodiscard]] uint16_t getPacketSeqCtrlRaw() const override; + [[nodiscard]] uint16_t getPacketDataLen() const override; + + SpacePacketParams &getParams(); + void setParams(SpacePacketParams params); + void setSecHeaderFlag(); + void setPacketType(ccsds::PacketType type); + void setApid(uint16_t apid); + void setSeqCount(uint16_t seqCount); + void setSeqFlags(ccsds::SequenceFlags flags); + void setDataLen(uint16_t dataLen); + + ReturnValue_t serialize(uint8_t **buffer, size_t *size, size_t maxSize, + Endianness streamEndianness) const override; + + [[nodiscard]] size_t getSerializedSize() const override; + ReturnValue_t deSerialize(const uint8_t **buffer, size_t *size, + Endianness streamEndianness) override; + + private: + void checkFieldValidity(); + bool valid{}; + SpacePacketParams params{}; +}; +#endif // FSFW_TMTCPACKET_SPACEPACKETCREATOR_H diff --git a/src/fsfw/tmtcpacket/ccsds/SpacePacketIF.h b/src/fsfw/tmtcpacket/ccsds/SpacePacketIF.h new file mode 100644 index 00000000..41d087ad --- /dev/null +++ b/src/fsfw/tmtcpacket/ccsds/SpacePacketIF.h @@ -0,0 +1,97 @@ +#ifndef FSFW_TMTCPACKET_SPACEPACKETIF_H +#define FSFW_TMTCPACKET_SPACEPACKETIF_H + +#include +#include + +#include "PacketId.h" +#include "PacketSeqCtrl.h" +#include "fsfw/tmtcpacket/ccsds/defs.h" +#include "header.h" + +class SpacePacketIF { + public: + /** + * This definition defines the CRC size in byte. + */ + static const uint8_t CRC_SIZE = 2; + /** + * This is the minimum size of a SpacePacket. + */ + static const uint16_t MIN_CCSDS_SIZE = sizeof(ccsds::PrimaryHeader) + CRC_SIZE; + + virtual ~SpacePacketIF() = default; + + /** + * CCSDS header always has 6 bytes + * @return + */ + static constexpr size_t getHeaderLen() { return ccsds::HEADER_LEN; } + + /** + * Returns the complete first two bytes of the packet, which together form + * the CCSDS packet ID + * @return The CCSDS packet ID + */ + [[nodiscard]] virtual uint16_t getPacketIdRaw() const = 0; + /** + * Returns the third and the fourth byte of the CCSDS header which are the packet sequence + * control field + * @return + */ + [[nodiscard]] virtual uint16_t getPacketSeqCtrlRaw() const = 0; + /** + * Returns the fifth and the sixth byte of the CCSDS header which is the packet length field + * @return + */ + [[nodiscard]] virtual uint16_t getPacketDataLen() const = 0; + + virtual PacketId getPacketId() { return PacketId::fromRaw(getPacketIdRaw()); } + + virtual PacketSeqCtrl getPacketSeqCtrl() { return PacketSeqCtrl::fromRaw(getPacketSeqCtrlRaw()); } + + [[nodiscard]] virtual uint16_t getApid() const { + // Uppermost 11 bits of packet ID + return getPacketIdRaw() & 0x7ff; + } + + /** + * Returns the CCSDS version number + * @return + */ + [[nodiscard]] virtual uint8_t getVersion() const { + uint16_t packetId = getPacketIdRaw(); + return (packetId >> 13) & 0b111; + } + + [[nodiscard]] virtual ccsds::PacketType getPacketType() const { + return static_cast((getPacketIdRaw() >> 12) & 0b1); + } + + [[nodiscard]] virtual bool isTc() const { return getPacketType() == ccsds::PacketType::TC; } + + [[nodiscard]] virtual bool isTm() const { return not isTc(); } + + /** + * The CCSDS header provides a secondary header flag (the fifth-highest bit), + * which is checked with this method. + * @return Returns true if the bit is set and false if not. + */ + [[nodiscard]] virtual bool hasSecHeader() const { return (getPacketIdRaw() >> 11) & 0b1; } + + [[nodiscard]] virtual ccsds::SequenceFlags getSequenceFlags() const { + return static_cast(getPacketSeqCtrlRaw() >> 14 & 0b11); + } + + [[nodiscard]] virtual uint16_t getSequenceCount() const { return getPacketSeqCtrlRaw() & 0x3FFF; } + + /** + * Returns the full packet length based of the packet data length field + * @return + */ + [[nodiscard]] virtual size_t getFullPacketLen() const { + return ccsds::HEADER_LEN + getPacketDataLen() + 1; + } +}; + +#endif // FSFW_TMTCPACKET_SPACEPACKETIF_H diff --git a/src/fsfw/tmtcpacket/ccsds/SpacePacketReader.cpp b/src/fsfw/tmtcpacket/ccsds/SpacePacketReader.cpp new file mode 100644 index 00000000..091a641a --- /dev/null +++ b/src/fsfw/tmtcpacket/ccsds/SpacePacketReader.cpp @@ -0,0 +1,54 @@ +#include "SpacePacketReader.h" + +#include "fsfw/serialize/SerializeIF.h" +#include "fsfw/serviceinterface/ServiceInterface.h" + +SpacePacketReader::SpacePacketReader(const uint8_t* setAddress, size_t maxSize_) { + setInternalFields(setAddress, maxSize_); +} + +ReturnValue_t SpacePacketReader::checkSize() const { + if (isNull()) { + return returnvalue::FAILED; + } + if (getFullPacketLen() > bufSize) { + return SerializeIF::STREAM_TOO_SHORT; + } + return returnvalue::OK; +} + +SpacePacketReader::~SpacePacketReader() = default; + +inline uint16_t SpacePacketReader::getPacketIdRaw() const { return ccsds::getPacketId(*spHeader); } + +const uint8_t* SpacePacketReader::getPacketData() { return packetDataField; } + +ReturnValue_t SpacePacketReader::setData(uint8_t* data, size_t maxSize_, void* args) { + return setInternalFields(data, maxSize_); +} + +uint16_t SpacePacketReader::getPacketSeqCtrlRaw() const { + return ccsds::getPacketSeqCtrl(*spHeader); +} + +uint16_t SpacePacketReader::getPacketDataLen() const { return ccsds::getPacketLen(*spHeader); } + +ReturnValue_t SpacePacketReader::setInternalFields(const uint8_t* data, size_t maxSize_) { + bufSize = maxSize_; + spHeader = reinterpret_cast(data); + if (maxSize_ > 6) { + packetDataField = data + ccsds::HEADER_LEN; + } + return checkSize(); +} + +const uint8_t* SpacePacketReader::getFullData() const { + return reinterpret_cast(spHeader); +} +size_t SpacePacketReader::getBufSize() const { return bufSize; } + +bool SpacePacketReader::isNull() const { return spHeader == nullptr; } + +ReturnValue_t SpacePacketReader::setReadOnlyData(const uint8_t* data, size_t maxSize) { + return setData(const_cast(data), maxSize, nullptr); +} diff --git a/src/fsfw/tmtcpacket/ccsds/SpacePacketReader.h b/src/fsfw/tmtcpacket/ccsds/SpacePacketReader.h new file mode 100644 index 00000000..ff22510c --- /dev/null +++ b/src/fsfw/tmtcpacket/ccsds/SpacePacketReader.h @@ -0,0 +1,97 @@ +#ifndef FSFW_TMTCPACKET_SPACEPACKETBASE_H_ +#define FSFW_TMTCPACKET_SPACEPACKETBASE_H_ + +#include + +#include "fsfw/returnvalues/returnvalue.h" +#include "fsfw/tmtcpacket/ReadablePacketIF.h" +#include "fsfw/tmtcpacket/RedirectableDataPointerIF.h" +#include "fsfw/tmtcpacket/ccsds/defs.h" + +/** + * @defgroup tmtcpackets Space Packets + * This is the group, where all classes associated with Telecommand and + * Telemetry packets belong to. + * The class hierarchy resembles the dependency between the different standards + * applied, namely the CCSDS Space Packet standard and the ECCSS Packet + * Utilization Standard. Most field and structure names are taken from these + * standards. + */ + +/** + * This class is the basic data handler for any CCSDS Space Packet + * compatible Telecommand and Telemetry packet. + * It does not contain the packet data itself but a pointer to the + * data must be set on instantiation or with the @setData or @setReadOnlyData call. + * The @isNull and @checkSize methods can be used to check the validity of the data pointed to. + * + * This is a zero-copy reader class. It does not contain the packet data itself but a pointer to + * the data. Calling any accessor methods without pointing the object to valid data first will + * cause undefined behaviour. + * @ingroup tmtcpackets + */ +class SpacePacketReader : public SpacePacketIF, + public ReadablePacketIF, + public RedirectableDataPointerIF { + public: + /** + * Initialize an empty space packet reader which points to no data + */ + SpacePacketReader() = default; + /** + * This is the default constructor. + * It sets its internal data pointer to the address passed. + * @param set_address The position where the packet data lies. + */ + explicit SpacePacketReader(const uint8_t* setAddress, size_t maxSize); + /** + * No data is allocated, so the destructor is empty. + */ + ~SpacePacketReader() override; + + /** + * Check whether any data is set for the reader object + * @return + */ + [[nodiscard]] bool isNull() const; + /** + * Get size of the buffer. This is the size which is passed to the constructor or to the + * @setData call. It is not the content of the CCSDS data length field and it is not necessarily + * equal to the full packet length of the space packet. + * @return + */ + [[nodiscard]] size_t getBufSize() const; + + [[nodiscard]] uint16_t getPacketIdRaw() const override; + [[nodiscard]] uint16_t getPacketSeqCtrlRaw() const override; + [[nodiscard]] uint16_t getPacketDataLen() const override; + + [[nodiscard]] const uint8_t* getFullData() const override; + + // Helper methods: + [[nodiscard]] ReturnValue_t checkSize() const; + + const uint8_t* getPacketData(); + + ReturnValue_t setReadOnlyData(const uint8_t* data, size_t maxSize); + + protected: + /** + * A pointer to a structure which defines the data structure of + * the packet header. + * To be hardware-safe, all elements are of byte size. + */ + const ccsds::PrimaryHeader* spHeader{}; + const uint8_t* packetDataField{}; + size_t bufSize = 0; + /** + * With this method, the packet data pointer can be redirected to another + * location. + * @param data A pointer to another raw Space Packet. + */ + ReturnValue_t setData(uint8_t* data, size_t maxSize, void* args) override; + + ReturnValue_t setInternalFields(const uint8_t* data, size_t maxSize); +}; + +#endif /* FSFW_TMTCPACKET_SPACEPACKETBASE_H_ */ diff --git a/src/fsfw/tmtcpacket/ccsds/defs.h b/src/fsfw/tmtcpacket/ccsds/defs.h new file mode 100644 index 00000000..1c7de540 --- /dev/null +++ b/src/fsfw/tmtcpacket/ccsds/defs.h @@ -0,0 +1,36 @@ +#ifndef CCSDS_HEADER_H_ +#define CCSDS_HEADER_H_ + +#include + +namespace ccsds { + +enum PacketType : uint8_t { TM = 0, TC = 1 }; + +enum SequenceFlags : uint8_t { + CONTINUATION = 0b00, + FIRST_SEGMENT = 0b01, + LAST_SEGMENT = 0b10, + UNSEGMENTED = 0b11 +}; + +static const uint16_t LIMIT_APID = 2048; // 2^11 +static const uint16_t LIMIT_SEQUENCE_COUNT = 16384; // 2^14 +static const uint16_t APID_IDLE_PACKET = 0x7FF; + +constexpr uint16_t getSpacePacketIdFromApid(bool isTc, uint16_t apid, + bool secondaryHeaderFlag = true) { + return ((isTc << 4) | (secondaryHeaderFlag << 3) | ((apid >> 8) & 0x07)) << 8 | (apid & 0x00ff); +} + +constexpr uint16_t getTcSpacePacketIdFromApid(uint16_t apid, bool secondaryHeaderFlag = true) { + return getSpacePacketIdFromApid(true, apid, secondaryHeaderFlag); +} + +constexpr uint16_t getTmSpacePacketIdFromApid(uint16_t apid, bool secondaryHeaderFlag = true) { + return getSpacePacketIdFromApid(false, apid, secondaryHeaderFlag); +} + +} // namespace ccsds + +#endif /* CCSDS_HEADER_H_ */ diff --git a/src/fsfw/tmtcpacket/ccsds/header.cpp b/src/fsfw/tmtcpacket/ccsds/header.cpp new file mode 100644 index 00000000..6491d207 --- /dev/null +++ b/src/fsfw/tmtcpacket/ccsds/header.cpp @@ -0,0 +1,34 @@ +#include "header.h" + +uint16_t ccsds::getPacketId(const PrimaryHeader &header) { + return ((header.packetIdHAndVersion & 0x1F) << 8) + header.packetIdL; +} + +uint16_t ccsds::getPacketSeqCtrl(const PrimaryHeader &header) { + return (header.packetSeqCtrlH << 8) | header.packetSeqCtrlL; +} + +uint8_t ccsds::getVersion(const PrimaryHeader &header) { + return (header.packetIdHAndVersion >> 5) & 0b111; +} + +uint16_t ccsds::getPacketLen(const PrimaryHeader &header) { + return (header.packetLenH << 8) | header.packetLenL; +} + +void ccsds::setPacketId(PrimaryHeader &header, uint16_t packetId) { + header.packetIdHAndVersion |= (packetId >> 8) & 0x1F; + header.packetIdL = packetId & 0xff; +} + +void ccsds::setApid(PrimaryHeader &header, uint16_t apid) { + uint16_t packetIdRaw = getPacketId(header); + packetIdRaw &= ~0x7FF; + packetIdRaw |= apid & 0x7FF; + setPacketId(header, packetIdRaw); +} + +void ccsds::setSequenceCount(PrimaryHeader &header, uint16_t seqCount) { + header.packetSeqCtrlH |= (seqCount >> 8) & 0x3F; + header.packetSeqCtrlL = seqCount & 0xFF; +} diff --git a/src/fsfw/tmtcpacket/ccsds/header.h b/src/fsfw/tmtcpacket/ccsds/header.h new file mode 100644 index 00000000..89e00601 --- /dev/null +++ b/src/fsfw/tmtcpacket/ccsds/header.h @@ -0,0 +1,31 @@ +#ifndef FSFW_TMTCPACKET_HEADER_H +#define FSFW_TMTCPACKET_HEADER_H + +#include +#include + +namespace ccsds { + +static constexpr size_t HEADER_LEN = 6; + +struct PrimaryHeader { + uint8_t packetIdHAndVersion; + uint8_t packetIdL; + uint8_t packetSeqCtrlH; + uint8_t packetSeqCtrlL; + uint8_t packetLenH; + uint8_t packetLenL; +}; + +uint16_t getPacketId(const PrimaryHeader& header); +uint16_t getPacketSeqCtrl(const PrimaryHeader& header); +uint8_t getVersion(const PrimaryHeader& header); +uint16_t getPacketLen(const PrimaryHeader& header); + +void setPacketId(PrimaryHeader& header, uint16_t packetId); +void setApid(PrimaryHeader& header, uint16_t apid); +void setSequenceCount(PrimaryHeader& header, uint16_t seqCount); + +} // namespace ccsds + +#endif // FSFW_TMTCPACKET_HEADER_H diff --git a/src/fsfw/tmtcpacket/ccsds_header.h b/src/fsfw/tmtcpacket/ccsds_header.h deleted file mode 100644 index 232790c0..00000000 --- a/src/fsfw/tmtcpacket/ccsds_header.h +++ /dev/null @@ -1,15 +0,0 @@ -#ifndef CCSDS_HEADER_H_ -#define CCSDS_HEADER_H_ - -#include - -struct CCSDSPrimaryHeader { - uint8_t packet_id_h; - uint8_t packet_id_l; - uint8_t sequence_control_h; - uint8_t sequence_control_l; - uint8_t packet_length_h; - uint8_t packet_length_l; -}; - -#endif /* CCSDS_HEADER_H_ */ diff --git a/src/fsfw/tmtcpacket/cfdp/CFDPPacket.cpp b/src/fsfw/tmtcpacket/cfdp/CFDPPacket.cpp deleted file mode 100644 index 5df50cd7..00000000 --- a/src/fsfw/tmtcpacket/cfdp/CFDPPacket.cpp +++ /dev/null @@ -1,20 +0,0 @@ -#include "fsfw/tmtcpacket/cfdp/CFDPPacket.h" - -#include - -#include "fsfw/globalfunctions/CRC.h" -#include "fsfw/globalfunctions/arrayprinter.h" -#include "fsfw/serviceinterface/ServiceInterface.h" - -CFDPPacket::CFDPPacket(const uint8_t* setData) : SpacePacketBase(setData) {} - -CFDPPacket::~CFDPPacket() {} - -void CFDPPacket::print() { -#if FSFW_CPP_OSTREAM_ENABLED == 1 - sif::info << "CFDPPacket::print:" << std::endl; -#else - sif::printInfo("CFDPPacket::print:\n"); -#endif - arrayprinter::print(getWholeData(), getFullSize()); -} diff --git a/src/fsfw/tmtcpacket/cfdp/CFDPPacketStored.cpp b/src/fsfw/tmtcpacket/cfdp/CFDPPacketStored.cpp deleted file mode 100644 index 6e0f7b22..00000000 --- a/src/fsfw/tmtcpacket/cfdp/CFDPPacketStored.cpp +++ /dev/null @@ -1,92 +0,0 @@ -#include "fsfw/tmtcpacket/cfdp/CFDPPacketStored.h" - -#include "fsfw/objectmanager/ObjectManager.h" - -StorageManagerIF* CFDPPacketStored::store = nullptr; - -CFDPPacketStored::CFDPPacketStored() : CFDPPacket(nullptr) {} - -CFDPPacketStored::CFDPPacketStored(store_address_t setAddress) : CFDPPacket(nullptr) { - this->setStoreAddress(setAddress); -} - -CFDPPacketStored::CFDPPacketStored(const uint8_t* data, size_t size) : CFDPPacket(data) { - if (this->getFullSize() != size) { - return; - } - if (this->checkAndSetStore()) { - ReturnValue_t status = store->addData(&storeAddress, data, size); - if (status != returnvalue::OK) { - this->setData(nullptr, -1); - } - const uint8_t* storePtr = nullptr; - // Repoint base data pointer to the data in the store. - store->getData(storeAddress, &storePtr, &size); - this->setData(const_cast(storePtr), size); - } -} - -ReturnValue_t CFDPPacketStored::deletePacket() { - ReturnValue_t result = this->store->deleteData(this->storeAddress); - this->storeAddress.raw = StorageManagerIF::INVALID_ADDRESS; - // To circumvent size checks - this->setData(nullptr, -1); - return result; -} - -// CFDPPacket* CFDPPacketStored::getPacketBase() { -// return this; -// } -void CFDPPacketStored::setStoreAddress(store_address_t setAddress) { - this->storeAddress = setAddress; - const uint8_t* tempData = nullptr; - size_t tempSize; - ReturnValue_t status = returnvalue::FAILED; - if (this->checkAndSetStore()) { - status = this->store->getData(this->storeAddress, &tempData, &tempSize); - } - if (status == returnvalue::OK) { - this->setData(const_cast(tempData), tempSize); - } else { - // To circumvent size checks - this->setData(nullptr, -1); - this->storeAddress.raw = StorageManagerIF::INVALID_ADDRESS; - } -} - -store_address_t CFDPPacketStored::getStoreAddress() { return this->storeAddress; } - -CFDPPacketStored::~CFDPPacketStored() {} - -ReturnValue_t CFDPPacketStored::getData(const uint8_t** dataPtr, size_t* dataSize) { - return returnvalue::OK; -} - -// ReturnValue_t CFDPPacketStored::setData(const uint8_t *data) { -// return returnvalue::OK; -// } - -bool CFDPPacketStored::checkAndSetStore() { - if (this->store == nullptr) { - this->store = ObjectManager::instance()->get(objects::TC_STORE); - if (this->store == nullptr) { -#if FSFW_CPP_OSTREAM_ENABLED == 1 - sif::error << "CFDPPacketStored::CFDPPacketStored: TC Store not found!" << std::endl; -#endif - return false; - } - } - return true; -} - -bool CFDPPacketStored::isSizeCorrect() { - const uint8_t* temp_data = nullptr; - size_t temp_size; - ReturnValue_t status = store->getData(this->storeAddress, &temp_data, &temp_size); - if (status == returnvalue::OK) { - if (this->getFullSize() == temp_size) { - return true; - } - } - return false; -} diff --git a/src/fsfw/tmtcpacket/cfdp/CMakeLists.txt b/src/fsfw/tmtcpacket/cfdp/CMakeLists.txt index 7d20aab8..a0d48465 100644 --- a/src/fsfw/tmtcpacket/cfdp/CMakeLists.txt +++ b/src/fsfw/tmtcpacket/cfdp/CMakeLists.txt @@ -1 +1 @@ -target_sources(${LIB_FSFW_NAME} PRIVATE CFDPPacket.cpp CFDPPacketStored.cpp) +target_sources(${LIB_FSFW_NAME} PRIVATE) diff --git a/src/fsfw/tmtcpacket/cfdp/CFDPPacket.h b/src/fsfw/tmtcpacket/cfdp/CfdpPacket.h similarity index 76% rename from src/fsfw/tmtcpacket/cfdp/CFDPPacket.h rename to src/fsfw/tmtcpacket/cfdp/CfdpPacket.h index 30ba98ae..e391202f 100644 --- a/src/fsfw/tmtcpacket/cfdp/CFDPPacket.h +++ b/src/fsfw/tmtcpacket/cfdp/CfdpPacket.h @@ -1,9 +1,9 @@ #ifndef FSFW_INC_FSFW_TMTCPACKET_CFDP_CFDPPACKET_H_ #define FSFW_INC_FSFW_TMTCPACKET_CFDP_CFDPPACKET_H_ -#include "fsfw/tmtcpacket/SpacePacketBase.h" +#include "fsfw/tmtcpacket/ccsds/SpacePacketReader.h" -class CFDPPacket : public SpacePacketBase { +class CfdpReader : public SpacePacketReader { public: /** * This is the default constructor. @@ -11,11 +11,11 @@ class CFDPPacket : public SpacePacketBase { * forwards the data pointer to the parent SpacePacketBase class. * @param setData The position where the packet data lies. */ - CFDPPacket(const uint8_t* setData); + explicit CfdpReader(const uint8_t* setData, size_t maxSize); /** * This is the empty default destructor. */ - virtual ~CFDPPacket(); + ~CfdpReader() override; /** * This is a debugging helper method that prints the whole packet content diff --git a/src/fsfw/tmtcpacket/cfdp/CFDPPacketStored.h b/src/fsfw/tmtcpacket/cfdp/CfdpPacketStored.h similarity index 58% rename from src/fsfw/tmtcpacket/cfdp/CFDPPacketStored.h rename to src/fsfw/tmtcpacket/cfdp/CfdpPacketStored.h index 329b62ff..8b0da723 100644 --- a/src/fsfw/tmtcpacket/cfdp/CFDPPacketStored.h +++ b/src/fsfw/tmtcpacket/cfdp/CfdpPacketStored.h @@ -1,25 +1,25 @@ -#ifndef FSFW_INC_FSFW_TMTCPACKET_CFDP_CFDPPACKETSTORED_H_ -#define FSFW_INC_FSFW_TMTCPACKET_CFDP_CFDPPACKETSTORED_H_ +#ifndef FSFW_TMTCPACKET_CFDP_CFDPPACKETSTORED_H_ +#define FSFW_TMTCPACKET_CFDP_CFDPPACKETSTORED_H_ -#include "../pus/tc/TcPacketStoredBase.h" -#include "CFDPPacket.h" +#include "CfdpPacket.h" +#include "fsfw/storagemanager/storeAddress.h" -class CFDPPacketStored : public CFDPPacket, public TcPacketStoredBase { +class CfdpPacketStored : public CfdpReader { public: /** * Create stored packet with existing data. * @param data * @param size */ - CFDPPacketStored(const uint8_t* data, size_t size); + CfdpPacketStored(const uint8_t* data, size_t size); /** * Create stored packet from existing packet in store * @param setAddress */ - CFDPPacketStored(store_address_t setAddress); - CFDPPacketStored(); + explicit CfdpPacketStored(store_address_t setAddress); + CfdpPacketStored(); - virtual ~CFDPPacketStored(); + ~CfdpPacketStored() override; /** * Getter function for the raw data. @@ -39,13 +39,6 @@ class CFDPPacketStored : public CFDPPacket, public TcPacketStoredBase { bool isSizeCorrect(); protected: - /** - * This is a pointer to the store all instances of the class use. - * If the store is not yet set (i.e. @c store is NULL), every constructor - * call tries to set it and throws an error message in case of failures. - * The default store is objects::TC_STORE. - */ - static StorageManagerIF* store; /** * The address where the packet data of the object instance is stored. */ @@ -60,4 +53,4 @@ class CFDPPacketStored : public CFDPPacket, public TcPacketStoredBase { bool checkAndSetStore(); }; -#endif /* FSFW_INC_FSFW_TMTCPACKET_CFDP_CFDPPACKETSTORED_H_ */ +#endif /* FSFW_TMTCPACKET_CFDP_CFDPPACKETSTORED_H_ */ diff --git a/src/fsfw/tmtcpacket/packetmatcher/ApidMatcher.h b/src/fsfw/tmtcpacket/packetmatcher/ApidMatcher.h index cf4c88f2..47e23f1c 100644 --- a/src/fsfw/tmtcpacket/packetmatcher/ApidMatcher.h +++ b/src/fsfw/tmtcpacket/packetmatcher/ApidMatcher.h @@ -1,32 +1,36 @@ #ifndef FSFW_TMTCPACKET_PACKETMATCHER_APIDMATCHER_H_ #define FSFW_TMTCPACKET_PACKETMATCHER_APIDMATCHER_H_ -#include "../../globalfunctions/matching/SerializeableMatcherIF.h" -#include "../../serialize/SerializeAdapter.h" -#include "../../tmtcpacket/pus/tm/TmPacketMinimal.h" +#include "fsfw/globalfunctions/matching/SerializeableMatcherIF.h" +#include "fsfw/serialize/SerializeAdapter.h" +#include "fsfw/tmtcpacket/pus/tm/PusTmIF.h" +#include "fsfw/tmtcpacket/pus/tm/PusTmMinimal.h" -class ApidMatcher : public SerializeableMatcherIF { +class ApidMatcher : public SerializeableMatcherIF { private: uint16_t apid; public: - ApidMatcher(uint16_t setApid) : apid(setApid) {} - ApidMatcher(TmPacketMinimal* test) : apid(test->getAPID()) {} - bool match(TmPacketMinimal* packet) { - if (packet->getAPID() == apid) { + explicit ApidMatcher(uint16_t setApid) : apid(setApid) {} + explicit ApidMatcher(PusTmIF* test) : apid(test->getApid()) {} + bool match(PusTmIF* packet) override { + if (packet->getApid() == apid) { return true; } else { return false; } } ReturnValue_t serialize(uint8_t** buffer, size_t* size, size_t maxSize, - Endianness streamEndianness) const { + Endianness streamEndianness) const override { return SerializeAdapter::serialize(&apid, buffer, size, maxSize, streamEndianness); } - size_t getSerializedSize() const { return SerializeAdapter::getSerializedSize(&apid); } - ReturnValue_t deSerialize(const uint8_t** buffer, size_t* size, Endianness streamEndianness) { + [[nodiscard]] size_t getSerializedSize() const override { + return SerializeAdapter::getSerializedSize(&apid); + } + ReturnValue_t deSerialize(const uint8_t** buffer, size_t* size, + Endianness streamEndianness) override { return SerializeAdapter::deSerialize(&apid, buffer, size, streamEndianness); } }; -#endif /* FRAMEWORK_TMTCPACKET_PACKETMATCHER_APIDMATCHER_H_ */ +#endif /* FSFW_TMTCPACKET_PACKETMATCHER_APIDMATCHER_H_ */ diff --git a/src/fsfw/tmtcpacket/packetmatcher/PacketMatchTree.cpp b/src/fsfw/tmtcpacket/packetmatcher/PacketMatchTree.cpp index e4688590..8542694a 100644 --- a/src/fsfw/tmtcpacket/packetmatcher/PacketMatchTree.cpp +++ b/src/fsfw/tmtcpacket/packetmatcher/PacketMatchTree.cpp @@ -1,5 +1,6 @@ #include "fsfw/tmtcpacket/packetmatcher/PacketMatchTree.h" +#include "fsfw/storagemanager/LocalPool.h" #include "fsfw/tmtcpacket/packetmatcher/ApidMatcher.h" #include "fsfw/tmtcpacket/packetmatcher/ServiceMatcher.h" #include "fsfw/tmtcpacket/packetmatcher/SubserviceMatcher.h" @@ -12,33 +13,34 @@ const LocalPool::LocalPoolConfig PacketMatchTree::poolConfig = { {40, sizeof(PacketMatchTree::Node)}}; PacketMatchTree::PacketMatchTree(Node* root) - : MatchTree(root, 2), + : MatchTree(root, 2), factoryBackend(0, poolConfig, false, true), factory(&factoryBackend) {} PacketMatchTree::PacketMatchTree(iterator root) - : MatchTree(root.element, 2), + : MatchTree(root.element, 2), factoryBackend(0, poolConfig, false, true), factory(&factoryBackend) {} PacketMatchTree::PacketMatchTree() - : MatchTree((Node*)NULL, 2), + : MatchTree(nullptr, 2), factoryBackend(0, poolConfig, false, true), factory(&factoryBackend) {} -PacketMatchTree::~PacketMatchTree() {} +PacketMatchTree::~PacketMatchTree() = default; ReturnValue_t PacketMatchTree::addMatch(uint16_t apid, uint8_t type, uint8_t subtype) { // We assume adding APID is always requested. - TmPacketMinimal::TmPacketMinimalPointer data; - data.data_field.service_type = type; - data.data_field.service_subtype = subtype; - TmPacketMinimal testPacket((uint8_t*)&data); - testPacket.setAPID(apid); + mintm::MinimalPusTm data{}; + data.secHeader.service = type; + data.secHeader.subservice = subtype; + PusTmMinimal testPacket((uint8_t*)&data); + testPacket.setApid(apid); + iterator lastTest; iterator rollback; ReturnValue_t result = - findOrInsertMatch(this->begin(), &testPacket, &lastTest); + findOrInsertMatch(this->begin(), &testPacket, &lastTest); if (result == NEW_NODE_CREATED) { rollback = lastTest; } else if (result != returnvalue::OK) { @@ -47,38 +49,36 @@ ReturnValue_t PacketMatchTree::addMatch(uint16_t apid, uint8_t type, uint8_t sub if (type == 0) { // Check if lastTest has no children, otherwise, delete them, // as a more general check is requested. - if (lastTest.left() != this->end()) { + if (lastTest.left() != PacketMatchTree::end()) { removeElementAndAllChildren(lastTest.left()); } return returnvalue::OK; } // Type insertion required. - result = - findOrInsertMatch(lastTest.left(), &testPacket, &lastTest); + result = findOrInsertMatch(lastTest.left(), &testPacket, &lastTest); if (result == NEW_NODE_CREATED) { - if (rollback == this->end()) { + if (rollback == PacketMatchTree::end()) { rollback = lastTest; } } else if (result != returnvalue::OK) { - if (rollback != this->end()) { + if (rollback != PacketMatchTree::end()) { removeElementAndAllChildren(rollback); } return result; } if (subtype == 0) { - if (lastTest.left() != this->end()) { + if (lastTest.left() != PacketMatchTree::end()) { // See above removeElementAndAllChildren(lastTest.left()); } return returnvalue::OK; } // Subtype insertion required. - result = findOrInsertMatch(lastTest.left(), &testPacket, - &lastTest); + result = findOrInsertMatch(lastTest.left(), &testPacket, &lastTest); if (result == NEW_NODE_CREATED) { return returnvalue::OK; } else if (result != returnvalue::OK) { - if (rollback != this->end()) { + if (rollback != PacketMatchTree::end()) { removeElementAndAllChildren(rollback); } return result; @@ -91,7 +91,7 @@ ReturnValue_t PacketMatchTree::findOrInsertMatch(iterator startAt, VALUE_T test, iterator* lastTest) { bool attachToBranch = AND; iterator iter = startAt; - while (iter != this->end()) { + while (iter != PacketMatchTree::end()) { bool isMatch = iter->match(test); attachToBranch = OR; *lastTest = iter; @@ -104,11 +104,11 @@ ReturnValue_t PacketMatchTree::findOrInsertMatch(iterator startAt, VALUE_T test, } // Only reached if nothing was found. SerializeableMatcherIF* newContent = factory.generate(test); - if (newContent == NULL) { + if (newContent == nullptr) { return FULL; } Node* newNode = factory.generate(newContent); - if (newNode == NULL) { + if (newNode == nullptr) { // Need to make sure partially generated content is deleted, otherwise, that's a leak. factory.destroy(static_cast(newContent)); return FULL; @@ -122,13 +122,13 @@ ReturnValue_t PacketMatchTree::findOrInsertMatch(iterator startAt, VALUE_T test, } ReturnValue_t PacketMatchTree::removeMatch(uint16_t apid, uint8_t type, uint8_t subtype) { - TmPacketMinimal::TmPacketMinimalPointer data; - data.data_field.service_type = type; - data.data_field.service_subtype = subtype; - TmPacketMinimal testPacket((uint8_t*)&data); - testPacket.setAPID(apid); + mintm::MinimalPusTm data{}; + data.secHeader.service = type; + data.secHeader.subservice = subtype; + PusTmMinimal testPacket((uint8_t*)&data); + testPacket.setApid(apid); iterator foundElement = findMatch(begin(), &testPacket); - if (foundElement == this->end()) { + if (foundElement == PacketMatchTree::end()) { return NO_MATCH; } if (type == 0) { @@ -158,7 +158,7 @@ ReturnValue_t PacketMatchTree::removeMatch(uint16_t apid, uint8_t type, uint8_t return removeElementAndReconnectChildren(foundElement); } -PacketMatchTree::iterator PacketMatchTree::findMatch(iterator startAt, TmPacketMinimal* test) { +PacketMatchTree::iterator PacketMatchTree::findMatch(iterator startAt, PusTmIF* test) { iterator iter = startAt; while (iter != end()) { bool isMatch = iter->match(test); diff --git a/src/fsfw/tmtcpacket/packetmatcher/PacketMatchTree.h b/src/fsfw/tmtcpacket/packetmatcher/PacketMatchTree.h index e8727d71..b9d03f1d 100644 --- a/src/fsfw/tmtcpacket/packetmatcher/PacketMatchTree.h +++ b/src/fsfw/tmtcpacket/packetmatcher/PacketMatchTree.h @@ -4,21 +4,22 @@ #include "fsfw/container/PlacementFactory.h" #include "fsfw/globalfunctions/matching/MatchTree.h" #include "fsfw/storagemanager/LocalPool.h" -#include "fsfw/tmtcpacket/pus/tm/TmPacketMinimal.h" +#include "fsfw/tmtcpacket/pus/tm/PusTmIF.h" +#include "fsfw/tmtcpacket/pus/tm/PusTmMinimal.h" -class PacketMatchTree : public MatchTree { +class PacketMatchTree : public MatchTree { public: - PacketMatchTree(Node* root); - PacketMatchTree(iterator root); + explicit PacketMatchTree(Node* root); + explicit PacketMatchTree(iterator root); PacketMatchTree(); - virtual ~PacketMatchTree(); + ~PacketMatchTree() override; ReturnValue_t changeMatch(bool addToMatch, uint16_t apid, uint8_t type = 0, uint8_t subtype = 0); ReturnValue_t addMatch(uint16_t apid, uint8_t type = 0, uint8_t subtype = 0); ReturnValue_t removeMatch(uint16_t apid, uint8_t type = 0, uint8_t subtype = 0); ReturnValue_t initialize(); protected: - ReturnValue_t cleanUpElement(iterator position); + ReturnValue_t cleanUpElement(iterator position) override; private: static const uint8_t N_POOLS = 4; @@ -29,7 +30,7 @@ class PacketMatchTree : public MatchTree { static const uint16_t N_ELEMENTS[N_POOLS]; template ReturnValue_t findOrInsertMatch(iterator startAt, VALUE_T test, iterator* lastTest); - iterator findMatch(iterator startAt, TmPacketMinimal* test); + iterator findMatch(iterator startAt, PusTmIF* test); }; -#endif /* FRAMEWORK_TMTCPACKET_PACKETMATCHER_PACKETMATCHTREE_H_ */ +#endif /* FSFW_TMTCPACKET_PACKETMATCHER_PACKETMATCHTREE_H_ */ diff --git a/src/fsfw/tmtcpacket/packetmatcher/ServiceMatcher.h b/src/fsfw/tmtcpacket/packetmatcher/ServiceMatcher.h index 752c0354..6ccd9a6b 100644 --- a/src/fsfw/tmtcpacket/packetmatcher/ServiceMatcher.h +++ b/src/fsfw/tmtcpacket/packetmatcher/ServiceMatcher.h @@ -3,16 +3,16 @@ #include "../../globalfunctions/matching/SerializeableMatcherIF.h" #include "../../serialize/SerializeAdapter.h" -#include "../pus/tm/TmPacketMinimal.h" +#include "../pus/tm/PusTmMinimal.h" -class ServiceMatcher : public SerializeableMatcherIF { +class ServiceMatcher : public SerializeableMatcherIF { private: uint8_t service; public: - ServiceMatcher(uint8_t setService) : service(setService) {} - ServiceMatcher(TmPacketMinimal* test) : service(test->getService()) {} - bool match(TmPacketMinimal* packet) { + explicit ServiceMatcher(uint8_t setService) : service(setService) {} + explicit ServiceMatcher(PusTmIF* test) : service(test->getService()) {} + bool match(PusTmIF* packet) override { if (packet->getService() == service) { return true; } else { @@ -20,11 +20,14 @@ class ServiceMatcher : public SerializeableMatcherIF { } } ReturnValue_t serialize(uint8_t** buffer, size_t* size, size_t maxSize, - Endianness streamEndianness) const { + Endianness streamEndianness) const override { return SerializeAdapter::serialize(&service, buffer, size, maxSize, streamEndianness); } - size_t getSerializedSize() const { return SerializeAdapter::getSerializedSize(&service); } - ReturnValue_t deSerialize(const uint8_t** buffer, size_t* size, Endianness streamEndianness) { + [[nodiscard]] size_t getSerializedSize() const override { + return SerializeAdapter::getSerializedSize(&service); + } + ReturnValue_t deSerialize(const uint8_t** buffer, size_t* size, + Endianness streamEndianness) override { return SerializeAdapter::deSerialize(&service, buffer, size, streamEndianness); } }; diff --git a/src/fsfw/tmtcpacket/packetmatcher/SubserviceMatcher.h b/src/fsfw/tmtcpacket/packetmatcher/SubserviceMatcher.h index 934e8cb8..8729bbd5 100644 --- a/src/fsfw/tmtcpacket/packetmatcher/SubserviceMatcher.h +++ b/src/fsfw/tmtcpacket/packetmatcher/SubserviceMatcher.h @@ -3,13 +3,13 @@ #include "../../globalfunctions/matching/SerializeableMatcherIF.h" #include "../../serialize/SerializeAdapter.h" -#include "../pus/tm/TmPacketMinimal.h" +#include "../pus/tm/PusTmMinimal.h" -class SubServiceMatcher : public SerializeableMatcherIF { +class SubServiceMatcher : public SerializeableMatcherIF { public: - SubServiceMatcher(uint8_t subService) : subService(subService) {} - SubServiceMatcher(TmPacketMinimal* test) : subService(test->getSubService()) {} - bool match(TmPacketMinimal* packet) { + explicit SubServiceMatcher(uint8_t subService) : subService(subService) {} + explicit SubServiceMatcher(PusTmIF* test) : subService(test->getSubService()) {} + bool match(PusTmIF* packet) override { if (packet->getSubService() == subService) { return true; } else { @@ -17,16 +17,19 @@ class SubServiceMatcher : public SerializeableMatcherIF { } } ReturnValue_t serialize(uint8_t** buffer, size_t* size, size_t maxSize, - Endianness streamEndianness) const { + Endianness streamEndianness) const override { return SerializeAdapter::serialize(&subService, buffer, size, maxSize, streamEndianness); } - size_t getSerializedSize() const { return SerializeAdapter::getSerializedSize(&subService); } - ReturnValue_t deSerialize(const uint8_t** buffer, size_t* size, Endianness streamEndianness) { + [[nodiscard]] size_t getSerializedSize() const override { + return SerializeAdapter::getSerializedSize(&subService); + } + ReturnValue_t deSerialize(const uint8_t** buffer, size_t* size, + Endianness streamEndianness) override { return SerializeAdapter::deSerialize(&subService, buffer, size, streamEndianness); } private: - uint8_t subService; + uint8_t subService{}; }; #endif /* FRAMEWORK_TMTCPACKET_PACKETMATCHER_SUBSERVICEMATCHER_H_ */ diff --git a/src/fsfw/tmtcpacket/pus/CustomUserDataIF.h b/src/fsfw/tmtcpacket/pus/CustomUserDataIF.h new file mode 100644 index 00000000..779a0414 --- /dev/null +++ b/src/fsfw/tmtcpacket/pus/CustomUserDataIF.h @@ -0,0 +1,12 @@ +#ifndef FSFW_TMTCPACKET_CREATORDATAIF_H +#define FSFW_TMTCPACKET_CREATORDATAIF_H + +#include "defs.h" + +class CustomUserDataIF { + public: + virtual ~CustomUserDataIF() = default; + virtual ReturnValue_t setRawUserData(const uint8_t* data, size_t len) = 0; + virtual ReturnValue_t setSerializableUserData(SerializeIF& serializable) = 0; +}; +#endif // FSFW_TMTCPACKET_CREATORDATAIF_H diff --git a/src/fsfw/tmtcpacket/pus/PacketTimestampInterpreterIF.h b/src/fsfw/tmtcpacket/pus/PacketTimestampInterpreterIF.h index 87517fb6..36743fe8 100644 --- a/src/fsfw/tmtcpacket/pus/PacketTimestampInterpreterIF.h +++ b/src/fsfw/tmtcpacket/pus/PacketTimestampInterpreterIF.h @@ -3,13 +3,13 @@ #include "fsfw/returnvalues/returnvalue.h" -class TmPacketMinimal; +class PusTmMinimal; class PacketTimestampInterpreterIF { public: virtual ~PacketTimestampInterpreterIF() {} - virtual ReturnValue_t getPacketTime(TmPacketMinimal* packet, timeval* timestamp) const = 0; - virtual ReturnValue_t getPacketTimeRaw(TmPacketMinimal* packet, const uint8_t** timePtr, + virtual ReturnValue_t getPacketTime(PusTmMinimal* packet, timeval* timestamp) const = 0; + virtual ReturnValue_t getPacketTimeRaw(PusTmMinimal* packet, const uint8_t** timePtr, uint32_t* size) const = 0; }; diff --git a/src/fsfw/tmtcpacket/pus/PusIF.h b/src/fsfw/tmtcpacket/pus/PusIF.h new file mode 100644 index 00000000..ed447c75 --- /dev/null +++ b/src/fsfw/tmtcpacket/pus/PusIF.h @@ -0,0 +1,39 @@ +#ifndef FSFW_TMTCPACKET_PUSIF_H +#define FSFW_TMTCPACKET_PUSIF_H + +#include + +#include "fsfw/returnvalues/FwClassIds.h" +#include "fsfw/tmtcpacket/ccsds/SpacePacketIF.h" + +class PusIF : public SpacePacketIF { + public: + static constexpr uint8_t INTERFACE_ID = CLASS_ID::PUS_IF; + static constexpr ReturnValue_t INVALID_PUS_VERSION = returnvalue::makeCode(INTERFACE_ID, 0); + static constexpr ReturnValue_t INVALID_CRC_16 = returnvalue::makeCode(INTERFACE_ID, 1); + + ~PusIF() override = default; + /** + * This command returns the TC Packet PUS Version Number. + * The version number of ECSS PUS 2003 is 1. + * It consists of the second to fourth highest bits of the + * first byte. + * @return + */ + [[nodiscard]] virtual uint8_t getPusVersion() const = 0; + + /** + * This is a getter for the packet's PUS Service ID, which is the second + * byte of the Data Field Header. + * @return The packet's PUS Service ID. + */ + [[nodiscard]] virtual uint8_t getService() const = 0; + /** + * This is a getter for the packet's PUS Service Subtype, which is the + * third byte of the Data Field Header. + * @return The packet's PUS Service Subtype. + */ + [[nodiscard]] virtual uint8_t getSubService() const = 0; +}; + +#endif // FSFW_TMTCPACKET_PUSIF_H diff --git a/src/fsfw/tmtcpacket/pus/RawUserDataReaderIF.h b/src/fsfw/tmtcpacket/pus/RawUserDataReaderIF.h new file mode 100644 index 00000000..799b7940 --- /dev/null +++ b/src/fsfw/tmtcpacket/pus/RawUserDataReaderIF.h @@ -0,0 +1,14 @@ +#ifndef FSFW_TMTCPACKET_RAWDATAIF_H +#define FSFW_TMTCPACKET_RAWDATAIF_H + +#include +#include + +class RawUserDataReaderIF { + public: + ~RawUserDataReaderIF() = default; + [[nodiscard]] virtual const uint8_t* getUserData() const = 0; + [[nodiscard]] virtual size_t getUserDataLen() const = 0; +}; + +#endif // FSFW_TMTCPACKET_RAWDATAIF_H diff --git a/src/fsfw/tmtcpacket/pus/definitions.h b/src/fsfw/tmtcpacket/pus/definitions.h deleted file mode 100644 index d4b649d0..00000000 --- a/src/fsfw/tmtcpacket/pus/definitions.h +++ /dev/null @@ -1,13 +0,0 @@ -#ifndef FSFW_SRC_FSFW_TMTCPACKET_PUS_TM_DEFINITIONS_H_ -#define FSFW_SRC_FSFW_TMTCPACKET_PUS_TM_DEFINITIONS_H_ - -#include - -namespace pus { - -//! Version numbers according to ECSS-E-ST-70-41C p.439 -enum PusVersion : uint8_t { PUS_A_VERSION = 1, PUS_C_VERSION = 2 }; - -} // namespace pus - -#endif /* FSFW_SRC_FSFW_TMTCPACKET_PUS_TM_DEFINITIONS_H_ */ diff --git a/src/fsfw/tmtcpacket/pus/defs.h b/src/fsfw/tmtcpacket/pus/defs.h new file mode 100644 index 00000000..c5172d8b --- /dev/null +++ b/src/fsfw/tmtcpacket/pus/defs.h @@ -0,0 +1,30 @@ +#ifndef FSFW_SRC_FSFW_TMTCPACKET_PUS_TM_DEFINITIONS_H_ +#define FSFW_SRC_FSFW_TMTCPACKET_PUS_TM_DEFINITIONS_H_ + +#include +#include + +#include "fsfw/serialize/SerializeIF.h" + +namespace ecss { + +using PusChecksumT = uint16_t; + +//! Version numbers according to ECSS-E-ST-70-41C p.439 +enum PusVersion : uint8_t { PUS_A = 1, PUS_C = 2 }; + +/** + * This struct defines the data structure of a Space Packet when accessed + * via a pointer. + * @ingroup tmtcpackets + */ +struct PusPointers { + const uint8_t* spHeaderStart; + const uint8_t* secHeaderStart; + const uint8_t* userDataStart; + const uint8_t* crcStart; +}; + +} // namespace ecss + +#endif /* FSFW_SRC_FSFW_TMTCPACKET_PUS_TM_DEFINITIONS_H_ */ diff --git a/src/fsfw/tmtcpacket/pus/tc.h b/src/fsfw/tmtcpacket/pus/tc.h index f5a467aa..e5e5f9f7 100644 --- a/src/fsfw/tmtcpacket/pus/tc.h +++ b/src/fsfw/tmtcpacket/pus/tc.h @@ -1,7 +1,7 @@ #ifndef FSFW_TMTCPACKET_PUS_TC_H_ #define FSFW_TMTCPACKET_PUS_TC_H_ -#include "tc/TcPacketPus.h" -#include "tc/TcPacketStoredPus.h" +#include "tc/PusTcCreator.h" +#include "tc/PusTcReader.h" #endif /* FSFW_TMTCPACKET_PUS_TC_H_ */ diff --git a/src/fsfw/tmtcpacket/pus/tc/CMakeLists.txt b/src/fsfw/tmtcpacket/pus/tc/CMakeLists.txt index 09c63bfd..adf7f34d 100644 --- a/src/fsfw/tmtcpacket/pus/tc/CMakeLists.txt +++ b/src/fsfw/tmtcpacket/pus/tc/CMakeLists.txt @@ -1,3 +1,2 @@ -target_sources( - ${LIB_FSFW_NAME} PRIVATE TcPacketPusBase.cpp TcPacketPus.cpp - TcPacketStoredBase.cpp TcPacketStoredPus.cpp) +target_sources(${LIB_FSFW_NAME} PRIVATE PusTcReader.cpp PusTcReader.cpp + PusTcCreator.cpp) diff --git a/src/fsfw/tmtcpacket/pus/tc/PusTcCreator.cpp b/src/fsfw/tmtcpacket/pus/tc/PusTcCreator.cpp new file mode 100644 index 00000000..14a440a0 --- /dev/null +++ b/src/fsfw/tmtcpacket/pus/tc/PusTcCreator.cpp @@ -0,0 +1,110 @@ +#include "PusTcCreator.h" + +#include + +#include "PusTcIF.h" +#include "fsfw/globalfunctions/CRC.h" +#include "fsfw/serialize/SerializeAdapter.h" + +PusTcCreator::PusTcCreator(SpacePacketParams spParams, PusTcParams pusParams) + : spCreator(std::move(spParams)), pusParams(pusParams) { + setup(); +} + +ReturnValue_t PusTcCreator::serialize(uint8_t **buffer, size_t *size, size_t maxSize, + SerializeIF::Endianness streamEndianness) const { + const uint8_t *start = *buffer; + size_t userDataLen = pusParams.dataWrapper.getLength(); + if (*size + getSerializedSize() > maxSize) { + return SerializeIF::BUFFER_TOO_SHORT; + } + if (pusParams.pusVersion != ecss::PusVersion::PUS_C) { + return PusIF::INVALID_PUS_VERSION; + } + ReturnValue_t result = spCreator.serialize(buffer, size, maxSize, streamEndianness); + if (result != returnvalue::OK) { + return result; + } + **buffer = pusParams.pusVersion << 4 | pusParams.ackFlags; + *buffer += 1; + **buffer = pusParams.service; + *buffer += 1; + **buffer = pusParams.subservice; + *buffer += 1; + *size += 3; + result = + SerializeAdapter::serialize(&pusParams.sourceId, buffer, size, maxSize, streamEndianness); + if (result != returnvalue::OK) { + return result; + } + if (pusParams.dataWrapper.type == util::DataTypes::RAW) { + const uint8_t *data = pusParams.dataWrapper.dataUnion.raw.data; + if (data != nullptr and userDataLen > 0) { + std::memcpy(*buffer, data, userDataLen); + *buffer += userDataLen; + *size += userDataLen; + } + } else if (pusParams.dataWrapper.type == util::DataTypes::SERIALIZABLE and + pusParams.dataWrapper.dataUnion.serializable != nullptr) { + result = pusParams.dataWrapper.dataUnion.serializable->serialize(buffer, size, maxSize, + streamEndianness); + if (result != returnvalue::OK) { + return result; + } + } + + uint16_t crc16 = CRC::crc16ccitt(start, getFullPacketLen() - sizeof(ecss::PusChecksumT)); + return SerializeAdapter::serialize(&crc16, buffer, size, maxSize, streamEndianness); +} + +void PusTcCreator::updateSpLengthField() { + spCreator.setDataLen(ecss::PusTcDataFieldHeader::MIN_SIZE + pusParams.dataWrapper.getLength() + + 1); +} + +size_t PusTcCreator::getSerializedSize() const { return spCreator.getFullPacketLen(); } + +ReturnValue_t PusTcCreator::deSerialize(const uint8_t **buffer, size_t *size, + SerializeIF::Endianness streamEndianness) { + return returnvalue::FAILED; +} + +uint16_t PusTcCreator::getPacketIdRaw() const { return spCreator.getPacketIdRaw(); } + +uint16_t PusTcCreator::getPacketSeqCtrlRaw() const { return spCreator.getPacketSeqCtrlRaw(); } + +uint16_t PusTcCreator::getPacketDataLen() const { return spCreator.getPacketDataLen(); } + +uint8_t PusTcCreator::getPusVersion() const { return pusParams.pusVersion; } + +uint8_t PusTcCreator::getAcknowledgeFlags() const { return pusParams.ackFlags; } + +uint8_t PusTcCreator::getService() const { return pusParams.service; } + +uint8_t PusTcCreator::getSubService() const { return pusParams.subservice; } + +uint16_t PusTcCreator::getSourceId() const { return pusParams.sourceId; } + +PusTcParams &PusTcCreator::getPusParams() { return pusParams; } + +SpacePacketParams &PusTcCreator::getSpParams() { return spCreator.getParams(); } + +ReturnValue_t PusTcCreator::setRawUserData(const uint8_t *data, size_t len) { + // TODO: Check length field? + pusParams.dataWrapper.setRawData({data, len}); + updateSpLengthField(); + return returnvalue::OK; +} + +ReturnValue_t PusTcCreator::setSerializableUserData(SerializeIF &serializable) { + // TODO: Check length field? + pusParams.dataWrapper.setSerializable(serializable); + updateSpLengthField(); + return returnvalue::OK; +} + +void PusTcCreator::setup() { + spCreator.setPacketType(ccsds::PacketType::TC); + spCreator.setSecHeaderFlag(); + updateSpLengthField(); +} diff --git a/src/fsfw/tmtcpacket/pus/tc/PusTcCreator.h b/src/fsfw/tmtcpacket/pus/tc/PusTcCreator.h new file mode 100644 index 00000000..4b0d81c8 --- /dev/null +++ b/src/fsfw/tmtcpacket/pus/tc/PusTcCreator.h @@ -0,0 +1,72 @@ +#ifndef FSFW_TMTCPACKET_TCPACKETDESERIALIZER_H +#define FSFW_TMTCPACKET_TCPACKETDESERIALIZER_H + +#include "fsfw/tmtcpacket/RedirectableDataPointerIF.h" +#include "fsfw/tmtcpacket/ccsds/SpacePacketCreator.h" +#include "fsfw/tmtcpacket/ccsds/SpacePacketIF.h" +#include "fsfw/tmtcpacket/pus/CustomUserDataIF.h" +#include "fsfw/tmtcpacket/pus/defs.h" +#include "fsfw/tmtcpacket/pus/tc/PusTcIF.h" +#include "fsfw/util/dataWrapper.h" + +struct PusTcParams { + PusTcParams(uint8_t service_, uint8_t subservice_) : service(service_), subservice(subservice_) {} + + uint8_t service; + uint8_t subservice; + uint8_t ackFlags = ecss::ACK_ALL; + uint16_t sourceId = 0; + util::DataWrapper dataWrapper{}; + uint8_t pusVersion = ecss::PusVersion::PUS_C; +}; + +/** + * This class provides a high-level interface to create PUS TC packets and then @serialize + * them into a raw byte format. It implements @SerializeIF for that purpose. + * A custom time stamper can be set, with the implementation of @TimeStamperIF as the only + * requirement. + */ +class PusTcCreator : public PusTcIF, public SerializeIF, public CustomUserDataIF { + public: + PusTcCreator(SpacePacketParams initSpParams, PusTcParams initPusParams); + + /** + * If the parameter structure is changed in a way which changes the resulting serialized packet + * size, this function should be called to set the data length field in the space packet + * header. This fields is the primary source of information for length information. + * + * The only case for a telecommand where this size changes would be if user data is set. + */ + void updateSpLengthField(); + PusTcParams &getPusParams(); + SpacePacketParams &getSpParams(); + + [[nodiscard]] size_t getSerializedSize() const override; + + [[nodiscard]] uint16_t getPacketIdRaw() const override; + [[nodiscard]] uint16_t getPacketSeqCtrlRaw() const override; + [[nodiscard]] uint16_t getPacketDataLen() const override; + [[nodiscard]] uint8_t getPusVersion() const override; + [[nodiscard]] uint8_t getAcknowledgeFlags() const override; + [[nodiscard]] uint8_t getService() const override; + [[nodiscard]] uint8_t getSubService() const override; + [[nodiscard]] uint16_t getSourceId() const override; + ReturnValue_t setRawUserData(const uint8_t *data, size_t len) override; + ReturnValue_t setSerializableUserData(SerializeIF &serializable) override; + + // Load all big endian helpers into the class namespace + using SerializeIF::serializeBe; + + private: + // Forbidden to use, enforce big endian serialization + ReturnValue_t serialize(uint8_t **buffer, size_t *size, size_t maxSize, + Endianness streamEndianness) const override; + // Forbidden to use + ReturnValue_t deSerialize(const uint8_t **buffer, size_t *size, + Endianness streamEndianness) override; + void setup(); + SpacePacketCreator spCreator; + PusTcParams pusParams; +}; + +#endif // FSFW_TMTCPACKET_TCPACKETDESERIALIZER_H diff --git a/src/fsfw/tmtcpacket/pus/tc/PusTcIF.h b/src/fsfw/tmtcpacket/pus/tc/PusTcIF.h new file mode 100644 index 00000000..43e9aab0 --- /dev/null +++ b/src/fsfw/tmtcpacket/pus/tc/PusTcIF.h @@ -0,0 +1,67 @@ +#ifndef FSFW_TMTCPACKET_PUSTCIF_H +#define FSFW_TMTCPACKET_PUSTCIF_H + +#include + +#include "fsfw/tmtcpacket/pus/PusIF.h" + +namespace ecss { + +enum AckField { + //! No acknowledgements are expected. + ACK_NONE = 0b0000, + //! Acknowledgements on acceptance are expected. + ACK_ACCEPTANCE = 0b0001, + //! Acknowledgements on start are expected. + ACK_START = 0b0010, + //! Acknowledgements on step are expected. + ACK_STEP = 0b0100, + //! Acknowledgement on completion are expected. + ACK_COMPLETION = 0b1000 +}; + +static constexpr uint8_t ACK_ALL = ACK_ACCEPTANCE | ACK_START | ACK_STEP | ACK_COMPLETION; + +/** + * This struct defines a byte-wise structured PUS C data Field Header. + * Any optional fields in the header must be added or removed here. + * Currently, the Source Id field is present with one byte. + * No spare byte support for now. + * @ingroup tmtcpackets + */ +struct PusTcDataFieldHeader { + // Version and ACK byte, Service Byte, Subservice Byte, 2 byte Source ID + static constexpr size_t MIN_SIZE = 5; + uint8_t pusVersion; + uint8_t ackFlags; + uint8_t serviceType; + uint8_t serviceSubtype; + uint16_t sourceId; +}; + +} // namespace ecss + +class PusTcIF : public PusIF { + public: + ~PusTcIF() override = default; + static const size_t MIN_SIZE = + (sizeof(ccsds::PrimaryHeader) + ecss::PusTcDataFieldHeader::MIN_SIZE + 2); + + /** + * This is a getter for the packet's Ack field, which are the lowest four + * bits of the first byte of the Data Field Header. + * + * It is packed in a uint8_t variable. + * @return The packet's PUS Ack field. + */ + [[nodiscard]] virtual uint8_t getAcknowledgeFlags() const = 0; + + /** + * The source ID can be used to have an additional identifier, e.g. for different ground + * station. + * @return + */ + [[nodiscard]] virtual uint16_t getSourceId() const = 0; +}; + +#endif // FSFW_TMTCPACKET_PUSTCIF_H diff --git a/src/fsfw/tmtcpacket/pus/tc/PusTcReader.cpp b/src/fsfw/tmtcpacket/pus/tc/PusTcReader.cpp new file mode 100644 index 00000000..06805e30 --- /dev/null +++ b/src/fsfw/tmtcpacket/pus/tc/PusTcReader.cpp @@ -0,0 +1,86 @@ +#include "PusTcReader.h" + +#include + +#include "fsfw/globalfunctions/CRC.h" +#include "fsfw/globalfunctions/arrayprinter.h" +#include "fsfw/serialize.h" +#include "fsfw/serviceinterface/ServiceInterface.h" + +PusTcReader::PusTcReader(const uint8_t* data, size_t size) { setReadOnlyData(data, size); } + +PusTcReader::~PusTcReader() = default; + +ReturnValue_t PusTcReader::parseDataWithCrcCheck() { return parseData(true); } + +ReturnValue_t PusTcReader::parseDataWithoutCrcCheck() { return parseData(false); } + +ReturnValue_t PusTcReader::parseData(bool withCrc) { + if (pointers.spHeaderStart == nullptr or spReader.isNull()) { + return returnvalue::FAILED; + } + ReturnValue_t result = spReader.checkSize(); + if (result != returnvalue::OK) { + return result; + } + size_t currentOffset = SpacePacketReader::getHeaderLen(); + pointers.secHeaderStart = pointers.spHeaderStart + currentOffset; + // Might become variable sized field in the future + // TODO: No support for spare bytes yet + currentOffset += ecss::PusTcDataFieldHeader::MIN_SIZE; + appDataSize = spReader.getFullPacketLen() - currentOffset - sizeof(ecss::PusChecksumT); + pointers.userDataStart = nullptr; + if (appDataSize > 0) { + pointers.userDataStart = pointers.spHeaderStart + currentOffset; + } + currentOffset += appDataSize; + pointers.crcStart = pointers.spHeaderStart + currentOffset; + if (withCrc) { + uint16_t crc16 = CRC::crc16ccitt(spReader.getFullData(), getFullPacketLen()); + if (crc16 != 0) { + // Checksum failure + return PusIF::INVALID_CRC_16; + } + } + return returnvalue::OK; +} + +uint8_t PusTcReader::getPusVersion() const { return (pointers.secHeaderStart[0] >> 4) & 0b1111; } + +uint8_t PusTcReader::getAcknowledgeFlags() const { return pointers.secHeaderStart[0] & 0b1111; } + +uint8_t PusTcReader::getService() const { return pointers.secHeaderStart[1]; } + +uint8_t PusTcReader::getSubService() const { return pointers.secHeaderStart[2]; } + +uint16_t PusTcReader::getSourceId() const { + return (pointers.secHeaderStart[3] << 8) | pointers.secHeaderStart[4]; +} + +uint16_t PusTcReader::getErrorControl() const { + return (pointers.crcStart[0] << 8) | pointers.crcStart[1]; +} + +uint16_t PusTcReader::getPacketIdRaw() const { return spReader.getPacketIdRaw(); } + +uint16_t PusTcReader::getPacketSeqCtrlRaw() const { return spReader.getPacketSeqCtrlRaw(); } + +uint16_t PusTcReader::getPacketDataLen() const { return spReader.getPacketDataLen(); } + +const uint8_t* PusTcReader::getFullData() const { return pointers.spHeaderStart; } + +ReturnValue_t PusTcReader::setData(uint8_t* pData, size_t size_, void* args) { + pointers.spHeaderStart = pData; + return spReader.setReadOnlyData(pData, size_); +} + +ReturnValue_t PusTcReader::setReadOnlyData(const uint8_t* data, size_t size_) { + return setData(const_cast(data), size_, nullptr); +} + +const uint8_t* PusTcReader::getUserData() const { return pointers.userDataStart; } +size_t PusTcReader::getUserDataLen() const { return appDataSize; } + +bool PusTcReader::isNull() const { return spReader.isNull(); } + +PusTcReader::operator bool() const { return not isNull(); } diff --git a/src/fsfw/tmtcpacket/pus/tc/PusTcReader.h b/src/fsfw/tmtcpacket/pus/tc/PusTcReader.h new file mode 100644 index 00000000..03af43a9 --- /dev/null +++ b/src/fsfw/tmtcpacket/pus/tc/PusTcReader.h @@ -0,0 +1,80 @@ +#ifndef TMTCPACKET_PUS_TCPACKETBASE_H_ +#define TMTCPACKET_PUS_TCPACKETBASE_H_ + +#include + +#include "PusTcIF.h" +#include "fsfw/tmtcpacket/RedirectableDataPointerIF.h" +#include "fsfw/tmtcpacket/ccsds/SpacePacketReader.h" +#include "fsfw/tmtcpacket/pus/RawUserDataReaderIF.h" +#include "fsfw/tmtcpacket/pus/defs.h" + +/** + * This class is the basic reader class to read ECSS PUS C Telecommand packets. + * + * 1. Implements the @SpacePacketIF to provide accessor methods for the contained space packet. + * 2. Implements the @PusTcIF to provide accessor methods for generic PUS C fields + * + * This is a zero-copy reader class. It does not contain the packet data itself but a pointer to + * the data. Calling any accessor methods without pointing the object to valid data first will + * cause undefined behaviour. + * @ingroup tmtcpackets + */ +class PusTcReader : public PusTcIF, + public RawUserDataReaderIF, + public ReadablePacketIF, + public RedirectableDataPointerIF { + public: + PusTcReader() = default; + /** + * This is the default constructor. + * It sets its internal data pointer to the address passed and also + * forwards the data pointer to the parent SpacePacketBase class. + * @param setData The position where the packet data lies. + */ + PusTcReader(const uint8_t* setData, size_t size); + ~PusTcReader() override; + + explicit operator bool() const; + [[nodiscard]] bool isNull() const; + ReturnValue_t parseDataWithCrcCheck(); + ReturnValue_t parseDataWithoutCrcCheck(); + + /** + * This is a debugging helper method that prints the whole packet content + * to the screen. + */ + // void print(); + [[nodiscard]] uint16_t getPacketIdRaw() const override; + [[nodiscard]] uint16_t getPacketSeqCtrlRaw() const override; + [[nodiscard]] uint16_t getPacketDataLen() const override; + [[nodiscard]] uint8_t getPusVersion() const override; + [[nodiscard]] uint8_t getAcknowledgeFlags() const override; + [[nodiscard]] uint8_t getService() const override; + [[nodiscard]] uint8_t getSubService() const override; + [[nodiscard]] uint16_t getSourceId() const override; + [[nodiscard]] uint16_t getErrorControl() const; + const uint8_t* getFullData() const override; + + ReturnValue_t setReadOnlyData(const uint8_t* data, size_t size); + [[nodiscard]] const uint8_t* getUserData() const override; + [[nodiscard]] size_t getUserDataLen() const override; + + protected: + /** + * With this method, the packet data pointer can be redirected to another + * location. + * This call overwrites the parent's setData method to set both its + * @c tc_data pointer and the parent's @c data pointer. + * + * @param p_data A pointer to another PUS Telecommand Packet. + */ + ReturnValue_t setData(uint8_t* pData, size_t size, void* args) override; + ReturnValue_t parseData(bool withCrc); + + SpacePacketReader spReader; + ecss::PusPointers pointers{}; + size_t appDataSize = 0; +}; + +#endif /* TMTCPACKET_PUS_TCPACKETBASE_H_ */ diff --git a/src/fsfw/tmtcpacket/pus/tc/TcPacketPus.cpp b/src/fsfw/tmtcpacket/pus/tc/TcPacketPus.cpp deleted file mode 100644 index 7120e62f..00000000 --- a/src/fsfw/tmtcpacket/pus/tc/TcPacketPus.cpp +++ /dev/null @@ -1,99 +0,0 @@ -#include "TcPacketPus.h" - -#include - -#include "fsfw/globalfunctions/CRC.h" - -TcPacketPus::TcPacketPus(const uint8_t *setData) : TcPacketPusBase(setData) { - tcData = reinterpret_cast(const_cast(setData)); -} - -void TcPacketPus::initializeTcPacket(uint16_t apid, uint16_t sequenceCount, uint8_t ack, - uint8_t service, uint8_t subservice, - pus::PusVersion pusVersion, uint16_t sourceId) { - initSpacePacketHeader(true, true, apid, sequenceCount); - std::memset(&tcData->dataField, 0, sizeof(tcData->dataField)); - setPacketDataLength(sizeof(PUSTcDataFieldHeader) + CRC_SIZE - 1); - // Data Field Header. For PUS A, the first bit (CCSDS Secondary Header Flag) is zero - tcData->dataField.versionTypeAck = pusVersion << 4 | (ack & 0x0F); - tcData->dataField.serviceType = service; - tcData->dataField.serviceSubtype = subservice; -#if FSFW_USE_PUS_C_TELECOMMANDS == 1 - tcData->dataField.sourceIdH = (sourceId >> 8) | 0xff; - tcData->dataField.sourceIdL = sourceId & 0xff; -#else - tcData->dataField.sourceId = sourceId; -#endif -} - -uint8_t TcPacketPus::getService() const { return tcData->dataField.serviceType; } - -uint8_t TcPacketPus::getSubService() const { return tcData->dataField.serviceSubtype; } - -uint8_t TcPacketPus::getAcknowledgeFlags() const { - return tcData->dataField.versionTypeAck & 0b00001111; -} - -const uint8_t *TcPacketPus::getApplicationData() const { return &tcData->appData; } - -uint16_t TcPacketPus::getApplicationDataSize() const { - return getPacketDataLength() - sizeof(tcData->dataField) - CRC_SIZE + 1; -} - -uint16_t TcPacketPus::getErrorControl() const { - uint16_t size = getApplicationDataSize() + CRC_SIZE; - uint8_t *p_to_buffer = &tcData->appData; - return (p_to_buffer[size - 2] << 8) + p_to_buffer[size - 1]; -} - -void TcPacketPus::setErrorControl() { - uint32_t full_size = getFullSize(); - uint16_t crc = CRC::crc16ccitt(getWholeData(), full_size - CRC_SIZE); - uint32_t size = getApplicationDataSize(); - (&tcData->appData)[size] = (crc & 0XFF00) >> 8; // CRCH - (&tcData->appData)[size + 1] = (crc)&0X00FF; // CRCL -} - -uint8_t TcPacketPus::getSecondaryHeaderFlag() const { -#if FSFW_USE_PUS_C_TELECOMMANDS == 1 - // Does not exist for PUS C - return 0; -#else - return (tcData->dataField.versionTypeAck & 0b10000000) >> 7; -#endif -} - -uint8_t TcPacketPus::getPusVersionNumber() const { -#if FSFW_USE_PUS_C_TELECOMMANDS == 1 - return (tcData->dataField.versionTypeAck & 0b11110000) >> 4; -#else - return (tcData->dataField.versionTypeAck & 0b01110000) >> 4; -#endif -} - -uint16_t TcPacketPus::getSourceId() const { -#if FSFW_USE_PUS_C_TELECOMMANDS == 1 - return (tcData->dataField.sourceIdH << 8) | tcData->dataField.sourceIdL; -#else - return tcData->dataField.sourceId; -#endif -} - -size_t TcPacketPus::calculateFullPacketLength(size_t appDataLen) const { - return sizeof(CCSDSPrimaryHeader) + sizeof(PUSTcDataFieldHeader) + appDataLen + - TcPacketPusBase::CRC_SIZE; -} - -ReturnValue_t TcPacketPus::setData(uint8_t *dataPtr, size_t maxSize, void *args) { - ReturnValue_t result = SpacePacketBase::setData(dataPtr, maxSize); - if (result != returnvalue::OK) { - return result; - } - if (maxSize < sizeof(TcPacketPointer)) { - return returnvalue::FAILED; - } - // This function is const-correct, but it was decided to keep the pointer non-const - // for convenience. Therefore, cast away constness here and then cast to packet type. - tcData = reinterpret_cast(const_cast(dataPtr)); - return returnvalue::OK; -} diff --git a/src/fsfw/tmtcpacket/pus/tc/TcPacketPus.h b/src/fsfw/tmtcpacket/pus/tc/TcPacketPus.h deleted file mode 100644 index 47173dad..00000000 --- a/src/fsfw/tmtcpacket/pus/tc/TcPacketPus.h +++ /dev/null @@ -1,88 +0,0 @@ -#ifndef FSFW_TMTCPACKET_PUS_TCPACKETPUSA_H_ -#define FSFW_TMTCPACKET_PUS_TCPACKETPUSA_H_ - -#include - -#include "../definitions.h" -#include "TcPacketPusBase.h" -#include "fsfw/FSFW.h" -#include "fsfw/tmtcpacket/ccsds_header.h" - -/** - * This struct defines a byte-wise structured PUS TC A Data Field Header. - * Any optional fields in the header must be added or removed here. - * Currently, the Source Id field is present with one byte. - * @ingroup tmtcpackets - */ -struct PUSTcDataFieldHeader { - uint8_t versionTypeAck; - uint8_t serviceType; - uint8_t serviceSubtype; -#if FSFW_USE_PUS_C_TELECOMMANDS == 1 - uint8_t sourceIdH; - uint8_t sourceIdL; -#else - uint8_t sourceId; -#endif -}; - -/** - * This struct defines the data structure of a PUS Telecommand A packet when - * accessed via a pointer. - * @ingroup tmtcpackets - */ -struct TcPacketPointer { - CCSDSPrimaryHeader primary; - PUSTcDataFieldHeader dataField; - uint8_t appData; -}; - -class TcPacketPus : public TcPacketPusBase { - public: - static const uint16_t TC_PACKET_MIN_SIZE = - (sizeof(CCSDSPrimaryHeader) + sizeof(PUSTcDataFieldHeader) + 2); - - /** - * Initialize a PUS A telecommand packet which already exists. You can also - * create an empty (invalid) object by passing nullptr as the data pointer - * @param setData - */ - TcPacketPus(const uint8_t* setData); - - // Base class overrides - uint8_t getSecondaryHeaderFlag() const override; - uint8_t getPusVersionNumber() const override; - uint8_t getAcknowledgeFlags() const override; - uint8_t getService() const override; - uint8_t getSubService() const override; - uint16_t getSourceId() const override; - const uint8_t* getApplicationData() const override; - uint16_t getApplicationDataSize() const override; - uint16_t getErrorControl() const override; - void setErrorControl() override; - size_t calculateFullPacketLength(size_t appDataLen) const override; - - protected: - ReturnValue_t setData(uint8_t* dataPtr, size_t maxSize, void* args = nullptr) override; - - /** - * Initializes the Tc Packet header. - * @param apid APID used. - * @param sequenceCount Sequence Count in the primary header. - * @param ack Which acknowledeges are expected from the receiver. - * @param service PUS Service - * @param subservice PUS Subservice - */ - void initializeTcPacket(uint16_t apid, uint16_t sequenceCount, uint8_t ack, uint8_t service, - uint8_t subservice, pus::PusVersion pusVersion, uint16_t sourceId = 0); - - /** - * A pointer to a structure which defines the data structure of - * the packet's data. - * - * To be hardware-safe, all elements are of byte size. - */ - TcPacketPointer* tcData = nullptr; -}; - -#endif /* FSFW_TMTCPACKET_PUS_TCPACKETPUSA_H_ */ diff --git a/src/fsfw/tmtcpacket/pus/tc/TcPacketPusBase.cpp b/src/fsfw/tmtcpacket/pus/tc/TcPacketPusBase.cpp deleted file mode 100644 index 812bae43..00000000 --- a/src/fsfw/tmtcpacket/pus/tc/TcPacketPusBase.cpp +++ /dev/null @@ -1,20 +0,0 @@ -#include "TcPacketPusBase.h" - -#include - -#include "fsfw/globalfunctions/CRC.h" -#include "fsfw/globalfunctions/arrayprinter.h" -#include "fsfw/serviceinterface/ServiceInterface.h" - -TcPacketPusBase::TcPacketPusBase(const uint8_t* setData) : SpacePacketBase(setData) {} - -TcPacketPusBase::~TcPacketPusBase() {} - -void TcPacketPusBase::print() { -#if FSFW_CPP_OSTREAM_ENABLED == 1 - sif::info << "TcPacketBase::print:" << std::endl; -#else - sif::printInfo("TcPacketBase::print:\n"); -#endif - arrayprinter::print(getWholeData(), getFullSize()); -} diff --git a/src/fsfw/tmtcpacket/pus/tc/TcPacketPusBase.h b/src/fsfw/tmtcpacket/pus/tc/TcPacketPusBase.h deleted file mode 100644 index 9f1d07ed..00000000 --- a/src/fsfw/tmtcpacket/pus/tc/TcPacketPusBase.h +++ /dev/null @@ -1,151 +0,0 @@ -#ifndef TMTCPACKET_PUS_TCPACKETBASE_H_ -#define TMTCPACKET_PUS_TCPACKETBASE_H_ - -#include - -#include - -#include "fsfw/tmtcpacket/SpacePacketBase.h" - -/** - * This class is the basic data handler for any ECSS PUS Telecommand packet. - * - * In addition to #SpacePacketBase, the class provides methods to handle - * the standardized entries of the PUS TC Packet Data Field Header. - * It does not contain the packet data itself but a pointer to the - * data must be set on instantiation. An invalid pointer may cause - * damage, as no getter method checks data validity. Anyway, a NULL - * check can be performed by making use of the getWholeData method. - * @ingroup tmtcpackets - */ -class TcPacketPusBase : public SpacePacketBase, virtual public RedirectableDataPointerIF { - friend class TcPacketStoredBase; - - public: - enum AckField { - //! No acknowledgements are expected. - ACK_NONE = 0b0000, - //! Acknowledgements on acceptance are expected. - ACK_ACCEPTANCE = 0b0001, - //! Acknowledgements on start are expected. - ACK_START = 0b0010, - //! Acknowledgements on step are expected. - ACK_STEP = 0b0100, - //! Acknowledfgement on completion are expected. - ACK_COMPLETION = 0b1000 - }; - - static constexpr uint8_t ACK_ALL = ACK_ACCEPTANCE | ACK_START | ACK_STEP | ACK_COMPLETION; - - /** - * This is the default constructor. - * It sets its internal data pointer to the address passed and also - * forwards the data pointer to the parent SpacePacketBase class. - * @param setData The position where the packet data lies. - */ - TcPacketPusBase(const uint8_t* setData); - /** - * This is the empty default destructor. - */ - virtual ~TcPacketPusBase(); - - /** - * This command returns the CCSDS Secondary Header Flag. - * It shall always be zero for PUS Packets. This is the - * highest bit of the first byte of the Data Field Header. - * @return the CCSDS Secondary Header Flag - */ - virtual uint8_t getSecondaryHeaderFlag() const = 0; - /** - * This command returns the TC Packet PUS Version Number. - * The version number of ECSS PUS 2003 is 1. - * It consists of the second to fourth highest bits of the - * first byte. - * @return - */ - virtual uint8_t getPusVersionNumber() const = 0; - /** - * This is a getter for the packet's Ack field, which are the lowest four - * bits of the first byte of the Data Field Header. - * - * It is packed in a uint8_t variable. - * @return The packet's PUS Ack field. - */ - virtual uint8_t getAcknowledgeFlags() const = 0; - /** - * This is a getter for the packet's PUS Service ID, which is the second - * byte of the Data Field Header. - * @return The packet's PUS Service ID. - */ - virtual uint8_t getService() const = 0; - /** - * This is a getter for the packet's PUS Service Subtype, which is the - * third byte of the Data Field Header. - * @return The packet's PUS Service Subtype. - */ - virtual uint8_t getSubService() const = 0; - /** - * The source ID can be used to have an additional identifier, e.g. for different ground - * station. - * @return - */ - virtual uint16_t getSourceId() const = 0; - - /** - * This is a getter for a pointer to the packet's Application data. - * - * These are the bytes that follow after the Data Field Header. They form - * the packet's application data. - * @return A pointer to the PUS Application Data. - */ - virtual const uint8_t* getApplicationData() const = 0; - /** - * This method calculates the size of the PUS Application data field. - * - * It takes the information stored in the CCSDS Packet Data Length field - * and subtracts the Data Field Header size and the CRC size. - * @return The size of the PUS Application Data (without Error Control - * field) - */ - virtual uint16_t getApplicationDataSize() const = 0; - /** - * This getter returns the Error Control Field of the packet. - * - * The field is placed after any possible Application Data. If no - * Application Data is present there's still an Error Control field. It is - * supposed to be a 16bit-CRC. - * @return The PUS Error Control - */ - virtual uint16_t getErrorControl() const = 0; - /** - * With this method, the Error Control Field is updated to match the - * current content of the packet. - */ - virtual void setErrorControl() = 0; - - /** - * Calculate full packet length from application data length. - * @param appDataLen - * @return - */ - virtual size_t calculateFullPacketLength(size_t appDataLen) const = 0; - - /** - * This is a debugging helper method that prints the whole packet content - * to the screen. - */ - void print(); - - protected: - /** - * With this method, the packet data pointer can be redirected to another - * location. - * This call overwrites the parent's setData method to set both its - * @c tc_data pointer and the parent's @c data pointer. - * - * @param p_data A pointer to another PUS Telecommand Packet. - */ - virtual ReturnValue_t setData(uint8_t* pData, size_t maxSize, void* args = nullptr) override = 0; -}; - -#endif /* TMTCPACKET_PUS_TCPACKETBASE_H_ */ diff --git a/src/fsfw/tmtcpacket/pus/tc/TcPacketStoredBase.cpp b/src/fsfw/tmtcpacket/pus/tc/TcPacketStoredBase.cpp deleted file mode 100644 index b7443b01..00000000 --- a/src/fsfw/tmtcpacket/pus/tc/TcPacketStoredBase.cpp +++ /dev/null @@ -1,63 +0,0 @@ -#include "fsfw/tmtcpacket/pus/tc/TcPacketStoredBase.h" - -#include - -#include "fsfw/objectmanager/ObjectManager.h" -#include "fsfw/objectmanager/frameworkObjects.h" -#include "fsfw/serviceinterface/ServiceInterface.h" - -StorageManagerIF* TcPacketStoredBase::STORE = nullptr; - -TcPacketStoredBase::TcPacketStoredBase() { - this->storeAddress.raw = StorageManagerIF::INVALID_ADDRESS; - TcPacketStoredBase::checkAndSetStore(); -} - -TcPacketStoredBase::~TcPacketStoredBase() = default; - -ReturnValue_t TcPacketStoredBase::getData(const uint8_t** dataPtr, size_t* dataSize) { - auto result = TcPacketStoredBase::STORE->getData(storeAddress, dataPtr, dataSize); - if (result != returnvalue::OK) { -#if FSFW_CPP_OSTREAM_ENABLED == 1 - sif::warning << "TcPacketStoredBase: Could not get data" << std::endl; -#else - sif::printWarning("TcPacketStoredBase: Could not get data!\n"); -#endif - } - return result; -} - -bool TcPacketStoredBase::checkAndSetStore() { - if (TcPacketStoredBase::STORE == nullptr) { - TcPacketStoredBase::STORE = ObjectManager::instance()->get(objects::TC_STORE); - if (TcPacketStoredBase::STORE == nullptr) { -#if FSFW_CPP_OSTREAM_ENABLED == 1 - sif::error << "TcPacketStoredBase::TcPacketStoredBase: TC Store not found" << std::endl; -#else - sif::printError("TcPacketStoredBase::TcPacketStoredBase: TC Store not found\n"); -#endif - return false; - } - } - return true; -} - -void TcPacketStoredBase::setStoreAddress(store_address_t setAddress, - RedirectableDataPointerIF* packet) { - this->storeAddress = setAddress; - const uint8_t* tempData = nullptr; - size_t tempSize; - ReturnValue_t status = returnvalue::FAILED; - if (this->checkAndSetStore()) { - status = TcPacketStoredBase::STORE->getData(this->storeAddress, &tempData, &tempSize); - } - - if (status == returnvalue::OK) { - packet->setData(const_cast(tempData), tempSize); - } else { - packet->setData(nullptr, -1); - this->storeAddress.raw = StorageManagerIF::INVALID_ADDRESS; - } -} - -store_address_t TcPacketStoredBase::getStoreAddress() { return this->storeAddress; } diff --git a/src/fsfw/tmtcpacket/pus/tc/TcPacketStoredBase.h b/src/fsfw/tmtcpacket/pus/tc/TcPacketStoredBase.h deleted file mode 100644 index 6602eeca..00000000 --- a/src/fsfw/tmtcpacket/pus/tc/TcPacketStoredBase.h +++ /dev/null @@ -1,83 +0,0 @@ -#ifndef TMTCPACKET_PUS_TCPACKETSTORED_H_ -#define TMTCPACKET_PUS_TCPACKETSTORED_H_ - -#include "TcPacketStoredIF.h" -#include "fsfw/storagemanager/StorageManagerIF.h" - -/** - * Base class for telecommand packets like CFDP or PUS packets. - * @ingroup tmtcpackets - */ -class TcPacketStoredBase : public TcPacketStoredIF { - public: - /** - * This is a default constructor which does not set the data pointer to initialize - * with an empty cached store address - */ - TcPacketStoredBase(); - /** - * Constructor to set to an existing store address. - * @param setAddress - */ - TcPacketStoredBase(store_address_t setAddress); - /** - * Another constructor to create a TcPacket from a raw packet stream. - * Takes the data and adds it unchecked to the TcStore. - * @param data Pointer to the complete TC Space Packet. - * @param Size size of the packet. - */ - TcPacketStoredBase(const uint8_t* data, uint32_t size); - - virtual ~TcPacketStoredBase(); - - /** - * Getter function for the raw data. - * @param dataPtr [out] Pointer to the data pointer to set - * @param dataSize [out] Address of size to set. - * @return -@c returnvalue::OK if data was retrieved successfully. - */ - ReturnValue_t getData(const uint8_t** dataPtr, size_t* dataSize) override; - - void setStoreAddress(store_address_t setAddress, RedirectableDataPointerIF* packet) override; - store_address_t getStoreAddress() override; - - /** - * With this call, the packet is deleted. - * It removes itself from the store and sets its data pointer to NULL. - * @return returncode from deleting the data. - */ - virtual ReturnValue_t deletePacket() = 0; - - /** - * This method performs a size check. - * It reads the stored size and compares it with the size entered in the - * packet header. This class is the optimal place for such a check as it - * has access to both the header data and the store. - * @return true if size is correct, false if packet is not registered in - * store or size is incorrect. - */ - virtual bool isSizeCorrect() = 0; - - protected: - /** - * This is a pointer to the store all instances of the class use. - * If the store is not yet set (i.e. @c store is NULL), every constructor - * call tries to set it and throws an error message in case of failures. - * The default store is objects::TC_STORE. - */ - static StorageManagerIF* STORE; - /** - * The address where the packet data of the object instance is stored. - */ - store_address_t storeAddress; - /** - * A helper method to check if a store is assigned to the class. - * If not, the method tries to retrieve the store from the global - * ObjectManager. - * @return @li @c true if the store is linked or could be created. - * @li @c false otherwise. - */ - static bool checkAndSetStore(); -}; - -#endif /* TMTCPACKET_PUS_TCPACKETSTORED_H_ */ diff --git a/src/fsfw/tmtcpacket/pus/tc/TcPacketStoredIF.h b/src/fsfw/tmtcpacket/pus/tc/TcPacketStoredIF.h deleted file mode 100644 index 3cfba870..00000000 --- a/src/fsfw/tmtcpacket/pus/tc/TcPacketStoredIF.h +++ /dev/null @@ -1,33 +0,0 @@ -#ifndef FSFW_TMTCPACKET_PUS_TCPACKETSTOREDIF_H_ -#define FSFW_TMTCPACKET_PUS_TCPACKETSTOREDIF_H_ - -#include - -#include "TcPacketPusBase.h" -#include "fsfw/returnvalues/returnvalue.h" -#include "fsfw/storagemanager/storeAddress.h" - -class TcPacketStoredIF { - public: - virtual ~TcPacketStoredIF() = default; - ; - - /** - * With this call, the stored packet can be set to another packet in a store. This is useful - * if the packet is a class member and used for more than one packet. - * @param setAddress The new packet id to link to. - */ - virtual void setStoreAddress(store_address_t setAddress, RedirectableDataPointerIF* packet) = 0; - - virtual store_address_t getStoreAddress() = 0; - - /** - * Getter function for the raw data. - * @param dataPtr [out] Pointer to the data pointer to set - * @param dataSize [out] Address of size to set. - * @return -@c returnvalue::OK if data was retrieved successfully. - */ - virtual ReturnValue_t getData(const uint8_t** dataPtr, size_t* dataSize) = 0; -}; - -#endif /* FSFW_TMTCPACKET_PUS_TCPACKETSTOREDIF_H_ */ diff --git a/src/fsfw/tmtcpacket/pus/tc/TcPacketStoredPus.cpp b/src/fsfw/tmtcpacket/pus/tc/TcPacketStoredPus.cpp deleted file mode 100644 index d25486e5..00000000 --- a/src/fsfw/tmtcpacket/pus/tc/TcPacketStoredPus.cpp +++ /dev/null @@ -1,78 +0,0 @@ -#include "fsfw/tmtcpacket/pus/tc/TcPacketStoredPus.h" - -#include - -#include "fsfw/serviceinterface/ServiceInterface.h" - -TcPacketStoredPus::TcPacketStoredPus(uint16_t apid, uint8_t service, uint8_t subservice, - uint8_t sequenceCount, const uint8_t* data, size_t size, - uint8_t ack) - : TcPacketPus(nullptr) { - this->storeAddress.raw = StorageManagerIF::INVALID_ADDRESS; - if (not this->checkAndSetStore()) { - return; - } - uint8_t* pData = nullptr; - ReturnValue_t returnValue = - this->STORE->getFreeElement(&this->storeAddress, (TC_PACKET_MIN_SIZE + size), &pData); - if (returnValue != returnvalue::OK) { -#if FSFW_CPP_OSTREAM_ENABLED == 1 - sif::warning << "TcPacketStoredBase: Could not get free element from store!" << std::endl; -#endif - return; - } - this->setData(pData, TC_PACKET_MIN_SIZE + size); -#if FSFW_USE_PUS_C_TELECOMMANDS == 1 - pus::PusVersion pusVersion = pus::PusVersion::PUS_C_VERSION; -#else - pus::PusVersion pusVersion = pus::PusVersion::PUS_A_VERSION; -#endif - initializeTcPacket(apid, sequenceCount, ack, service, subservice, pusVersion); - std::memcpy(&tcData->appData, data, size); - this->setPacketDataLength(size + sizeof(PUSTcDataFieldHeader) + CRC_SIZE - 1); - this->setErrorControl(); -} - -TcPacketStoredPus::TcPacketStoredPus() : TcPacketStoredBase(), TcPacketPus(nullptr) {} - -TcPacketStoredPus::TcPacketStoredPus(store_address_t setAddress) : TcPacketPus(nullptr) { - TcPacketStoredBase::setStoreAddress(setAddress, this); -} - -TcPacketStoredPus::TcPacketStoredPus(const uint8_t* data, size_t size) : TcPacketPus(data) { - if (this->getFullSize() != size) { - return; - } - if (this->checkAndSetStore()) { - ReturnValue_t status = STORE->addData(&storeAddress, data, size); - if (status != returnvalue::OK) { - this->setData(nullptr, size); - } - const uint8_t* storePtr = nullptr; - // Repoint base data pointer to the data in the store. - STORE->getData(storeAddress, &storePtr, &size); - this->setData(const_cast(storePtr), size); - } -} - -ReturnValue_t TcPacketStoredPus::deletePacket() { - ReturnValue_t result = this->STORE->deleteData(this->storeAddress); - this->storeAddress.raw = StorageManagerIF::INVALID_ADDRESS; - // To circumvent size checks - this->setData(nullptr, -1); - return result; -} - -TcPacketPusBase* TcPacketStoredPus::getPacketBase() { return this; } - -bool TcPacketStoredPus::isSizeCorrect() { - const uint8_t* temp_data = nullptr; - size_t temp_size; - ReturnValue_t status = this->STORE->getData(this->storeAddress, &temp_data, &temp_size); - if (status == returnvalue::OK) { - if (this->getFullSize() == temp_size) { - return true; - } - } - return false; -} diff --git a/src/fsfw/tmtcpacket/pus/tc/TcPacketStoredPus.h b/src/fsfw/tmtcpacket/pus/tc/TcPacketStoredPus.h deleted file mode 100644 index 45dec293..00000000 --- a/src/fsfw/tmtcpacket/pus/tc/TcPacketStoredPus.h +++ /dev/null @@ -1,48 +0,0 @@ -#ifndef FSFW_TMTCPACKET_PUS_TCPACKETSTOREDPUSA_H_ -#define FSFW_TMTCPACKET_PUS_TCPACKETSTOREDPUSA_H_ - -#include "TcPacketPus.h" -#include "TcPacketStoredBase.h" - -class TcPacketStoredPus : public TcPacketStoredBase, public TcPacketPus { - public: - /** - * With this constructor, new space is allocated in the packet store and - * a new PUS Telecommand Packet is created there. - * Packet Application Data passed in data is copied into the packet. - * @param apid Sets the packet's APID field. - * @param service Sets the packet's Service ID field. - * This specifies the destination service. - * @param subservice Sets the packet's Service Subtype field. - * This specifies the destination sub-service. - * @param sequence_count Sets the packet's Source Sequence Count field. - * @param data The data to be copied to the Application Data Field. - * @param size The amount of data to be copied. - * @param ack Set's the packet's Ack field, which specifies - * number of verification packets returned - * for this command. - */ - TcPacketStoredPus(uint16_t apid, uint8_t service, uint8_t subservice, uint8_t sequence_count = 0, - const uint8_t* data = nullptr, size_t size = 0, - uint8_t ack = TcPacketPusBase::ACK_ALL); - /** - * Create stored packet with existing data. - * @param data - * @param size - */ - TcPacketStoredPus(const uint8_t* data, size_t size); - /** - * Create stored packet from existing packet in store - * @param setAddress - */ - TcPacketStoredPus(store_address_t setAddress); - TcPacketStoredPus(); - - ReturnValue_t deletePacket() override; - TcPacketPusBase* getPacketBase(); - - private: - bool isSizeCorrect() override; -}; - -#endif /* FSFW_TMTCPACKET_PUS_TCPACKETSTOREDPUSA_H_ */ diff --git a/src/fsfw/tmtcpacket/pus/tm.h b/src/fsfw/tmtcpacket/pus/tm.h index afbe8251..fc3f0b94 100644 --- a/src/fsfw/tmtcpacket/pus/tm.h +++ b/src/fsfw/tmtcpacket/pus/tm.h @@ -1,16 +1,8 @@ #ifndef FSFW_TMTCPACKET_PUS_TM_H_ #define FSFW_TMTCPACKET_PUS_TM_H_ -#include "fsfw/FSFW.h" - -#if FSFW_USE_PUS_C_TELEMETRY == 1 -#include "tm/TmPacketPusC.h" -#include "tm/TmPacketStoredPusC.h" -#else -#include "tm/TmPacketPusA.h" -#include "tm/TmPacketStoredPusA.h" -#endif - -#include "tm/TmPacketMinimal.h" +#include "tm/PusTmCreator.h" +#include "tm/PusTmReader.h" +#include "tm/PusTmZcWriter.h" #endif /* FSFW_TMTCPACKET_PUS_TM_H_ */ diff --git a/src/fsfw/tmtcpacket/pus/tm/CMakeLists.txt b/src/fsfw/tmtcpacket/pus/tm/CMakeLists.txt index ded74ce2..1395d927 100644 --- a/src/fsfw/tmtcpacket/pus/tm/CMakeLists.txt +++ b/src/fsfw/tmtcpacket/pus/tm/CMakeLists.txt @@ -1,9 +1,2 @@ -target_sources( - ${LIB_FSFW_NAME} - PRIVATE TmPacketStoredPusA.cpp - TmPacketStoredPusC.cpp - TmPacketPusA.cpp - TmPacketPusC.cpp - TmPacketStoredBase.cpp - TmPacketBase.cpp - TmPacketMinimal.cpp) +target_sources(${LIB_FSFW_NAME} PRIVATE PusTmCreator.cpp PusTmReader.cpp + PusTmMinimal.cpp PusTmZcWriter.cpp) diff --git a/src/fsfw/tmtcpacket/pus/tm/PusTmCreator.cpp b/src/fsfw/tmtcpacket/pus/tm/PusTmCreator.cpp new file mode 100644 index 00000000..b754e990 --- /dev/null +++ b/src/fsfw/tmtcpacket/pus/tm/PusTmCreator.cpp @@ -0,0 +1,152 @@ +#include "PusTmCreator.h" + +#include + +#include "fsfw/globalfunctions/CRC.h" +#include "fsfw/timemanager/TimeStamperIF.h" + +PusTmCreator::PusTmCreator(SpacePacketParams initSpParams, PusTmParams initPusParams) + : pusParams(initPusParams), spCreator(std::move(initSpParams)) { + setup(); +} + +PusTmCreator::PusTmCreator() { setup(); } + +void PusTmCreator::disableCrcCalculation() { calculateCrcOnSerialization = false; } + +void PusTmCreator::enableCrcCalculation() { calculateCrcOnSerialization = true; } + +uint16_t PusTmCreator::getPacketIdRaw() const { return spCreator.getPacketIdRaw(); } + +uint16_t PusTmCreator::getPacketSeqCtrlRaw() const { return spCreator.getPacketSeqCtrlRaw(); } + +uint16_t PusTmCreator::getPacketDataLen() const { return spCreator.getPacketDataLen(); } + +uint8_t PusTmCreator::getPusVersion() const { return pusParams.secHeader.pusVersion; } + +uint8_t PusTmCreator::getService() const { return pusParams.secHeader.service; } + +uint8_t PusTmCreator::getSubService() const { return pusParams.secHeader.subservice; } + +PusTmParams& PusTmCreator::getParams() { return pusParams; } + +void PusTmCreator::setTimeStamper(TimeStamperIF& timeStamper_) { + pusParams.secHeader.timeStamper = &timeStamper_; + updateSpLengthField(); +} + +uint8_t PusTmCreator::getScTimeRefStatus() { return pusParams.secHeader.scTimeRefStatus; } + +uint16_t PusTmCreator::getMessageTypeCounter() { return pusParams.secHeader.messageTypeCounter; } + +uint16_t PusTmCreator::getDestId() { return pusParams.secHeader.destId; } + +ReturnValue_t PusTmCreator::serialize(uint8_t** buffer, size_t* size, size_t maxSize, + SerializeIF::Endianness streamEndianness) const { + const uint8_t* start = *buffer; + if (*size + getSerializedSize() > maxSize) { + return SerializeIF::BUFFER_TOO_SHORT; + } + ReturnValue_t result = spCreator.serialize(buffer, size, maxSize, streamEndianness); + if (result != returnvalue::OK) { + return result; + } + size_t userDataLen = pusParams.dataWrapper.getLength(); + **buffer = + ((pusParams.secHeader.pusVersion << 4) & 0xF0) | (pusParams.secHeader.scTimeRefStatus & 0x0F); + *buffer += 1; + **buffer = pusParams.secHeader.service; + *buffer += 1; + **buffer = pusParams.secHeader.subservice; + *buffer += 1; + *size += 3; + result = SerializeAdapter::serialize(&pusParams.secHeader.messageTypeCounter, buffer, size, + maxSize, streamEndianness); + if (result != returnvalue::OK) { + return result; + } + result = SerializeAdapter::serialize(&pusParams.secHeader.destId, buffer, size, maxSize, + streamEndianness); + if (result != returnvalue::OK) { + return result; + } + if (getTimestamper() != nullptr) { + result = pusParams.secHeader.timeStamper->serialize(buffer, size, maxSize, streamEndianness); + if (result != returnvalue::OK) { + return result; + } + } + + if (pusParams.dataWrapper.type == util::DataTypes::RAW and + pusParams.dataWrapper.dataUnion.raw.data != nullptr) { + std::memcpy(*buffer, pusParams.dataWrapper.dataUnion.raw.data, userDataLen); + *buffer += userDataLen; + *size += userDataLen; + } else if (pusParams.dataWrapper.type == util::DataTypes::SERIALIZABLE and + pusParams.dataWrapper.dataUnion.serializable != nullptr) { + result = pusParams.dataWrapper.dataUnion.serializable->serialize(buffer, size, maxSize, + streamEndianness); + if (result != returnvalue::OK) { + return result; + } + } + if (calculateCrcOnSerialization) { + uint16_t crc16 = CRC::crc16ccitt(start, getFullPacketLen() - sizeof(ecss::PusChecksumT)); + return SerializeAdapter::serialize(&crc16, buffer, size, maxSize, streamEndianness); + } + // Even if no CRC is calculated, account for the space taken by it + *size += 2; + *buffer += 2; + return returnvalue::OK; +} + +size_t PusTmCreator::getSerializedSize() const { return getFullPacketLen(); } +ReturnValue_t PusTmCreator::deSerialize(const uint8_t** buffer, size_t* size, + SerializeIF::Endianness streamEndianness) { + return returnvalue::FAILED; +} + +TimeStamperIF* PusTmCreator::getTimestamper() const { return pusParams.secHeader.timeStamper; } + +SpacePacketParams& PusTmCreator::getSpParams() { return spCreator.getParams(); } + +void PusTmCreator::updateSpLengthField() { + size_t headerLen = PusTmIF::MIN_SEC_HEADER_LEN + pusParams.dataWrapper.getLength() + + sizeof(ecss::PusChecksumT) - 1; + if (pusParams.secHeader.timeStamper != nullptr) { + headerLen += pusParams.secHeader.timeStamper->getSerializedSize(); + } + spCreator.setDataLen(headerLen); +} + +void PusTmCreator::setApid(uint16_t apid) { spCreator.setApid(apid); } + +void PusTmCreator::setup() { + updateSpLengthField(); + spCreator.setPacketType(ccsds::PacketType::TM); + spCreator.setSecHeaderFlag(); +} + +void PusTmCreator::setMessageTypeCounter(uint16_t messageTypeCounter) { + pusParams.secHeader.messageTypeCounter = messageTypeCounter; +}; + +void PusTmCreator::setDestId(uint16_t destId) { pusParams.secHeader.destId = destId; } + +ReturnValue_t PusTmCreator::setRawUserData(const uint8_t* data, size_t len) { + pusParams.dataWrapper.setRawData({data, len}); + updateSpLengthField(); + return returnvalue::OK; +} +ReturnValue_t PusTmCreator::setSerializableUserData(SerializeIF& serializable) { + pusParams.dataWrapper.setSerializable(serializable); + updateSpLengthField(); + return returnvalue::OK; +} + +void PusTmCreator::setService(uint8_t service) { pusParams.secHeader.service = service; } + +void PusTmCreator::setSubservice(uint8_t subservice) { + pusParams.secHeader.subservice = subservice; +} +bool PusTmCreator::crcCalculationEnabled() const { return calculateCrcOnSerialization; } diff --git a/src/fsfw/tmtcpacket/pus/tm/PusTmCreator.h b/src/fsfw/tmtcpacket/pus/tm/PusTmCreator.h new file mode 100644 index 00000000..8fd4f690 --- /dev/null +++ b/src/fsfw/tmtcpacket/pus/tm/PusTmCreator.h @@ -0,0 +1,105 @@ +#ifndef FSFW_TMTCPACKET_TMPACKETCREATOR_H +#define FSFW_TMTCPACKET_TMPACKETCREATOR_H + +#include "PusTmIF.h" +#include "fsfw/tmtcpacket/ccsds/SpacePacketCreator.h" +#include "fsfw/tmtcpacket/pus/CustomUserDataIF.h" +#include "fsfw/util/dataWrapper.h" + +struct PusTmSecHeader { + PusTmSecHeader() = default; + PusTmSecHeader(uint8_t service, uint8_t subservice, TimeStamperIF* timeStamper) + : service(service), subservice(subservice), timeStamper(timeStamper) {} + + uint8_t service = 0; + uint8_t subservice = 0; + TimeStamperIF* timeStamper = nullptr; + uint8_t pusVersion = ecss::PusVersion::PUS_C; + uint8_t scTimeRefStatus = 0; + uint16_t messageTypeCounter = 0; + uint16_t destId = 0; +}; + +struct PusTmParams { + PusTmParams() = default; + explicit PusTmParams(PusTmSecHeader secHeader) : secHeader(secHeader){}; + PusTmParams(PusTmSecHeader secHeader, util::DataWrapper dataWrapper) + : secHeader(secHeader), dataWrapper(dataWrapper) {} + + PusTmParams(uint8_t service, uint8_t subservice, TimeStamperIF* timeStamper) + : secHeader(service, subservice, timeStamper) {} + + PusTmParams(uint8_t service, uint8_t subservice, TimeStamperIF* timeStamper, + util::DataWrapper dataWrapper_) + : PusTmParams(service, subservice, timeStamper) { + dataWrapper = dataWrapper_; + } + PusTmSecHeader secHeader; + util::DataWrapper dataWrapper{}; +}; + +class TimeStamperIF; + +/** + * This class provides a high-level interface to create PUS TM packets and then @serialize + * them into a raw byte format. It implements @SerializeIF for that purpose. + * A custom time stamper can be set, with the implementation of @TimeStamperIF as the only + * requirement. + */ +class PusTmCreator : public SerializeIF, public PusTmIF, public CustomUserDataIF { + public: + /** + * Empty creator with all-default parameters. Please note that serializing this will + * generate an invalid PUS packet with no timestamp. + */ + PusTmCreator(); + PusTmCreator(SpacePacketParams initSpParams, PusTmParams initPusParams); + ~PusTmCreator() override = default; + + void setTimeStamper(TimeStamperIF& timeStamper); + /** + * This function disables the CRC16 calculation on serialization. This is useful to avoid + * duplicate calculation if some lower level component needs to update fields like the sequence + * count, which would require a checksum update. + */ + void disableCrcCalculation(); + void enableCrcCalculation(); + [[nodiscard]] bool crcCalculationEnabled() const; + + SpacePacketParams& getSpParams(); + void setApid(uint16_t apid); + void setDestId(uint16_t destId); + void setService(uint8_t service); + void setSubservice(uint8_t subservice); + void setMessageTypeCounter(uint16_t messageTypeCounter); + PusTmParams& getParams(); + void updateSpLengthField(); + [[nodiscard]] uint16_t getPacketIdRaw() const override; + [[nodiscard]] uint16_t getPacketSeqCtrlRaw() const override; + [[nodiscard]] uint16_t getPacketDataLen() const override; + [[nodiscard]] uint8_t getPusVersion() const override; + [[nodiscard]] uint8_t getService() const override; + [[nodiscard]] uint8_t getSubService() const override; + uint8_t getScTimeRefStatus() override; + uint16_t getMessageTypeCounter() override; + uint16_t getDestId() override; + ReturnValue_t serialize(uint8_t** buffer, size_t* size, size_t maxSize, + Endianness streamEndianness) const override; + [[nodiscard]] size_t getSerializedSize() const override; + [[nodiscard]] TimeStamperIF* getTimestamper() const; + ReturnValue_t setRawUserData(const uint8_t* data, size_t len) override; + ReturnValue_t setSerializableUserData(SerializeIF& serializable) override; + + // Load all big endian (network endian) helpers into scope + using SerializeIF::serializeBe; + + private: + // Forbidden to use + ReturnValue_t deSerialize(const uint8_t** buffer, size_t* size, + Endianness streamEndianness) override; + void setup(); + PusTmParams pusParams{}; + bool calculateCrcOnSerialization = true; + SpacePacketCreator spCreator; +}; +#endif // FSFW_TMTCPACKET_TMPACKETCREATOR_H diff --git a/src/fsfw/tmtcpacket/pus/tm/PusTmIF.h b/src/fsfw/tmtcpacket/pus/tm/PusTmIF.h new file mode 100644 index 00000000..356cf20b --- /dev/null +++ b/src/fsfw/tmtcpacket/pus/tm/PusTmIF.h @@ -0,0 +1,29 @@ +#ifndef FSFW_TMTCPACKET_PUSTMIF_H +#define FSFW_TMTCPACKET_PUSTMIF_H + +#include +#include + +#include "fsfw/timemanager/TimeStamperIF.h" +#include "fsfw/tmtcpacket/pus/PusIF.h" +#include "fsfw/tmtcpacket/pus/defs.h" + +class PusTmIF : public PusIF { + public: + ~PusTmIF() override = default; + + /** + * Minimum length without timestamp + */ + static constexpr size_t MIN_SEC_HEADER_LEN = 7; + /** + * 2 bytes for CRC16 + */ + static constexpr size_t MIN_SIZE = sizeof(ccsds::PrimaryHeader) + MIN_SEC_HEADER_LEN + 2; + + virtual uint8_t getScTimeRefStatus() = 0; + virtual uint16_t getMessageTypeCounter() = 0; + virtual uint16_t getDestId() = 0; +}; + +#endif // FSFW_TMTCPACKET_PUSTMIF_H diff --git a/src/fsfw/tmtcpacket/pus/tm/PusTmMinimal.cpp b/src/fsfw/tmtcpacket/pus/tm/PusTmMinimal.cpp new file mode 100644 index 00000000..3c0e6f64 --- /dev/null +++ b/src/fsfw/tmtcpacket/pus/tm/PusTmMinimal.cpp @@ -0,0 +1,49 @@ +#include "fsfw/tmtcpacket/pus/tm/PusTmMinimal.h" + +#include +#include + +#include "fsfw/tmtcpacket/pus/PacketTimestampInterpreterIF.h" + +PusTmMinimal::PusTmMinimal(mintm::MinimalPusTm* data) { tmData = data; } +PusTmMinimal::PusTmMinimal(uint8_t* data) { + this->tmData = reinterpret_cast(data); +} + +PusTmMinimal::~PusTmMinimal() = default; + +ReturnValue_t PusTmMinimal::getPacketTime(timeval* timestamp) { + if (timestampInterpreter == nullptr) { + return returnvalue::FAILED; + } + return timestampInterpreter->getPacketTime(this, timestamp); +} + +void PusTmMinimal::setInterpretTimestampObject(PacketTimestampInterpreterIF* interpreter) { + if (PusTmMinimal::timestampInterpreter == nullptr) { + PusTmMinimal::timestampInterpreter = interpreter; + } +} + +PacketTimestampInterpreterIF* PusTmMinimal::timestampInterpreter = nullptr; +// TODO: Implement all of this +ReturnValue_t PusTmMinimal::setData(uint8_t* dataPtr, size_t size, void* args) { return 0; } +uint16_t PusTmMinimal::getPacketIdRaw() const { return 0; } +uint16_t PusTmMinimal::getPacketSeqCtrlRaw() const { return 0; } +uint16_t PusTmMinimal::getPacketDataLen() const { return 0; } +uint8_t PusTmMinimal::getPusVersion() const { return 0; } +uint8_t PusTmMinimal::getService() const { return tmData->secHeader.service; } +uint8_t PusTmMinimal::getSubService() const { return tmData->secHeader.subservice; } +uint8_t PusTmMinimal::getScTimeRefStatus() { return 0; } +uint16_t PusTmMinimal::getMessageTypeCounter() { + return (tmData->secHeader.messageTypeH << 8) | tmData->secHeader.messageTypeL; +} +uint16_t PusTmMinimal::getDestId() { return 0; } +void PusTmMinimal::setApid(uint16_t apid) { + /* TODO: Implement. Maybe provide low level function to do this */ +} +size_t PusTmMinimal::getUserDataLen() const { return userDataLen; } + +const uint8_t* PusTmMinimal::getUserData() const { + return reinterpret_cast(&tmData->rest); +} diff --git a/src/fsfw/tmtcpacket/pus/tm/PusTmMinimal.h b/src/fsfw/tmtcpacket/pus/tm/PusTmMinimal.h new file mode 100644 index 00000000..3b2e7600 --- /dev/null +++ b/src/fsfw/tmtcpacket/pus/tm/PusTmMinimal.h @@ -0,0 +1,92 @@ +#ifndef FRAMEWORK_TMTCPACKET_PUS_TMPACKETMINIMAL_H_ +#define FRAMEWORK_TMTCPACKET_PUS_TMPACKETMINIMAL_H_ + +#include "PusTmIF.h" +#include "fsfw/returnvalues/returnvalue.h" +#include "fsfw/tmtcpacket/ccsds/SpacePacketReader.h" +#include "fsfw/tmtcpacket/pus/RawUserDataReaderIF.h" + +struct timeval; + +class PacketTimestampInterpreterIF; + +namespace mintm { + +// NOTE: Only PUS C compatible! +struct PusTmMinimalSecHeaderPacked { + uint8_t versionAndScTimeRefStatus; + uint8_t service; + uint8_t subservice; + uint8_t messageTypeH; + uint8_t messageTypeL; +}; + +/** + * This struct defines the data structure of a PUS Telecommand Packet when + * accessed via a pointer. + * @ingroup tmtcpackets + */ +struct MinimalPusTm { + ccsds::PrimaryHeader primary; + PusTmMinimalSecHeaderPacked secHeader; + uint8_t rest; +}; + +// Must include a checksum and is therefore at least one larger than the above struct. +static const uint16_t MINIMUM_SIZE = sizeof(MinimalPusTm) + 1; + +} // namespace mintm + +/** + * This is a minimal version of a PUS TmPacket without any variable field, or, + * in other words with Service Type, Subtype and subcounter only. + * This is required for handling TM packets with different APIDs with different + * secondary headers. + */ +class PusTmMinimal : public PusTmIF, public RawUserDataReaderIF, public RedirectableDataPointerIF { + public: + explicit PusTmMinimal(mintm::MinimalPusTm* data); + /** + * This is the default constructor. + * It sets its internal data pointer to the address passed and also + * forwards the data pointer to the parent SpacePacketBase class. + * @param set_address The position where the packet data lies. + */ + explicit PusTmMinimal(uint8_t* data); + /** + * This is the empty default destructor. + */ + ~PusTmMinimal() override; + + void setApid(uint16_t apid); + + ReturnValue_t getPacketTime(timeval* timestamp); + + static void setInterpretTimestampObject(PacketTimestampInterpreterIF* interpreter); + ReturnValue_t setData(uint8_t* dataPtr, size_t size, void* args) override; + [[nodiscard]] uint16_t getPacketIdRaw() const override; + [[nodiscard]] uint16_t getPacketSeqCtrlRaw() const override; + [[nodiscard]] uint16_t getPacketDataLen() const override; + [[nodiscard]] uint8_t getPusVersion() const override; + [[nodiscard]] uint8_t getService() const override; + [[nodiscard]] uint8_t getSubService() const override; + uint8_t getScTimeRefStatus() override; + uint16_t getMessageTypeCounter() override; + uint16_t getDestId() override; + const uint8_t* getUserData() const override; + size_t getUserDataLen() const override; + + protected: + /** + * A pointer to a structure which defines the data structure of + * the packet's data. + * + * To be hardware-safe, all elements are of byte size. + */ + size_t userDataLen = 0; + mintm::MinimalPusTm* tmData; + + static PacketTimestampInterpreterIF* timestampInterpreter; +}; + +#endif /* FRAMEWORK_TMTCPACKET_PUS_TMPACKETMINIMAL_H_ */ diff --git a/src/fsfw/tmtcpacket/pus/tm/PusTmReader.cpp b/src/fsfw/tmtcpacket/pus/tm/PusTmReader.cpp new file mode 100644 index 00000000..491eccac --- /dev/null +++ b/src/fsfw/tmtcpacket/pus/tm/PusTmReader.cpp @@ -0,0 +1,91 @@ +#include "PusTmReader.h" + +#include "fsfw/globalfunctions/CRC.h" + +PusTmReader::PusTmReader(TimeReaderIF *timeReader) : timeReader(timeReader) {} + +PusTmReader::PusTmReader(const uint8_t *data, size_t size) { setReadOnlyData(data, size); } + +PusTmReader::PusTmReader(TimeReaderIF *timeReader, const uint8_t *data, size_t size) + : PusTmReader(timeReader) { + setReadOnlyData(data, size); +} + +ReturnValue_t PusTmReader::parseDataWithCrcCheck() { return parseData(true); } + +ReturnValue_t PusTmReader::parseDataWithoutCrcCheck() { return parseData(false); } + +const uint8_t *PusTmReader::getFullData() const { return spReader.getFullData(); } + +ReturnValue_t PusTmReader::setReadOnlyData(const uint8_t *data, size_t size) { + return setData(const_cast(data), size, nullptr); +} + +ReturnValue_t PusTmReader::setData(uint8_t *dataPtr, size_t size, void *args) { + pointers.spHeaderStart = dataPtr; + return spReader.setReadOnlyData(dataPtr, size); +} + +uint16_t PusTmReader::getPacketIdRaw() const { return spReader.getPacketIdRaw(); } +uint16_t PusTmReader::getPacketSeqCtrlRaw() const { return spReader.getPacketSeqCtrlRaw(); } +uint16_t PusTmReader::getPacketDataLen() const { return spReader.getPacketDataLen(); } +uint8_t PusTmReader::getPusVersion() const { return (pointers.secHeaderStart[0] >> 4) & 0b1111; } +uint8_t PusTmReader::getScTimeRefStatus() { return pointers.secHeaderStart[0] & 0b1111; } +uint8_t PusTmReader::getService() const { return pointers.secHeaderStart[1]; } +uint8_t PusTmReader::getSubService() const { return pointers.secHeaderStart[2]; } +const uint8_t *PusTmReader::getUserData() const { return pointers.userDataStart; } +size_t PusTmReader::getUserDataLen() const { return sourceDataLen; } + +uint16_t PusTmReader::getMessageTypeCounter() { + return (pointers.secHeaderStart[3] << 8) | pointers.secHeaderStart[4]; +} + +uint16_t PusTmReader::getDestId() { + return (pointers.secHeaderStart[5] << 8) | pointers.secHeaderStart[6]; +} + +void PusTmReader::setTimeReader(TimeReaderIF *timeReader_) { timeReader = timeReader_; } + +TimeReaderIF *PusTmReader::getTimeReader() { return timeReader; } + +ReturnValue_t PusTmReader::parseData(bool crcCheck) { + // Time reader is required to read the time stamp length at run-time + if (pointers.spHeaderStart == nullptr or spReader.isNull() or timeReader == nullptr) { + return returnvalue::FAILED; + } + ReturnValue_t result = spReader.checkSize(); + if (result != returnvalue::OK) { + return result; + } + size_t currentOffset = SpacePacketReader::getHeaderLen(); + pointers.secHeaderStart = pointers.spHeaderStart + currentOffset; + currentOffset += PusTmIF::MIN_SEC_HEADER_LEN; + size_t minTimestampLen = spReader.getFullPacketLen() - currentOffset; + result = timeReader->readTimeStamp(pointers.spHeaderStart + currentOffset, minTimestampLen); + if (result != returnvalue::OK) { + return result; + } + size_t timestampLen = timeReader->getTimestampSize(); + if (currentOffset + timestampLen > spReader.getBufSize()) { + return SerializeIF::STREAM_TOO_SHORT; + } + currentOffset += timestampLen; + sourceDataLen = spReader.getFullPacketLen() - currentOffset - sizeof(ecss::PusChecksumT); + pointers.userDataStart = nullptr; + if (sourceDataLen > 0) { + pointers.userDataStart = pointers.spHeaderStart + currentOffset; + } + currentOffset += sourceDataLen; + pointers.crcStart = pointers.spHeaderStart + currentOffset; + if (crcCheck) { + uint16_t crc16 = CRC::crc16ccitt(spReader.getFullData(), getFullPacketLen()); + if (crc16 != 0) { + // Checksum failure + return PusIF::INVALID_CRC_16; + } + } + return returnvalue::OK; +} +bool PusTmReader::isNull() const { return spReader.isNull() or pointers.secHeaderStart == nullptr; } + +PusTmReader::operator bool() const { return not isNull(); } diff --git a/src/fsfw/tmtcpacket/pus/tm/PusTmReader.h b/src/fsfw/tmtcpacket/pus/tm/PusTmReader.h new file mode 100644 index 00000000..c12bb4c8 --- /dev/null +++ b/src/fsfw/tmtcpacket/pus/tm/PusTmReader.h @@ -0,0 +1,83 @@ +#ifndef FSFW_TMTCPACKET_PUSTMREADER_H +#define FSFW_TMTCPACKET_PUSTMREADER_H + +#include "fsfw/timemanager/TimeReaderIF.h" +#include "fsfw/tmtcpacket/ReadablePacketIF.h" +#include "fsfw/tmtcpacket/RedirectableDataPointerIF.h" +#include "fsfw/tmtcpacket/ccsds/SpacePacketReader.h" +#include "fsfw/tmtcpacket/pus/RawUserDataReaderIF.h" +#include "fsfw/tmtcpacket/pus/tm/PusTmIF.h" + +/** + * This object can be used to read existing PUS TM packets in raw byte format. + * It is a zero-copy object, so reading a TM packet with will not copy anything. + * + * Please note that a parser function must be called after the constructor. This will also check + * the packet for validity. + * + * There are two parser function, where one does not perform the CRC check. This is useful + * if the CRC calculation will is performed in a separate step. + * This object also requires an explicit time stamp reader to allow flexibility in the used + * timestamp. + */ +class PusTmReader : public PusTmIF, + public RawUserDataReaderIF, + public ReadablePacketIF, + public RedirectableDataPointerIF { + public: + explicit PusTmReader(TimeReaderIF* timeReader); + PusTmReader(const uint8_t* data, size_t size); + PusTmReader(TimeReaderIF* timeReader, const uint8_t* data, size_t size); + + /** + * No CRC check will be performed + * @return + */ + ReturnValue_t parseDataWithoutCrcCheck(); + /** + * Performs a CRC check on the data as well + * @return + * - HasReturnvaluesIF::RETURN_OK: Successfully parsed the packet + * - SerializeIF::STREAM_TOO_SHORT: Stream too short for detected packet size + * - PusIF::INVALID_CRC_16 on invalid CRC + */ + ReturnValue_t parseDataWithCrcCheck(); + [[nodiscard]] const uint8_t* getFullData() const override; + + /** + * Returns @isNull + * @return + */ + explicit operator bool() const; + /** + * No (valid) data was set yet or the parse function was not called yet. + * @return + */ + [[nodiscard]] bool isNull() const; + void setTimeReader(TimeReaderIF* timeReader); + TimeReaderIF* getTimeReader(); + ReturnValue_t setReadOnlyData(const uint8_t* data, size_t size); + [[nodiscard]] uint16_t getPacketIdRaw() const override; + [[nodiscard]] uint16_t getPacketSeqCtrlRaw() const override; + [[nodiscard]] uint16_t getPacketDataLen() const override; + [[nodiscard]] uint8_t getPusVersion() const override; + [[nodiscard]] uint8_t getService() const override; + [[nodiscard]] uint8_t getSubService() const override; + [[nodiscard]] const uint8_t* getUserData() const override; + [[nodiscard]] size_t getUserDataLen() const override; + uint8_t getScTimeRefStatus() override; + uint16_t getMessageTypeCounter() override; + uint16_t getDestId() override; + + protected: + ecss::PusPointers pointers{}; + SpacePacketReader spReader{}; + size_t sourceDataLen = 0; + TimeReaderIF* timeReader{}; + ReturnValue_t setData(uint8_t* dataPtr, size_t size, void* args) override; + ReturnValue_t parseData(bool crcCheck); + + private: +}; + +#endif // FSFW_TMTCPACKET_PUSTMREADER_H diff --git a/src/fsfw/tmtcpacket/pus/tm/PusTmZcWriter.cpp b/src/fsfw/tmtcpacket/pus/tm/PusTmZcWriter.cpp new file mode 100644 index 00000000..6a9f6235 --- /dev/null +++ b/src/fsfw/tmtcpacket/pus/tm/PusTmZcWriter.cpp @@ -0,0 +1,26 @@ +#include "PusTmZcWriter.h" + +#include "fsfw/globalfunctions/CRC.h" + +PusTmZeroCopyWriter::PusTmZeroCopyWriter(TimeReaderIF& timeReader, uint8_t* data, size_t size) + : PusTmReader(&timeReader, data, size) {} + +void PusTmZeroCopyWriter::setSequenceCount(uint16_t seqCount) { + if (isNull()) { + return; + } + auto* spHeader = + reinterpret_cast(const_cast((pointers.spHeaderStart))); + ccsds::setSequenceCount(*spHeader, seqCount); +} + +void PusTmZeroCopyWriter::updateErrorControl() { + if (isNull()) { + return; + } + auto* crcStart = const_cast((pointers.crcStart)); + uint16_t crc16 = + CRC::crc16ccitt(PusTmReader::getFullData(), getFullPacketLen() - sizeof(ecss::PusChecksumT)); + crcStart[0] = (crc16 >> 8) & 0xff; + crcStart[1] = crc16 & 0xff; +} diff --git a/src/fsfw/tmtcpacket/pus/tm/PusTmZcWriter.h b/src/fsfw/tmtcpacket/pus/tm/PusTmZcWriter.h new file mode 100644 index 00000000..36c43f51 --- /dev/null +++ b/src/fsfw/tmtcpacket/pus/tm/PusTmZcWriter.h @@ -0,0 +1,21 @@ +#ifndef FSFW_EXAMPLE_HOSTED_PUSTMZCWRITER_H +#define FSFW_EXAMPLE_HOSTED_PUSTMZCWRITER_H + +#include "PusTmReader.h" + +/** + * This packet allows to update specific fields of a PUS TM packet where it is useful or necessary + * to update them in a second step. Otherwise, it offers the same interface as @PusTmReader. + * + * Right now, this class supports updating the CCSDS Sequence Count and the Error Control. + */ +class PusTmZeroCopyWriter : public PusTmReader { + public: + PusTmZeroCopyWriter(TimeReaderIF& timeReader, uint8_t* data, size_t size); + + void setSequenceCount(uint16_t seqCount); + void updateErrorControl(); + + private: +}; +#endif // FSFW_EXAMPLE_HOSTED_PUSTMZCWRITER_H diff --git a/src/fsfw/tmtcpacket/pus/tm/TmPacketBase.cpp b/src/fsfw/tmtcpacket/pus/tm/TmPacketBase.cpp deleted file mode 100644 index bc761d0d..00000000 --- a/src/fsfw/tmtcpacket/pus/tm/TmPacketBase.cpp +++ /dev/null @@ -1,65 +0,0 @@ -#include "fsfw/tmtcpacket/pus/tm/TmPacketBase.h" - -#include - -#include "fsfw/globalfunctions/CRC.h" -#include "fsfw/globalfunctions/arrayprinter.h" -#include "fsfw/objectmanager/ObjectManager.h" -#include "fsfw/serviceinterface/ServiceInterface.h" -#include "fsfw/timemanager/CCSDSTime.h" - -TimeStamperIF* TmPacketBase::timeStamper = nullptr; -object_id_t TmPacketBase::timeStamperId = objects::NO_OBJECT; - -TmPacketBase::TmPacketBase(uint8_t* setData) : SpacePacketBase(setData) {} - -TmPacketBase::~TmPacketBase() { - // Nothing to do. -} - -uint16_t TmPacketBase::getSourceDataSize() { - return getPacketDataLength() - getDataFieldSize() - CRC_SIZE + 1; -} - -uint16_t TmPacketBase::getErrorControl() { - uint32_t size = getSourceDataSize() + CRC_SIZE; - uint8_t* p_to_buffer = getSourceData(); - return (p_to_buffer[size - 2] << 8) + p_to_buffer[size - 1]; -} - -void TmPacketBase::setErrorControl() { - uint32_t full_size = getFullSize(); - uint16_t crc = CRC::crc16ccitt(getWholeData(), full_size - CRC_SIZE); - uint32_t size = getSourceDataSize(); - getSourceData()[size] = (crc & 0XFF00) >> 8; // CRCH - getSourceData()[size + 1] = (crc)&0X00FF; // CRCL -} - -ReturnValue_t TmPacketBase::getPacketTime(timeval* timestamp) const { - size_t tempSize = 0; - return CCSDSTime::convertFromCcsds(timestamp, getPacketTimeRaw(), &tempSize, getTimestampSize()); -} - -bool TmPacketBase::checkAndSetStamper() { - if (timeStamper == NULL) { - timeStamper = ObjectManager::instance()->get(timeStamperId); - if (timeStamper == NULL) { -#if FSFW_CPP_OSTREAM_ENABLED == 1 - sif::warning << "TmPacketBase::checkAndSetStamper: Stamper not found!" << std::endl; -#else - sif::printWarning("TmPacketBase::checkAndSetStamper: Stamper not found!\n"); -#endif - return false; - } - } - return true; -} - -void TmPacketBase::print() { -#if FSFW_CPP_OSTREAM_ENABLED == 1 - sif::info << "TmPacketBase::print:" << std::endl; -#else - sif::printInfo("TmPacketBase::print:\n"); -#endif - arrayprinter::print(getWholeData(), getFullSize()); -} diff --git a/src/fsfw/tmtcpacket/pus/tm/TmPacketBase.h b/src/fsfw/tmtcpacket/pus/tm/TmPacketBase.h deleted file mode 100644 index 72f3abd4..00000000 --- a/src/fsfw/tmtcpacket/pus/tm/TmPacketBase.h +++ /dev/null @@ -1,135 +0,0 @@ -#ifndef TMTCPACKET_PUS_TMPACKETBASE_H_ -#define TMTCPACKET_PUS_TMPACKETBASE_H_ - -#include "fsfw/objectmanager/SystemObjectIF.h" -#include "fsfw/timemanager/Clock.h" -#include "fsfw/timemanager/TimeStamperIF.h" -#include "fsfw/tmtcpacket/SpacePacketBase.h" - -namespace Factory { - -void setStaticFrameworkObjectIds(); - -} - -/** - * This class is the basic data handler for any ECSS PUS Telemetry packet. - * - * In addition to #SpacePacketBase, the class provides methods to handle - * the standardized entries of the PUS TM Packet Data Field Header. - * It does not contain the packet data itself but a pointer to the - * data must be set on instantiation. An invalid pointer may cause - * damage, as no getter method checks data validity. Anyway, a NULL - * check can be performed by making use of the getWholeData method. - * @ingroup tmtcpackets - */ -class TmPacketBase : public SpacePacketBase { - friend void(Factory::setStaticFrameworkObjectIds)(); - - public: - //! Maximum size of a TM Packet in this mission. - //! TODO: Make this dependant on a config variable. - static const uint32_t MISSION_TM_PACKET_MAX_SIZE = 2048; - - /** - * This is the default constructor. - * It sets its internal data pointer to the address passed and also - * forwards the data pointer to the parent SpacePacketBase class. - * @param set_address The position where the packet data lies. - */ - TmPacketBase(uint8_t* setData); - /** - * This is the empty default destructor. - */ - virtual ~TmPacketBase(); - - /** - * This is a getter for the packet's PUS Service ID, which is the second - * byte of the Data Field Header. - * @return The packet's PUS Service ID. - */ - virtual uint8_t getService() = 0; - /** - * This is a getter for the packet's PUS Service Subtype, which is the - * third byte of the Data Field Header. - * @return The packet's PUS Service Subtype. - */ - virtual uint8_t getSubService() = 0; - /** - * This is a getter for a pointer to the packet's Source data. - * - * These are the bytes that follow after the Data Field Header. They form - * the packet's source data. - * @return A pointer to the PUS Source Data. - */ - virtual uint8_t* getSourceData() = 0; - /** - * This method calculates the size of the PUS Source data field. - * - * It takes the information stored in the CCSDS Packet Data Length field - * and subtracts the Data Field Header size and the CRC size. - * @return The size of the PUS Source Data (without Error Control field) - */ - virtual uint16_t getSourceDataSize() = 0; - - /** - * Get size of data field which can differ based on implementation - * @return - */ - virtual uint16_t getDataFieldSize() = 0; - - virtual size_t getPacketMinimumSize() const = 0; - - /** - * Interprets the "time"-field in the secondary header and returns it in - * timeval format. - * @return Converted timestamp of packet. - */ - virtual ReturnValue_t getPacketTime(timeval* timestamp) const; - /** - * Returns a raw pointer to the beginning of the time field. - * @return Raw pointer to time field. - */ - virtual uint8_t* getPacketTimeRaw() const = 0; - - virtual size_t getTimestampSize() const = 0; - - /** - * This is a debugging helper method that prints the whole packet content - * to the screen. - */ - void print(); - /** - * With this method, the Error Control Field is updated to match the - * current content of the packet. This method is not protected because - * a recalculation by the user might be necessary when manipulating fields - * like the sequence count. - */ - void setErrorControl(); - /** - * This getter returns the Error Control Field of the packet. - * - * The field is placed after any possible Source Data. If no - * Source Data is present there's still an Error Control field. It is - * supposed to be a 16bit-CRC. - * @return The PUS Error Control - */ - uint16_t getErrorControl(); - - protected: - /** - * The timeStamper is responsible for adding a timestamp to the packet. - * It is initialized lazy. - */ - static TimeStamperIF* timeStamper; - //! The ID to use when looking for a time stamper. - static object_id_t timeStamperId; - - /** - * Checks if a time stamper is available and tries to set it if not. - * @return Returns false if setting failed. - */ - bool checkAndSetStamper(); -}; - -#endif /* TMTCPACKET_PUS_TMPACKETBASE_H_ */ diff --git a/src/fsfw/tmtcpacket/pus/tm/TmPacketMinimal.cpp b/src/fsfw/tmtcpacket/pus/tm/TmPacketMinimal.cpp deleted file mode 100644 index 80f28878..00000000 --- a/src/fsfw/tmtcpacket/pus/tm/TmPacketMinimal.cpp +++ /dev/null @@ -1,40 +0,0 @@ -#include "fsfw/tmtcpacket/pus/tm/TmPacketMinimal.h" - -#include -#include - -#include "fsfw/tmtcpacket/pus/PacketTimestampInterpreterIF.h" - -TmPacketMinimal::TmPacketMinimal(const uint8_t* set_data) : SpacePacketBase(set_data) { - this->tm_data = (TmPacketMinimalPointer*)set_data; -} - -TmPacketMinimal::~TmPacketMinimal() {} - -uint8_t TmPacketMinimal::getService() { return tm_data->data_field.service_type; } - -uint8_t TmPacketMinimal::getSubService() { return tm_data->data_field.service_subtype; } - -uint8_t TmPacketMinimal::getPacketSubcounter() { return tm_data->data_field.subcounter; } - -ReturnValue_t TmPacketMinimal::getPacketTime(timeval* timestamp) { - if (timestampInterpreter == NULL) { - return returnvalue::FAILED; - } - return timestampInterpreter->getPacketTime(this, timestamp); -} - -ReturnValue_t TmPacketMinimal::getPacketTimeRaw(const uint8_t** timePtr, uint32_t* size) { - if (timestampInterpreter == NULL) { - return returnvalue::FAILED; - } - return timestampInterpreter->getPacketTimeRaw(this, timePtr, size); -} - -void TmPacketMinimal::setInterpretTimestampObject(PacketTimestampInterpreterIF* interpreter) { - if (TmPacketMinimal::timestampInterpreter == NULL) { - TmPacketMinimal::timestampInterpreter = interpreter; - } -} - -PacketTimestampInterpreterIF* TmPacketMinimal::timestampInterpreter = NULL; diff --git a/src/fsfw/tmtcpacket/pus/tm/TmPacketMinimal.h b/src/fsfw/tmtcpacket/pus/tm/TmPacketMinimal.h deleted file mode 100644 index 581d5dfa..00000000 --- a/src/fsfw/tmtcpacket/pus/tm/TmPacketMinimal.h +++ /dev/null @@ -1,82 +0,0 @@ -#ifndef FRAMEWORK_TMTCPACKET_PUS_TMPACKETMINIMAL_H_ -#define FRAMEWORK_TMTCPACKET_PUS_TMPACKETMINIMAL_H_ - -#include "../../../returnvalues/returnvalue.h" -#include "../../SpacePacketBase.h" - -struct timeval; -class PacketTimestampInterpreterIF; -/** - * This is a minimal version of a PUS TmPacket without any variable field, or, - * in other words with Service Type, Subtype and subcounter only. - * This is required for handling TM packets with different APIDs with different - * secondary headers. - */ -class TmPacketMinimal : public SpacePacketBase { - public: - /** - * This is the default constructor. - * It sets its internal data pointer to the address passed and also - * forwards the data pointer to the parent SpacePacketBase class. - * @param set_address The position where the packet data lies. - */ - TmPacketMinimal(const uint8_t* set_data); - /** - * This is the empty default destructor. - */ - virtual ~TmPacketMinimal(); - /** - * This is a getter for the packet's PUS Service ID, which is the second - * byte of the Data Field Header. - * @return The packet's PUS Service ID. - */ - uint8_t getService(); - /** - * This is a getter for the packet's PUS Service Subtype, which is the - * third byte of the Data Field Header. - * @return The packet's PUS Service Subtype. - */ - uint8_t getSubService(); - /** - * Returns the subcounter. - * @return the subcounter of the Data Field Header. - */ - uint8_t getPacketSubcounter(); - struct PUSTmMinimalHeader { - uint8_t version_type_ack; - uint8_t service_type; - uint8_t service_subtype; - uint8_t subcounter; - }; - - ReturnValue_t getPacketTime(timeval* timestamp); - - ReturnValue_t getPacketTimeRaw(const uint8_t** timePtr, uint32_t* size); - - static void setInterpretTimestampObject(PacketTimestampInterpreterIF* interpreter); - /** - * This struct defines the data structure of a PUS Telecommand Packet when - * accessed via a pointer. - * @ingroup tmtcpackets - */ - struct TmPacketMinimalPointer { - CCSDSPrimaryHeader primary; - PUSTmMinimalHeader data_field; - uint8_t rest; - }; - // Must include a checksum and is therefore at least one larger than the above struct. - static const uint16_t MINIMUM_SIZE = sizeof(TmPacketMinimalPointer) + 1; - - protected: - /** - * A pointer to a structure which defines the data structure of - * the packet's data. - * - * To be hardware-safe, all elements are of byte size. - */ - TmPacketMinimalPointer* tm_data; - - static PacketTimestampInterpreterIF* timestampInterpreter; -}; - -#endif /* FRAMEWORK_TMTCPACKET_PUS_TMPACKETMINIMAL_H_ */ diff --git a/src/fsfw/tmtcpacket/pus/tm/TmPacketPusA.cpp b/src/fsfw/tmtcpacket/pus/tm/TmPacketPusA.cpp deleted file mode 100644 index be9cc39d..00000000 --- a/src/fsfw/tmtcpacket/pus/tm/TmPacketPusA.cpp +++ /dev/null @@ -1,68 +0,0 @@ -#include "TmPacketPusA.h" - -#include - -#include "../definitions.h" -#include "TmPacketBase.h" -#include "fsfw/globalfunctions/CRC.h" -#include "fsfw/globalfunctions/arrayprinter.h" -#include "fsfw/objectmanager/ObjectManagerIF.h" -#include "fsfw/serviceinterface/ServiceInterface.h" -#include "fsfw/timemanager/CCSDSTime.h" - -TmPacketPusA::TmPacketPusA(uint8_t* setData) : TmPacketBase(setData) { - tmData = reinterpret_cast(setData); -} - -TmPacketPusA::~TmPacketPusA() { - // Nothing to do. -} - -uint8_t TmPacketPusA::getService() { return tmData->data_field.service_type; } - -uint8_t TmPacketPusA::getSubService() { return tmData->data_field.service_subtype; } - -uint8_t* TmPacketPusA::getSourceData() { return &tmData->data; } - -uint16_t TmPacketPusA::getSourceDataSize() { - return getPacketDataLength() - sizeof(tmData->data_field) - CRC_SIZE + 1; -} - -ReturnValue_t TmPacketPusA::setData(uint8_t* p_Data, size_t maxSize, void* args) { - ReturnValue_t result = SpacePacketBase::setData(p_Data, maxSize); - if (result != returnvalue::OK) { - return result; - } - tmData = reinterpret_cast(const_cast(p_Data)); - return returnvalue::OK; -} - -size_t TmPacketPusA::getPacketMinimumSize() const { return TM_PACKET_MIN_SIZE; } - -uint16_t TmPacketPusA::getDataFieldSize() { return sizeof(PUSTmDataFieldHeaderPusA); } - -uint8_t* TmPacketPusA::getPacketTimeRaw() const { return tmData->data_field.time; } - -void TmPacketPusA::initializeTmPacket(uint16_t apid, uint8_t service, uint8_t subservice, - uint8_t packetSubcounter) { - // Set primary header: - initSpacePacketHeader(false, true, apid); - // Set data Field Header: - // First, set to zero. - memset(&tmData->data_field, 0, sizeof(tmData->data_field)); - - tmData->data_field.version_type_ack = pus::PusVersion::PUS_A_VERSION << 4; - tmData->data_field.service_type = service; - tmData->data_field.service_subtype = subservice; - tmData->data_field.subcounter = packetSubcounter; - // Timestamp packet - if (TmPacketBase::checkAndSetStamper()) { - timeStamper->addTimeStamp(tmData->data_field.time, sizeof(tmData->data_field.time)); - } -} - -void TmPacketPusA::setSourceDataSize(uint16_t size) { - setPacketDataLength(size + sizeof(PUSTmDataFieldHeaderPusA) + CRC_SIZE - 1); -} - -size_t TmPacketPusA::getTimestampSize() const { return sizeof(tmData->data_field.time); } diff --git a/src/fsfw/tmtcpacket/pus/tm/TmPacketPusA.h b/src/fsfw/tmtcpacket/pus/tm/TmPacketPusA.h deleted file mode 100644 index a84547ff..00000000 --- a/src/fsfw/tmtcpacket/pus/tm/TmPacketPusA.h +++ /dev/null @@ -1,129 +0,0 @@ -#ifndef FSFW_TMTCPACKET_PUS_TMPACKETPUSA_H_ -#define FSFW_TMTCPACKET_PUS_TMPACKETPUSA_H_ - -#include "TmPacketBase.h" -#include "fsfw/objectmanager/SystemObjectIF.h" -#include "fsfw/timemanager/Clock.h" -#include "fsfw/timemanager/TimeStamperIF.h" -#include "fsfw/tmtcpacket/SpacePacketBase.h" - -namespace Factory { -void setStaticFrameworkObjectIds(); -} - -/** - * This struct defines a byte-wise structured PUS TM Data Field Header. - * Any optional fields in the header must be added or removed here. - * Currently, no Destination field is present, but an eigth-byte representation - * for a time tag. - * @ingroup tmtcpackets - */ -struct PUSTmDataFieldHeaderPusA { - uint8_t version_type_ack; - uint8_t service_type; - uint8_t service_subtype; - uint8_t subcounter; - // uint8_t destination; - uint8_t time[TimeStamperIF::MISSION_TIMESTAMP_SIZE]; -}; - -/** - * This struct defines the data structure of a PUS Telecommand Packet when - * accessed via a pointer. - * @ingroup tmtcpackets - */ -struct TmPacketPointerPusA { - CCSDSPrimaryHeader primary; - PUSTmDataFieldHeaderPusA data_field; - uint8_t data; -}; - -/** - * PUS A packet implementation - * @ingroup tmtcpackets - */ -class TmPacketPusA : public TmPacketBase { - friend void(Factory::setStaticFrameworkObjectIds)(); - - public: - /** - * This constant defines the minimum size of a valid PUS Telemetry Packet. - */ - static const uint32_t TM_PACKET_MIN_SIZE = - (sizeof(CCSDSPrimaryHeader) + sizeof(PUSTmDataFieldHeaderPusA) + 2); - //! Maximum size of a TM Packet in this mission. - static const uint32_t MISSION_TM_PACKET_MAX_SIZE = fsfwconfig::FSFW_MAX_TM_PACKET_SIZE; - - /** - * This is the default constructor. - * It sets its internal data pointer to the address passed and also - * forwards the data pointer to the parent SpacePacketBase class. - * @param set_address The position where the packet data lies. - */ - TmPacketPusA(uint8_t* setData); - /** - * This is the empty default destructor. - */ - virtual ~TmPacketPusA(); - - /* TmPacketBase implementations */ - uint8_t getService() override; - uint8_t getSubService() override; - uint8_t* getSourceData() override; - uint16_t getSourceDataSize() override; - uint16_t getDataFieldSize() override; - - /** - * Returns a raw pointer to the beginning of the time field. - * @return Raw pointer to time field. - */ - uint8_t* getPacketTimeRaw() const override; - size_t getTimestampSize() const override; - - size_t getPacketMinimumSize() const override; - - protected: - /** - * A pointer to a structure which defines the data structure of - * the packet's data. - * - * To be hardware-safe, all elements are of byte size. - */ - TmPacketPointerPusA* tmData; - - /** - * Initializes the Tm Packet header. - * Does set the timestamp (to now), but not the error control field. - * @param apid APID used. - * @param service PUS Service - * @param subservice PUS Subservice - * @param packetSubcounter Additional subcounter used. - */ - void initializeTmPacket(uint16_t apid, uint8_t service, uint8_t subservice, - uint8_t packetSubcounter); - - /** - * With this method, the packet data pointer can be redirected to another - * location. - * - * This call overwrites the parent's setData method to set both its - * @c tc_data pointer and the parent's @c data pointer. - * - * @param p_data A pointer to another PUS Telemetry Packet. - */ - ReturnValue_t setData(uint8_t* pData, size_t maxSize, void* args = nullptr) override; - - /** - * In case data was filled manually (almost never the case). - * @param size Size of source data (without CRC and data filed header!). - */ - void setSourceDataSize(uint16_t size); - - /** - * Checks if a time stamper is available and tries to set it if not. - * @return Returns false if setting failed. - */ - bool checkAndSetStamper(); -}; - -#endif /* FSFW_TMTCPACKET_PUS_TMPACKETPUSA_H_ */ diff --git a/src/fsfw/tmtcpacket/pus/tm/TmPacketPusC.cpp b/src/fsfw/tmtcpacket/pus/tm/TmPacketPusC.cpp deleted file mode 100644 index 00c889e3..00000000 --- a/src/fsfw/tmtcpacket/pus/tm/TmPacketPusC.cpp +++ /dev/null @@ -1,82 +0,0 @@ -#include "TmPacketPusC.h" - -#include - -#include "../definitions.h" -#include "TmPacketBase.h" -#include "fsfw/globalfunctions/CRC.h" -#include "fsfw/globalfunctions/arrayprinter.h" -#include "fsfw/objectmanager/ObjectManagerIF.h" -#include "fsfw/serviceinterface/ServiceInterface.h" -#include "fsfw/timemanager/CCSDSTime.h" - -TmPacketPusC::TmPacketPusC(uint8_t* setData) : TmPacketBase(setData) { - tmData = reinterpret_cast(setData); -} - -TmPacketPusC::~TmPacketPusC() { - // Nothing to do. -} - -uint8_t TmPacketPusC::getService() { return tmData->dataField.serviceType; } - -uint8_t TmPacketPusC::getSubService() { return tmData->dataField.serviceSubtype; } - -uint8_t* TmPacketPusC::getSourceData() { return &tmData->data; } - -uint16_t TmPacketPusC::getSourceDataSize() { - return getPacketDataLength() - sizeof(tmData->dataField) - CRC_SIZE + 1; -} - -ReturnValue_t TmPacketPusC::setData(uint8_t* p_Data, size_t maxSize, void* args) { - ReturnValue_t result = SpacePacketBase::setData(p_Data, maxSize); - if (result != returnvalue::OK) { - return result; - } - if (maxSize < sizeof(TmPacketPointerPusC)) { - return returnvalue::OK; - } - tmData = reinterpret_cast(const_cast(p_Data)); - return returnvalue::OK; -} - -size_t TmPacketPusC::getPacketMinimumSize() const { return TM_PACKET_MIN_SIZE; } - -uint16_t TmPacketPusC::getDataFieldSize() { return sizeof(PUSTmDataFieldHeaderPusC); } - -uint8_t* TmPacketPusC::getPacketTimeRaw() const { return tmData->dataField.time; } - -ReturnValue_t TmPacketPusC::initializeTmPacket(uint16_t apid, uint8_t service, uint8_t subservice, - uint16_t packetSubcounter, uint16_t destinationId, - uint8_t timeRefField) { - // Set primary header: - ReturnValue_t result = initSpacePacketHeader(false, true, apid); - if (result != returnvalue::OK) { - return result; - } - // Set data Field Header: - // First, set to zero. - memset(&tmData->dataField, 0, sizeof(tmData->dataField)); - - /* Only account for last 4 bytes for time reference field */ - timeRefField &= 0b1111; - tmData->dataField.versionTimeReferenceField = - (pus::PusVersion::PUS_C_VERSION << 4) | timeRefField; - tmData->dataField.serviceType = service; - tmData->dataField.serviceSubtype = subservice; - tmData->dataField.subcounterMsb = packetSubcounter << 8 & 0xff; - tmData->dataField.subcounterLsb = packetSubcounter & 0xff; - tmData->dataField.destinationIdMsb = destinationId << 8 & 0xff; - tmData->dataField.destinationIdLsb = destinationId & 0xff; - // Timestamp packet - if (TmPacketBase::checkAndSetStamper()) { - timeStamper->addTimeStamp(tmData->dataField.time, sizeof(tmData->dataField.time)); - } - return returnvalue::OK; -} - -void TmPacketPusC::setSourceDataSize(uint16_t size) { - setPacketDataLength(size + sizeof(PUSTmDataFieldHeaderPusC) + CRC_SIZE - 1); -} - -size_t TmPacketPusC::getTimestampSize() const { return sizeof(tmData->dataField.time); } diff --git a/src/fsfw/tmtcpacket/pus/tm/TmPacketPusC.h b/src/fsfw/tmtcpacket/pus/tm/TmPacketPusC.h deleted file mode 100644 index bbd69693..00000000 --- a/src/fsfw/tmtcpacket/pus/tm/TmPacketPusC.h +++ /dev/null @@ -1,126 +0,0 @@ -#ifndef FSFW_TMTCPACKET_PUS_TMPACKETPUSC_H_ -#define FSFW_TMTCPACKET_PUS_TMPACKETPUSC_H_ - -#include "TmPacketBase.h" -#include "fsfw/objectmanager/SystemObjectIF.h" -#include "fsfw/timemanager/Clock.h" -#include "fsfw/timemanager/TimeStamperIF.h" -#include "fsfw/tmtcpacket/SpacePacketBase.h" - -namespace Factory { -void setStaticFrameworkObjectIds(); -} - -/** - * This struct defines a byte-wise structured PUS TM Data Field Header. - * Any optional fields in the header must be added or removed here. - * Currently, no Destination field is present, but an eigth-byte representation - * for a time tag. - * @ingroup tmtcpackets - */ -struct PUSTmDataFieldHeaderPusC { - uint8_t versionTimeReferenceField; - uint8_t serviceType; - uint8_t serviceSubtype; - uint8_t subcounterMsb; - uint8_t subcounterLsb; - uint8_t destinationIdMsb; - uint8_t destinationIdLsb; - uint8_t time[TimeStamperIF::MISSION_TIMESTAMP_SIZE]; -}; - -/** - * This struct defines the data structure of a PUS Telecommand Packet when - * accessed via a pointer. - * @ingroup tmtcpackets - */ -struct TmPacketPointerPusC { - CCSDSPrimaryHeader primary; - PUSTmDataFieldHeaderPusC dataField; - uint8_t data; -}; - -/** - * PUS A packet implementation - * @ingroup tmtcpackets - */ -class TmPacketPusC : public TmPacketBase { - friend void(Factory::setStaticFrameworkObjectIds)(); - - public: - /** - * This constant defines the minimum size of a valid PUS Telemetry Packet. - */ - static const uint32_t TM_PACKET_MIN_SIZE = - (sizeof(CCSDSPrimaryHeader) + sizeof(PUSTmDataFieldHeaderPusC) + 2); - //! Maximum size of a TM Packet in this mission. - static const uint32_t MISSION_TM_PACKET_MAX_SIZE = fsfwconfig::FSFW_MAX_TM_PACKET_SIZE; - - /** - * This is the default constructor. - * It sets its internal data pointer to the address passed and also - * forwards the data pointer to the parent SpacePacketBase class. - * @param set_address The position where the packet data lies. - */ - TmPacketPusC(uint8_t* setData); - /** - * This is the empty default destructor. - */ - virtual ~TmPacketPusC(); - - /* TmPacketBase implementations */ - uint8_t getService() override; - uint8_t getSubService() override; - uint8_t* getSourceData() override; - uint16_t getSourceDataSize() override; - uint16_t getDataFieldSize() override; - - /** - * Returns a raw pointer to the beginning of the time field. - * @return Raw pointer to time field. - */ - uint8_t* getPacketTimeRaw() const override; - size_t getTimestampSize() const override; - - size_t getPacketMinimumSize() const override; - - protected: - /** - * A pointer to a structure which defines the data structure of - * the packet's data. - * - * To be hardware-safe, all elements are of byte size. - */ - TmPacketPointerPusC* tmData; - - /** - * Initializes the Tm Packet header. - * Does set the timestamp (to now), but not the error control field. - * @param apid APID used. - * @param service PUS Service - * @param subservice PUS Subservice - * @param packetSubcounter Additional subcounter used. - */ - ReturnValue_t initializeTmPacket(uint16_t apid, uint8_t service, uint8_t subservice, - uint16_t packetSubcounter, uint16_t destinationId = 0, - uint8_t timeRefField = 0); - - /** - * With this method, the packet data pointer can be redirected to another - * location. - * - * This call overwrites the parent's setData method to set both its - * @c tc_data pointer and the parent's @c data pointer. - * - * @param pData A pointer to another PUS Telemetry Packet. - */ - ReturnValue_t setData(uint8_t* pData, size_t maxSize, void* args = nullptr) override; - - /** - * In case data was filled manually (almost never the case). - * @param size Size of source data (without CRC and data filed header!). - */ - void setSourceDataSize(uint16_t size); -}; - -#endif /* FSFW_TMTCPACKET_PUS_TMPACKETPUSC_H_ */ diff --git a/src/fsfw/tmtcpacket/pus/tm/TmPacketStored.h b/src/fsfw/tmtcpacket/pus/tm/TmPacketStored.h deleted file mode 100644 index de10655f..00000000 --- a/src/fsfw/tmtcpacket/pus/tm/TmPacketStored.h +++ /dev/null @@ -1,12 +0,0 @@ -#ifndef FSFW_TMTCPACKET_PUS_TMPACKETSTORED_H_ -#define FSFW_TMTCPACKET_PUS_TMPACKETSTORED_H_ - -#include - -#if FSFW_USE_PUS_C_TELEMETRY == 1 -#include "TmPacketStoredPusC.h" -#else -#include "TmPacketStoredPusA.h" -#endif - -#endif /* FSFW_TMTCPACKET_PUS_TMPACKETSTORED_H_ */ diff --git a/src/fsfw/tmtcpacket/pus/tm/TmPacketStoredBase.cpp b/src/fsfw/tmtcpacket/pus/tm/TmPacketStoredBase.cpp deleted file mode 100644 index 44e25e16..00000000 --- a/src/fsfw/tmtcpacket/pus/tm/TmPacketStoredBase.cpp +++ /dev/null @@ -1,121 +0,0 @@ -#include "fsfw/tmtcpacket/pus/tm/TmPacketStoredBase.h" - -#include - -#include "fsfw/objectmanager/ObjectManager.h" -#include "fsfw/serviceinterface/ServiceInterface.h" -#include "fsfw/tmtcservices/TmTcMessage.h" - -StorageManagerIF *TmPacketStoredBase::store = nullptr; -InternalErrorReporterIF *TmPacketStoredBase::internalErrorReporter = nullptr; - -TmPacketStoredBase::TmPacketStoredBase(store_address_t setAddress) : storeAddress(setAddress) { - setStoreAddress(storeAddress); -} - -TmPacketStoredBase::TmPacketStoredBase() {} - -TmPacketStoredBase::~TmPacketStoredBase() {} - -store_address_t TmPacketStoredBase::getStoreAddress() { return storeAddress; } - -void TmPacketStoredBase::deletePacket() { - store->deleteData(storeAddress); - storeAddress.raw = StorageManagerIF::INVALID_ADDRESS; - setData(nullptr, -1); -} - -void TmPacketStoredBase::setStoreAddress(store_address_t setAddress) { - storeAddress = setAddress; - const uint8_t *tempData = nullptr; - size_t tempSize; - if (not checkAndSetStore()) { - return; - } - ReturnValue_t status = store->getData(storeAddress, &tempData, &tempSize); - if (status == returnvalue::OK) { - setData(const_cast(tempData), tempSize); - } else { - setData(nullptr, -1); - storeAddress.raw = StorageManagerIF::INVALID_ADDRESS; - } -} - -bool TmPacketStoredBase::checkAndSetStore() { - if (store == nullptr) { - store = ObjectManager::instance()->get(objects::TM_STORE); - if (store == nullptr) { -#if FSFW_CPP_OSTREAM_ENABLED == 1 - sif::error << "TmPacketStored::TmPacketStored: TM Store not found!" << std::endl; -#endif - return false; - } - } - return true; -} - -ReturnValue_t TmPacketStoredBase::sendPacket(MessageQueueId_t destination, - MessageQueueId_t sentFrom, bool doErrorReporting) { - if (getAllTmData() == nullptr) { - // SHOULDDO: More decent code. - return returnvalue::FAILED; - } - TmTcMessage tmMessage(getStoreAddress()); - ReturnValue_t result = MessageQueueSenderIF::sendMessage(destination, &tmMessage, sentFrom); - if (result != returnvalue::OK) { - deletePacket(); - if (doErrorReporting) { - checkAndReportLostTm(); - } - return result; - } - // SHOULDDO: In many cases, some counter is incremented for successfully sent packets. The check - // is often not done, but just incremented. - return returnvalue::OK; -} - -void TmPacketStoredBase::checkAndReportLostTm() { - if (internalErrorReporter == nullptr) { - internalErrorReporter = - ObjectManager::instance()->get(objects::INTERNAL_ERROR_REPORTER); - } - if (internalErrorReporter != nullptr) { - internalErrorReporter->lostTm(); - } -} - -void TmPacketStoredBase::handleStoreFailure(const char *const packetType, ReturnValue_t result, - size_t sizeToReserve) { - checkAndReportLostTm(); -#if FSFW_VERBOSE_LEVEL >= 1 - switch (result) { -#if FSFW_CPP_OSTREAM_ENABLED == 1 - case (StorageManagerIF::DATA_STORAGE_FULL): { - sif::warning << "TmPacketStoredPus" << packetType << ": " - << "Store full for packet with size" << sizeToReserve << std::endl; - break; - } - case (StorageManagerIF::DATA_TOO_LARGE): { - sif::warning << "TmPacketStoredPus" << packetType << ": Data with size " << sizeToReserve - << " too large" << std::endl; - break; - } -#else - case (StorageManagerIF::DATA_STORAGE_FULL): { - sif::printWarning( - "TmPacketStoredPus%s: Store full for packet with " - "size %d\n", - packetType, sizeToReserve); - break; - } - case (StorageManagerIF::DATA_TOO_LARGE): { - sif::printWarning( - "TmPacketStoredPus%s: Data with size " - "%d too large\n", - packetType, sizeToReserve); - break; - } -#endif - } -#endif -} diff --git a/src/fsfw/tmtcpacket/pus/tm/TmPacketStoredBase.h b/src/fsfw/tmtcpacket/pus/tm/TmPacketStoredBase.h deleted file mode 100644 index 1732f000..00000000 --- a/src/fsfw/tmtcpacket/pus/tm/TmPacketStoredBase.h +++ /dev/null @@ -1,87 +0,0 @@ -#ifndef FSFW_TMTCPACKET_PUS_TMPACKETSTOREDBASE_H_ -#define FSFW_TMTCPACKET_PUS_TMPACKETSTOREDBASE_H_ - -#include "TmPacketBase.h" -#include "TmPacketPusA.h" -#include "TmPacketStoredBase.h" -#include "fsfw/FSFW.h" -#include "fsfw/internalerror/InternalErrorReporterIF.h" -#include "fsfw/ipc/MessageQueueSenderIF.h" -#include "fsfw/serialize/SerializeIF.h" -#include "fsfw/storagemanager/StorageManagerIF.h" - -/** - * This class generates a ECSS PUS Telemetry packet within a given - * intermediate storage. - * As most packets are passed between tasks with the help of a storage - * anyway, it seems logical to create a Packet-In-Storage access class - * which saves the user almost all storage handling operation. - * Packets can both be newly created with the class and be "linked" to - * packets in a store with the help of a storeAddress. - * @ingroup tmtcpackets - */ -class TmPacketStoredBase : virtual public RedirectableDataPointerIF { - public: - /** - * This is a default constructor which does not set the data pointer. - * However, it does try to set the packet store. - */ - TmPacketStoredBase(store_address_t setAddress); - TmPacketStoredBase(); - - virtual ~TmPacketStoredBase(); - - virtual uint8_t* getAllTmData() = 0; - - /** - * This is a getter for the current store address of the packet. - * @return The current store address. The (raw) value is - * @c StorageManagerIF::INVALID_ADDRESS if - * the packet is not linked. - */ - store_address_t getStoreAddress(); - /** - * With this call, the packet is deleted. - * It removes itself from the store and sets its data pointer to NULL. - */ - void deletePacket(); - /** - * With this call, a packet can be linked to another store. This is useful - * if the packet is a class member and used for more than one packet. - * @param setAddress The new packet id to link to. - */ - void setStoreAddress(store_address_t setAddress); - - ReturnValue_t sendPacket(MessageQueueId_t destination, MessageQueueId_t sentFrom, - bool doErrorReporting = true); - - protected: - /** - * This is a pointer to the store all instances of the class use. - * If the store is not yet set (i.e. @c store is NULL), every constructor - * call tries to set it and throws an error message in case of failures. - * The default store is objects::TM_STORE. - */ - static StorageManagerIF* store; - - static InternalErrorReporterIF* internalErrorReporter; - - /** - * The address where the packet data of the object instance is stored. - */ - store_address_t storeAddress; - /** - * A helper method to check if a store is assigned to the class. - * If not, the method tries to retrieve the store from the global - * ObjectManager. - * @return @li @c true if the store is linked or could be created. - * @li @c false otherwise. - */ - bool checkAndSetStore(); - - void checkAndReportLostTm(); - - void handleStoreFailure(const char* const packetType, ReturnValue_t result, size_t sizeToReserve); -}; - -#endif /* FSFW_TMTCPACKET_PUS_TMPACKETSTOREDBASE_H_ */ diff --git a/src/fsfw/tmtcpacket/pus/tm/TmPacketStoredPusA.cpp b/src/fsfw/tmtcpacket/pus/tm/TmPacketStoredPusA.cpp deleted file mode 100644 index 4d9da5a9..00000000 --- a/src/fsfw/tmtcpacket/pus/tm/TmPacketStoredPusA.cpp +++ /dev/null @@ -1,73 +0,0 @@ -#include "fsfw/tmtcpacket/pus/tm/TmPacketStoredPusA.h" - -#include - -#include "fsfw/serviceinterface/ServiceInterface.h" -#include "fsfw/tmtcservices/TmTcMessage.h" - -TmPacketStoredPusA::TmPacketStoredPusA(store_address_t setAddress) - : TmPacketStoredBase(setAddress), TmPacketPusA(nullptr) {} - -TmPacketStoredPusA::TmPacketStoredPusA(uint16_t apid, uint8_t service, uint8_t subservice, - uint8_t packetSubcounter, const uint8_t *data, uint32_t size, - const uint8_t *headerData, uint32_t headerSize) - : TmPacketPusA(nullptr) { - storeAddress.raw = StorageManagerIF::INVALID_ADDRESS; - if (not TmPacketStoredBase::checkAndSetStore()) { - return; - } - uint8_t *pData = nullptr; - size_t sizeToReserve = getPacketMinimumSize() + size + headerSize; - ReturnValue_t returnValue = store->getFreeElement(&storeAddress, sizeToReserve, &pData); - - if (returnValue != returnvalue::OK) { - handleStoreFailure("A", returnValue, sizeToReserve); - return; - } - setData(pData, sizeToReserve); - initializeTmPacket(apid, service, subservice, packetSubcounter); - memcpy(getSourceData(), headerData, headerSize); - memcpy(getSourceData() + headerSize, data, size); - setPacketDataLength(size + headerSize + sizeof(PUSTmDataFieldHeaderPusA) + CRC_SIZE - 1); -} - -TmPacketStoredPusA::TmPacketStoredPusA(uint16_t apid, uint8_t service, uint8_t subservice, - uint8_t packetSubcounter, SerializeIF *content, - SerializeIF *header) - : TmPacketPusA(nullptr) { - storeAddress.raw = StorageManagerIF::INVALID_ADDRESS; - if (not TmPacketStoredBase::checkAndSetStore()) { - return; - } - size_t sourceDataSize = 0; - if (content != nullptr) { - sourceDataSize += content->getSerializedSize(); - } - if (header != nullptr) { - sourceDataSize += header->getSerializedSize(); - } - uint8_t *pData = nullptr; - size_t sizeToReserve = getPacketMinimumSize() + sourceDataSize; - ReturnValue_t returnValue = store->getFreeElement(&storeAddress, sizeToReserve, &pData); - if (returnValue != returnvalue::OK) { - handleStoreFailure("A", returnValue, sizeToReserve); - return; - } - setData(pData, sizeToReserve); - initializeTmPacket(apid, service, subservice, packetSubcounter); - uint8_t *putDataHere = getSourceData(); - size_t size = 0; - if (header != nullptr) { - header->serialize(&putDataHere, &size, sourceDataSize, SerializeIF::Endianness::BIG); - } - if (content != nullptr) { - content->serialize(&putDataHere, &size, sourceDataSize, SerializeIF::Endianness::BIG); - } - setPacketDataLength(sourceDataSize + sizeof(PUSTmDataFieldHeaderPusA) + CRC_SIZE - 1); -} - -uint8_t *TmPacketStoredPusA::getAllTmData() { return getWholeData(); } - -ReturnValue_t TmPacketStoredPusA::setData(uint8_t *newPointer, size_t maxSize, void *args) { - return TmPacketPusA::setData(newPointer, maxSize); -} diff --git a/src/fsfw/tmtcpacket/pus/tm/TmPacketStoredPusA.h b/src/fsfw/tmtcpacket/pus/tm/TmPacketStoredPusA.h deleted file mode 100644 index f2db99e9..00000000 --- a/src/fsfw/tmtcpacket/pus/tm/TmPacketStoredPusA.h +++ /dev/null @@ -1,69 +0,0 @@ -#ifndef FSFW_TMTCPACKET_PUS_TMPACKETSTORED_PUSA_H_ -#define FSFW_TMTCPACKET_PUS_TMPACKETSTORED_PUSA_H_ - -#include - -#include "TmPacketPusA.h" -#include "TmPacketStoredBase.h" - -/** - * This class generates a ECSS PUS A Telemetry packet within a given - * intermediate storage. - * As most packets are passed between tasks with the help of a storage - * anyway, it seems logical to create a Packet-In-Storage access class - * which saves the user almost all storage handling operation. - * Packets can both be newly created with the class and be "linked" to - * packets in a store with the help of a storeAddress. - * @ingroup tmtcpackets - */ -class TmPacketStoredPusA : public TmPacketStoredBase, public TmPacketPusA { - public: - /** - * This is a default constructor which does not set the data pointer. - * However, it does try to set the packet store. - */ - TmPacketStoredPusA(store_address_t setAddress); - /** - * With this constructor, new space is allocated in the packet store and - * a new PUS Telemetry Packet is created there. - * Packet Application Data passed in data is copied into the packet. - * The Application data is passed in two parts, first a header, then a - * data field. This allows building a Telemetry Packet from two separate - * data sources. - * @param apid Sets the packet's APID field. - * @param service Sets the packet's Service ID field. - * This specifies the source service. - * @param subservice Sets the packet's Service Subtype field. - * This specifies the source sub-service. - * @param packet_counter Sets the Packet counter field of this packet - * @param data The payload data to be copied to the - * Application Data Field - * @param size The amount of data to be copied. - * @param headerData The header Data of the Application field, - * will be copied in front of data - * @param headerSize The size of the headerDataF - */ - TmPacketStoredPusA(uint16_t apid, uint8_t service, uint8_t subservice, uint8_t packet_counter = 0, - const uint8_t* data = nullptr, uint32_t size = 0, - const uint8_t* headerData = nullptr, uint32_t headerSize = 0); - /** - * Another ctor to directly pass structured content and header data to the - * packet to avoid additional buffers. - */ - TmPacketStoredPusA(uint16_t apid, uint8_t service, uint8_t subservice, uint8_t packet_counter, - SerializeIF* content, SerializeIF* header = nullptr); - - uint8_t* getAllTmData() override; - - private: - /** - * Implementation required by base class - * @param newPointer - * @param maxSize - * @param args - * @return - */ - ReturnValue_t setData(uint8_t* newPointer, size_t maxSize, void* args = nullptr) override; -}; - -#endif /* FSFW_TMTCPACKET_PUS_TMPACKETSTORED_PUSA_H_ */ diff --git a/src/fsfw/tmtcpacket/pus/tm/TmPacketStoredPusC.cpp b/src/fsfw/tmtcpacket/pus/tm/TmPacketStoredPusC.cpp deleted file mode 100644 index 55a5637a..00000000 --- a/src/fsfw/tmtcpacket/pus/tm/TmPacketStoredPusC.cpp +++ /dev/null @@ -1,76 +0,0 @@ -#include "fsfw/tmtcpacket/pus/tm/TmPacketStoredPusC.h" - -#include - -#include "fsfw/serviceinterface/ServiceInterface.h" -#include "fsfw/tmtcservices/TmTcMessage.h" - -TmPacketStoredPusC::TmPacketStoredPusC(store_address_t setAddress) - : TmPacketStoredBase(setAddress), TmPacketPusC(nullptr) {} - -TmPacketStoredPusC::TmPacketStoredPusC(uint16_t apid, uint8_t service, uint8_t subservice, - uint16_t packetSubcounter, const uint8_t *data, - uint32_t size, const uint8_t *headerData, - uint32_t headerSize, uint16_t destinationId, - uint8_t timeRefField) - : TmPacketPusC(nullptr) { - storeAddress.raw = StorageManagerIF::INVALID_ADDRESS; - if (not TmPacketStoredBase::checkAndSetStore()) { - return; - } - uint8_t *pData = nullptr; - size_t sizeToReserve = getPacketMinimumSize() + size + headerSize; - ReturnValue_t returnValue = store->getFreeElement(&storeAddress, sizeToReserve, &pData); - - if (returnValue != returnvalue::OK) { - handleStoreFailure("C", returnValue, sizeToReserve); - return; - } - setData(pData, sizeToReserve); - initializeTmPacket(apid, service, subservice, packetSubcounter, destinationId, timeRefField); - memcpy(getSourceData(), headerData, headerSize); - memcpy(getSourceData() + headerSize, data, size); - setPacketDataLength(size + headerSize + sizeof(PUSTmDataFieldHeaderPusC) + CRC_SIZE - 1); -} - -TmPacketStoredPusC::TmPacketStoredPusC(uint16_t apid, uint8_t service, uint8_t subservice, - uint16_t packetSubcounter, SerializeIF *content, - SerializeIF *header, uint16_t destinationId, - uint8_t timeRefField) - : TmPacketPusC(nullptr) { - storeAddress.raw = StorageManagerIF::INVALID_ADDRESS; - if (not TmPacketStoredBase::checkAndSetStore()) { - return; - } - size_t sourceDataSize = 0; - if (content != nullptr) { - sourceDataSize += content->getSerializedSize(); - } - if (header != nullptr) { - sourceDataSize += header->getSerializedSize(); - } - uint8_t *pData = nullptr; - size_t sizeToReserve = getPacketMinimumSize() + sourceDataSize; - ReturnValue_t returnValue = store->getFreeElement(&storeAddress, sizeToReserve, &pData); - if (returnValue != returnvalue::OK) { - handleStoreFailure("C", returnValue, sizeToReserve); - return; - } - TmPacketPusC::setData(pData, sizeToReserve); - initializeTmPacket(apid, service, subservice, packetSubcounter, destinationId, timeRefField); - uint8_t *putDataHere = getSourceData(); - size_t size = 0; - if (header != nullptr) { - header->serialize(&putDataHere, &size, sourceDataSize, SerializeIF::Endianness::BIG); - } - if (content != nullptr) { - content->serialize(&putDataHere, &size, sourceDataSize, SerializeIF::Endianness::BIG); - } - setPacketDataLength(sourceDataSize + sizeof(PUSTmDataFieldHeaderPusC) + CRC_SIZE - 1); -} - -uint8_t *TmPacketStoredPusC::getAllTmData() { return getWholeData(); } - -ReturnValue_t TmPacketStoredPusC::setData(uint8_t *newPointer, size_t maxSize, void *args) { - return TmPacketPusC::setData(newPointer, maxSize); -} diff --git a/src/fsfw/tmtcpacket/pus/tm/TmPacketStoredPusC.h b/src/fsfw/tmtcpacket/pus/tm/TmPacketStoredPusC.h deleted file mode 100644 index ef84e238..00000000 --- a/src/fsfw/tmtcpacket/pus/tm/TmPacketStoredPusC.h +++ /dev/null @@ -1,72 +0,0 @@ -#ifndef FSFW_TMTCPACKET_PUS_TMPACKETSTOREDPUSC_H_ -#define FSFW_TMTCPACKET_PUS_TMPACKETSTOREDPUSC_H_ - -#include "TmPacketPusC.h" -#include "TmPacketStoredBase.h" - -/** - * This class generates a ECSS PUS C Telemetry packet within a given - * intermediate storage. - * As most packets are passed between tasks with the help of a storage - * anyway, it seems logical to create a Packet-In-Storage access class - * which saves the user almost all storage handling operation. - * Packets can both be newly created with the class and be "linked" to - * packets in a store with the help of a storeAddress. - * @ingroup tmtcpackets - */ -class TmPacketStoredPusC : public TmPacketStoredBase, public TmPacketPusC { - public: - /** - * This is a default constructor which does not set the data pointer. - * However, it does try to set the packet store. - */ - TmPacketStoredPusC(store_address_t setAddress); - /** - * With this constructor, new space is allocated in the packet store and - * a new PUS Telemetry Packet is created there. - * Packet Application Data passed in data is copied into the packet. - * The Application data is passed in two parts, first a header, then a - * data field. This allows building a Telemetry Packet from two separate - * data sources. - * @param apid Sets the packet's APID field. - * @param service Sets the packet's Service ID field. - * This specifies the source service. - * @param subservice Sets the packet's Service Subtype field. - * This specifies the source sub-service. - * @param packet_counter Sets the Packet counter field of this packet - * @param data The payload data to be copied to the - * Application Data Field - * @param size The amount of data to be copied. - * @param headerData The header Data of the Application field, - * will be copied in front of data - * @param headerSize The size of the headerDataF - * @param destinationId Destination ID containing the application process ID as specified - * by PUS C - * @param timeRefField 4 bit time reference field as specified by PUS C - */ - TmPacketStoredPusC(uint16_t apid, uint8_t service, uint8_t subservice, uint16_t packetCounter = 0, - const uint8_t* data = nullptr, uint32_t size = 0, - const uint8_t* headerData = nullptr, uint32_t headerSize = 0, - uint16_t destinationId = 0, uint8_t timeRefField = 0); - /** - * Another ctor to directly pass structured content and header data to the - * packet to avoid additional buffers. - */ - TmPacketStoredPusC(uint16_t apid, uint8_t service, uint8_t subservice, uint16_t packetCounter, - SerializeIF* content, SerializeIF* header = nullptr, - uint16_t destinationId = 0, uint8_t timeRefField = 0); - - uint8_t* getAllTmData() override; - - private: - /** - * Implementation required by base class - * @param newPointer - * @param maxSize - * @param args - * @return - */ - ReturnValue_t setData(uint8_t* newPointer, size_t maxSize, void* args = nullptr) override; -}; - -#endif /* FSFW_TMTCPACKET_PUS_TMPACKETSTOREDPUSC_H_ */ diff --git a/src/fsfw/tmtcservices/AcceptsTelemetryIF.h b/src/fsfw/tmtcservices/AcceptsTelemetryIF.h index 0e715130..6f8a6226 100644 --- a/src/fsfw/tmtcservices/AcceptsTelemetryIF.h +++ b/src/fsfw/tmtcservices/AcceptsTelemetryIF.h @@ -1,7 +1,7 @@ #ifndef FSFW_TMTCSERVICES_ACCEPTSTELEMETRYIF_H_ #define FSFW_TMTCSERVICES_ACCEPTSTELEMETRYIF_H_ -#include "../ipc/MessageQueueSenderIF.h" +#include "fsfw/ipc/MessageQueueSenderIF.h" /** * @brief This interface is implemented by classes that are sinks for * Telemetry. @@ -13,13 +13,15 @@ class AcceptsTelemetryIF { /** * @brief The virtual destructor as it is mandatory for C++ interfaces. */ - virtual ~AcceptsTelemetryIF() {} + virtual ~AcceptsTelemetryIF() = default; /** * @brief This method returns the message queue id of the telemetry * receiving message queue. * @return The telemetry reception message queue id. */ - virtual MessageQueueId_t getReportReceptionQueue(uint8_t virtualChannel = 0) = 0; + virtual MessageQueueId_t getReportReceptionQueue(uint8_t virtualChannel) = 0; + + virtual MessageQueueId_t getReportReceptionQueue() { return getReportReceptionQueue(0); } }; #endif /* FSFW_TMTCSERVICES_ACCEPTSTELEMETRYIF_H_ */ diff --git a/src/fsfw/tmtcservices/AcceptsVerifyMessageIF.h b/src/fsfw/tmtcservices/AcceptsVerifyMessageIF.h index 7e58187b..daf67080 100644 --- a/src/fsfw/tmtcservices/AcceptsVerifyMessageIF.h +++ b/src/fsfw/tmtcservices/AcceptsVerifyMessageIF.h @@ -1,11 +1,11 @@ #ifndef FSFW_TMTCSERVICES_ACCEPTSVERIFICATIONMESSAGEIF_H_ #define FSFW_TMTCSERVICES_ACCEPTSVERIFICATIONMESSAGEIF_H_ -#include "../ipc/MessageQueueSenderIF.h" +#include "fsfw/ipc/MessageQueueSenderIF.h" class AcceptsVerifyMessageIF { public: - virtual ~AcceptsVerifyMessageIF() {} + virtual ~AcceptsVerifyMessageIF() = default; virtual MessageQueueId_t getVerificationQueue() = 0; }; diff --git a/src/fsfw/tmtcservices/CMakeLists.txt b/src/fsfw/tmtcservices/CMakeLists.txt index d2a3f4ed..ca3c887e 100644 --- a/src/fsfw/tmtcservices/CMakeLists.txt +++ b/src/fsfw/tmtcservices/CMakeLists.txt @@ -6,4 +6,9 @@ target_sources( TmTcBridge.cpp TmTcMessage.cpp VerificationReporter.cpp - SpacePacketParser.cpp) + SpacePacketParser.cpp + TmStoreHelper.cpp + TmSendHelper.cpp + TmStoreAndSendHelper.cpp + tcHelpers.cpp + tmHelpers.cpp) diff --git a/src/fsfw/tmtcservices/CommandingServiceBase.cpp b/src/fsfw/tmtcservices/CommandingServiceBase.cpp index 5a4c05b5..d3314fa6 100644 --- a/src/fsfw/tmtcservices/CommandingServiceBase.cpp +++ b/src/fsfw/tmtcservices/CommandingServiceBase.cpp @@ -5,31 +5,38 @@ #include "fsfw/serviceinterface/ServiceInterface.h" #include "fsfw/tcdistribution/PUSDistributorIF.h" #include "fsfw/tmtcpacket/pus/tc.h" -#include "fsfw/tmtcpacket/pus/tm.h" #include "fsfw/tmtcservices/AcceptsTelemetryIF.h" #include "fsfw/tmtcservices/TmTcMessage.h" +#include "fsfw/tmtcservices/tcHelpers.h" +#include "fsfw/tmtcservices/tmHelpers.h" object_id_t CommandingServiceBase::defaultPacketSource = objects::NO_OBJECT; object_id_t CommandingServiceBase::defaultPacketDestination = objects::NO_OBJECT; CommandingServiceBase::CommandingServiceBase(object_id_t setObjectId, uint16_t apid, uint8_t service, uint8_t numberOfParallelCommands, - uint16_t commandTimeoutSeconds, size_t queueDepth) + uint16_t commandTimeoutSeconds, size_t queueDepth, + VerificationReporterIF* verificationReporter) : SystemObject(setObjectId), apid(apid), service(service), timeoutSeconds(commandTimeoutSeconds), + tmStoreHelper(apid), + tmHelper(service, tmStoreHelper, tmSendHelper), + verificationReporter(verificationReporter), commandMap(numberOfParallelCommands) { - commandQueue = QueueFactory::instance()->createMessageQueue(queueDepth); - requestQueue = QueueFactory::instance()->createMessageQueue(queueDepth); + auto mqArgs = MqArgs(setObjectId, static_cast(this)); + size_t mqSz = MessageQueueMessage::MAX_MESSAGE_SIZE; + commandQueue = QueueFactory::instance()->createMessageQueue(queueDepth, mqSz, &mqArgs); + requestQueue = QueueFactory::instance()->createMessageQueue(queueDepth, mqSz, &mqArgs); } -void CommandingServiceBase::setPacketSource(object_id_t packetSource) { - this->packetSource = packetSource; +void CommandingServiceBase::setPacketSource(object_id_t packetSource_) { + packetSource = packetSource_; } -void CommandingServiceBase::setPacketDestination(object_id_t packetDestination) { - this->packetDestination = packetDestination; +void CommandingServiceBase::setPacketDestination(object_id_t packetDestination_) { + packetDestination = packetDestination_; } CommandingServiceBase::~CommandingServiceBase() { @@ -58,13 +65,12 @@ ReturnValue_t CommandingServiceBase::initialize() { if (packetDestination == objects::NO_OBJECT) { packetDestination = defaultPacketDestination; } - AcceptsTelemetryIF* packetForwarding = - ObjectManager::instance()->get(packetDestination); + auto* packetForwarding = ObjectManager::instance()->get(packetDestination); if (packetSource == objects::NO_OBJECT) { packetSource = defaultPacketSource; } - PUSDistributorIF* distributor = ObjectManager::instance()->get(packetSource); + auto* distributor = ObjectManager::instance()->get(packetSource); if (packetForwarding == nullptr or distributor == nullptr) { #if FSFW_CPP_OSTREAM_ENABLED == 1 @@ -78,10 +84,10 @@ ReturnValue_t CommandingServiceBase::initialize() { distributor->registerService(this); requestQueue->setDefaultDestination(packetForwarding->getReportReceptionQueue()); - IPCStore = ObjectManager::instance()->get(objects::IPC_STORE); - TCStore = ObjectManager::instance()->get(objects::TC_STORE); + ipcStore = ObjectManager::instance()->get(objects::IPC_STORE); + tcStore = ObjectManager::instance()->get(objects::TC_STORE); - if (IPCStore == nullptr or TCStore == nullptr) { + if (ipcStore == nullptr or tcStore == nullptr) { #if FSFW_CPP_OSTREAM_ENABLED == 1 sif::error << "CommandingServiceBase::intialize: IPC store or TC store " "not initialized yet!" @@ -89,13 +95,48 @@ ReturnValue_t CommandingServiceBase::initialize() { #endif return ObjectManagerIF::CHILD_INIT_FAILED; } + if (tmStoreHelper.getTmStore() == nullptr) { + auto* tmStore = ObjectManager::instance()->get(objects::TM_STORE); + if (tmStore == nullptr) { + return ObjectManagerIF::CHILD_INIT_FAILED; + } + tmStoreHelper.setTmStore(*tmStore); + } + // Generally, all TM packets will pass through a layer where the sequence count is set. + // This avoids duplicate calculation of the CRC16 + tmStoreHelper.disableCrcCalculation(); + if (tmTimeStamper == nullptr) { + tmTimeStamper = ObjectManager::instance()->get(objects::TIME_STAMPER); + if (tmTimeStamper == nullptr) { + return ObjectManagerIF::CHILD_INIT_FAILED; + } + } + tmStoreHelper.setTimeStamper(*tmTimeStamper); + if (errReporter == nullptr) { + errReporter = + ObjectManager::instance()->get(objects::INTERNAL_ERROR_REPORTER); + if (errReporter != nullptr) { + tmSendHelper.setInternalErrorReporter(*errReporter); + } + } else { + tmSendHelper.setInternalErrorReporter(*errReporter); + } + tmSendHelper.setMsgQueue(*requestQueue); + + if (verificationReporter == nullptr) { + verificationReporter = + ObjectManager::instance()->get(objects::VERIFICATION_REPORTER); + if (verificationReporter == nullptr) { + return ObjectManagerIF::CHILD_INIT_FAILED; + } + } return returnvalue::OK; } void CommandingServiceBase::handleCommandQueue() { CommandMessage reply; - ReturnValue_t result = returnvalue::FAILED; + ReturnValue_t result; while (true) { result = commandQueue->receiveMessage(&reply); if (result == returnvalue::OK) { @@ -160,16 +201,14 @@ void CommandingServiceBase::handleCommandMessage(CommandMessage* reply) { break; default: if (isStep) { - verificationReporter.sendFailureReport( - tc_verification::PROGRESS_FAILURE, iter->second.tcInfo.ackFlags, - iter->second.tcInfo.tcPacketId, iter->second.tcInfo.tcSequenceControl, result, - ++iter->second.step, failureParameter1, failureParameter2); + prepareVerificationFailureWithFullInfo(tcverif::PROGRESS_FAILURE, iter->second.tcInfo, + result, true); + failParams.step = ++iter->second.step; } else { - verificationReporter.sendFailureReport( - tc_verification::COMPLETION_FAILURE, iter->second.tcInfo.ackFlags, - iter->second.tcInfo.tcPacketId, iter->second.tcInfo.tcSequenceControl, result, 0, - failureParameter1, failureParameter2); + prepareVerificationFailureWithFullInfo(tcverif::COMPLETION_FAILURE, iter->second.tcInfo, + result, true); } + verificationReporter->sendFailureReport(failParams); failureParameter1 = 0; failureParameter2 = 0; checkAndExecuteFifo(iter); @@ -192,29 +231,26 @@ void CommandingServiceBase::handleReplyHandlerResult(ReturnValue_t result, Comma if (sendResult == returnvalue::OK) { if (isStep and result != NO_STEP_MESSAGE) { - verificationReporter.sendSuccessReport( - tc_verification::PROGRESS_SUCCESS, iter->second.tcInfo.ackFlags, - iter->second.tcInfo.tcPacketId, iter->second.tcInfo.tcSequenceControl, - ++iter->second.step); + prepareVerificationSuccessWithFullInfo(tcverif::PROGRESS_SUCCESS, iter->second.tcInfo); + successParams.step = ++iter->second.step; + verificationReporter->sendSuccessReport(successParams); } else { - verificationReporter.sendSuccessReport( - tc_verification::COMPLETION_SUCCESS, iter->second.tcInfo.ackFlags, - iter->second.tcInfo.tcPacketId, iter->second.tcInfo.tcSequenceControl, 0); + prepareVerificationSuccessWithFullInfo(tcverif::COMPLETION_SUCCESS, iter->second.tcInfo); + verificationReporter->sendSuccessReport(successParams); checkAndExecuteFifo(iter); } } else { if (isStep) { + prepareVerificationFailureWithFullInfo(tcverif::PROGRESS_FAILURE, iter->second.tcInfo, result, + true); + failParams.step = ++iter->second.step; nextCommand->clearCommandMessage(); - verificationReporter.sendFailureReport( - tc_verification::PROGRESS_FAILURE, iter->second.tcInfo.ackFlags, - iter->second.tcInfo.tcPacketId, iter->second.tcInfo.tcSequenceControl, sendResult, - ++iter->second.step, failureParameter1, failureParameter2); + verificationReporter->sendFailureReport(failParams); } else { + prepareVerificationFailureWithFullInfo(tcverif::COMPLETION_FAILURE, iter->second.tcInfo, + result, true); nextCommand->clearCommandMessage(); - verificationReporter.sendFailureReport( - tc_verification::COMPLETION_FAILURE, iter->second.tcInfo.ackFlags, - iter->second.tcInfo.tcPacketId, iter->second.tcInfo.tcSequenceControl, sendResult, 0, - failureParameter1, failureParameter2); + verificationReporter->sendFailureReport(failParams); } failureParameter1 = 0; failureParameter2 = 0; @@ -226,24 +262,26 @@ void CommandingServiceBase::handleRequestQueue() { TmTcMessage message; ReturnValue_t result; store_address_t address; - TcPacketStoredPus packet; MessageQueueId_t queue; object_id_t objectId; for (result = requestQueue->receiveMessage(&message); result == returnvalue::OK; result = requestQueue->receiveMessage(&message)) { address = message.getStorageId(); - packet.setStoreAddress(address, &packet); - - if ((packet.getSubService() == 0) or - (isValidSubservice(packet.getSubService()) != returnvalue::OK)) { - rejectPacket(tc_verification::START_FAILURE, &packet, INVALID_SUBSERVICE); + result = setUpTcReader(address); + if (result != returnvalue::OK) { + rejectPacketInvalidTc(result, address); + continue; + } + if ((tcReader.getSubService() == 0) or + (isValidSubservice(tcReader.getSubService()) != returnvalue::OK)) { + rejectPacket(tcverif::START_FAILURE, address, INVALID_SUBSERVICE); continue; } - result = getMessageQueueAndObject(packet.getSubService(), packet.getApplicationData(), - packet.getApplicationDataSize(), &queue, &objectId); + result = getMessageQueueAndObject(tcReader.getSubService(), tcReader.getUserData(), + tcReader.getUserDataLen(), &queue, &objectId); if (result != returnvalue::OK) { - rejectPacket(tc_verification::START_FAILURE, &packet, result); + rejectPacket(tcverif::START_FAILURE, address, result); continue; } @@ -254,89 +292,54 @@ void CommandingServiceBase::handleRequestQueue() { if (iter != commandMap.end()) { result = iter->second.fifo.insert(address); if (result != returnvalue::OK) { - rejectPacket(tc_verification::START_FAILURE, &packet, OBJECT_BUSY); + rejectPacket(tcverif::START_FAILURE, address, OBJECT_BUSY); } } else { CommandInfo newInfo; // Info will be set by startExecution if neccessary newInfo.objectId = objectId; result = commandMap.insert(queue, newInfo, &iter); if (result != returnvalue::OK) { - rejectPacket(tc_verification::START_FAILURE, &packet, BUSY); + rejectPacket(tcverif::START_FAILURE, address, BUSY); } else { - startExecution(&packet, iter); + startExecution(address, iter); } } } } -ReturnValue_t CommandingServiceBase::sendTmPacket(uint8_t subservice, const uint8_t* data, - size_t dataLen, const uint8_t* headerData, - size_t headerSize) { -#if FSFW_USE_PUS_C_TELEMETRY == 0 - TmPacketStoredPusA tmPacketStored(this->apid, this->service, subservice, this->tmPacketCounter, - data, dataLen, headerData, headerSize); -#else - TmPacketStoredPusC tmPacketStored(this->apid, this->service, subservice, this->tmPacketCounter, - data, dataLen, headerData, headerSize); -#endif - ReturnValue_t result = - tmPacketStored.sendPacket(requestQueue->getDefaultDestination(), requestQueue->getId()); - if (result == returnvalue::OK) { - this->tmPacketCounter++; +ReturnValue_t CommandingServiceBase::sendTmPacket(uint8_t subservice, const uint8_t* sourceData, + size_t sourceDataLen) { + ReturnValue_t result = tmHelper.prepareTmPacket(subservice, sourceData, sourceDataLen); + if (result != returnvalue::OK) { + return result; } - return result; + return tmHelper.storeAndSendTmPacket(); } ReturnValue_t CommandingServiceBase::sendTmPacket(uint8_t subservice, object_id_t objectId, const uint8_t* data, size_t dataLen) { - uint8_t buffer[sizeof(object_id_t)]; - uint8_t* pBuffer = buffer; - size_t size = 0; - SerializeAdapter::serialize(&objectId, &pBuffer, &size, sizeof(object_id_t), - SerializeIF::Endianness::BIG); -#if FSFW_USE_PUS_C_TELEMETRY == 0 - TmPacketStoredPusA tmPacketStored(this->apid, this->service, subservice, this->tmPacketCounter, - data, dataLen, buffer, size); -#else - TmPacketStoredPusC tmPacketStored(this->apid, this->service, subservice, this->tmPacketCounter, - data, dataLen, buffer, size); -#endif - ReturnValue_t result = - tmPacketStored.sendPacket(requestQueue->getDefaultDestination(), requestQueue->getId()); - if (result == returnvalue::OK) { - this->tmPacketCounter++; + telemetry::DataWithObjectIdPrefix dataWithObjId(objectId, data, dataLen); + ReturnValue_t result = tmHelper.prepareTmPacket(subservice, dataWithObjId); + if (result != returnvalue::OK) { + return result; } - return result; + return tmHelper.storeAndSendTmPacket(); } -ReturnValue_t CommandingServiceBase::sendTmPacket(uint8_t subservice, SerializeIF* content, - SerializeIF* header) { -#if FSFW_USE_PUS_C_TELEMETRY == 0 - TmPacketStoredPusA tmPacketStored(this->apid, this->service, subservice, this->tmPacketCounter, - content, header); -#else - TmPacketStoredPusC tmPacketStored(this->apid, this->service, subservice, this->tmPacketCounter, - content, header); -#endif - ReturnValue_t result = - tmPacketStored.sendPacket(requestQueue->getDefaultDestination(), requestQueue->getId()); - if (result == returnvalue::OK) { - this->tmPacketCounter++; +ReturnValue_t CommandingServiceBase::sendTmPacket(uint8_t subservice, SerializeIF& sourceData) { + ReturnValue_t result = tmHelper.prepareTmPacket(subservice, sourceData); + if (result != returnvalue::OK) { + return result; } - return result; + return tmHelper.storeAndSendTmPacket(); } -void CommandingServiceBase::startExecution(TcPacketStoredPus* storedPacket, CommandMapIter iter) { - ReturnValue_t result = returnvalue::OK; +void CommandingServiceBase::startExecution(store_address_t storeId, CommandMapIter& iter) { CommandMessage command; - // TcPacketPusBase* tcPacketBase = storedPacket->getPacketBase(); - if (storedPacket == nullptr) { - return; - } - iter->second.subservice = storedPacket->getSubService(); - result = prepareCommand(&command, iter->second.subservice, storedPacket->getApplicationData(), - storedPacket->getApplicationDataSize(), &iter->second.state, - iter->second.objectId); + iter->second.subservice = tcReader.getSubService(); + ReturnValue_t result = + prepareCommand(&command, iter->second.subservice, tcReader.getUserData(), + tcReader.getUserDataLen(), &iter->second.state, iter->second.objectId); ReturnValue_t sendResult = returnvalue::OK; switch (result) { @@ -347,15 +350,15 @@ void CommandingServiceBase::startExecution(TcPacketStoredPus* storedPacket, Comm if (sendResult == returnvalue::OK) { Clock::getUptime(&iter->second.uptimeOfStart); iter->second.step = 0; - iter->second.subservice = storedPacket->getSubService(); + iter->second.subservice = tcReader.getSubService(); iter->second.command = command.getCommand(); - iter->second.tcInfo.ackFlags = storedPacket->getAcknowledgeFlags(); - iter->second.tcInfo.tcPacketId = storedPacket->getPacketId(); - iter->second.tcInfo.tcSequenceControl = storedPacket->getPacketSequenceControl(); - acceptPacket(tc_verification::START_SUCCESS, storedPacket); + iter->second.tcInfo.ackFlags = tcReader.getAcknowledgeFlags(); + iter->second.tcInfo.tcPacketId = tcReader.getPacketIdRaw(); + iter->second.tcInfo.tcSequenceControl = tcReader.getPacketSeqCtrlRaw(); + acceptPacket(tcverif::START_SUCCESS, storeId); } else { command.clearCommandMessage(); - rejectPacket(tc_verification::START_FAILURE, storedPacket, sendResult); + rejectPacket(tcverif::START_FAILURE, storeId, sendResult); checkAndExecuteFifo(iter); } break; @@ -365,33 +368,46 @@ void CommandingServiceBase::startExecution(TcPacketStoredPus* storedPacket, Comm sendResult = commandQueue->sendMessage(iter.value->first, &command); } if (sendResult == returnvalue::OK) { - verificationReporter.sendSuccessReport(tc_verification::START_SUCCESS, - storedPacket->getPacketBase()); - acceptPacket(tc_verification::COMPLETION_SUCCESS, storedPacket); + verificationReporter->sendSuccessReport( + VerifSuccessParams(tcverif::START_SUCCESS, tcReader)); + acceptPacket(tcverif::COMPLETION_SUCCESS, storeId); checkAndExecuteFifo(iter); } else { command.clearCommandMessage(); - rejectPacket(tc_verification::START_FAILURE, storedPacket, sendResult); + rejectPacket(tcverif::START_FAILURE, storeId, sendResult); checkAndExecuteFifo(iter); } break; default: - rejectPacket(tc_verification::START_FAILURE, storedPacket, result); + rejectPacket(tcverif::START_FAILURE, storeId, result); checkAndExecuteFifo(iter); break; } } -void CommandingServiceBase::rejectPacket(uint8_t reportId, TcPacketStoredPus* packet, - ReturnValue_t errorCode) { - verificationReporter.sendFailureReport(reportId, dynamic_cast(packet), - errorCode); - packet->deletePacket(); +ReturnValue_t CommandingServiceBase::rejectPacketInvalidTc(ReturnValue_t errorCode, + store_address_t tcStoreId) { + failureParameter1 = INVALID_TC; + prepareVerificationFailureWithNoTcInfo(tcverif::START_FAILURE, errorCode, true); + if (tcStoreId != store_address_t::invalid()) { + tcStore->deleteData(tcStoreId); + } + return verificationReporter->sendFailureReport(failParams); } -void CommandingServiceBase::acceptPacket(uint8_t reportId, TcPacketStoredPus* packet) { - verificationReporter.sendSuccessReport(reportId, dynamic_cast(packet)); - packet->deletePacket(); +ReturnValue_t CommandingServiceBase::rejectPacket(uint8_t reportId, store_address_t tcStoreId, + ReturnValue_t errorCode) { + ReturnValue_t result = + verificationReporter->sendFailureReport(VerifFailureParams(reportId, tcReader, errorCode)); + tcStore->deleteData(tcStoreId); + return result; +} + +ReturnValue_t CommandingServiceBase::acceptPacket(uint8_t reportId, store_address_t tcStoreId) { + ReturnValue_t result = + verificationReporter->sendSuccessReport(VerifSuccessParams(reportId, tcReader)); + tcStore->deleteData(tcStoreId); + return result; } void CommandingServiceBase::checkAndExecuteFifo(CommandMapIter& iter) { @@ -399,8 +415,13 @@ void CommandingServiceBase::checkAndExecuteFifo(CommandMapIter& iter) { if (iter->second.fifo.retrieve(&address) != returnvalue::OK) { commandMap.erase(&iter); } else { - TcPacketStoredPus newPacket(address); - startExecution(&newPacket, iter); + ReturnValue_t result = setUpTcReader(address); + if (result == returnvalue::OK) { + startExecution(address, iter); + } else { + // TODO: Warning? + rejectPacket(tcverif::START_FAILURE, address, result); + } } } @@ -418,12 +439,55 @@ void CommandingServiceBase::checkTimeout() { CommandMapIter iter; for (iter = commandMap.begin(); iter != commandMap.end(); ++iter) { if ((iter->second.uptimeOfStart + (timeoutSeconds * 1000)) < uptime) { - verificationReporter.sendFailureReport( - tc_verification::COMPLETION_FAILURE, iter->second.tcInfo.ackFlags, - iter->second.tcInfo.tcPacketId, iter->second.tcInfo.tcSequenceControl, TIMEOUT); + prepareVerificationFailureWithFullInfo(tcverif::COMPLETION_FAILURE, iter->second.tcInfo, + TIMEOUT, false); + verificationReporter->sendFailureReport(failParams); checkAndExecuteFifo(iter); } } } void CommandingServiceBase::setTaskIF(PeriodicTaskIF* task_) { executingTask = task_; } + +void CommandingServiceBase::setCustomTmStore(StorageManagerIF& store) { + tmStoreHelper.setTmStore(store); +} + +ReturnValue_t CommandingServiceBase::setUpTcReader(store_address_t storeId) { + return tc::prepareTcReader(*tcStore, storeId, tcReader); +} + +void CommandingServiceBase::prepareVerificationFailureWithNoTcInfo(uint8_t reportId, + ReturnValue_t errorCode, + bool setCachedFailParams) { + failParams.resetTcFields(); + failParams.resetFailParams(); + failParams.reportId = reportId; + failParams.errorCode = errorCode; + if (setCachedFailParams) { + failParams.errorParam1 = failureParameter1; + failParams.errorParam2 = failureParameter2; + } +} +void CommandingServiceBase::prepareVerificationFailureWithFullInfo(uint8_t reportId, + CommandInfo::TcInfo& tcInfo, + ReturnValue_t errorCode, + bool setCachedFailParams) { + failParams.reportId = reportId; + failParams.tcPacketId = tcInfo.tcPacketId; + failParams.tcPsc = tcInfo.tcSequenceControl; + failParams.ackFlags = tcInfo.ackFlags; + failParams.resetFailParams(); + failParams.errorCode = errorCode; + if (setCachedFailParams) { + failParams.errorParam1 = failureParameter1; + failParams.errorParam2 = failureParameter2; + } +} +void CommandingServiceBase::prepareVerificationSuccessWithFullInfo( + uint8_t reportId, CommandingServiceBase::CommandInfo::TcInfo& tcInfo) { + successParams.reportId = reportId; + successParams.tcPacketId = tcInfo.tcPacketId; + successParams.tcPsc = tcInfo.tcSequenceControl; + successParams.ackFlags = tcInfo.ackFlags; +} diff --git a/src/fsfw/tmtcservices/CommandingServiceBase.h b/src/fsfw/tmtcservices/CommandingServiceBase.h index 1de1f977..9dfbd8bf 100644 --- a/src/fsfw/tmtcservices/CommandingServiceBase.h +++ b/src/fsfw/tmtcservices/CommandingServiceBase.h @@ -2,6 +2,8 @@ #define FSFW_TMTCSERVICES_COMMANDINGSERVICEBASE_H_ #include "AcceptsTelecommandsIF.h" +#include "TmSendHelper.h" +#include "TmStoreHelper.h" #include "VerificationReporter.h" #include "fsfw/FSFW.h" #include "fsfw/container/FIFO.h" @@ -12,32 +14,34 @@ #include "fsfw/serialize/SerializeIF.h" #include "fsfw/storagemanager/StorageManagerIF.h" #include "fsfw/tasks/ExecutableObjectIF.h" - -class TcPacketStoredBase; -class TcPacketStoredPus; +#include "fsfw/tmtcservices/TmStoreAndSendHelper.h" namespace Factory { void setStaticFrameworkObjectIds(); -} +}; /** * @brief This class is the basis for all PUS Services, which have to * relay Telecommands to software bus. * * It manages Telecommand reception and the generation of Verification Reports - * similar to PusServiceBase. This class is used if a telecommand can't be + * similar to @PusServiceBase. This class is used if a telecommand can't be * handled immediately and must be relayed to the internal software bus. * - isValidSubservice * - getMessageQueueAndObject * - prepareCommand * - handleReply + * + * Please note that the TM packets generated by this class will not have a valid CRC. It is + * generally assumed that all packets will pass through a layer where the sequence count is set + * and the CRC16 needs to be re-calculated anyway. * @author gaisser * @ingroup pus_services */ class CommandingServiceBase : public SystemObject, public AcceptsTelecommandsIF, public ExecutableObjectIF { - friend void(Factory::setStaticFrameworkObjectIds)(); + friend void Factory::setStaticFrameworkObjectIds(); public: // We could make this configurable via preprocessor and the FSFWConfig file. @@ -47,7 +51,13 @@ class CommandingServiceBase : public SystemObject, static const ReturnValue_t EXECUTION_COMPLETE = MAKE_RETURN_CODE(1); static const ReturnValue_t NO_STEP_MESSAGE = MAKE_RETURN_CODE(2); + /** + * Target object has too many pending requests + */ static const ReturnValue_t OBJECT_BUSY = MAKE_RETURN_CODE(3); + /** + * Command map is full + */ static const ReturnValue_t BUSY = MAKE_RETURN_CODE(4); static const ReturnValue_t INVALID_TC = MAKE_RETURN_CODE(5); static const ReturnValue_t INVALID_OBJECT = MAKE_RETURN_CODE(6); @@ -67,9 +77,10 @@ class CommandingServiceBase : public SystemObject, */ CommandingServiceBase(object_id_t setObjectId, uint16_t apid, uint8_t service, uint8_t numberOfParallelCommands, uint16_t commandTimeoutSeconds, - size_t queueDepth = 20); - virtual ~CommandingServiceBase(); + size_t queueDepth = 20, VerificationReporterIF* reporter = nullptr); + ~CommandingServiceBase() override; + void setCustomTmStore(StorageManagerIF& store); /** * This setter can be used to set the packet source individually instead * of using the default static framework ID set in the factory. @@ -92,9 +103,9 @@ class CommandingServiceBase : public SystemObject, * @param opCode is unused here at the moment * @return returnvalue::OK */ - virtual ReturnValue_t performOperation(uint8_t opCode) override; + ReturnValue_t performOperation(uint8_t opCode) override; - virtual uint16_t getIdentifier() override; + uint16_t getIdentifier() override; /** * Returns the requestQueue MessageQueueId_t @@ -103,7 +114,7 @@ class CommandingServiceBase : public SystemObject, * * @return requestQueue messageQueueId_t */ - virtual MessageQueueId_t getRequestQueue() override; + MessageQueueId_t getRequestQueue() override; /** * Returns the commandQueue MessageQueueId_t @@ -113,7 +124,7 @@ class CommandingServiceBase : public SystemObject, */ virtual MessageQueueId_t getCommandQueue(); - virtual ReturnValue_t initialize() override; + ReturnValue_t initialize() override; /** * Implementation of ExecutableObjectIF function @@ -121,7 +132,7 @@ class CommandingServiceBase : public SystemObject, * Used to setup the reference of the task, that executes this component * @param task Pointer to the taskIF of this task */ - virtual void setTaskIF(PeriodicTaskIF* task) override; + void setTaskIF(PeriodicTaskIF* task) override; protected: /** @@ -143,7 +154,7 @@ class CommandingServiceBase : public SystemObject, * @param id MessageQueue ID is stored here * @param objectId Object ID is extracted and stored here * @return - * - @c returnvalue::OK Cotinue message handling + * - @c returnvalue::OK Continue message handling * - @c returnvalue::FAILED Reject the packet and generates a start failure * verification */ @@ -216,7 +227,7 @@ class CommandingServiceBase : public SystemObject, virtual void doPeriodicOperation(); struct CommandInfo : public SerializeIF { - struct tcInfo { + struct TcInfo { uint8_t ackFlags; uint16_t tcPacketId; uint16_t tcSequenceControl; @@ -229,15 +240,15 @@ class CommandingServiceBase : public SystemObject, object_id_t objectId; FIFO fifo; - virtual ReturnValue_t serialize(uint8_t** buffer, size_t* size, size_t maxSize, - Endianness streamEndianness) const override { + ReturnValue_t serialize(uint8_t** buffer, size_t* size, size_t maxSize, + Endianness streamEndianness) const override { return returnvalue::FAILED; }; - virtual size_t getSerializedSize() const override { return 0; }; + [[nodiscard]] size_t getSerializedSize() const override { return 0; }; - virtual ReturnValue_t deSerialize(const uint8_t** buffer, size_t* size, - Endianness streamEndianness) override { + ReturnValue_t deSerialize(const uint8_t** buffer, size_t* size, + Endianness streamEndianness) override { return returnvalue::FAILED; }; }; @@ -250,17 +261,21 @@ class CommandingServiceBase : public SystemObject, const uint16_t timeoutSeconds; - uint8_t tmPacketCounter = 0; + PusTcReader tcReader; + TmStoreHelper tmStoreHelper; + TmSendHelper tmSendHelper; + TmStoreAndSendWrapper tmHelper; - StorageManagerIF* IPCStore = nullptr; - - StorageManagerIF* TCStore = nullptr; + StorageManagerIF* tcStore = nullptr; + StorageManagerIF* ipcStore = nullptr; MessageQueueIF* commandQueue = nullptr; - MessageQueueIF* requestQueue = nullptr; - VerificationReporter verificationReporter; + TimeStamperIF* tmTimeStamper = nullptr; + VerificationReporterIF* verificationReporter; + + InternalErrorReporterIF* errReporter = nullptr; FixedMap commandMap; @@ -279,45 +294,19 @@ class CommandingServiceBase : public SystemObject, */ PeriodicTaskIF* executingTask = nullptr; - /** - * @brief Send TM data from pointer to data. - * If a header is supplied it is added before data - * @param subservice Number of subservice - * @param data Pointer to the data in the Packet - * @param dataLen Lenght of data in the Packet - * @param headerData HeaderData will be placed before data - * @param headerSize Size of HeaderData - */ - ReturnValue_t sendTmPacket(uint8_t subservice, const uint8_t* data, size_t dataLen, - const uint8_t* headerData = nullptr, size_t headerSize = 0); - - /** - * @brief To send TM packets of objects that still need to be serialized - * and consist of an object ID with appended data. - * @param subservice Number of subservice - * @param objectId ObjectId is placed before data - * @param data Data to append to the packet - * @param dataLen Length of Data - */ + ReturnValue_t sendTmPacket(uint8_t subservice, const uint8_t* sourceData, size_t sourceDataLen); ReturnValue_t sendTmPacket(uint8_t subservice, object_id_t objectId, const uint8_t* data, size_t dataLen); - - /** - * @brief To send packets which are contained inside a class implementing - * SerializeIF. - * @param subservice Number of subservice - * @param content This is a pointer to the serialized packet - * @param header Serialize IF header which will be placed before content - */ - ReturnValue_t sendTmPacket(uint8_t subservice, SerializeIF* content, - SerializeIF* header = nullptr); + ReturnValue_t sendTmPacket(uint8_t subservice, SerializeIF& sourceData); void checkAndExecuteFifo(CommandMapIter& iter); + VerifFailureParams failParams; + VerifSuccessParams successParams; private: /** * This method handles internal execution of a command, - * once it has been started by @sa{startExecution()} in the request + * once it has been started by @startExecution in the request * queue handler. * It handles replies generated by the devices and relayed by the specific * service implementation. This means that it determines further course of @@ -337,23 +326,36 @@ class CommandingServiceBase : public SystemObject, * @brief Handler function for request queue * @details * Sequence of request queue handling: - * isValidSubservice -> getMessageQueueAndObject -> startExecution + * @isValidSubservice -> @getMessageQueueAndObject -> @startExecution * Generates a Start Success Reports TM[1,3] in subfunction - * @sa{startExecution()} or a Start Failure Report TM[1,4] by using the + * @startExecution or a Start Failure Report TM[1,4] by using the * TC Verification Service. */ void handleRequestQueue(); - void rejectPacket(uint8_t reportId, TcPacketStoredPus* packet, ReturnValue_t errorCode); + ReturnValue_t setUpTcReader(store_address_t storeId); - void acceptPacket(uint8_t reportId, TcPacketStoredPus* packet); + /** + * The TC format is invalid or there was an issue retrieving a TC packet from the store. + * @param errorCode Result of the failed operation, will be sent with the verification failure + * message + * @return + */ + ReturnValue_t rejectPacketInvalidTc(ReturnValue_t errorCode, store_address_t tcStoreId); + ReturnValue_t rejectPacket(uint8_t reportId, store_address_t tcStoreId, ReturnValue_t errorCode); - void startExecution(TcPacketStoredPus* storedPacket, CommandMapIter iter); + ReturnValue_t acceptPacket(uint8_t reportId, store_address_t tcStoreId); + + void startExecution(store_address_t storeId, CommandMapIter& iter); void handleCommandMessage(CommandMessage* reply); void handleReplyHandlerResult(ReturnValue_t result, CommandMapIter iter, CommandMessage* nextCommand, CommandMessage* reply, bool& isStep); - + void prepareVerificationFailureWithNoTcInfo(uint8_t reportId, ReturnValue_t errorCode, + bool setCachedFailParams); + void prepareVerificationFailureWithFullInfo(uint8_t reportId, CommandInfo::TcInfo& tcInfo, + ReturnValue_t errorCode, bool setCachedFailParams); + void prepareVerificationSuccessWithFullInfo(uint8_t reportId, CommandInfo::TcInfo& tcInfo); void checkTimeout(); }; diff --git a/src/fsfw/tmtcservices/PusServiceBase.cpp b/src/fsfw/tmtcservices/PusServiceBase.cpp index 0ee358b0..6900a2ac 100644 --- a/src/fsfw/tmtcservices/PusServiceBase.cpp +++ b/src/fsfw/tmtcservices/PusServiceBase.cpp @@ -4,113 +4,201 @@ #include "fsfw/objectmanager/ObjectManager.h" #include "fsfw/serviceinterface/ServiceInterface.h" #include "fsfw/tcdistribution/PUSDistributorIF.h" +#include "fsfw/timemanager/CdsShortTimeStamper.h" #include "fsfw/tmtcservices/AcceptsTelemetryIF.h" #include "fsfw/tmtcservices/PusVerificationReport.h" #include "fsfw/tmtcservices/TmTcMessage.h" +#include "fsfw/tmtcservices/tcHelpers.h" -object_id_t PusServiceBase::packetSource = 0; -object_id_t PusServiceBase::packetDestination = 0; +object_id_t PusServiceBase::PACKET_DESTINATION = 0; +object_id_t PusServiceBase::PUS_DISTRIBUTOR = 0; -PusServiceBase::PusServiceBase(object_id_t setObjectId, uint16_t setApid, uint8_t setServiceId) - : SystemObject(setObjectId), apid(setApid), serviceId(setServiceId) { - requestQueue = QueueFactory::instance()->createMessageQueue(PUS_SERVICE_MAX_RECEPTION); +PusServiceBase::PusServiceBase(PsbParams params) + : SystemObject(params.objectId), psbParams(params) {} + +PusServiceBase::~PusServiceBase() { + if (ownedQueue) { + QueueFactory::instance()->deleteMessageQueue(psbParams.reqQueue); + } } -PusServiceBase::~PusServiceBase() { QueueFactory::instance()->deleteMessageQueue(requestQueue); } - ReturnValue_t PusServiceBase::performOperation(uint8_t opCode) { handleRequestQueue(); - ReturnValue_t result = this->performService(); + ReturnValue_t result = performService(); if (result != returnvalue::OK) { #if FSFW_CPP_OSTREAM_ENABLED == 1 - sif::error << "PusService " << (uint16_t)this->serviceId << ": performService returned with " - << (int16_t)result << std::endl; + sif::error << "PusService " << psbParams.serviceId << ": performService returned with " + << static_cast(result) << std::endl; #endif return returnvalue::FAILED; } return returnvalue::OK; } -void PusServiceBase::setTaskIF(PeriodicTaskIF* taskHandle) { this->taskHandle = taskHandle; } +void PusServiceBase::setTaskIF(PeriodicTaskIF* taskHandle_) { this->taskHandle = taskHandle_; } void PusServiceBase::handleRequestQueue() { TmTcMessage message; - ReturnValue_t result = returnvalue::FAILED; + ReturnValue_t result; for (uint8_t count = 0; count < PUS_SERVICE_MAX_RECEPTION; count++) { - ReturnValue_t status = this->requestQueue->receiveMessage(&message); - // if(status != MessageQueueIF::EMPTY) { -#if FSFW_CPP_OSTREAM_ENABLED == 1 - // sif::debug << "PusServiceBase::performOperation: Receiving from " - // << "MQ ID: " << std::hex << "0x" << std::setw(8) - // << std::setfill('0') << this->requestQueue->getId() - // << std::dec << " returned: " << status << std::setfill(' ') - // << std::endl; -#endif - // } - - if (status == returnvalue::OK) { - this->currentPacket.setStoreAddress(message.getStorageId(), ¤tPacket); - // info << "Service " << (uint16_t) this->serviceId << - // ": new packet!" << std::endl; - - result = this->handleRequest(currentPacket.getSubService()); - - // debug << "Service " << (uint16_t)this->serviceId << - // ": handleRequest returned: " << (int)return_code << std::endl; - if (result == returnvalue::OK) { - this->verifyReporter.sendSuccessReport(tc_verification::COMPLETION_SUCCESS, - &this->currentPacket); - } else { - this->verifyReporter.sendFailureReport(tc_verification::COMPLETION_FAILURE, - &this->currentPacket, result, 0, errorParameter1, - errorParameter2); - } - this->currentPacket.deletePacket(); - errorParameter1 = 0; - errorParameter2 = 0; - } else if (status == MessageQueueIF::EMPTY) { - status = returnvalue::OK; - // debug << "PusService " << (uint16_t)this->serviceId << - // ": no new packet." << std::endl; + ReturnValue_t status = psbParams.reqQueue->receiveMessage(&message); + if (status == MessageQueueIF::EMPTY) { break; - } else { + } else if (status != returnvalue::OK) { #if FSFW_CPP_OSTREAM_ENABLED == 1 - sif::error << "PusServiceBase::performOperation: Service " << this->serviceId + sif::error << "PusServiceBase::performOperation: Service " << psbParams.serviceId << ": Error receiving packet. Code: " << std::hex << status << std::dec << std::endl; +#else + sif::printError( + "PusServiceBase::performOperation: Service %d. Error receiving packet. Code: %04x\n", + psbParams.serviceId, status); #endif + break; } + result = tc::prepareTcReader(*psbParams.tcPool, message.getStorageId(), currentPacket); + if (result != returnvalue::OK) { + // We were not even able to retrieve the TC, so we can not retrieve any TC properties either + // without segfaulting + auto verifParams = VerifFailureParams(tcverif::START_FAILURE, 0, 0, result); + verifParams.errorParam1 = errorParameter1; + verifParams.errorParam2 = errorParameter2; + psbParams.verifReporter->sendFailureReport(verifParams); + continue; + } + result = handleRequest(currentPacket.getSubService()); + if (result == returnvalue::OK) { + psbParams.verifReporter->sendSuccessReport( + VerifSuccessParams(tcverif::COMPLETION_SUCCESS, currentPacket)); + } else { + auto failParams = VerifFailureParams(tcverif::COMPLETION_FAILURE, currentPacket, result); + failParams.errorParam1 = errorParameter1; + failParams.errorParam2 = errorParameter2; + psbParams.verifReporter->sendFailureReport(failParams); + } + psbParams.tcPool->deleteData(message.getStorageId()); + errorParameter1 = 0; + errorParameter2 = 0; } } -uint16_t PusServiceBase::getIdentifier() { return this->serviceId; } +uint16_t PusServiceBase::getIdentifier() { return psbParams.serviceId; } -MessageQueueId_t PusServiceBase::getRequestQueue() { return this->requestQueue->getId(); } +MessageQueueId_t PusServiceBase::getRequestQueue() { + if (psbParams.reqQueue == nullptr) { + return MessageQueueIF::NO_QUEUE; + } + return psbParams.reqQueue->getId(); +} ReturnValue_t PusServiceBase::initialize() { ReturnValue_t result = SystemObject::initialize(); if (result != returnvalue::OK) { return result; } - AcceptsTelemetryIF* destService = - ObjectManager::instance()->get(packetDestination); - PUSDistributorIF* distributor = ObjectManager::instance()->get(packetSource); - if (destService == nullptr or distributor == nullptr) { -#if FSFW_CPP_OSTREAM_ENABLED == 1 - sif::error << "PusServiceBase::PusServiceBase: Service " << this->serviceId - << ": Configuration error. Make sure " - << "packetSource and packetDestination are defined correctly" << std::endl; -#endif - return ObjectManagerIF::CHILD_INIT_FAILED; + if (psbParams.reqQueue == nullptr) { + ownedQueue = true; + psbParams.reqQueue = QueueFactory::instance()->createMessageQueue(PSB_DEFAULT_QUEUE_DEPTH); + } else { + ownedQueue = false; + } + + if (psbParams.tmReceiver == nullptr) { + psbParams.tmReceiver = ObjectManager::instance()->get(PACKET_DESTINATION); + if (psbParams.tmReceiver != nullptr) { + psbParams.reqQueue->setDefaultDestination(psbParams.tmReceiver->getReportReceptionQueue()); + } + } + + if (psbParams.pusDistributor == nullptr) { + psbParams.pusDistributor = ObjectManager::instance()->get(PUS_DISTRIBUTOR); + if (psbParams.pusDistributor != nullptr) { + registerService(*psbParams.pusDistributor); + } + } + + if (psbParams.tcPool == nullptr) { + psbParams.tcPool = ObjectManager::instance()->get(objects::TC_STORE); + if (psbParams.tcPool == nullptr) { + return ObjectManagerIF::CHILD_INIT_FAILED; + } + } + + if (psbParams.verifReporter == nullptr) { + psbParams.verifReporter = + ObjectManager::instance()->get(objects::VERIFICATION_REPORTER); + if (psbParams.verifReporter == nullptr) { + return ObjectManagerIF::CHILD_INIT_FAILED; + } } - this->requestQueue->setDefaultDestination(destService->getReportReceptionQueue()); - distributor->registerService(this); return returnvalue::OK; } -ReturnValue_t PusServiceBase::initializeAfterTaskCreation() { - // If task parameters, for example task frequency are required, this - // function should be overriden and the system object task IF can - // be used to get those parameters. +void PusServiceBase::setTcPool(StorageManagerIF& tcPool) { psbParams.tcPool = &tcPool; } + +void PusServiceBase::setErrorReporter(InternalErrorReporterIF& errReporter_) { + psbParams.errReporter = &errReporter_; +} + +ReturnValue_t PusServiceBase::initializeTmHelpers(TmSendHelper& tmSendHelper, + TmStoreHelper& tmStoreHelper) { + ReturnValue_t result = initializeTmSendHelper(tmSendHelper); + if (result != returnvalue::OK) { + return result; + } + return initializeTmStoreHelper(tmStoreHelper); +} + +ReturnValue_t PusServiceBase::initializeTmSendHelper(TmSendHelper& tmSendHelper) { + if (psbParams.reqQueue != nullptr) { + tmSendHelper.setMsgQueue(*psbParams.reqQueue); + tmSendHelper.setDefaultDestination(psbParams.reqQueue->getDefaultDestination()); + } + + if (psbParams.errReporter == nullptr) { + psbParams.errReporter = + ObjectManager::instance()->get(objects::INTERNAL_ERROR_REPORTER); + if (psbParams.errReporter != nullptr) { + tmSendHelper.setInternalErrorReporter(*psbParams.errReporter); + } + } else { + tmSendHelper.setInternalErrorReporter(*psbParams.errReporter); + } return returnvalue::OK; } + +ReturnValue_t PusServiceBase::initializeTmStoreHelper(TmStoreHelper& tmStoreHelper) const { + tmStoreHelper.setApid(psbParams.apid); + if (tmStoreHelper.getTmStore() == nullptr) { + auto* tmStore = ObjectManager::instance()->get(objects::TM_STORE); + if (tmStore == nullptr) { + return ObjectManagerIF::CHILD_INIT_FAILED; + } + tmStoreHelper.setTmStore(*tmStore); + } + + if (psbParams.timeStamper == nullptr) { + auto timerStamper = ObjectManager::instance()->get(objects::TIME_STAMPER); + if (timerStamper != nullptr) { + tmStoreHelper.setTimeStamper(*timerStamper); + } + } + // Generally, all TM packets will pass through a layer where the sequence count is set. + // This avoids duplicate calculation of the CRC16 + tmStoreHelper.disableCrcCalculation(); + return returnvalue::OK; +} + +void PusServiceBase::setVerificationReporter(VerificationReporterIF& reporter) { + psbParams.verifReporter = &reporter; +} + +ReturnValue_t PusServiceBase::registerService(PUSDistributorIF& distributor) { + return distributor.registerService(this); +} + +void PusServiceBase::setTmReceiver(AcceptsTelemetryIF& tmReceiver_) { + psbParams.tmReceiver = &tmReceiver_; +} + +void PusServiceBase::setRequestQueue(MessageQueueIF& reqQueue) { psbParams.reqQueue = &reqQueue; } diff --git a/src/fsfw/tmtcservices/PusServiceBase.h b/src/fsfw/tmtcservices/PusServiceBase.h index d7a2ee47..ce4b03f5 100644 --- a/src/fsfw/tmtcservices/PusServiceBase.h +++ b/src/fsfw/tmtcservices/PusServiceBase.h @@ -2,6 +2,9 @@ #define FSFW_TMTCSERVICES_PUSSERVICEBASE_H_ #include "AcceptsTelecommandsIF.h" +#include "AcceptsTelemetryIF.h" +#include "TmSendHelper.h" +#include "TmStoreHelper.h" #include "VerificationCodes.h" #include "VerificationReporter.h" #include "fsfw/ipc/MessageQueueIF.h" @@ -9,7 +12,61 @@ #include "fsfw/objectmanager/SystemObject.h" #include "fsfw/returnvalues/returnvalue.h" #include "fsfw/tasks/ExecutableObjectIF.h" -#include "fsfw/tmtcpacket/pus/tc.h" +#include "fsfw/tcdistribution/PUSDistributorIF.h" + +class StorageManagerIF; + +/** + * Configuration parameters for the PUS Service Base + */ +struct PsbParams { + PsbParams() = default; + PsbParams(uint16_t apid, AcceptsTelemetryIF* tmReceiver) : apid(apid), tmReceiver(tmReceiver) {} + PsbParams(object_id_t objectId, uint16_t apid, uint8_t serviceId) + : objectId(objectId), apid(apid), serviceId(serviceId) {} + + object_id_t objectId = objects::NO_OBJECT; + uint16_t apid = 0; + uint8_t serviceId = 0; + /** + * The default destination ID for generated telemetry. If this is not set, @initialize of PSB + * will attempt to find a suitable object with the object ID @PusServiceBase::packetDestination + */ + AcceptsTelemetryIF* tmReceiver = nullptr; + /** + * An instance of the VerificationReporter class, that simplifies + * sending any kind of verification message to the TC Verification Service. If this is not set, + * @initialize of PSB will attempt to find a suitable global object with the ID + * @objects::TC_VERIFICATOR + */ + VerificationReporterIF* verifReporter = nullptr; + /** + * This is a complete instance of the telecommand reception queue + * of the class. It is initialized on construction of the class. + */ + MessageQueueIF* reqQueue = nullptr; + /** + * The internal error reporter which will be used if there are issues sending telemetry. + * If this is not set, and the TM send or store helpers are initialized with the PSB, + * the class will attempt to find a suitable global object with the ID + * @objects::INTERNAL_ERROR_REPORTER + */ + InternalErrorReporterIF* errReporter = nullptr; + /** + * The storage manager which will be used to retrieve any TC packet using the store ID + * received via a message. If this is not set, the class will attempt to find a suitable global + * object with the ID @objects::TC_STORE + */ + StorageManagerIF* tcPool = nullptr; + /** + * Usually, packets are sent via a dedicated PUS distributor. If this distributor is set, + * the PUS service will register itself there. Otherwise, the base class will try to find + * a suitable global distributor with the static ID @PusServiceBase::pusDistributor and + * register itself at that object. + */ + PUSDistributorIF* pusDistributor = nullptr; + TimeStamperIF* timeStamper = nullptr; +}; namespace Factory { void setStaticFrameworkObjectIds(); @@ -36,24 +93,58 @@ void setStaticFrameworkObjectIds(); class PusServiceBase : public ExecutableObjectIF, public AcceptsTelecommandsIF, public SystemObject { - friend void(Factory::setStaticFrameworkObjectIds)(); + friend void Factory::setStaticFrameworkObjectIds(); public: + /** + * This constant sets the maximum number of packets accepted per call. + * Remember that one packet must be completely handled in one + * #handleRequest call. + */ + static constexpr uint8_t PUS_SERVICE_MAX_RECEPTION = 10; + static constexpr uint8_t PSB_DEFAULT_QUEUE_DEPTH = 10; + /** * @brief The passed values are set, but inter-object initialization is * done in the initialize method. - * @param setObjectId - * The system object identifier of this Service instance. - * @param setApid - * The APID the Service is instantiated for. - * @param setServiceId - * The Service Identifier as specified in ECSS PUS. + * @param params All configuration parameters for the PUS Service Base */ - PusServiceBase(object_id_t setObjectId, uint16_t setApid, uint8_t setServiceId); + explicit PusServiceBase(PsbParams params); /** * The destructor is empty. */ - virtual ~PusServiceBase(); + ~PusServiceBase() override; + + ReturnValue_t registerService(PUSDistributorIF& distributor); + /** + * Set the request queue which is used to receive requests. If none is set, the initialize + * function will create one + * @param reqQueue + */ + void setRequestQueue(MessageQueueIF& reqQueue); + void setTmReceiver(AcceptsTelemetryIF& tmReceiver); + void setTcPool(StorageManagerIF& tcStore); + void setVerificationReporter(VerificationReporterIF& reporter); + void setErrorReporter(InternalErrorReporterIF& errReporter); + + /** + * Helper methods if the implementing class wants to send telemetry + * @param tmSendHelper + */ + ReturnValue_t initializeTmSendHelper(TmSendHelper& tmSendHelper); + /** + * Helper methods if the implementing class wants to store telemetry. It will set the correct APID + * and it will also attempt to set a valid time stamper. If the manually specified time stamper is + * null, it will attempt to find a suitable one using @objects::TIME_STAMPER + * @param tmSendHelper + */ + ReturnValue_t initializeTmStoreHelper(TmStoreHelper& tmStoreHelper) const; + /** + * Helper methods if the implementing class wants to both send and store telemetry + * @param tmSendHelper + */ + ReturnValue_t initializeTmHelpers(TmSendHelper& tmSendHelper, TmStoreHelper& tmStoreHelper); + /** * @brief The handleRequest method shall handle any kind of Telecommand * Request immediately. @@ -93,15 +184,14 @@ class PusServiceBase : public ExecutableObjectIF, * the TC requests afterwards. * performService is always executed afterwards. * @return @c returnvalue::OK if the periodic performService was successful. - * @c returnvalue::FAILED else. + * @c returnvalue::FAILED else. */ ReturnValue_t performOperation(uint8_t opCode) override; - virtual uint16_t getIdentifier() override; + uint16_t getIdentifier() override; MessageQueueId_t getRequestQueue() override; - virtual ReturnValue_t initialize() override; + ReturnValue_t initialize() override; - virtual void setTaskIF(PeriodicTaskIF* taskHandle) override; - virtual ReturnValue_t initializeAfterTaskCreation() override; + void setTaskIF(PeriodicTaskIF* taskHandle) override; protected: /** @@ -110,14 +200,6 @@ class PusServiceBase : public ExecutableObjectIF, * Will be set by setTaskIF(), which is called on task creation. */ PeriodicTaskIF* taskHandle = nullptr; - /** - * The APID of this instance of the Service. - */ - uint16_t apid; - /** - * The Service Identifier. - */ - uint8_t serviceId; /** * One of two error parameters for additional error information. */ @@ -126,34 +208,18 @@ class PusServiceBase : public ExecutableObjectIF, * One of two error parameters for additional error information. */ uint32_t errorParameter2 = 0; - /** - * This is a complete instance of the telecommand reception queue - * of the class. It is initialized on construction of the class. - */ - MessageQueueIF* requestQueue = nullptr; - /** - * An instance of the VerificationReporter class, that simplifies - * sending any kind of verification message to the TC Verification Service. - */ - VerificationReporter verifyReporter; + PsbParams psbParams; /** * The current Telecommand to be processed. * It is deleted after handleRequest was executed. */ - TcPacketStoredPus currentPacket; + PusTcReader currentPacket; + bool ownedQueue = true; - static object_id_t packetSource; - - static object_id_t packetDestination; + static object_id_t PACKET_DESTINATION; + static object_id_t PUS_DISTRIBUTOR; private: - /** - * This constant sets the maximum number of packets accepted per call. - * Remember that one packet must be completely handled in one - * #handleRequest call. - */ - static const uint8_t PUS_SERVICE_MAX_RECEPTION = 10; - void handleRequestQueue(); }; diff --git a/src/fsfw/tmtcservices/PusVerificationReport.h b/src/fsfw/tmtcservices/PusVerificationReport.h index 4f5302f1..f0cad337 100644 --- a/src/fsfw/tmtcservices/PusVerificationReport.h +++ b/src/fsfw/tmtcservices/PusVerificationReport.h @@ -4,7 +4,7 @@ #include "VerificationCodes.h" #include "fsfw/ipc/MessageQueueMessage.h" #include "fsfw/returnvalues/returnvalue.h" -#include "fsfw/tmtcpacket/pus/tc/TcPacketPusBase.h" +#include "fsfw/tmtcpacket/pus/tc/PusTcReader.h" class PusVerificationMessage : public MessageQueueMessage { private: diff --git a/src/fsfw/tmtcservices/SourceSequenceCounter.h b/src/fsfw/tmtcservices/SourceSequenceCounter.h index e981a945..43b6945c 100644 --- a/src/fsfw/tmtcservices/SourceSequenceCounter.h +++ b/src/fsfw/tmtcservices/SourceSequenceCounter.h @@ -1,24 +1,32 @@ #ifndef FSFW_TMTCSERVICES_SOURCESEQUENCECOUNTER_H_ #define FSFW_TMTCSERVICES_SOURCESEQUENCECOUNTER_H_ -#include "../tmtcpacket/SpacePacketBase.h" +#include "fsfw/tmtcpacket/ccsds/SpacePacketReader.h" class SourceSequenceCounter { private: - uint16_t sequenceCount; + uint16_t sequenceCount = 0; public: - SourceSequenceCounter() : sequenceCount(0) {} - void increment() { - sequenceCount = (sequenceCount + 1) % (SpacePacketBase::LIMIT_SEQUENCE_COUNT); - } - void decrement() { - sequenceCount = (sequenceCount - 1) % (SpacePacketBase::LIMIT_SEQUENCE_COUNT); - } + SourceSequenceCounter(uint16_t initialSequenceCount = 0) : sequenceCount(initialSequenceCount) {} + void increment() { sequenceCount = (sequenceCount + 1) % (ccsds::LIMIT_SEQUENCE_COUNT); } + void decrement() { sequenceCount = (sequenceCount - 1) % (ccsds::LIMIT_SEQUENCE_COUNT); } uint16_t get() { return this->sequenceCount; } - void reset(uint16_t toValue = 0) { - sequenceCount = toValue % (SpacePacketBase::LIMIT_SEQUENCE_COUNT); + void reset(uint16_t toValue = 0) { sequenceCount = toValue % (ccsds::LIMIT_SEQUENCE_COUNT); } + SourceSequenceCounter& operator++(int) { + this->increment(); + return *this; } + SourceSequenceCounter& operator--(int) { + this->decrement(); + return *this; + } + SourceSequenceCounter& operator=(const uint16_t& newCount) { + sequenceCount = newCount; + return *this; + } + + operator uint16_t() { return this->get(); } }; #endif /* FSFW_TMTCSERVICES_SOURCESEQUENCECOUNTER_H_ */ diff --git a/src/fsfw/tmtcservices/TmSendHelper.cpp b/src/fsfw/tmtcservices/TmSendHelper.cpp new file mode 100644 index 00000000..210ed5f6 --- /dev/null +++ b/src/fsfw/tmtcservices/TmSendHelper.cpp @@ -0,0 +1,61 @@ +#include "TmSendHelper.h" + +#include "fsfw/ipc/MessageQueueSenderIF.h" + +TmSendHelper::TmSendHelper() = default; + +TmSendHelper::TmSendHelper(MessageQueueIF &queue, InternalErrorReporterIF &reporter, + MessageQueueId_t defaultDest) + : queue(&queue), errReporter(&reporter) { + queue.setDefaultDestination(defaultDest); +} + +TmSendHelper::TmSendHelper(MessageQueueIF &queue, InternalErrorReporterIF &reporter) + : queue(&queue), errReporter(&reporter) {} + +TmSendHelper::TmSendHelper(InternalErrorReporterIF &reporter) : errReporter(&reporter) {} + +ReturnValue_t TmSendHelper::sendPacket(const store_address_t &storeId) { + return sendPacket(getDefaultDestination(), storeId); +} + +void TmSendHelper::setDefaultDestination(MessageQueueId_t msgDest) { + if (queue != nullptr) { + queue->setDefaultDestination(msgDest); + }; +} + +void TmSendHelper::setInternalErrorReporter(InternalErrorReporterIF &reporter) { + errReporter = &reporter; +} +void TmSendHelper::setMsgQueue(MessageQueueIF &queue_) { queue = &queue_; } + +ReturnValue_t TmSendHelper::sendPacket(MessageQueueId_t dest, const store_address_t &storeId) { + if (queue == nullptr) { + return returnvalue::FAILED; + } + TmTcMessage message(storeId); + ReturnValue_t result = queue->sendMessage(dest, &message, ignoreFault); + if (result != returnvalue::OK) { + if (errReporter != nullptr and not ignoreFault) { + errReporter->lostTm(); + } + return result; + } + return result; +} + +MessageQueueId_t TmSendHelper::getDefaultDestination() const { + if (queue != nullptr) { + return queue->getDefaultDestination(); + }; + return MessageQueueIF::NO_QUEUE; +} + +bool TmSendHelper::areFaultsIgnored() const { return ignoreFault; } +void TmSendHelper::ignoreFaults() { ignoreFault = true; } +void TmSendHelper::dontIgnoreFaults() { ignoreFault = false; } + +InternalErrorReporterIF *TmSendHelper::getInternalErrorReporter() const { return errReporter; } + +MessageQueueIF *TmSendHelper::getMsgQueue() const { return queue; } diff --git a/src/fsfw/tmtcservices/TmSendHelper.h b/src/fsfw/tmtcservices/TmSendHelper.h new file mode 100644 index 00000000..9fee84c4 --- /dev/null +++ b/src/fsfw/tmtcservices/TmSendHelper.h @@ -0,0 +1,37 @@ +#ifndef FSFW_TMTCPACKET_TMSENDHELPER_H +#define FSFW_TMTCPACKET_TMSENDHELPER_H + +#include "TmTcMessage.h" +#include "fsfw/internalerror/InternalErrorReporterIF.h" +#include "fsfw/ipc/MessageQueueIF.h" +#include "fsfw/ipc/messageQueueDefinitions.h" +#include "fsfw/returnvalues/returnvalue.h" + +class TmSendHelper { + public: + TmSendHelper(); + TmSendHelper(MessageQueueIF& queue, InternalErrorReporterIF& reporter, + MessageQueueId_t tmtcMsgDest); + TmSendHelper(MessageQueueIF& queue, InternalErrorReporterIF& reporter); + explicit TmSendHelper(InternalErrorReporterIF& reporter); + + void setMsgQueue(MessageQueueIF& queue); + [[nodiscard]] MessageQueueIF* getMsgQueue() const; + + void setDefaultDestination(MessageQueueId_t msgDest); + [[nodiscard]] MessageQueueId_t getDefaultDestination() const; + [[nodiscard]] bool areFaultsIgnored() const; + void ignoreFaults(); + void dontIgnoreFaults(); + void setInternalErrorReporter(InternalErrorReporterIF& reporter); + [[nodiscard]] InternalErrorReporterIF* getInternalErrorReporter() const; + ReturnValue_t sendPacket(MessageQueueId_t dest, const store_address_t& storeId); + ReturnValue_t sendPacket(const store_address_t& storeId); + + private: + bool ignoreFault = false; + MessageQueueIF* queue = nullptr; + InternalErrorReporterIF* errReporter = nullptr; +}; + +#endif // FSFW_TMTCPACKET_TMSENDHELPER_H diff --git a/src/fsfw/tmtcservices/TmStoreAndSendHelper.cpp b/src/fsfw/tmtcservices/TmStoreAndSendHelper.cpp new file mode 100644 index 00000000..3057800a --- /dev/null +++ b/src/fsfw/tmtcservices/TmStoreAndSendHelper.cpp @@ -0,0 +1,65 @@ +#include "TmStoreAndSendHelper.h" + +#include "tmHelpers.h" + +TmStoreAndSendWrapper::TmStoreAndSendWrapper(uint8_t defaultService, TmStoreHelper& storeHelper, + TmSendHelper& sendHelper) + : storeHelper(storeHelper), sendHelper(sendHelper), defaultService(defaultService) {} + +/** + * Helper wrapper which stores the TM packet into the store and then sends it. + * @return + * - StorageManagerIF returnvalue if storage fails + * - MessageQueueIF returnvalue if sending fails + */ +ReturnValue_t TmStoreAndSendWrapper::storeAndSendTmPacket() { + ReturnValue_t result = storeHelper.addPacketToStore(); + if (result != returnvalue::OK) { + return result; + } + result = sendHelper.sendPacket(storeHelper.getCurrentAddr()); + if (result != returnvalue::OK) { + if (delOnFailure) { + storeHelper.deletePacket(); + } + return result; + } + if (incrementSendCounter) { + sendCounter++; + } + return result; +} + +ReturnValue_t TmStoreAndSendWrapper::prepareTmPacket(uint8_t subservice, const uint8_t* sourceData, + size_t sourceDataLen) { + ReturnValue_t result = storeHelper.preparePacket(defaultService, subservice, sendCounter); + if (result != returnvalue::OK) { + return result; + } + return storeHelper.setSourceDataRaw(sourceData, sourceDataLen); +} + +ReturnValue_t TmStoreAndSendWrapper::prepareTmPacket( + uint8_t subservice, telemetry::DataWithObjectIdPrefix& dataWithObjectId) { + ReturnValue_t result = storeHelper.preparePacket(defaultService, subservice, sendCounter); + if (result != returnvalue::OK) { + return result; + } + return storeHelper.setSourceDataSerializable(dataWithObjectId); +} + +ReturnValue_t TmStoreAndSendWrapper::prepareTmPacket(uint8_t subservice, SerializeIF& sourceData) { + ReturnValue_t result = storeHelper.preparePacket(defaultService, subservice, sendCounter); + if (result != returnvalue::OK) { + return result; + } + return storeHelper.setSourceDataSerializable(sourceData); +} + +ReturnValue_t TmStoreAndSendWrapper::prepareTmPacket(uint8_t subservice) { + ReturnValue_t result = storeHelper.preparePacket(defaultService, subservice, sendCounter); + if (result != returnvalue::OK) { + return result; + } + return storeHelper.setSourceDataRaw(nullptr, 0); +} diff --git a/src/fsfw/tmtcservices/TmStoreAndSendHelper.h b/src/fsfw/tmtcservices/TmStoreAndSendHelper.h new file mode 100644 index 00000000..eef3a373 --- /dev/null +++ b/src/fsfw/tmtcservices/TmStoreAndSendHelper.h @@ -0,0 +1,60 @@ +#ifndef FSFW_TMTCSERVICES_TMSTOREANDSENDHELPER_H +#define FSFW_TMTCSERVICES_TMSTOREANDSENDHELPER_H + +#include "TmSendHelper.h" +#include "TmStoreHelper.h" +#include "tmHelpers.h" + +/** + * Wrapper class intended to help with PUS TM handling. This wrapper class also caches the current + * packet count and the service ID + */ +class TmStoreAndSendWrapper { + public: + TmStoreAndSendWrapper(uint8_t defaultService, TmStoreHelper& storeHelper, + TmSendHelper& sendHelper); + + /** + * Prepares a TM packet with the given parameters. It will also set the default service. + * @param subservice + * @return + */ + ReturnValue_t prepareTmPacket(uint8_t subservice); + /** + * Prepares a TM packet with the given parameters. It will also set the default service. + * @param subservice Number of subservice + * @param sourceData Custom source data + * @param sourceDataLen Lenght of data in the Packet + */ + ReturnValue_t prepareTmPacket(uint8_t subservice, const uint8_t* sourceData, + size_t sourceDataLen); + + /** + * Prepares a TM packet with the given parameters. It will also set the default service. + * @param subservice Number of subservice + * @param objectId ObjectId is placed before data + * @param data Data to append to the packet + * @param dataLen Length of Data + */ + ReturnValue_t prepareTmPacket(uint8_t subservice, + telemetry::DataWithObjectIdPrefix& dataWithObjectId); + + /** + * Prepares a TM packet with the given parameters. It will also set the default service. + * @param subservice Number of subservice + * @param content This is a pointer to the serialized packet + * @param header Serialize IF header which will be placed before content + */ + ReturnValue_t prepareTmPacket(uint8_t subservice, SerializeIF& sourceData); + + ReturnValue_t storeAndSendTmPacket(); + + bool incrementSendCounter = true; + TmStoreHelper& storeHelper; + TmSendHelper& sendHelper; + bool delOnFailure = true; + uint8_t defaultService = 0; + uint16_t sendCounter = 0; +}; + +#endif // FSFW_TMTCSERVICES_TMSTOREANDSENDHELPER_H diff --git a/src/fsfw/tmtcservices/TmStoreHelper.cpp b/src/fsfw/tmtcservices/TmStoreHelper.cpp new file mode 100644 index 00000000..501a7840 --- /dev/null +++ b/src/fsfw/tmtcservices/TmStoreHelper.cpp @@ -0,0 +1,80 @@ +#include "TmStoreHelper.h" + +#include "TmTcMessage.h" + +TmStoreHelper::TmStoreHelper(uint16_t defaultApid) : tmStore(nullptr) { + creator.setApid(defaultApid); +} + +TmStoreHelper::TmStoreHelper(uint16_t defaultApid, StorageManagerIF& tmStore) : tmStore(&tmStore) { + creator.setApid(defaultApid); +} + +TmStoreHelper::TmStoreHelper(uint16_t defaultApid, StorageManagerIF& tmStore, + TimeStamperIF& timeStamper) + : tmStore(&tmStore) { + creator.setApid(defaultApid); + creator.setTimeStamper(timeStamper); +} + +ReturnValue_t TmStoreHelper::preparePacket(uint8_t service, uint8_t subservice, uint16_t counter) { + creator.setService(service); + creator.setSubservice(subservice); + creator.setMessageTypeCounter(counter); + return returnvalue::OK; +} + +StorageManagerIF* TmStoreHelper::getTmStore() const { return tmStore; } + +void TmStoreHelper::setTmStore(StorageManagerIF& store) { tmStore = &store; } + +const store_address_t& TmStoreHelper::getCurrentAddr() const { return currentAddr; } + +ReturnValue_t TmStoreHelper::deletePacket() { + ReturnValue_t result = tmStore->deleteData(currentAddr); + if (result == returnvalue::OK) { + currentAddr = store_address_t::invalid(); + } + return result; +} + +ReturnValue_t TmStoreHelper::setSourceDataRaw(const uint8_t* data, size_t len) { + return creator.setRawUserData(data, len); +} + +ReturnValue_t TmStoreHelper::setSourceDataSerializable(SerializeIF& serializable) { + return creator.setSerializableUserData(serializable); +} + +ReturnValue_t TmStoreHelper::addPacketToStore() { + creator.updateSpLengthField(); + uint8_t* dataPtr; + ReturnValue_t result = + tmStore->getFreeElement(¤tAddr, creator.getSerializedSize(), &dataPtr); + if (result != returnvalue::OK) { + return result; + } + size_t serLen = 0; + return creator.serialize(&dataPtr, &serLen, creator.getSerializedSize(), + SerializeIF::Endianness::NETWORK); +} + +void TmStoreHelper::setTimeStamper(TimeStamperIF& timeStamper_) { + creator.setTimeStamper(timeStamper_); +} + +void TmStoreHelper::setApid(uint16_t apid) { creator.setApid(apid); } + +PusTmCreator& TmStoreHelper::getCreatorRef() { return creator; } + +TimeStamperIF* TmStoreHelper::getTimeStamper() const { return creator.getTimestamper(); } + +uint16_t TmStoreHelper::getApid() const { return creator.getApid(); } + +void TmStoreHelper::setService(uint8_t service) { creator.setService(service); } + +void TmStoreHelper::setSubservice(uint8_t subservice) { creator.setSubservice(subservice); } + +void TmStoreHelper::disableCrcCalculation() { creator.disableCrcCalculation(); } + +bool TmStoreHelper::crcCalculationEnabled() const { return creator.crcCalculationEnabled(); } diff --git a/src/fsfw/tmtcservices/TmStoreHelper.h b/src/fsfw/tmtcservices/TmStoreHelper.h new file mode 100644 index 00000000..449a2287 --- /dev/null +++ b/src/fsfw/tmtcservices/TmStoreHelper.h @@ -0,0 +1,46 @@ +#ifndef FSFW_TMTCSERVICES_STOREHELPER_H +#define FSFW_TMTCSERVICES_STOREHELPER_H + +#include "fsfw/internalerror/InternalErrorReporterIF.h" +#include "fsfw/ipc/MessageQueueMessageIF.h" +#include "fsfw/storagemanager/StorageManagerIF.h" +#include "fsfw/timemanager/TimeStamperIF.h" +#include "fsfw/tmtcpacket/pus/tm/PusTmCreator.h" + +class TmStoreHelper { + public: + explicit TmStoreHelper(uint16_t defaultApid); + TmStoreHelper(uint16_t defaultApid, StorageManagerIF& tmStore); + TmStoreHelper(uint16_t defaultApid, StorageManagerIF& tmStore, TimeStamperIF& timeStamper); + + void disableCrcCalculation(); + [[nodiscard]] bool crcCalculationEnabled() const; + + ReturnValue_t preparePacket(uint8_t service, uint8_t subservice, uint16_t counter); + + PusTmCreator& getCreatorRef(); + + void setTimeStamper(TimeStamperIF& timeStamper); + [[nodiscard]] TimeStamperIF* getTimeStamper() const; + + [[nodiscard]] StorageManagerIF* getTmStore() const; + void setTmStore(StorageManagerIF& store); + + void setApid(uint16_t apid); + [[nodiscard]] uint16_t getApid() const; + + [[nodiscard]] const store_address_t& getCurrentAddr() const; + void setService(uint8_t service); + void setSubservice(uint8_t subservice); + ReturnValue_t setSourceDataRaw(const uint8_t* data, size_t len); + ReturnValue_t setSourceDataSerializable(SerializeIF& serializable); + + ReturnValue_t addPacketToStore(); + ReturnValue_t deletePacket(); + + private: + PusTmCreator creator; + store_address_t currentAddr{}; + StorageManagerIF* tmStore; +}; +#endif // FSFW_TMTCSERVICES_STOREHELPER_H diff --git a/src/fsfw/tmtcservices/TmTcBridge.cpp b/src/fsfw/tmtcservices/TmTcBridge.cpp index 87869a52..a5a64b1d 100644 --- a/src/fsfw/tmtcservices/TmTcBridge.cpp +++ b/src/fsfw/tmtcservices/TmTcBridge.cpp @@ -15,7 +15,9 @@ TmTcBridge::TmTcBridge(object_id_t objectId, object_id_t tcDestination, object_i tcDestination(tcDestination) { - tmTcReceptionQueue = QueueFactory::instance()->createMessageQueue(TMTC_RECEPTION_QUEUE_DEPTH); + auto mqArgs = MqArgs(objectId, static_cast(this)); + tmTcReceptionQueue = QueueFactory::instance()->createMessageQueue( + TMTC_RECEPTION_QUEUE_DEPTH, MessageQueueMessage::MAX_MESSAGE_SIZE, &mqArgs); } TmTcBridge::~TmTcBridge() { QueueFactory::instance()->deleteMessageQueue(tmTcReceptionQueue); } @@ -34,7 +36,7 @@ ReturnValue_t TmTcBridge::setNumberOfSentPacketsPerCycle(uint8_t sentPacketsPerC } } -ReturnValue_t TmTcBridge::setMaxNumberOfPacketsStored(uint8_t maxNumberOfPacketsStored) { +ReturnValue_t TmTcBridge::setMaxNumberOfPacketsStored(unsigned int maxNumberOfPacketsStored) { if (maxNumberOfPacketsStored <= LIMIT_DOWNLINK_PACKETS_STORED) { this->maxNumberOfPacketsStored = maxNumberOfPacketsStored; return returnvalue::OK; @@ -165,21 +167,24 @@ ReturnValue_t TmTcBridge::handleTmQueue() { } ReturnValue_t TmTcBridge::storeDownlinkData(TmTcMessage* message) { - store_address_t storeId = 0; + store_address_t storeId; if (tmFifo == nullptr) { return returnvalue::FAILED; } if (tmFifo->full()) { + if (warningSwitch) { #if FSFW_CPP_OSTREAM_ENABLED == 1 - sif::warning << "TmTcBridge::storeDownlinkData: TM downlink max. number " - "of stored packet IDs reached!" - << std::endl; + sif::warning << "TmTcBridge::storeDownlinkData: TM downlink max. number " + "of stored packet IDs reached!" + << std::endl; #else - sif::printWarning( - "TmTcBridge::storeDownlinkData: TM downlink max. number " - "of stored packet IDs reached!\n"); + sif::printWarning( + "TmTcBridge::storeDownlinkData: TM downlink max. number " + "of stored packet IDs reached!\n"); #endif + warningSwitch = true; + } if (overwriteOld) { tmFifo->retrieve(&storeId); tmStore->deleteData(storeId); diff --git a/src/fsfw/tmtcservices/TmTcBridge.h b/src/fsfw/tmtcservices/TmTcBridge.h index e2e5bfa5..887cbd13 100644 --- a/src/fsfw/tmtcservices/TmTcBridge.h +++ b/src/fsfw/tmtcservices/TmTcBridge.h @@ -17,7 +17,7 @@ class TmTcBridge : public AcceptsTelemetryIF, public: static constexpr uint8_t TMTC_RECEPTION_QUEUE_DEPTH = 20; static constexpr uint8_t LIMIT_STORED_DATA_SENT_PER_CYCLE = 15; - static constexpr uint8_t LIMIT_DOWNLINK_PACKETS_STORED = 200; + static constexpr unsigned int LIMIT_DOWNLINK_PACKETS_STORED = 1000; static constexpr uint8_t DEFAULT_STORED_DATA_SENT_PER_CYCLE = 5; static constexpr uint8_t DEFAULT_DOWNLINK_PACKETS_STORED = 10; @@ -31,7 +31,7 @@ class TmTcBridge : public AcceptsTelemetryIF, * value must be smaller than MAX_STORED_DATA_SENT_PER_CYCLE * @param sentPacketsPerCycle * @return -@c returnvalue::OK if value was set successfully - * -@c returnvalue::FAILED otherwise, stored value stays the same + * -@c returnvalue::FAILED otherwise, stored value stays the same */ ReturnValue_t setNumberOfSentPacketsPerCycle(uint8_t sentPacketsPerCycle); @@ -42,7 +42,7 @@ class TmTcBridge : public AcceptsTelemetryIF, * @return -@c returnvalue::OK if value was set successfully * -@c returnvalue::FAILED otherwise, stored value stays the same */ - ReturnValue_t setMaxNumberOfPacketsStored(uint8_t maxNumberOfPacketsStored); + ReturnValue_t setMaxNumberOfPacketsStored(unsigned int maxNumberOfPacketsStored); /** * This will set up the bridge to overwrite old data in the FIFO. @@ -71,6 +71,8 @@ class TmTcBridge : public AcceptsTelemetryIF, virtual uint16_t getIdentifier() override; virtual MessageQueueId_t getRequestQueue() override; + bool warningSwitch = true; + protected: //! Cached for initialize function. object_id_t tmStoreId = objects::NO_OBJECT; @@ -149,7 +151,7 @@ class TmTcBridge : public AcceptsTelemetryIF, */ DynamicFIFO* tmFifo = nullptr; uint8_t sentPacketsPerCycle = DEFAULT_STORED_DATA_SENT_PER_CYCLE; - uint8_t maxNumberOfPacketsStored = DEFAULT_DOWNLINK_PACKETS_STORED; + unsigned int maxNumberOfPacketsStored = DEFAULT_DOWNLINK_PACKETS_STORED; }; #endif /* FSFW_TMTCSERVICES_TMTCBRIDGE_H_ */ diff --git a/src/fsfw/tmtcservices/TmTcMessage.cpp b/src/fsfw/tmtcservices/TmTcMessage.cpp index ca76760f..bd071b5b 100644 --- a/src/fsfw/tmtcservices/TmTcMessage.cpp +++ b/src/fsfw/tmtcservices/TmTcMessage.cpp @@ -4,7 +4,7 @@ TmTcMessage::TmTcMessage() { this->messageSize += sizeof(store_address_t); } -TmTcMessage::~TmTcMessage() {} +TmTcMessage::~TmTcMessage() = default; store_address_t TmTcMessage::getStorageId() { store_address_t temp_id; @@ -18,9 +18,9 @@ TmTcMessage::TmTcMessage(store_address_t storeId) { } size_t TmTcMessage::getMinimumMessageSize() const { - return this->HEADER_SIZE + sizeof(store_address_t); + return TmTcMessage::HEADER_SIZE + sizeof(store_address_t); } void TmTcMessage::setStorageId(store_address_t storeId) { - memcpy(this->getData(), &storeId, sizeof(store_address_t)); + std::memcpy(this->getData(), &storeId, sizeof(store_address_t)); } diff --git a/src/fsfw/tmtcservices/TmTcMessage.h b/src/fsfw/tmtcservices/TmTcMessage.h index a0f67894..3fba6d7a 100644 --- a/src/fsfw/tmtcservices/TmTcMessage.h +++ b/src/fsfw/tmtcservices/TmTcMessage.h @@ -18,7 +18,7 @@ class TmTcMessage : public MessageQueueMessage { * @brief This call always returns the same fixed size of the message. * @return Returns HEADER_SIZE + @c sizeof(store_address_t). */ - size_t getMinimumMessageSize() const override; + [[nodiscard]] size_t getMinimumMessageSize() const override; public: /** @@ -30,11 +30,11 @@ class TmTcMessage : public MessageQueueMessage { * into the message. * @param packet_id The packet id to put into the message. */ - TmTcMessage(store_address_t packetId); + explicit TmTcMessage(store_address_t packetId); /** * @brief The class's destructor is empty. */ - ~TmTcMessage(); + ~TmTcMessage() override; /** * @brief This getter returns the packet id in the correct format. * @return Returns the packet id. diff --git a/src/fsfw/tmtcservices/VerificationCodes.h b/src/fsfw/tmtcservices/VerificationCodes.h index 73edbc1d..479074eb 100644 --- a/src/fsfw/tmtcservices/VerificationCodes.h +++ b/src/fsfw/tmtcservices/VerificationCodes.h @@ -1,9 +1,11 @@ #ifndef VERIFICATIONCODES_H_ #define VERIFICATIONCODES_H_ -namespace tc_verification { +#include -enum verification_flags { +namespace tcverif { + +enum VerificationFlags : uint8_t { NONE = 0b0000, ACCEPTANCE = 0b0001, START = 0b0010, @@ -11,7 +13,7 @@ enum verification_flags { COMPLETION = 0b1000 }; -enum subservice_ids { +enum Subservices : uint8_t { NOTHING_TO_REPORT = 0, ACCEPTANCE_SUCCESS = 1, ACCEPTANCE_FAILURE = 2, @@ -23,6 +25,6 @@ enum subservice_ids { COMPLETION_FAILURE = 8, }; -} // namespace tc_verification +} // namespace tcverif #endif /* VERIFICATIONCODES_H_ */ diff --git a/src/fsfw/tmtcservices/VerificationReporter.cpp b/src/fsfw/tmtcservices/VerificationReporter.cpp index f833b445..1d229183 100644 --- a/src/fsfw/tmtcservices/VerificationReporter.cpp +++ b/src/fsfw/tmtcservices/VerificationReporter.cpp @@ -1,29 +1,29 @@ #include "fsfw/tmtcservices/VerificationReporter.h" -#include "fsfw/ipc/MessageQueueIF.h" -#include "fsfw/objectmanager/ObjectManager.h" -#include "fsfw/objectmanager/frameworkObjects.h" +#include "fsfw/objectmanager.h" #include "fsfw/serviceinterface/ServiceInterface.h" -#include "fsfw/tmtcservices/AcceptsVerifyMessageIF.h" #include "fsfw/tmtcservices/PusVerificationReport.h" -object_id_t VerificationReporter::messageReceiver = objects::PUS_SERVICE_1_VERIFICATION; +object_id_t VerificationReporter::DEFAULT_RECEIVER = objects::PUS_SERVICE_1_VERIFICATION; +object_id_t VerificationReporter::DEFAULT_REPORTER = objects::VERIFICATION_REPORTER; -VerificationReporter::VerificationReporter() : acknowledgeQueue(MessageQueueIF::NO_QUEUE) {} - -VerificationReporter::~VerificationReporter() {} - -void VerificationReporter::sendSuccessReport(uint8_t set_report_id, TcPacketPusBase* currentPacket, - uint8_t set_step) { - if (acknowledgeQueue == MessageQueueIF::NO_QUEUE) { - this->initialize(); +VerificationReporter::VerificationReporter(object_id_t objectId, AcceptsVerifyMessageIF* receiver) + : SystemObject(objectId) { + if (receiver != nullptr) { + acknowledgeQueue = receiver->getVerificationQueue(); } - if (currentPacket == nullptr) { - return; - } - PusVerificationMessage message(set_report_id, currentPacket->getAcknowledgeFlags(), - currentPacket->getPacketId(), - currentPacket->getPacketSequenceControl(), 0, set_step); +} + +VerificationReporter::~VerificationReporter() = default; + +void VerificationReporter::setReceiver(AcceptsVerifyMessageIF& receiver) { + acknowledgeQueue = receiver.getVerificationQueue(); +} + +ReturnValue_t VerificationReporter::sendFailureReport(VerifFailureParams params) { + PusVerificationMessage message(params.reportId, params.ackFlags, params.tcPacketId, params.tcPsc, + params.errorCode, params.step, params.errorParam1, + params.errorParam2); ReturnValue_t status = MessageQueueSenderIF::sendMessage(acknowledgeQueue, &message); if (status != returnvalue::OK) { #if FSFW_CPP_OSTREAM_ENABLED == 1 @@ -31,16 +31,12 @@ void VerificationReporter::sendSuccessReport(uint8_t set_report_id, TcPacketPusB << "to queue. Code: " << std::hex << status << std::dec << std::endl; #endif } + return status; } -void VerificationReporter::sendSuccessReport(uint8_t set_report_id, uint8_t ackFlags, - uint16_t tcPacketId, uint16_t tcSequenceControl, - uint8_t set_step) { - if (acknowledgeQueue == MessageQueueIF::NO_QUEUE) { - this->initialize(); - } - PusVerificationMessage message(set_report_id, ackFlags, tcPacketId, tcSequenceControl, 0, - set_step); +ReturnValue_t VerificationReporter::sendSuccessReport(VerifSuccessParams params) { + PusVerificationMessage message(params.reportId, params.ackFlags, params.tcPacketId, params.tcPsc, + returnvalue::OK, params.step); ReturnValue_t status = MessageQueueSenderIF::sendMessage(acknowledgeQueue, &message); if (status != returnvalue::OK) { #if FSFW_CPP_OSTREAM_ENABLED == 1 @@ -48,65 +44,28 @@ void VerificationReporter::sendSuccessReport(uint8_t set_report_id, uint8_t ackF << "to queue. Code: " << std::hex << status << std::dec << std::endl; #endif } + return status; } -void VerificationReporter::sendFailureReport(uint8_t report_id, TcPacketPusBase* currentPacket, - ReturnValue_t error_code, uint8_t step, - uint32_t parameter1, uint32_t parameter2) { +ReturnValue_t VerificationReporter::initialize() { if (acknowledgeQueue == MessageQueueIF::NO_QUEUE) { - this->initialize(); - } - if (currentPacket == nullptr) { - return; - } - PusVerificationMessage message( - report_id, currentPacket->getAcknowledgeFlags(), currentPacket->getPacketId(), - currentPacket->getPacketSequenceControl(), error_code, step, parameter1, parameter2); - ReturnValue_t status = MessageQueueSenderIF::sendMessage(acknowledgeQueue, &message); - if (status != returnvalue::OK) { + auto* receiver = ObjectManager::instance()->get(DEFAULT_RECEIVER); + if (receiver != nullptr) { + acknowledgeQueue = receiver->getVerificationQueue(); + } else { #if FSFW_CPP_OSTREAM_ENABLED == 1 - sif::error << "VerificationReporter::sendFailureReport: Error writing " - << "to queue. Code: " << std::hex << "0x" << status << std::dec << std::endl; + sif::error + << "Could not find a suitable verification message receiver. Please ensure that it is set" + " via the constructor or creating a global one with the ID " + "VerificationReporter::DEFAULT_RECEIVER" + << std::endl; +#else + sif::printError( + "Could not find a suitable verification message receiver. Please ensure " + "that it is set via the constructor or creating a global one with the ID " + "VerificationReporter::DEFAULT_RECEIVER\n"); #endif + } } -} - -void VerificationReporter::sendFailureReport(uint8_t report_id, uint8_t ackFlags, - uint16_t tcPacketId, uint16_t tcSequenceControl, - ReturnValue_t error_code, uint8_t step, - uint32_t parameter1, uint32_t parameter2) { - if (acknowledgeQueue == MessageQueueIF::NO_QUEUE) { - this->initialize(); - } - PusVerificationMessage message(report_id, ackFlags, tcPacketId, tcSequenceControl, error_code, - step, parameter1, parameter2); - ReturnValue_t status = MessageQueueSenderIF::sendMessage(acknowledgeQueue, &message); - if (status != returnvalue::OK) { -#if FSFW_CPP_OSTREAM_ENABLED == 1 - sif::error << "VerificationReporter::sendFailureReport: Error writing " - << "to queue. Code: " << std::hex << "0x" << status << std::dec << std::endl; -#endif - } -} - -void VerificationReporter::initialize() { - if (messageReceiver == objects::NO_OBJECT) { -#if FSFW_CPP_OSTREAM_ENABLED == 1 - sif::warning << "VerificationReporter::initialize: Verification message" - " receiver object ID not set yet in Factory!" - << std::endl; -#endif - return; - } - AcceptsVerifyMessageIF* temp = - ObjectManager::instance()->get(messageReceiver); - if (temp == nullptr) { -#if FSFW_CPP_OSTREAM_ENABLED == 1 - sif::error << "VerificationReporter::initialize: Message " - << "receiver invalid. Make sure it is set up properly and " - << "implementsAcceptsVerifyMessageIF" << std::endl; -#endif - return; - } - this->acknowledgeQueue = temp->getVerificationQueue(); + return SystemObject::initialize(); } diff --git a/src/fsfw/tmtcservices/VerificationReporter.h b/src/fsfw/tmtcservices/VerificationReporter.h index c29afd60..f6152614 100644 --- a/src/fsfw/tmtcservices/VerificationReporter.h +++ b/src/fsfw/tmtcservices/VerificationReporter.h @@ -2,7 +2,11 @@ #define FSFW_TMTCSERVICES_VERIFICATIONREPORTER_H_ #include "PusVerificationReport.h" +#include "VerificationReporterIF.h" #include "fsfw/objectmanager/ObjectManagerIF.h" +#include "fsfw/objectmanager/SystemObject.h" +#include "fsfw/tmtcpacket/pus/tc/PusTcCreator.h" +#include "fsfw/tmtcservices/AcceptsVerifyMessageIF.h" namespace Factory { void setStaticFrameworkObjectIds(); @@ -19,30 +23,25 @@ void setStaticFrameworkObjectIds(); * to the PUS standard. * */ -class VerificationReporter { - friend void(Factory::setStaticFrameworkObjectIds)(); +class VerificationReporter : public SystemObject, public VerificationReporterIF { + friend void Factory::setStaticFrameworkObjectIds(); public: - VerificationReporter(); - virtual ~VerificationReporter(); + explicit VerificationReporter(object_id_t objectId = DEFAULT_REPORTER, + AcceptsVerifyMessageIF* receiver = nullptr); + ~VerificationReporter() override; - void sendSuccessReport(uint8_t set_report_id, TcPacketPusBase* current_packet, - uint8_t set_step = 0); - void sendSuccessReport(uint8_t set_report_id, uint8_t ackFlags, uint16_t tcPacketId, - uint16_t tcSequenceControl, uint8_t set_step = 0); + void setReceiver(AcceptsVerifyMessageIF& receiver); - void sendFailureReport(uint8_t report_id, TcPacketPusBase* current_packet, - ReturnValue_t error_code = 0, uint8_t step = 0, uint32_t parameter1 = 0, - uint32_t parameter2 = 0); - void sendFailureReport(uint8_t report_id, uint8_t ackFlags, uint16_t tcPacketId, - uint16_t tcSequenceControl, ReturnValue_t error_code = 0, uint8_t step = 0, - uint32_t parameter1 = 0, uint32_t parameter2 = 0); + ReturnValue_t sendSuccessReport(VerifSuccessParams params) override; + ReturnValue_t sendFailureReport(VerifFailureParams params) override; - void initialize(); + static object_id_t DEFAULT_REPORTER; + static object_id_t DEFAULT_RECEIVER; + ReturnValue_t initialize() override; private: - static object_id_t messageReceiver; - MessageQueueId_t acknowledgeQueue; + MessageQueueId_t acknowledgeQueue = MessageQueueIF::NO_QUEUE; }; #endif /* FSFW_TMTCSERVICES_VERIFICATIONREPORTER_H_ */ diff --git a/src/fsfw/tmtcservices/VerificationReporterIF.h b/src/fsfw/tmtcservices/VerificationReporterIF.h new file mode 100644 index 00000000..d2330b88 --- /dev/null +++ b/src/fsfw/tmtcservices/VerificationReporterIF.h @@ -0,0 +1,69 @@ +#ifndef FSFW_TMTCSERVICES_VERIFICATIONREPORTERIF_H +#define FSFW_TMTCSERVICES_VERIFICATIONREPORTERIF_H + +#include "fsfw/retval.h" +#include "fsfw/tmtcpacket/pus/tc.h" + +struct VerifParamsBase { + VerifParamsBase() : reportId(0), tcPacketId(0), tcPsc(0) {} + VerifParamsBase(uint8_t reportId, uint16_t tcPacketId, uint16_t tcPsc) + : reportId(reportId), tcPacketId(tcPacketId), tcPsc(tcPsc) {} + uint8_t reportId; + uint16_t tcPacketId; + uint16_t tcPsc; + uint8_t ackFlags = ecss::ACK_ALL; + uint8_t step = 0; + + void resetTcFields() { + tcPacketId = 0; + tcPsc = 0; + ackFlags = 0; + } +}; + +struct VerifSuccessParams : public VerifParamsBase { + VerifSuccessParams() = default; + VerifSuccessParams(uint8_t reportId, uint16_t tcPacketId, uint16_t tcPsc) + : VerifParamsBase(reportId, tcPacketId, tcPsc) {} + VerifSuccessParams(uint8_t reportId, PusTcIF& tc) + : VerifParamsBase(reportId, tc.getPacketIdRaw(), tc.getPacketSeqCtrlRaw()) {} +}; + +struct VerifFailureParams : public VerifParamsBase { + VerifFailureParams() = default; + VerifFailureParams(uint8_t reportId, uint16_t tcPacketId, uint16_t tcPsc, ReturnValue_t errorCode, + uint32_t errorParam1, uint32_t errorParams2) + : VerifParamsBase(reportId, tcPacketId, tcPsc), + errorCode(errorCode), + errorParam1(errorParam1), + errorParam2(errorParams2) {} + VerifFailureParams(uint8_t reportId, uint16_t tcPacketId, uint16_t tcPsc, ReturnValue_t errorCode) + : VerifParamsBase(reportId, tcPacketId, tcPsc), errorCode(errorCode) {} + VerifFailureParams(uint8_t reportId, uint16_t tcPacketId, uint16_t tcPsc) + : VerifParamsBase(reportId, tcPacketId, tcPsc) {} + VerifFailureParams(uint8_t reportId, PusTcIF& tc, ReturnValue_t errorCode) + : VerifParamsBase(reportId, tc.getPacketIdRaw(), tc.getPacketSeqCtrlRaw()), + errorCode(errorCode) {} + VerifFailureParams(uint8_t reportId, PusTcIF& tc) + : VerifParamsBase(reportId, tc.getPacketIdRaw(), tc.getPacketSeqCtrlRaw()) {} + + void resetFailParams() { + errorCode = returnvalue::FAILED; + errorParam1 = 0; + errorParam2 = 0; + } + + ReturnValue_t errorCode = returnvalue::FAILED; + uint8_t step = 0; + uint32_t errorParam1 = 0; + uint32_t errorParam2 = 0; +}; +class VerificationReporterIF { + public: + virtual ~VerificationReporterIF() = default; + + virtual ReturnValue_t sendSuccessReport(VerifSuccessParams params) = 0; + virtual ReturnValue_t sendFailureReport(VerifFailureParams params) = 0; +}; + +#endif // FSFW_TMTCSERVICES_VERIFICATIONREPORTERIF_H diff --git a/src/fsfw/tmtcservices/tcHelpers.cpp b/src/fsfw/tmtcservices/tcHelpers.cpp new file mode 100644 index 00000000..c497979b --- /dev/null +++ b/src/fsfw/tmtcservices/tcHelpers.cpp @@ -0,0 +1,16 @@ +#include "tcHelpers.h" + +ReturnValue_t tc::prepareTcReader(StorageManagerIF &tcStore, store_address_t storeId, + PusTcReader &tcReader) { + const uint8_t *dataPtr; + size_t dataLen = 0; + ReturnValue_t result = tcStore.getData(storeId, &dataPtr, &dataLen); + if (result != returnvalue::OK) { + return result; + } + result = tcReader.setReadOnlyData(dataPtr, dataLen); + if (result != returnvalue::OK) { + return result; + } + return tcReader.parseDataWithoutCrcCheck(); +} diff --git a/src/fsfw/tmtcservices/tcHelpers.h b/src/fsfw/tmtcservices/tcHelpers.h new file mode 100644 index 00000000..9b1e1fdb --- /dev/null +++ b/src/fsfw/tmtcservices/tcHelpers.h @@ -0,0 +1,15 @@ +#ifndef FSFW_TMTCSERVICES_TCHELPERS_H +#define FSFW_TMTCSERVICES_TCHELPERS_H + +#include "fsfw/returnvalues/returnvalue.h" +#include "fsfw/storagemanager/StorageManagerIF.h" +#include "fsfw/tmtcpacket/pus/tc.h" + +namespace tc { + +ReturnValue_t prepareTcReader(StorageManagerIF& tcStore, store_address_t storeId, + PusTcReader& tcReader); + +} // namespace tc + +#endif // FSFW_TMTCSERVICES_TCHELPERS_H diff --git a/src/fsfw/tmtcservices/tmHelpers.cpp b/src/fsfw/tmtcservices/tmHelpers.cpp new file mode 100644 index 00000000..abe2ae78 --- /dev/null +++ b/src/fsfw/tmtcservices/tmHelpers.cpp @@ -0,0 +1 @@ +#include "tmHelpers.h" diff --git a/src/fsfw/tmtcservices/tmHelpers.h b/src/fsfw/tmtcservices/tmHelpers.h new file mode 100644 index 00000000..845a73b8 --- /dev/null +++ b/src/fsfw/tmtcservices/tmHelpers.h @@ -0,0 +1,71 @@ +#ifndef FSFW_TMTCSERVICES_TMHELPERS_H_ +#define FSFW_TMTCSERVICES_TMHELPERS_H_ + +#include "TmSendHelper.h" +#include "TmStoreHelper.h" + +// I'd prefer to use tm, but there have been nameclashes with the tm struct +namespace telemetry { + +class DataWithObjectIdPrefix : public SerializeIF { + public: + DataWithObjectIdPrefix(object_id_t objectId, const uint8_t* srcData, size_t srcDataLen) + : objectId(objectId) { + dataWrapper.type = util::DataTypes::RAW; + dataWrapper.dataUnion.raw.data = srcData; + dataWrapper.dataUnion.raw.len = srcDataLen; + } + + DataWithObjectIdPrefix(object_id_t objectId, SerializeIF& serializable) : objectId(objectId) { + dataWrapper.type = util::DataTypes::SERIALIZABLE; + dataWrapper.dataUnion.serializable = &serializable; + } + + ReturnValue_t serialize(uint8_t** buffer, size_t* size, size_t maxSize, + Endianness streamEndianness) const override { + if (*size + getSerializedSize() > maxSize) { + return SerializeIF::BUFFER_TOO_SHORT; + } + if (dataWrapper.type != util::DataTypes::RAW) { + if ((dataWrapper.dataUnion.raw.data == nullptr) and (dataWrapper.dataUnion.raw.len > 0)) { + return returnvalue::FAILED; + } + } else if (dataWrapper.type == util::DataTypes::SERIALIZABLE) { + if (dataWrapper.dataUnion.serializable == nullptr) { + return returnvalue::FAILED; + } + } + ReturnValue_t result = + SerializeAdapter::serialize(&objectId, buffer, size, maxSize, streamEndianness); + if (result != returnvalue::OK) { + return result; + } + if (dataWrapper.type != util::DataTypes::RAW) { + std::memcpy(*buffer, dataWrapper.dataUnion.raw.data, dataWrapper.dataUnion.raw.len); + *buffer += dataWrapper.dataUnion.raw.len; + *size += dataWrapper.dataUnion.raw.len; + } else { + return dataWrapper.dataUnion.serializable->serialize(buffer, size, maxSize, streamEndianness); + } + return returnvalue::OK; + } + + [[nodiscard]] size_t getSerializedSize() const override { + return sizeof(objectId) + dataWrapper.getLength(); + } + + ReturnValue_t deSerialize(const uint8_t** buffer, size_t* size, + Endianness streamEndianness) override { + // As long as there is no way to know how long the expected data will be, this function + // does not make sense + return returnvalue::FAILED; + } + + private: + object_id_t objectId; + util::DataWrapper dataWrapper{}; +}; + +} // namespace telemetry + +#endif // FSFW_TMTCSERVICES_TMHELPERS_H_ diff --git a/src/fsfw/util/dataWrapper.h b/src/fsfw/util/dataWrapper.h new file mode 100644 index 00000000..84a9814f --- /dev/null +++ b/src/fsfw/util/dataWrapper.h @@ -0,0 +1,77 @@ +#ifndef FSFW_UTIL_DATAWRAPPER_H +#define FSFW_UTIL_DATAWRAPPER_H + +#include +#include +#include + +#include "fsfw/serialize.h" + +namespace util { + +using BufPair = std::pair; + +struct RawData { + RawData() = default; + const uint8_t* data = nullptr; + size_t len = 0; +}; + +enum DataTypes { NONE, RAW, SERIALIZABLE }; + +union DataUnion { + RawData raw{}; + SerializeIF* serializable; +}; + +struct DataWrapper { + + DataWrapper() = default; + + DataWrapper(const uint8_t* data, size_t size): type(DataTypes::RAW) { + setRawData({data, size}); + } + + explicit DataWrapper(BufPair raw): type(DataTypes::RAW) { + setRawData(raw); + } + + explicit DataWrapper(SerializeIF& serializable): type(DataTypes::SERIALIZABLE) { + setSerializable(serializable); + } + + DataTypes type = DataTypes::NONE; + DataUnion dataUnion; + + [[nodiscard]] size_t getLength() const { + if (type == DataTypes::RAW) { + return dataUnion.raw.len; + } else if (type == DataTypes::SERIALIZABLE and dataUnion.serializable != nullptr) { + return dataUnion.serializable->getSerializedSize(); + } + return 0; + } + + [[nodiscard]] bool isNull() const { + if ((type == DataTypes::NONE) or (type == DataTypes::RAW and dataUnion.raw.data == nullptr) or + (type == DataTypes::SERIALIZABLE and dataUnion.serializable == nullptr)) { + return true; + } + return false; + } + + void setRawData(BufPair bufPair) { + type = DataTypes::RAW; + dataUnion.raw.data = bufPair.first; + dataUnion.raw.len = bufPair.second; + } + + void setSerializable(SerializeIF& serializable) { + type = DataTypes::SERIALIZABLE; + dataUnion.serializable = &serializable; + } +}; + +} // namespace util + +#endif // FSFW_UTIL_DATAWRAPPER_H diff --git a/src/fsfw_hal/common/gpio/GpioIF.h b/src/fsfw_hal/common/gpio/GpioIF.h index a8abb126..20ae8a26 100644 --- a/src/fsfw_hal/common/gpio/GpioIF.h +++ b/src/fsfw_hal/common/gpio/GpioIF.h @@ -46,9 +46,9 @@ class GpioIF { * an ouput or input gpio. * * @param gpioId A unique number which specifies the GPIO to read. - * @param gpioState State of GPIO will be written to this pointer. + * @param gpioState State of GPIO will be written to this reference */ - virtual ReturnValue_t readGpio(gpioId_t gpioId, int* gpioState) = 0; + virtual ReturnValue_t readGpio(gpioId_t gpioId, gpio::Levels& gpioState) = 0; }; #endif /* COMMON_GPIO_GPIOIF_H_ */ diff --git a/src/fsfw_hal/common/gpio/gpioDefinitions.h b/src/fsfw_hal/common/gpio/gpioDefinitions.h index eb90629e..a15ffbc0 100644 --- a/src/fsfw_hal/common/gpio/gpioDefinitions.h +++ b/src/fsfw_hal/common/gpio/gpioDefinitions.h @@ -9,7 +9,7 @@ using gpioId_t = uint16_t; namespace gpio { -enum class Levels : int { LOW = 0, HIGH = 1, NONE = 99 }; +enum class Levels : int { LOW = 0, HIGH = 1, FAILED = -1, NONE = 99 }; enum class Direction : int { IN = 0, OUT = 1 }; diff --git a/src/fsfw_hal/devicehandlers/GyroL3GD20Handler.cpp b/src/fsfw_hal/devicehandlers/GyroL3GD20Handler.cpp index 1ffc60f1..46ca17b9 100644 --- a/src/fsfw_hal/devicehandlers/GyroL3GD20Handler.cpp +++ b/src/fsfw_hal/devicehandlers/GyroL3GD20Handler.cpp @@ -252,6 +252,8 @@ ReturnValue_t GyroHandlerL3GD20H::initializeLocalDataPool(localpool::DataPool &l localDataPoolMap.emplace(L3GD20H::ANG_VELOC_Y, new PoolEntry({0.0})); localDataPoolMap.emplace(L3GD20H::ANG_VELOC_Z, new PoolEntry({0.0})); localDataPoolMap.emplace(L3GD20H::TEMPERATURE, new PoolEntry({0.0})); + poolManager.subscribeForRegularPeriodicPacket( + subdp::RegularHkPeriodicParams(dataset.getSid(), false, 10.0)); return returnvalue::OK; } diff --git a/src/fsfw_hal/devicehandlers/MgmLIS3MDLHandler.cpp b/src/fsfw_hal/devicehandlers/MgmLIS3MDLHandler.cpp index b4d64dbc..d925285f 100644 --- a/src/fsfw_hal/devicehandlers/MgmLIS3MDLHandler.cpp +++ b/src/fsfw_hal/devicehandlers/MgmLIS3MDLHandler.cpp @@ -371,13 +371,16 @@ float MgmLIS3MDLHandler::getSensitivityFactor(MGMLIS3MDL::Sensitivies sens) { ReturnValue_t MgmLIS3MDLHandler::enableTemperatureSensor(const uint8_t *commandData, size_t commandDataLen) { + if (commandData == nullptr) { + return INVALID_COMMAND_PARAMETER; + } triggerEvent(CHANGE_OF_SETUP_PARAMETER); uint32_t size = 2; commandBuffer[0] = writeCommand(MGMLIS3MDL::CTRL_REG1); if (commandDataLen > 1) { return INVALID_NUMBER_OR_LENGTH_OF_PARAMETERS; } - switch (*commandData) { + switch (commandData[0]) { case (MGMLIS3MDL::ON): { commandBuffer[1] = registers[0] | (1 << 7); break; @@ -466,7 +469,7 @@ ReturnValue_t MgmLIS3MDLHandler::initializeLocalDataPool(localpool::DataPool &lo LocalDataPoolManager &poolManager) { localDataPoolMap.emplace(MGMLIS3MDL::FIELD_STRENGTHS, &mgmXYZ); localDataPoolMap.emplace(MGMLIS3MDL::TEMPERATURE_CELCIUS, &temperature); - poolManager.subscribeForPeriodicPacket(dataset.getSid(), false, 10.0, false); + poolManager.subscribeForRegularPeriodicPacket({dataset.getSid(), false, 10.0}); return returnvalue::OK; } diff --git a/src/fsfw_hal/devicehandlers/MgmRM3100Handler.cpp b/src/fsfw_hal/devicehandlers/MgmRM3100Handler.cpp index 86c6e888..a32153eb 100644 --- a/src/fsfw_hal/devicehandlers/MgmRM3100Handler.cpp +++ b/src/fsfw_hal/devicehandlers/MgmRM3100Handler.cpp @@ -305,12 +305,12 @@ void MgmRM3100Handler::fillCommandAndReplyMap() { insertInCommandAndReplyMap(RM3100::READ_DATA, 3, &primaryDataset); } -void MgmRM3100Handler::modeChanged(void) { internalState = InternalState::NONE; } +void MgmRM3100Handler::modeChanged() { internalState = InternalState::NONE; } ReturnValue_t MgmRM3100Handler::initializeLocalDataPool(localpool::DataPool &localDataPoolMap, LocalDataPoolManager &poolManager) { localDataPoolMap.emplace(RM3100::FIELD_STRENGTHS, &mgmXYZ); - poolManager.subscribeForPeriodicPacket(primaryDataset.getSid(), false, 10.0, false); + poolManager.subscribeForRegularPeriodicPacket({primaryDataset.getSid(), false, 10.0}); return returnvalue::OK; } diff --git a/src/fsfw_hal/linux/CommandExecutor.cpp b/src/fsfw_hal/linux/CommandExecutor.cpp index 8b81d94f..27cf8aca 100644 --- a/src/fsfw_hal/linux/CommandExecutor.cpp +++ b/src/fsfw_hal/linux/CommandExecutor.cpp @@ -32,6 +32,8 @@ ReturnValue_t CommandExecutor::execute() { } else if (state == States::PENDING) { return COMMAND_PENDING; } + // Reset data in read vector + std::memset(readVec.data(), 0, readVec.size()); currentCmdFile = popen(currentCmd.c_str(), "r"); if (currentCmdFile == nullptr) { lastError = errno; @@ -205,3 +207,5 @@ ReturnValue_t CommandExecutor::executeBlocking() { } return returnvalue::OK; } + +const std::vector& CommandExecutor::getReadVector() const { return readVec; } diff --git a/src/fsfw_hal/linux/CommandExecutor.h b/src/fsfw_hal/linux/CommandExecutor.h index 70cb071e..80996bae 100644 --- a/src/fsfw_hal/linux/CommandExecutor.h +++ b/src/fsfw_hal/linux/CommandExecutor.h @@ -49,7 +49,7 @@ class CommandExecutor { * executed process. * @param maxSize */ - CommandExecutor(const size_t maxSize); + explicit CommandExecutor(size_t maxSize); /** * Load a new command which should be executed @@ -107,6 +107,8 @@ class CommandExecutor { */ void reset(); + const std::vector& getReadVector() const; + private: std::string currentCmd; bool blocking = true; diff --git a/src/fsfw_hal/linux/UnixFileGuard.cpp b/src/fsfw_hal/linux/UnixFileGuard.cpp index 41293815..3e916ba2 100644 --- a/src/fsfw_hal/linux/UnixFileGuard.cpp +++ b/src/fsfw_hal/linux/UnixFileGuard.cpp @@ -6,7 +6,7 @@ #include "fsfw/FSFW.h" #include "fsfw/serviceinterface.h" -UnixFileGuard::UnixFileGuard(std::string device, int* fileDescriptor, int flags, +UnixFileGuard::UnixFileGuard(const std::string& device, int* fileDescriptor, int flags, std::string diagnosticPrefix) : fileDescriptor(fileDescriptor) { if (fileDescriptor == nullptr) { diff --git a/src/fsfw_hal/linux/UnixFileGuard.h b/src/fsfw_hal/linux/UnixFileGuard.h index 3e4ddca8..eec85233 100644 --- a/src/fsfw_hal/linux/UnixFileGuard.h +++ b/src/fsfw_hal/linux/UnixFileGuard.h @@ -15,7 +15,7 @@ class UnixFileGuard { static constexpr ReturnValue_t OPEN_FILE_FAILED = 1; - UnixFileGuard(std::string device, int* fileDescriptor, int flags, + UnixFileGuard(const std::string& device, int* fileDescriptor, int flags, std::string diagnosticPrefix = ""); virtual ~UnixFileGuard(); diff --git a/src/fsfw_hal/linux/gpio/Gpio.h b/src/fsfw_hal/linux/gpio/Gpio.h new file mode 100644 index 00000000..40cc1df5 --- /dev/null +++ b/src/fsfw_hal/linux/gpio/Gpio.h @@ -0,0 +1,27 @@ +#ifndef FSFW_HAL_SRC_FSFW_HAL_LINUX_GPIO_GPIO_H_ +#define FSFW_HAL_SRC_FSFW_HAL_LINUX_GPIO_GPIO_H_ + +#include "fsfw_hal/common/gpio/GpioIF.h" +#include "fsfw_hal/common/gpio/gpioDefinitions.h" + +/** + * @brief Additional abstraction layer for handling GPIOs. + * + * @author J. Meier + */ +class Gpio { + public: + Gpio(gpioId_t gpioId, GpioIF* gpioIF) : gpioId(gpioId), gpioIF(gpioIF) { + if (gpioIF == nullptr) { + sif::error << "Gpio::Gpio: Invalid GpioIF" << std::endl; + } + } + ReturnValue_t pullHigh() { return gpioIF->pullHigh(gpioId); } + ReturnValue_t pullLow() { return gpioIF->pullLow(gpioId); } + + private: + gpioId_t gpioId = gpio::NO_GPIO; + GpioIF* gpioIF = nullptr; +}; + +#endif /* FSFW_HAL_SRC_FSFW_HAL_LINUX_GPIO_GPIO_H_ */ diff --git a/src/fsfw_hal/linux/gpio/LinuxLibgpioIF.cpp b/src/fsfw_hal/linux/gpio/LinuxLibgpioIF.cpp index cecc1f3f..9113a89a 100644 --- a/src/fsfw_hal/linux/gpio/LinuxLibgpioIF.cpp +++ b/src/fsfw_hal/linux/gpio/LinuxLibgpioIF.cpp @@ -294,7 +294,7 @@ ReturnValue_t LinuxLibgpioIF::driveGpio(gpioId_t gpioId, GpiodRegularBase& regul return returnvalue::OK; } -ReturnValue_t LinuxLibgpioIF::readGpio(gpioId_t gpioId, int* gpioState) { +ReturnValue_t LinuxLibgpioIF::readGpio(gpioId_t gpioId, gpio::Levels& gpioState) { gpioMapIter = gpioMap.find(gpioId); if (gpioMapIter == gpioMap.end()) { #if FSFW_CPP_OSTREAM_ENABLED == 1 @@ -313,7 +313,10 @@ ReturnValue_t LinuxLibgpioIF::readGpio(gpioId_t gpioId, int* gpioState) { if (regularGpio == nullptr) { return GPIO_TYPE_FAILURE; } - *gpioState = gpiod_line_get_value(regularGpio->lineHandle); + gpioState = static_cast(gpiod_line_get_value(regularGpio->lineHandle)); + if (gpioState == gpio::Levels::FAILED) { + return GPIO_GET_VALUE_FAILED; + } } else { auto gpioCallback = dynamic_cast(gpioMapIter->second); if (gpioCallback->callback == nullptr) { diff --git a/src/fsfw_hal/linux/gpio/LinuxLibgpioIF.h b/src/fsfw_hal/linux/gpio/LinuxLibgpioIF.h index bb8e890d..337fa1a8 100644 --- a/src/fsfw_hal/linux/gpio/LinuxLibgpioIF.h +++ b/src/fsfw_hal/linux/gpio/LinuxLibgpioIF.h @@ -25,6 +25,8 @@ class LinuxLibgpioIF : public GpioIF, public SystemObject { static constexpr ReturnValue_t GPIO_INVALID_INSTANCE = returnvalue::makeCode(gpioRetvalId, 4); static constexpr ReturnValue_t GPIO_DUPLICATE_DETECTED = returnvalue::makeCode(gpioRetvalId, 5); static constexpr ReturnValue_t GPIO_INIT_FAILED = returnvalue::makeCode(gpioRetvalId, 6); + // Will be returned if getting the line value failed. Error type will be set to errno in this case + static constexpr ReturnValue_t GPIO_GET_VALUE_FAILED = returnvalue::makeCode(gpioRetvalId, 7); LinuxLibgpioIF(object_id_t objectId); virtual ~LinuxLibgpioIF(); @@ -32,7 +34,7 @@ class LinuxLibgpioIF : public GpioIF, public SystemObject { ReturnValue_t addGpios(GpioCookie* gpioCookie) override; ReturnValue_t pullHigh(gpioId_t gpioId) override; ReturnValue_t pullLow(gpioId_t gpioId) override; - ReturnValue_t readGpio(gpioId_t gpioId, int* gpioState) override; + ReturnValue_t readGpio(gpioId_t gpioId, gpio::Levels& gpioState) override; private: static const size_t MAX_CHIPNAME_LENGTH = 11; diff --git a/src/fsfw_hal/linux/i2c/I2cComIF.cpp b/src/fsfw_hal/linux/i2c/I2cComIF.cpp index 8edeb8ab..7c365a20 100644 --- a/src/fsfw_hal/linux/i2c/I2cComIF.cpp +++ b/src/fsfw_hal/linux/i2c/I2cComIF.cpp @@ -170,18 +170,20 @@ ReturnValue_t I2cComIF::requestReceiveMessage(CookieIF* cookie, size_t requestLe int readLen = read(fd, replyBuffer, requestLen); if (readLen != static_cast(requestLen)) { -#if FSFW_VERBOSE_LEVEL >= 1 and FSFW_CPP_OSTREAM_ENABLED == 1 - sif::error << "I2cComIF::requestReceiveMessage: Reading from I2C " - << "device failed with error code " << errno << ". Description" - << " of error: " << strerror(errno) << std::endl; - sif::error << "I2cComIF::requestReceiveMessage: Read only " << readLen << " from " << requestLen - << " bytes" << std::endl; +#if FSFW_VERBOSE_LEVEL >= 1 +#if FSFW_CPP_OSTREAM_ENABLED == 1 + if (readLen < 0) { + sif::warning << "I2cComIF::requestReceiveMessage: Reading from I2C " + << "device failed with error code " << errno << " | " << strerror(errno) + << std::endl; + } else { + sif::warning << "I2cComIF::requestReceiveMessage: Read only " << readLen << " from " + << requestLen << " bytes" << std::endl; + } +#else +#endif #endif i2cDeviceMapIter->second.replyLen = 0; -#if FSFW_CPP_OSTREAM_ENABLED == 1 - sif::debug << "I2cComIF::requestReceiveMessage: Read " << readLen << " of " << requestLen - << " bytes" << std::endl; -#endif return returnvalue::FAILED; } diff --git a/src/fsfw_hal/linux/spi/ManualCsLockGuard.h b/src/fsfw_hal/linux/spi/ManualCsLockGuard.h new file mode 100644 index 00000000..feb6dd83 --- /dev/null +++ b/src/fsfw_hal/linux/spi/ManualCsLockGuard.h @@ -0,0 +1,43 @@ +#pragma once + +#include "fsfw/ipc/MutexIF.h" +#include "fsfw/returnvalues/returnvalue.h" +#include "fsfw_hal/common/gpio/GpioIF.h" + +class ManualCsLockWrapper { + public: + ManualCsLockWrapper(MutexIF* lock, GpioIF* gpioIF, SpiCookie* cookie, + MutexIF::TimeoutType type = MutexIF::TimeoutType::BLOCKING, + uint32_t timeoutMs = 0) + : lock(lock), gpioIF(gpioIF), cookie(cookie), type(type), timeoutMs(timeoutMs) { + if (cookie == nullptr) { + // TODO: Error? Or maybe throw exception.. + return; + } + cookie->setCsLockManual(true); + lockResult = lock->lockMutex(type, timeoutMs); + if (lockResult != returnvalue::OK) { + return; + } + gpioResult = gpioIF->pullLow(cookie->getChipSelectPin()); + } + + ~ManualCsLockWrapper() { + if (gpioResult == returnvalue::OK) { + gpioIF->pullHigh(cookie->getChipSelectPin()); + } + cookie->setCsLockManual(false); + if (lockResult == returnvalue::OK) { + lock->unlockMutex(); + } + } + ReturnValue_t lockResult; + ReturnValue_t gpioResult; + + private: + MutexIF* lock; + GpioIF* gpioIF; + SpiCookie* cookie; + MutexIF::TimeoutType type; + uint32_t timeoutMs = 0; +}; diff --git a/src/fsfw_hal/linux/spi/SpiComIF.cpp b/src/fsfw_hal/linux/spi/SpiComIF.cpp index cc52b689..dc30e94b 100644 --- a/src/fsfw_hal/linux/spi/SpiComIF.cpp +++ b/src/fsfw_hal/linux/spi/SpiComIF.cpp @@ -15,8 +15,8 @@ #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) { +SpiComIF::SpiComIF(object_id_t objectId, std::string devname, GpioIF* gpioComIF) + : SystemObject(objectId), gpioComIF(gpioComIF), dev(std::move(devname)) { if (gpioComIF == nullptr) { #if FSFW_VERBOSE_LEVEL >= 1 #if FSFW_CPP_OSTREAM_ENABLED == 1 @@ -27,7 +27,7 @@ SpiComIF::SpiComIF(object_id_t objectId, GpioIF* gpioComIF) #endif /* FSFW_VERBOSE_LEVEL >= 1 */ } - spiMutex = MutexFactory::instance()->createMutex(); + csMutex = MutexFactory::instance()->createMutex(); } ReturnValue_t SpiComIF::initializeInterface(CookieIF* cookie) { @@ -85,8 +85,7 @@ ReturnValue_t SpiComIF::initializeInterface(CookieIF* cookie) { spiCookie->getSpiParameters(spiMode, spiSpeed, ¶ms); int fileDescriptor = 0; - UnixFileGuard fileHelper(spiCookie->getSpiDevice(), &fileDescriptor, O_RDWR, - "SpiComIF::initializeInterface"); + UnixFileGuard fileHelper(dev, &fileDescriptor, O_RDWR, "SpiComIF::initializeInterface"); if (fileHelper.getOpenResult() != returnvalue::OK) { return fileHelper.getOpenResult(); } @@ -182,8 +181,7 @@ ReturnValue_t SpiComIF::performRegularSendOperation(SpiCookie* spiCookie, const int retval = 0; /* Prepare transfer */ int fileDescriptor = 0; - std::string device = spiCookie->getSpiDevice(); - UnixFileGuard fileHelper(device, &fileDescriptor, O_RDWR, "SpiComIF::sendMessage"); + UnixFileGuard fileHelper(dev, &fileDescriptor, O_RDWR, "SpiComIF::sendMessage"); if (fileHelper.getOpenResult() != returnvalue::OK) { return OPENING_FILE_FAILED; } @@ -196,20 +194,27 @@ ReturnValue_t SpiComIF::performRegularSendOperation(SpiCookie* spiCookie, const bool fullDuplex = spiCookie->isFullDuplex(); gpioId_t gpioId = spiCookie->getChipSelectPin(); + bool csLockManual = spiCookie->getCsLockManual(); - /* Pull SPI CS low. For now, no support for active high given */ - if (gpioId != gpio::NO_GPIO) { - result = spiMutex->lockMutex(timeoutType, timeoutMs); + MutexIF::TimeoutType csType; + dur_millis_t csTimeout = 0; + // Pull SPI CS low. For now, no support for active high given + if (gpioId != gpio::NO_GPIO and not csLockManual) { + spiCookie->getMutexParams(csType, csTimeout); + result = csMutex->lockMutex(csType, csTimeout); if (result != returnvalue::OK) { #if FSFW_VERBOSE_LEVEL >= 1 #if FSFW_CPP_OSTREAM_ENABLED == 1 - sif::error << "SpiComIF::sendMessage: Failed to lock mutex" << std::endl; + sif::error << "SpiComIF::sendMessage: Failed to lock mutex with code " + << "0x" << std::hex << std::setfill('0') << std::setw(4) << result << std::dec + << std::endl; #else - sif::printError("SpiComIF::sendMessage: Failed to lock mutex\n"); + sif::printError("SpiComIF::sendMessage: Failed to lock mutex with code %d\n", result); #endif #endif return result; } + updateLinePolarity(fileDescriptor); result = gpioComIF->pullLow(gpioId); if (result != returnvalue::OK) { #if FSFW_VERBOSE_LEVEL >= 1 @@ -221,6 +226,8 @@ ReturnValue_t SpiComIF::performRegularSendOperation(SpiCookie* spiCookie, const #endif return result; } + } else { + updateLinePolarity(fileDescriptor); } /* Execute transfer */ @@ -248,9 +255,9 @@ ReturnValue_t SpiComIF::performRegularSendOperation(SpiCookie* spiCookie, const } } - if (gpioId != gpio::NO_GPIO) { + if (gpioId != gpio::NO_GPIO and not csLockManual) { gpioComIF->pullHigh(gpioId); - result = spiMutex->unlockMutex(); + result = csMutex->unlockMutex(); if (result != returnvalue::OK) { #if FSFW_CPP_OSTREAM_ENABLED == 1 sif::error << "SpiComIF::sendMessage: Failed to unlock mutex" << std::endl; @@ -278,9 +285,8 @@ ReturnValue_t SpiComIF::requestReceiveMessage(CookieIF* cookie, size_t requestLe ReturnValue_t SpiComIF::performHalfDuplexReception(SpiCookie* spiCookie) { ReturnValue_t result = returnvalue::OK; - std::string device = spiCookie->getSpiDevice(); int fileDescriptor = 0; - UnixFileGuard fileHelper(device, &fileDescriptor, O_RDWR, "SpiComIF::requestReceiveMessage"); + UnixFileGuard fileHelper(dev, &fileDescriptor, O_RDWR, "SpiComIF::requestReceiveMessage"); if (fileHelper.getOpenResult() != returnvalue::OK) { return OPENING_FILE_FAILED; } @@ -292,12 +298,22 @@ ReturnValue_t SpiComIF::performHalfDuplexReception(SpiCookie* spiCookie) { return result; } + bool csLockManual = spiCookie->getCsLockManual(); gpioId_t gpioId = spiCookie->getChipSelectPin(); - if (gpioId != gpio::NO_GPIO) { - result = spiMutex->lockMutex(timeoutType, timeoutMs); + MutexIF::TimeoutType csType; + dur_millis_t csTimeout = 0; + if (gpioId != gpio::NO_GPIO and not csLockManual) { + spiCookie->getMutexParams(csType, csTimeout); + result = csMutex->lockMutex(csType, csTimeout); if (result != returnvalue::OK) { +#if FSFW_VERBOSE_LEVEL >= 1 #if FSFW_CPP_OSTREAM_ENABLED == 1 - sif::error << "SpiComIF::getSendSuccess: Failed to lock mutex" << std::endl; + sif::error << "SpiComIF::sendMessage: Failed to lock mutex with code " + << "0x" << std::hex << std::setfill('0') << std::setw(4) << result << std::dec + << std::endl; +#else + sif::printError("SpiComIF::sendMessage: Failed to lock mutex with code %d\n", result); +#endif #endif return result; } @@ -315,9 +331,9 @@ ReturnValue_t SpiComIF::performHalfDuplexReception(SpiCookie* spiCookie) { result = HALF_DUPLEX_TRANSFER_FAILED; } - if (gpioId != gpio::NO_GPIO) { + if (gpioId != gpio::NO_GPIO and not csLockManual) { gpioComIF->pullHigh(gpioId); - result = spiMutex->unlockMutex(); + result = csMutex->unlockMutex(); if (result != returnvalue::OK) { #if FSFW_CPP_OSTREAM_ENABLED == 1 sif::error << "SpiComIF::getSendSuccess: Failed to unlock mutex" << std::endl; @@ -346,15 +362,7 @@ ReturnValue_t SpiComIF::readReceivedMessage(CookieIF* cookie, uint8_t** buffer, return returnvalue::OK; } -MutexIF* SpiComIF::getMutex(MutexIF::TimeoutType* timeoutType, uint32_t* timeoutMs) { - if (timeoutType != nullptr) { - *timeoutType = this->timeoutType; - } - if (timeoutMs != nullptr) { - *timeoutMs = this->timeoutMs; - } - return spiMutex; -} +MutexIF* SpiComIF::getCsMutex() { return csMutex; } void SpiComIF::performSpiWiretapping(SpiCookie* spiCookie) { if (spiCookie == nullptr) { @@ -401,11 +409,27 @@ void SpiComIF::setSpiSpeedAndMode(int spiFd, spi::SpiModes mode, uint32_t speed) if (retval != 0) { utility::handleIoctlError("SpiComIF::setSpiSpeedAndMode: Setting SPI speed failed"); } - // This updates the SPI clock default polarity. Only setting the mode does not update - // the line state, which can be an issue on mode switches because the clock line will - // switch the state after the chip select is pulled low +} + +void SpiComIF::getSpiSpeedAndMode(int spiFd, spi::SpiModes& mode, uint32_t& speed) const { + uint8_t tmpMode = 0; + int retval = ioctl(spiFd, SPI_IOC_RD_MODE, &tmpMode); + if (retval != 0) { + utility::handleIoctlError("SpiComIF::getSpiSpeedAndMode: Reading SPI mode failed"); + } + mode = static_cast(tmpMode); + + retval = ioctl(spiFd, SPI_IOC_RD_MAX_SPEED_HZ, &speed); + if (retval != 0) { + utility::handleIoctlError("SpiComIF::getSpiSpeedAndMode: Getting SPI speed failed"); + } +} + +const std::string& SpiComIF::getSpiDev() const { return dev; } + +void SpiComIF::updateLinePolarity(int spiFd) { clockUpdateTransfer.len = 0; - retval = ioctl(spiFd, SPI_IOC_MESSAGE(1), &clockUpdateTransfer); + int retval = ioctl(spiFd, SPI_IOC_MESSAGE(1), &clockUpdateTransfer); if (retval != 0) { utility::handleIoctlError("SpiComIF::setSpiSpeedAndMode: Updating SPI default clock failed"); } diff --git a/src/fsfw_hal/linux/spi/SpiComIF.h b/src/fsfw_hal/linux/spi/SpiComIF.h index 11defdce..c3e39b11 100644 --- a/src/fsfw_hal/linux/spi/SpiComIF.h +++ b/src/fsfw_hal/linux/spi/SpiComIF.h @@ -31,7 +31,7 @@ class SpiComIF : public DeviceCommunicationIF, public SystemObject { static constexpr ReturnValue_t HALF_DUPLEX_TRANSFER_FAILED = returnvalue::makeCode(spiRetvalId, 2); - SpiComIF(object_id_t objectId, GpioIF* gpioComIF); + SpiComIF(object_id_t objectId, std::string devname, GpioIF* gpioComIF); ReturnValue_t initializeInterface(CookieIF* cookie) override; ReturnValue_t sendMessage(CookieIF* cookie, const uint8_t* sendData, size_t sendLen) override; @@ -43,7 +43,8 @@ class SpiComIF : public DeviceCommunicationIF, public SystemObject { * @brief This function returns the mutex which can be used to protect the spi bus when * the chip select must be driven from outside of the com if. */ - MutexIF* getMutex(MutexIF::TimeoutType* timeoutType = nullptr, uint32_t* timeoutMs = nullptr); + MutexIF* getCsMutex(); + void setMutexParams(MutexIF::TimeoutType timeoutType, uint32_t timeoutMs); /** * Perform a regular send operation using Linux iotcl. This is public so it can be used @@ -58,6 +59,20 @@ class SpiComIF : public DeviceCommunicationIF, public SystemObject { GpioIF* getGpioInterface(); void setSpiSpeedAndMode(int spiFd, spi::SpiModes mode, uint32_t speed); + void getSpiSpeedAndMode(int spiFd, spi::SpiModes& mode, uint32_t& speed) const; + + /** + * This updates the SPI clock default polarity. Only setting the mode does not update + * the line state, which can be an issue on mode switches because the clock line will + * switch the state after the chip select is pulled low. + * + * It is recommended to call this function after #setSpiSpeedAndMode and after locking the + * CS mutex if the SPI bus has multiple SPI devices with different speed and SPI modes attached. + * @param spiFd + */ + void updateLinePolarity(int spiFd); + + const std::string& getSpiDev() const; void performSpiWiretapping(SpiCookie* spiCookie); ReturnValue_t getReadBuffer(address_t spiAddress, uint8_t** buffer); @@ -69,10 +84,14 @@ class SpiComIF : public DeviceCommunicationIF, public SystemObject { }; GpioIF* gpioComIF = nullptr; - - MutexIF* spiMutex = nullptr; - MutexIF::TimeoutType timeoutType = MutexIF::TimeoutType::WAITING; - uint32_t timeoutMs = 20; + std::string dev = ""; + /** + * Protects the chip select operations. Lock when GPIO is pulled low, unlock after it was + * pulled high + */ + MutexIF* csMutex = nullptr; + // MutexIF::TimeoutType timeoutType = MutexIF::TimeoutType::WAITING; + // uint32_t timeoutMs = DEFAULT_MUTEX_TIMEOUT; spi_ioc_transfer clockUpdateTransfer = {}; using SpiDeviceMap = std::unordered_map; diff --git a/src/fsfw_hal/linux/spi/SpiCookie.cpp b/src/fsfw_hal/linux/spi/SpiCookie.cpp index c94fcdf1..e61703e6 100644 --- a/src/fsfw_hal/linux/spi/SpiCookie.cpp +++ b/src/fsfw_hal/linux/spi/SpiCookie.cpp @@ -1,26 +1,25 @@ #include "SpiCookie.h" -SpiCookie::SpiCookie(address_t spiAddress, gpioId_t chipSelect, std::string spiDev, - const size_t maxSize, spi::SpiModes spiMode, uint32_t spiSpeed) - : SpiCookie(spi::SpiComIfModes::REGULAR, spiAddress, chipSelect, spiDev, maxSize, spiMode, - spiSpeed, nullptr, nullptr) {} - -SpiCookie::SpiCookie(address_t spiAddress, std::string spiDev, const size_t maxSize, +SpiCookie::SpiCookie(address_t spiAddress, gpioId_t chipSelect, const size_t maxSize, spi::SpiModes spiMode, uint32_t spiSpeed) - : SpiCookie(spiAddress, gpio::NO_GPIO, spiDev, maxSize, spiMode, spiSpeed) {} + : SpiCookie(spi::SpiComIfModes::REGULAR, spiAddress, chipSelect, maxSize, spiMode, spiSpeed, + nullptr, nullptr) {} -SpiCookie::SpiCookie(address_t spiAddress, gpioId_t chipSelect, std::string spiDev, - const size_t maxSize, spi::SpiModes spiMode, uint32_t spiSpeed, +SpiCookie::SpiCookie(address_t spiAddress, const size_t maxSize, spi::SpiModes spiMode, + uint32_t spiSpeed) + : SpiCookie(spiAddress, gpio::NO_GPIO, maxSize, spiMode, spiSpeed) {} + +SpiCookie::SpiCookie(address_t spiAddress, gpioId_t chipSelect, const size_t maxSize, + spi::SpiModes spiMode, uint32_t spiSpeed, spi::send_callback_function_t callback, void* args) - : SpiCookie(spi::SpiComIfModes::CALLBACK, spiAddress, chipSelect, spiDev, maxSize, spiMode, - spiSpeed, callback, args) {} + : SpiCookie(spi::SpiComIfModes::CALLBACK, spiAddress, chipSelect, maxSize, spiMode, spiSpeed, + callback, args) {} SpiCookie::SpiCookie(spi::SpiComIfModes comIfMode, address_t spiAddress, gpioId_t chipSelect, - std::string spiDev, const size_t maxSize, spi::SpiModes spiMode, - uint32_t spiSpeed, spi::send_callback_function_t callback, void* args) + const size_t maxSize, spi::SpiModes spiMode, uint32_t spiSpeed, + spi::send_callback_function_t callback, void* args) : spiAddress(spiAddress), chipSelectPin(chipSelect), - spiDevice(spiDev), comIfMode(comIfMode), maxSize(maxSize), spiMode(spiMode), @@ -50,8 +49,6 @@ size_t SpiCookie::getMaxBufferSize() const { return maxSize; } address_t SpiCookie::getSpiAddress() const { return spiAddress; } -std::string SpiCookie::getSpiDevice() const { return spiDevice; } - void SpiCookie::setThreeWireSpi(bool enable) { uncommonParameters.threeWireSpi = enable; } void SpiCookie::setLsbFirst(bool enable) { uncommonParameters.lsbFirst = enable; } @@ -107,3 +104,17 @@ void SpiCookie::getCallback(spi::send_callback_function_t* callback, void** args *callback = this->sendCallback; *args = this->callbackArgs; } + +void SpiCookie::setCsLockManual(bool enable) { manualCsLock = enable; } + +bool SpiCookie::getCsLockManual() const { return manualCsLock; } + +void SpiCookie::getMutexParams(MutexIF::TimeoutType& csTimeoutType, dur_millis_t& csTimeout) const { + csTimeoutType = this->csTimeoutType; + csTimeout = this->csTimeout; +} + +void SpiCookie::setMutexParams(MutexIF::TimeoutType csTimeoutType, dur_millis_t csTimeout) { + this->csTimeoutType = csTimeoutType; + this->csTimeout = csTimeout; +} diff --git a/src/fsfw_hal/linux/spi/SpiCookie.h b/src/fsfw_hal/linux/spi/SpiCookie.h index 5f4bf2d5..2104e2eb 100644 --- a/src/fsfw_hal/linux/spi/SpiCookie.h +++ b/src/fsfw_hal/linux/spi/SpiCookie.h @@ -2,6 +2,8 @@ #define LINUX_SPI_SPICOOKIE_H_ #include +#include +#include #include #include "../../common/gpio/gpioDefinitions.h" @@ -20,6 +22,8 @@ */ class SpiCookie : public CookieIF { public: + static constexpr dur_millis_t DEFAULT_MUTEX_TIMEOUT = 20; + /** * Each SPI device will have a corresponding cookie. The cookie is used by the communication * interface and contains device specific information like the largest expected size to be @@ -29,23 +33,22 @@ class SpiCookie : public CookieIF { * @param spiDev * @param maxSize */ - SpiCookie(address_t spiAddress, gpioId_t chipSelect, std::string spiDev, const size_t maxSize, - spi::SpiModes spiMode, uint32_t spiSpeed); + SpiCookie(address_t spiAddress, gpioId_t chipSelect, const size_t maxSize, spi::SpiModes spiMode, + uint32_t spiSpeed); /** * Like constructor above, but without a dedicated GPIO CS. Can be used for hardware * slave select or if CS logic is performed with decoders. */ - SpiCookie(address_t spiAddress, std::string spiDev, const size_t maxReplySize, - spi::SpiModes spiMode, uint32_t spiSpeed); + SpiCookie(address_t spiAddress, const size_t maxReplySize, spi::SpiModes spiMode, + uint32_t spiSpeed); /** * Use the callback mode of the SPI communication interface. The user can pass the callback * function here or by using the setter function #setCallbackMode */ - SpiCookie(address_t spiAddress, gpioId_t chipSelect, std::string spiDev, const size_t maxSize, - spi::SpiModes spiMode, uint32_t spiSpeed, spi::send_callback_function_t callback, - void* args); + SpiCookie(address_t spiAddress, gpioId_t chipSelect, const size_t maxSize, spi::SpiModes spiMode, + uint32_t spiSpeed, spi::send_callback_function_t callback, void* args); /** * Get the callback function @@ -55,7 +58,6 @@ class SpiCookie : public CookieIF { void getCallback(spi::send_callback_function_t* callback, void** args); address_t getSpiAddress() const; - std::string getSpiDevice() const; gpioId_t getChipSelectPin() const; size_t getMaxBufferSize() const; @@ -139,9 +141,42 @@ class SpiCookie : public CookieIF { */ void activateCsDeselect(bool deselectCs, uint16_t delayUsecs); + void getMutexParams(MutexIF::TimeoutType& csTimeoutType, dur_millis_t& csTimeout) const; + void setMutexParams(MutexIF::TimeoutType csTimeoutType, dur_millis_t csTimeout); + + void setCsLockManual(bool enable); + bool getCsLockManual() const; + spi_ioc_transfer* getTransferStructHandle(); private: + address_t spiAddress; + gpioId_t chipSelectPin; + + spi::SpiComIfModes comIfMode; + + // Required for regular mode + const size_t maxSize; + spi::SpiModes spiMode; + /** + * If this is set to true, the SPI ComIF will not perform any mutex locking for the + * CS mechanism. The user is responsible to locking and unlocking the mutex for the + * whole duration of the transfers. + */ + bool manualCsLock = false; + uint32_t spiSpeed; + bool halfDuplex = false; + + MutexIF::TimeoutType csTimeoutType = MutexIF::TimeoutType::WAITING; + dur_millis_t csTimeout = DEFAULT_MUTEX_TIMEOUT; + + // Required for callback mode + spi::send_callback_function_t sendCallback = nullptr; + void* callbackArgs = nullptr; + + struct spi_ioc_transfer spiTransferStruct = {}; + UncommonParameters uncommonParameters; + /** * Internal constructor which initializes every field * @param spiAddress @@ -154,27 +189,8 @@ class SpiCookie : public CookieIF { * @param args */ SpiCookie(spi::SpiComIfModes comIfMode, 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); - - address_t spiAddress; - gpioId_t chipSelectPin; - std::string spiDevice; - - spi::SpiComIfModes comIfMode; - - // Required for regular mode - const size_t maxSize; - spi::SpiModes spiMode; - uint32_t spiSpeed; - bool halfDuplex = false; - - // Required for callback mode - spi::send_callback_function_t sendCallback = nullptr; - void* callbackArgs = nullptr; - - struct spi_ioc_transfer spiTransferStruct = {}; - UncommonParameters uncommonParameters; }; #endif /* LINUX_SPI_SPICOOKIE_H_ */ diff --git a/src/fsfw_hal/linux/uart/UartCookie.cpp b/src/fsfw_hal/linux/uart/UartCookie.cpp index 3fedc9d4..31dbc903 100644 --- a/src/fsfw_hal/linux/uart/UartCookie.cpp +++ b/src/fsfw_hal/linux/uart/UartCookie.cpp @@ -2,8 +2,8 @@ #include -UartCookie::UartCookie(object_id_t handlerId, std::string deviceFile, UartModes uartMode, - UartBaudRate baudrate, size_t maxReplyLen) +UartCookie::UartCookie(object_id_t handlerId, std::string deviceFile, UartBaudRate baudrate, + size_t maxReplyLen, UartModes uartMode) : handlerId(handlerId), deviceFile(deviceFile), uartMode(uartMode), diff --git a/src/fsfw_hal/linux/uart/UartCookie.h b/src/fsfw_hal/linux/uart/UartCookie.h index 6840b352..cae33d58 100644 --- a/src/fsfw_hal/linux/uart/UartCookie.h +++ b/src/fsfw_hal/linux/uart/UartCookie.h @@ -69,8 +69,8 @@ class UartCookie : public CookieIF { * 8 databits (number of bits transfered with one uart frame) * One stop bit */ - UartCookie(object_id_t handlerId, std::string deviceFile, UartModes uartMode, - UartBaudRate baudrate, size_t maxReplyLen); + UartCookie(object_id_t handlerId, std::string deviceFile, UartBaudRate baudrate, + size_t maxReplyLen, UartModes uartMode = UartModes::NON_CANONICAL); virtual ~UartCookie(); diff --git a/src/fsfw_tests/integration/devices/TestDeviceHandler.cpp b/src/fsfw_tests/integration/devices/TestDeviceHandler.cpp index e2df55c3..fdf02a70 100644 --- a/src/fsfw_tests/integration/devices/TestDeviceHandler.cpp +++ b/src/fsfw_tests/integration/devices/TestDeviceHandler.cpp @@ -645,7 +645,7 @@ ReturnValue_t TestDevice::initializeLocalDataPool(localpool::DataPool& localData sid_t sid(this->getObjectId(), td::TEST_SET_ID); /* Subscribe for periodic HK packets but do not enable reporting for now. Non-diangostic with a period of one second */ - poolManager.subscribeForPeriodicPacket(sid, false, 1.0, false); + poolManager.subscribeForRegularPeriodicPacket({sid, false, 1.0}); return returnvalue::OK; } diff --git a/unittests/CMakeLists.txt b/unittests/CMakeLists.txt index 8c7f2463..fc03a728 100644 --- a/unittests/CMakeLists.txt +++ b/unittests/CMakeLists.txt @@ -28,5 +28,6 @@ add_subdirectory(cfdp) add_subdirectory(hal) add_subdirectory(internalerror) add_subdirectory(devicehandler) +add_subdirectory(tmtcservices) target_include_directories(${FSFW_TEST_TGT} PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}) diff --git a/unittests/CatchFactory.cpp b/unittests/CatchFactory.cpp index 860a9bed..0d855cb3 100644 --- a/unittests/CatchFactory.cpp +++ b/unittests/CatchFactory.cpp @@ -7,11 +7,9 @@ #include #include #include -#include #include #include -#include "datapoollocal/LocalPoolOwnerBase.h" #include "mocks/HkReceiverMock.h" #include "tests/TestsConfig.h" @@ -36,14 +34,6 @@ void Factory::produceFrameworkObjects(void* args) { new HealthTable(objects::HEALTH_TABLE); new InternalErrorReporter(objects::INTERNAL_ERROR_REPORTER); - new LocalPoolOwnerBase(objects::TEST_LOCAL_POOL_OWNER_BASE); - new HkReceiverMock(objects::HK_RECEIVER_MOCK); - - { - PoolManager::LocalPoolConfig poolCfg = {{100, 16}, {50, 32}, {25, 64}, {15, 128}, {5, 1024}}; - new PoolManager(objects::TC_STORE, poolCfg); - } - { PoolManager::LocalPoolConfig poolCfg = {{100, 16}, {50, 32}, {25, 64}, {15, 128}, {5, 1024}}; new PoolManager(objects::TM_STORE, poolCfg); @@ -55,23 +45,20 @@ void Factory::produceFrameworkObjects(void* args) { } } +// TODO: Our tests, and the code base in general should really not depend on some arbitrary function +// like this. Instead, this should be more like a general struct containing all important +// object IDs which are then explicitely passed in the object constructor void Factory::setStaticFrameworkObjectIds() { - PusServiceBase::packetSource = objects::NO_OBJECT; - PusServiceBase::packetDestination = objects::NO_OBJECT; + PusServiceBase::PACKET_DESTINATION = objects::NO_OBJECT; CommandingServiceBase::defaultPacketSource = objects::NO_OBJECT; CommandingServiceBase::defaultPacketDestination = objects::NO_OBJECT; - VerificationReporter::messageReceiver = objects::PUS_SERVICE_1_VERIFICATION; - DeviceHandlerBase::powerSwitcherId = objects::NO_OBJECT; DeviceHandlerBase::rawDataReceiverId = objects::NO_OBJECT; - LocalDataPoolManager::defaultHkDestination = objects::HK_RECEIVER_MOCK; - + LocalDataPoolManager::defaultHkDestination = objects::NO_OBJECT; DeviceHandlerFailureIsolation::powerConfirmationId = objects::NO_OBJECT; - - TmPacketBase::timeStamperId = objects::NO_OBJECT; } #endif diff --git a/unittests/CatchRunner.cpp b/unittests/CatchRunner.cpp index 1377049c..9bdcb676 100644 --- a/unittests/CatchRunner.cpp +++ b/unittests/CatchRunner.cpp @@ -13,6 +13,7 @@ #include extern int customSetup(); +extern int customTeardown(); int main(int argc, char* argv[]) { customSetup(); @@ -21,5 +22,6 @@ int main(int argc, char* argv[]) { int result = Catch::Session().run(argc, argv); // global clean-up + customTeardown(); return result; } diff --git a/unittests/CatchSetup.cpp b/unittests/CatchSetup.cpp index 06f5190a..9206c2e1 100644 --- a/unittests/CatchSetup.cpp +++ b/unittests/CatchSetup.cpp @@ -29,3 +29,5 @@ int customSetup() { objMan->initialize(); return 0; } + +int customTeardown() { return 0; } diff --git a/unittests/action/TestActionHelper.cpp b/unittests/action/TestActionHelper.cpp index 823d873d..77c055aa 100644 --- a/unittests/action/TestActionHelper.cpp +++ b/unittests/action/TestActionHelper.cpp @@ -6,11 +6,12 @@ #include #include -#include "mocks/MessageQueueMockBase.h" +#include "mocks/MessageQueueMock.h" TEST_CASE("Action Helper", "[ActionHelper]") { ActionHelperOwnerMockBase testDhMock; - MessageQueueMockBase testMqMock; + // TODO: Setting another number here breaks the test. Find out why + MessageQueueMock testMqMock(MessageQueueIF::NO_QUEUE); ActionHelper actionHelper = ActionHelper(&testDhMock, dynamic_cast(&testMqMock)); CommandMessage actionMessage; ActionId_t testActionId = 777; @@ -57,7 +58,7 @@ TEST_CASE("Action Helper", "[ActionHelper]") { step += 1; CHECK(testMqMock.wasMessageSent()); CommandMessage testMessage; - REQUIRE(testMqMock.receiveMessage(&testMessage) == static_cast(returnvalue::OK)); + REQUIRE(testMqMock.getNextSentMessage(testMessage) == returnvalue::OK); REQUIRE(testMessage.getCommand() == static_cast(ActionMessage::STEP_FAILED)); REQUIRE(testMessage.getParameter() == static_cast(testActionId)); uint32_t parameter2 = ((uint32_t)step << 16) | (uint32_t)status; @@ -71,14 +72,14 @@ TEST_CASE("Action Helper", "[ActionHelper]") { actionHelper.finish(false, testMqMock.getId(), testActionId, status); CHECK(testMqMock.wasMessageSent()); CommandMessage testMessage; - REQUIRE(testMqMock.receiveMessage(&testMessage) == static_cast(returnvalue::OK)); + REQUIRE(testMqMock.getNextSentMessage(testMessage) == returnvalue::OK); REQUIRE(testMessage.getCommand() == static_cast(ActionMessage::COMPLETION_FAILED)); REQUIRE(ActionMessage::getActionId(&testMessage) == testActionId); REQUIRE(ActionMessage::getReturnCode(&testMessage) == static_cast(status)); } SECTION("Handle failed") { - store_address_t toLongParamAddress = StorageManagerIF::INVALID_ADDRESS; + store_address_t toLongParamAddress = store_address_t::invalid(); std::array toLongData = {5, 4, 3, 2, 1}; REQUIRE(ipcStore->addData(&toLongParamAddress, toLongData.data(), 5) == returnvalue::OK); ActionMessage::setCommand(&actionMessage, testActionId, toLongParamAddress); @@ -87,7 +88,7 @@ TEST_CASE("Action Helper", "[ActionHelper]") { REQUIRE(ipcStore->getData(toLongParamAddress).first == static_cast(StorageManagerIF::DATA_DOES_NOT_EXIST)); CommandMessage testMessage; - REQUIRE(testMqMock.receiveMessage(&testMessage) == static_cast(returnvalue::OK)); + REQUIRE(testMqMock.getNextSentMessage(testMessage) == returnvalue::OK); REQUIRE(testMessage.getCommand() == static_cast(ActionMessage::STEP_FAILED)); REQUIRE(ActionMessage::getReturnCode(&testMessage) == 0xAFFE); REQUIRE(ActionMessage::getStep(&testMessage) == 0); @@ -95,11 +96,11 @@ TEST_CASE("Action Helper", "[ActionHelper]") { } SECTION("Missing IPC Data") { - ActionMessage::setCommand(&actionMessage, testActionId, StorageManagerIF::INVALID_ADDRESS); + ActionMessage::setCommand(&actionMessage, testActionId, store_address_t::invalid()); CHECK(not testDhMock.executeActionCalled); REQUIRE(actionHelper.handleActionMessage(&actionMessage) == returnvalue::OK); CommandMessage testMessage; - REQUIRE(testMqMock.receiveMessage(&testMessage) == static_cast(returnvalue::OK)); + REQUIRE(testMqMock.getNextSentMessage(testMessage) == returnvalue::OK); REQUIRE(testMessage.getCommand() == static_cast(ActionMessage::STEP_FAILED)); REQUIRE(ActionMessage::getReturnCode(&testMessage) == static_cast(StorageManagerIF::ILLEGAL_STORAGE_ID)); diff --git a/unittests/container/TestDynamicFifo.cpp b/unittests/container/TestDynamicFifo.cpp index 445d3d91..1e3d4a62 100644 --- a/unittests/container/TestDynamicFifo.cpp +++ b/unittests/container/TestDynamicFifo.cpp @@ -81,9 +81,6 @@ TEST_CASE("Dynamic Fifo Tests", "[TestDynamicFifo]") { REQUIRE(fifo.pop() == static_cast(returnvalue::OK)); REQUIRE(fifo.size() == 0); REQUIRE(fifo.empty()); - // struct Test* ptr = nullptr; - // REQUIRE(fifo.retrieve(ptr) == static_cast(returnvalue::FAILED)); - // REQUIRE(fifo.peek(ptr) == static_cast(returnvalue::FAILED)); }; SECTION("Copy Test") { REQUIRE(fifo.insert(structOne) == static_cast(returnvalue::OK)); diff --git a/unittests/datapoollocal/CMakeLists.txt b/unittests/datapoollocal/CMakeLists.txt index bf465282..016645fd 100644 --- a/unittests/datapoollocal/CMakeLists.txt +++ b/unittests/datapoollocal/CMakeLists.txt @@ -1,7 +1,6 @@ target_sources(${FSFW_TEST_TGT} PRIVATE - LocalPoolVariableTest.cpp - LocalPoolVectorTest.cpp - DataSetTest.cpp - LocalPoolManagerTest.cpp - LocalPoolOwnerBase.cpp + testLocalPoolVariable.cpp + testLocalPoolVector.cpp + testDataSet.cpp + testLocalPoolManager.cpp ) diff --git a/unittests/datapoollocal/LocalPoolManagerTest.cpp b/unittests/datapoollocal/LocalPoolManagerTest.cpp deleted file mode 100644 index e72b108f..00000000 --- a/unittests/datapoollocal/LocalPoolManagerTest.cpp +++ /dev/null @@ -1,413 +0,0 @@ -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include - -#include "CatchDefinitions.h" -#include "LocalPoolOwnerBase.h" - -TEST_CASE("LocalPoolManagerTest", "[LocManTest]") { - LocalPoolOwnerBase* poolOwner = - ObjectManager::instance()->get(objects::TEST_LOCAL_POOL_OWNER_BASE); - REQUIRE(poolOwner != nullptr); - REQUIRE(poolOwner->initializeHkManager() == returnvalue::OK); - REQUIRE(poolOwner->initializeHkManagerAfterTaskCreation() == returnvalue::OK); - - MessageQueueMockBase* poolOwnerMock = poolOwner->getMockQueueHandle(); - REQUIRE(poolOwnerMock != nullptr); - - // MessageQueueIF* hkCommander = QueueFactory::instance()->createMessageQueue(); - CommandMessage messageSent; - uint8_t messagesSent = 0; - - SECTION("BasicTest") { - { - /* For code coverage, should not crash */ - LocalDataPoolManager manager(nullptr, nullptr); - } - auto owner = poolOwner->poolManager.getOwner(); - REQUIRE(owner != nullptr); - CHECK(owner->getObjectId() == objects::TEST_LOCAL_POOL_OWNER_BASE); - - /* Subscribe for message generation on update. */ - REQUIRE(poolOwner->subscribeWrapperSetUpdate() == returnvalue::OK); - /* Subscribe for an update message. */ - poolOwner->dataset.setChanged(true); - /* Now the update message should be generated. */ - REQUIRE(poolOwner->poolManager.performHkOperation() == returnvalue::OK); - REQUIRE(poolOwnerMock->wasMessageSent() == true); - - REQUIRE(poolOwnerMock->receiveMessage(&messageSent) == returnvalue::OK); - CHECK(messageSent.getCommand() == - static_cast(HousekeepingMessage::UPDATE_NOTIFICATION_SET)); - - /* Should have been reset. */ - CHECK(poolOwner->dataset.hasChanged() == false); - /* Set changed again, result should be the same. */ - poolOwner->dataset.setChanged(true); - REQUIRE(poolOwner->poolManager.performHkOperation() == returnvalue::OK); - - REQUIRE(poolOwnerMock->wasMessageSent(&messagesSent) == true); - CHECK(messagesSent == 1); - REQUIRE(poolOwnerMock->receiveMessage(&messageSent) == returnvalue::OK); - CHECK(messageSent.getCommand() == - static_cast(HousekeepingMessage::UPDATE_NOTIFICATION_SET)); - - /* Now subscribe for set update HK as well. */ - REQUIRE(poolOwner->subscribeWrapperSetUpdateHk() == returnvalue::OK); - poolOwner->dataset.setChanged(true); - REQUIRE(poolOwner->poolManager.performHkOperation() == returnvalue::OK); - REQUIRE(poolOwnerMock->wasMessageSent(&messagesSent) == true); - CHECK(messagesSent == 2); - /* first message sent should be the update notification, considering - the internal list is a vector checked in insertion order. */ - REQUIRE(poolOwnerMock->receiveMessage(&messageSent) == returnvalue::OK); - CHECK(messageSent.getCommand() == - static_cast(HousekeepingMessage::UPDATE_NOTIFICATION_SET)); - - REQUIRE(poolOwnerMock->receiveMessage(&messageSent) == returnvalue::OK); - CHECK(messageSent.getCommand() == static_cast(HousekeepingMessage::HK_REPORT)); - /* Clear message to avoid memory leak, our mock won't do it for us (yet) */ - CommandMessageCleaner::clearCommandMessage(&messageSent); - } - - SECTION("SetSnapshotUpdateTest") { - /* Set the variables in the set to certain values. These are checked later. */ - { - PoolReadGuard readHelper(&poolOwner->dataset); - REQUIRE(readHelper.getReadResult() == returnvalue::OK); - poolOwner->dataset.localPoolVarUint8.value = 5; - poolOwner->dataset.localPoolVarFloat.value = -12.242; - poolOwner->dataset.localPoolUint16Vec.value[0] = 2; - poolOwner->dataset.localPoolUint16Vec.value[1] = 32; - poolOwner->dataset.localPoolUint16Vec.value[2] = 42932; - } - - /* Subscribe for snapshot generation on update. */ - REQUIRE(poolOwner->subscribeWrapperSetUpdateSnapshot() == returnvalue::OK); - poolOwner->dataset.setChanged(true); - - /* Store current time, we are going to check the (approximate) time equality later */ - timeval now; - Clock::getClock_timeval(&now); - - /* Trigger generation of snapshot */ - REQUIRE(poolOwner->poolManager.performHkOperation() == returnvalue::OK); - REQUIRE(poolOwnerMock->wasMessageSent(&messagesSent) == true); - CHECK(messagesSent == 1); - REQUIRE(poolOwnerMock->receiveMessage(&messageSent) == returnvalue::OK); - /* Check that snapshot was generated */ - CHECK(messageSent.getCommand() == static_cast(HousekeepingMessage::UPDATE_SNAPSHOT_SET)); - /* Now we deserialize the snapshot into a new dataset instance */ - CCSDSTime::CDS_short cdsShort; - LocalPoolTestDataSet newSet; - HousekeepingSnapshot snapshot(&cdsShort, &newSet); - store_address_t storeId; - HousekeepingMessage::getUpdateSnapshotSetCommand(&messageSent, &storeId); - ConstAccessorPair accessorPair = tglob::getIpcStoreHandle()->getData(storeId); - REQUIRE(accessorPair.first == returnvalue::OK); - const uint8_t* readOnlyPtr = accessorPair.second.data(); - size_t sizeToDeserialize = accessorPair.second.size(); - CHECK(newSet.localPoolVarFloat.value == 0); - CHECK(newSet.localPoolVarUint8 == 0); - CHECK(newSet.localPoolUint16Vec.value[0] == 0); - CHECK(newSet.localPoolUint16Vec.value[1] == 0); - CHECK(newSet.localPoolUint16Vec.value[2] == 0); - /* Fill the dataset and timestamp */ - REQUIRE(snapshot.deSerialize(&readOnlyPtr, &sizeToDeserialize, - SerializeIF::Endianness::MACHINE) == returnvalue::OK); - /* Now we check that the snapshot is actually correct */ - CHECK(newSet.localPoolVarFloat.value == Catch::Approx(-12.242)); - CHECK(newSet.localPoolVarUint8 == 5); - CHECK(newSet.localPoolUint16Vec.value[0] == 2); - CHECK(newSet.localPoolUint16Vec.value[1] == 32); - CHECK(newSet.localPoolUint16Vec.value[2] == 42932); - - /* Now we check that both times are equal */ - timeval timeFromHK; - auto result = CCSDSTime::convertFromCDS(&timeFromHK, &cdsShort); - CHECK(result == returnvalue::OK); - timeval difference = timeFromHK - now; - CHECK(timevalOperations::toDouble(difference) < 1.0); - } - - SECTION("VariableSnapshotTest") { - /* Acquire subscription interface */ - ProvidesDataPoolSubscriptionIF* subscriptionIF = poolOwner->getSubscriptionInterface(); - REQUIRE(subscriptionIF != nullptr); - - /* Subscribe for variable snapshot */ - REQUIRE(poolOwner->subscribeWrapperVariableSnapshot(lpool::uint8VarId) == returnvalue::OK); - auto poolVar = - dynamic_cast*>(poolOwner->getPoolObjectHandle(lpool::uint8VarId)); - REQUIRE(poolVar != nullptr); - - { - PoolReadGuard rg(poolVar); - CHECK(rg.getReadResult() == returnvalue::OK); - poolVar->value = 25; - } - - poolVar->setChanged(true); - /* Store current time, we are going to check the (approximate) time equality later */ - CCSDSTime::CDS_short timeCdsNow; - timeval now; - Clock::getClock_timeval(&now); - REQUIRE(poolOwner->poolManager.performHkOperation() == returnvalue::OK); - - /* Check update snapshot was sent. */ - REQUIRE(poolOwnerMock->wasMessageSent(&messagesSent) == true); - CHECK(messagesSent == 1); - - /* Should have been reset. */ - CHECK(poolVar->hasChanged() == false); - REQUIRE(poolOwnerMock->receiveMessage(&messageSent) == returnvalue::OK); - CHECK(messageSent.getCommand() == - static_cast(HousekeepingMessage::UPDATE_SNAPSHOT_VARIABLE)); - /* Now we deserialize the snapshot into a new dataset instance */ - CCSDSTime::CDS_short cdsShort; - lp_var_t varCopy = lp_var_t(lpool::uint8VarGpid); - HousekeepingSnapshot snapshot(&cdsShort, &varCopy); - store_address_t storeId; - HousekeepingMessage::getUpdateSnapshotVariableCommand(&messageSent, &storeId); - ConstAccessorPair accessorPair = tglob::getIpcStoreHandle()->getData(storeId); - REQUIRE(accessorPair.first == returnvalue::OK); - const uint8_t* readOnlyPtr = accessorPair.second.data(); - size_t sizeToDeserialize = accessorPair.second.size(); - CHECK(varCopy.value == 0); - /* Fill the dataset and timestamp */ - REQUIRE(snapshot.deSerialize(&readOnlyPtr, &sizeToDeserialize, - SerializeIF::Endianness::MACHINE) == returnvalue::OK); - CHECK(varCopy.value == 25); - - /* Now we check that both times are equal */ - timeval timeFromHK; - auto result = CCSDSTime::convertFromCDS(&timeFromHK, &cdsShort); - CHECK(result == returnvalue::OK); - timeval difference = timeFromHK - now; - CHECK(timevalOperations::toDouble(difference) < 1.0); - } - - SECTION("VariableNotificationTest") { - /* Acquire subscription interface */ - ProvidesDataPoolSubscriptionIF* subscriptionIF = poolOwner->getSubscriptionInterface(); - REQUIRE(subscriptionIF != nullptr); - - /* Subscribe for variable update */ - REQUIRE(poolOwner->subscribeWrapperVariableUpdate(lpool::uint8VarId) == returnvalue::OK); - lp_var_t* poolVar = - dynamic_cast*>(poolOwner->getPoolObjectHandle(lpool::uint8VarId)); - REQUIRE(poolVar != nullptr); - poolVar->setChanged(true); - REQUIRE(poolVar->hasChanged() == true); - REQUIRE(poolOwner->poolManager.performHkOperation() == returnvalue::OK); - - /* Check update notification was sent. */ - REQUIRE(poolOwnerMock->wasMessageSent(&messagesSent) == true); - CHECK(messagesSent == 1); - /* Should have been reset. */ - CHECK(poolVar->hasChanged() == false); - REQUIRE(poolOwnerMock->receiveMessage(&messageSent) == returnvalue::OK); - CHECK(messageSent.getCommand() == - static_cast(HousekeepingMessage::UPDATE_NOTIFICATION_VARIABLE)); - /* Now subscribe for the dataset update (HK and update) again with subscription interface */ - REQUIRE(subscriptionIF->subscribeForSetUpdateMessage(lpool::testSetId, objects::NO_OBJECT, - objects::HK_RECEIVER_MOCK, - false) == returnvalue::OK); - REQUIRE(poolOwner->subscribeWrapperSetUpdateHk() == returnvalue::OK); - - poolOwner->dataset.setChanged(true); - REQUIRE(poolOwner->poolManager.performHkOperation() == returnvalue::OK); - /* Now two messages should be sent. */ - REQUIRE(poolOwnerMock->wasMessageSent(&messagesSent) == true); - CHECK(messagesSent == 2); - poolOwnerMock->clearMessages(true); - - poolOwner->dataset.setChanged(true); - poolVar->setChanged(true); - REQUIRE(poolOwner->poolManager.performHkOperation() == returnvalue::OK); - /* Now three messages should be sent. */ - REQUIRE(poolOwnerMock->wasMessageSent(&messagesSent) == true); - CHECK(messagesSent == 3); - REQUIRE(poolOwnerMock->receiveMessage(&messageSent) == returnvalue::OK); - CHECK(messageSent.getCommand() == - static_cast(HousekeepingMessage::UPDATE_NOTIFICATION_VARIABLE)); - REQUIRE(poolOwnerMock->receiveMessage(&messageSent) == returnvalue::OK); - CHECK(messageSent.getCommand() == - static_cast(HousekeepingMessage::UPDATE_NOTIFICATION_SET)); - REQUIRE(poolOwnerMock->receiveMessage(&messageSent) == returnvalue::OK); - CHECK(messageSent.getCommand() == static_cast(HousekeepingMessage::HK_REPORT)); - CommandMessageCleaner::clearCommandMessage(&messageSent); - REQUIRE(poolOwnerMock->receiveMessage(&messageSent) == static_cast(MessageQueueIF::EMPTY)); - } - - SECTION("PeriodicHKAndMessaging") { - /* Now we subcribe for a HK periodic generation. Even when it's difficult to simulate - the temporal behaviour correctly the HK manager should generate a HK packet - immediately and the periodic helper depends on HK op function calls anyway instead of - using the clock, so we could also just call performHkOperation multiple times */ - REQUIRE(poolOwner->subscribePeriodicHk(true) == returnvalue::OK); - REQUIRE(poolOwner->poolManager.performHkOperation() == returnvalue::OK); - /* Now HK packet should be sent as message immediately. */ - REQUIRE(poolOwnerMock->wasMessageSent(&messagesSent) == true); - CHECK(messagesSent == 1); - CHECK(poolOwnerMock->popMessage() == returnvalue::OK); - - LocalPoolDataSetBase* setHandle = poolOwner->getDataSetHandle(lpool::testSid); - REQUIRE(setHandle != nullptr); - CHECK(poolOwner->poolManager.generateHousekeepingPacket(lpool::testSid, setHandle, false) == - returnvalue::OK); - REQUIRE(poolOwnerMock->wasMessageSent(&messagesSent) == true); - CHECK(messagesSent == 1); - CHECK(poolOwnerMock->popMessage() == returnvalue::OK); - - CHECK(setHandle->getReportingEnabled() == true); - CommandMessage hkCmd; - HousekeepingMessage::setToggleReportingCommand(&hkCmd, lpool::testSid, false, false); - CHECK(poolOwner->poolManager.handleHousekeepingMessage(&hkCmd) == returnvalue::OK); - CHECK(setHandle->getReportingEnabled() == false); - REQUIRE(poolOwnerMock->wasMessageSent(&messagesSent) == true); - CHECK(messagesSent == 1); - CHECK(poolOwnerMock->popMessage() == returnvalue::OK); - - HousekeepingMessage::setToggleReportingCommand(&hkCmd, lpool::testSid, true, false); - CHECK(poolOwner->poolManager.handleHousekeepingMessage(&hkCmd) == returnvalue::OK); - CHECK(setHandle->getReportingEnabled() == true); - REQUIRE(poolOwnerMock->wasMessageSent(&messagesSent) == true); - CHECK(poolOwnerMock->popMessage() == returnvalue::OK); - - HousekeepingMessage::setToggleReportingCommand(&hkCmd, lpool::testSid, false, false); - CHECK(poolOwner->poolManager.handleHousekeepingMessage(&hkCmd) == returnvalue::OK); - CHECK(setHandle->getReportingEnabled() == false); - REQUIRE(poolOwnerMock->wasMessageSent(&messagesSent) == true); - CHECK(poolOwnerMock->popMessage() == returnvalue::OK); - - HousekeepingMessage::setCollectionIntervalModificationCommand(&hkCmd, lpool::testSid, 0.4, - false); - CHECK(poolOwner->poolManager.handleHousekeepingMessage(&hkCmd) == returnvalue::OK); - /* For non-diagnostics and a specified minimum frequency of 0.2 seconds, the - resulting collection interval should be 1.0 second */ - CHECK(poolOwner->dataset.getCollectionInterval() == 1.0); - REQUIRE(poolOwnerMock->wasMessageSent(&messagesSent) == true); - CHECK(messagesSent == 1); - CHECK(poolOwnerMock->popMessage() == returnvalue::OK); - - HousekeepingMessage::setStructureReportingCommand(&hkCmd, lpool::testSid, false); - REQUIRE(poolOwner->poolManager.performHkOperation() == returnvalue::OK); - CHECK(poolOwner->poolManager.handleHousekeepingMessage(&hkCmd) == returnvalue::OK); - /* Now HK packet should be sent as message. */ - REQUIRE(poolOwnerMock->wasMessageSent(&messagesSent) == true); - CHECK(messagesSent == 1); - CHECK(poolOwnerMock->popMessage() == returnvalue::OK); - - HousekeepingMessage::setOneShotReportCommand(&hkCmd, lpool::testSid, false); - CHECK(poolOwner->poolManager.handleHousekeepingMessage(&hkCmd) == returnvalue::OK); - REQUIRE(poolOwnerMock->wasMessageSent(&messagesSent) == true); - CHECK(messagesSent == 1); - CHECK(poolOwnerMock->popMessage() == returnvalue::OK); - - HousekeepingMessage::setUpdateNotificationSetCommand(&hkCmd, lpool::testSid); - sid_t sidToCheck; - store_address_t storeId; - CHECK(poolOwner->poolManager.handleHousekeepingMessage(&hkCmd) == returnvalue::OK); - CHECK(poolOwner->changedDataSetCallbackWasCalled(sidToCheck, storeId) == true); - CHECK(sidToCheck == lpool::testSid); - - /* Now we test the handling is the dataset is set to diagnostic */ - poolOwner->dataset.setDiagnostic(true); - - HousekeepingMessage::setStructureReportingCommand(&hkCmd, lpool::testSid, false); - CHECK(poolOwner->poolManager.handleHousekeepingMessage(&hkCmd) == - static_cast(LocalDataPoolManager::WRONG_HK_PACKET_TYPE)); - /* We still expect a failure message being sent */ - REQUIRE(poolOwnerMock->wasMessageSent(&messagesSent) == true); - CHECK(messagesSent == 1); - CHECK(poolOwnerMock->popMessage() == returnvalue::OK); - - HousekeepingMessage::setCollectionIntervalModificationCommand(&hkCmd, lpool::testSid, 0.4, - false); - CHECK(poolOwner->poolManager.handleHousekeepingMessage(&hkCmd) == - static_cast(LocalDataPoolManager::WRONG_HK_PACKET_TYPE)); - REQUIRE(poolOwnerMock->wasMessageSent(&messagesSent) == true); - CHECK(messagesSent == 1); - CHECK(poolOwnerMock->popMessage() == returnvalue::OK); - - HousekeepingMessage::setStructureReportingCommand(&hkCmd, lpool::testSid, false); - CHECK(poolOwner->poolManager.handleHousekeepingMessage(&hkCmd) == - static_cast(LocalDataPoolManager::WRONG_HK_PACKET_TYPE)); - REQUIRE(poolOwnerMock->wasMessageSent(&messagesSent) == true); - CHECK(messagesSent == 1); - CHECK(poolOwnerMock->popMessage() == returnvalue::OK); - - HousekeepingMessage::setStructureReportingCommand(&hkCmd, lpool::testSid, true); - CHECK(poolOwner->poolManager.handleHousekeepingMessage(&hkCmd) == returnvalue::OK); - REQUIRE(poolOwnerMock->wasMessageSent(&messagesSent) == true); - CHECK(messagesSent == 1); - CHECK(poolOwnerMock->popMessage() == returnvalue::OK); - - HousekeepingMessage::setCollectionIntervalModificationCommand(&hkCmd, lpool::testSid, 0.4, - true); - CHECK(poolOwner->poolManager.handleHousekeepingMessage(&hkCmd) == returnvalue::OK); - REQUIRE(poolOwnerMock->wasMessageSent(&messagesSent) == true); - CHECK(messagesSent == 1); - CHECK(poolOwnerMock->popMessage() == returnvalue::OK); - - HousekeepingMessage::setToggleReportingCommand(&hkCmd, lpool::testSid, true, true); - CHECK(poolOwner->poolManager.handleHousekeepingMessage(&hkCmd) == returnvalue::OK); - REQUIRE(poolOwnerMock->wasMessageSent(&messagesSent) == true); - CHECK(messagesSent == 1); - CHECK(poolOwnerMock->popMessage() == returnvalue::OK); - - HousekeepingMessage::setToggleReportingCommand(&hkCmd, lpool::testSid, false, true); - CHECK(poolOwner->poolManager.handleHousekeepingMessage(&hkCmd) == returnvalue::OK); - REQUIRE(poolOwnerMock->wasMessageSent(&messagesSent) == true); - CHECK(messagesSent == 1); - CHECK(poolOwnerMock->popMessage() == returnvalue::OK); - - HousekeepingMessage::setOneShotReportCommand(&hkCmd, lpool::testSid, false); - CHECK(poolOwner->poolManager.handleHousekeepingMessage(&hkCmd) == - static_cast(LocalDataPoolManager::WRONG_HK_PACKET_TYPE)); - REQUIRE(poolOwnerMock->wasMessageSent(&messagesSent) == true); - CHECK(messagesSent == 1); - CHECK(poolOwnerMock->popMessage() == returnvalue::OK); - - HousekeepingMessage::setOneShotReportCommand(&hkCmd, lpool::testSid, true); - CHECK(poolOwner->poolManager.handleHousekeepingMessage(&hkCmd) == returnvalue::OK); - REQUIRE(poolOwnerMock->wasMessageSent(&messagesSent) == true); - CHECK(messagesSent == 1); - CHECK(poolOwnerMock->popMessage() == returnvalue::OK); - - HousekeepingMessage::setUpdateNotificationVariableCommand(&hkCmd, lpool::uint8VarGpid); - gp_id_t gpidToCheck; - CHECK(poolOwner->poolManager.handleHousekeepingMessage(&hkCmd) == returnvalue::OK); - CHECK(poolOwner->changedVariableCallbackWasCalled(gpidToCheck, storeId) == true); - CHECK(gpidToCheck == lpool::uint8VarGpid); - - HousekeepingMessage::setUpdateSnapshotSetCommand(&hkCmd, lpool::testSid, - storeId::INVALID_STORE_ADDRESS); - CHECK(poolOwner->poolManager.handleHousekeepingMessage(&hkCmd) == returnvalue::OK); - CHECK(poolOwner->changedDataSetCallbackWasCalled(sidToCheck, storeId) == true); - CHECK(sidToCheck == lpool::testSid); - - HousekeepingMessage::setUpdateSnapshotVariableCommand(&hkCmd, lpool::uint8VarGpid, - storeId::INVALID_STORE_ADDRESS); - CHECK(poolOwner->poolManager.handleHousekeepingMessage(&hkCmd) == returnvalue::OK); - CHECK(poolOwner->changedVariableCallbackWasCalled(gpidToCheck, storeId) == true); - CHECK(gpidToCheck == lpool::uint8VarGpid); - - poolOwner->poolManager.printPoolEntry(lpool::uint8VarId); - } - - /* we need to reset the subscription list because the pool owner - is a global object. */ - CHECK(poolOwner->reset() == returnvalue::OK); - poolOwnerMock->clearMessages(true); -} diff --git a/unittests/datapoollocal/DataSetTest.cpp b/unittests/datapoollocal/testDataSet.cpp similarity index 91% rename from unittests/datapoollocal/DataSetTest.cpp rename to unittests/datapoollocal/testDataSet.cpp index 5ccae911..8bc0abb7 100644 --- a/unittests/datapoollocal/DataSetTest.cpp +++ b/unittests/datapoollocal/testDataSet.cpp @@ -9,15 +9,17 @@ #include #include "CatchDefinitions.h" -#include "LocalPoolOwnerBase.h" +#include "mocks/LocalPoolOwnerBase.h" +#include "mocks/MessageQueueMock.h" #include "tests/TestsConfig.h" +using namespace returnvalue; + TEST_CASE("DataSetTest", "[DataSetTest]") { - LocalPoolOwnerBase* poolOwner = - ObjectManager::instance()->get(objects::TEST_LOCAL_POOL_OWNER_BASE); - REQUIRE(poolOwner != nullptr); - REQUIRE(poolOwner->initializeHkManager() == returnvalue::OK); - REQUIRE(poolOwner->initializeHkManagerAfterTaskCreation() == returnvalue::OK); + auto queue = MessageQueueMock(1); + LocalPoolOwnerBase poolOwner(queue, objects::TEST_LOCAL_POOL_OWNER_BASE); + REQUIRE(poolOwner.initializeHkManager() == OK); + REQUIRE(poolOwner.initializeHkManagerAfterTaskCreation() == OK); LocalPoolStaticTestDataSet localSet; SECTION("BasicTest") { @@ -30,9 +32,9 @@ TEST_CASE("DataSetTest", "[DataSetTest]") { size_t maxSize = localSet.getLocalPoolIdsSerializedSize(true); uint8_t localPoolIdBuff[maxSize]; /* Skip size field */ - lp_id_t* lpIds = reinterpret_cast(localPoolIdBuff + 1); + auto* lpIds = reinterpret_cast(localPoolIdBuff + 1); size_t serSize = 0; - uint8_t* localPoolIdBuffPtr = reinterpret_cast(localPoolIdBuff); + auto* localPoolIdBuffPtr = reinterpret_cast(localPoolIdBuff); /* Test local pool ID serialization */ CHECK(localSet.serializeLocalPoolIds(&localPoolIdBuffPtr, &serSize, maxSize, @@ -47,8 +49,7 @@ TEST_CASE("DataSetTest", "[DataSetTest]") { localPoolIdBuffPtr = localPoolIdBuff; serSize = 0; CHECK(localSet.serializeLocalPoolIds(&localPoolIdBuffPtr, &serSize, maxSize, - SerializeIF::Endianness::MACHINE, - false) == returnvalue::OK); + SerializeIF::Endianness::MACHINE, false) == OK); CHECK(serSize == maxSize - sizeof(uint8_t)); CHECK(lpIds[0] == localSet.localPoolVarUint8.getDataPoolId()); CHECK(lpIds[1] == localSet.localPoolVarFloat.getDataPoolId()); @@ -200,7 +201,7 @@ TEST_CASE("DataSetTest", "[DataSetTest]") { } /* Common fault test cases */ - LocalPoolObjectBase* variableHandle = poolOwner->getPoolObjectHandle(lpool::uint32VarId); + LocalPoolObjectBase* variableHandle = poolOwner.getPoolObjectHandle(lpool::uint32VarId); CHECK(variableHandle != nullptr); CHECK(localSet.registerVariable(variableHandle) == static_cast(DataSetIF::DATA_SET_FULL)); variableHandle = nullptr; @@ -209,7 +210,7 @@ TEST_CASE("DataSetTest", "[DataSetTest]") { } SECTION("MorePoolVariables") { - LocalDataSet set(poolOwner, 2, 10); + LocalDataSet set(&poolOwner, 2, 10); /* Register same variables again to get more than 8 registered variables */ for (uint8_t idx = 0; idx < 8; idx++) { @@ -232,9 +233,8 @@ TEST_CASE("DataSetTest", "[DataSetTest]") { /* Already reserve additional space for validity buffer, will be needed later */ uint8_t buffer[maxSize + 1]; uint8_t* buffPtr = buffer; - CHECK(set.serialize(&buffPtr, &serSize, maxSize, SerializeIF::Endianness::MACHINE) == - returnvalue::OK); - std::array validityBuffer; + CHECK(set.serialize(&buffPtr, &serSize, maxSize, SerializeIF::Endianness::MACHINE) == OK); + std::array validityBuffer{}; std::memcpy(validityBuffer.data(), buffer + 9 + sizeof(uint16_t) * 3, 2); /* The first 9 variables should be valid */ CHECK(validityBuffer[0] == 0xff); @@ -258,7 +258,7 @@ TEST_CASE("DataSetTest", "[DataSetTest]") { SECTION("SharedDataSet") { object_id_t sharedSetId = objects::SHARED_SET_ID; - SharedLocalDataSet sharedSet(sharedSetId, poolOwner, lpool::testSetId, 5); + SharedLocalDataSet sharedSet(sharedSetId, &poolOwner, lpool::testSetId, 5); localSet.localPoolVarUint8.setReadWriteMode(pool_rwm_t::VAR_WRITE); localSet.localPoolUint16Vec.setReadWriteMode(pool_rwm_t::VAR_WRITE); CHECK(sharedSet.registerVariable(&localSet.localPoolVarUint8) == returnvalue::OK); @@ -269,7 +269,7 @@ TEST_CASE("DataSetTest", "[DataSetTest]") { { // PoolReadGuard rg(&sharedSet); - // CHECK(rg.getReadResult() == result::OK); + // CHECK(rg.getReadResult() == returnvalue::OK); localSet.localPoolVarUint8.value = 5; localSet.localPoolUint16Vec.value[0] = 1; localSet.localPoolUint16Vec.value[1] = 2; @@ -279,8 +279,4 @@ TEST_CASE("DataSetTest", "[DataSetTest]") { sharedSet.setReadCommitProtectionBehaviour(true); } - - /* we need to reset the subscription list because the pool owner - is a global object. */ - CHECK(poolOwner->reset() == returnvalue::OK); } diff --git a/unittests/datapoollocal/testLocalPoolManager.cpp b/unittests/datapoollocal/testLocalPoolManager.cpp new file mode 100644 index 00000000..91cd011d --- /dev/null +++ b/unittests/datapoollocal/testLocalPoolManager.cpp @@ -0,0 +1,429 @@ +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +#include "CatchDefinitions.h" +#include "mocks/HkReceiverMock.h" +#include "mocks/LocalPoolOwnerBase.h" + +TEST_CASE("Local Pool Manager Tests", "[LocManTest]") { + const MessageQueueId_t defaultDestId = 1; + const MessageQueueId_t hkDest = defaultDestId; + const MessageQueueId_t subscriberId = 2; + auto hkReceiver = HkReceiverMock(hkDest); + auto queue = MessageQueueMock(3); + LocalPoolOwnerBase poolOwner(queue, objects::TEST_LOCAL_POOL_OWNER_BASE); + REQUIRE(poolOwner.initializeHkManager() == returnvalue::OK); + REQUIRE(poolOwner.initializeHkManagerAfterTaskCreation() == returnvalue::OK); + + MessageQueueMock& poolOwnerMock = poolOwner.getMockQueueHandle(); + + // TODO: This is ugly. This should be an arbitrary ctor argument. Fix this in the pool + // manager + poolOwnerMock.setDefaultDestination(defaultDestId); + poolOwner.setHkDestId(hkDest); + + auto* hkMan = poolOwner.getHkManagerHandle(); + + CommandMessage messageSent; + + SECTION("Basic Test") { + { + /* For code coverage, should not crash */ + LocalDataPoolManager manager(nullptr, nullptr); + } + auto owner = poolOwner.poolManager.getOwner(); + REQUIRE(owner != nullptr); + CHECK(owner->getObjectId() == objects::TEST_LOCAL_POOL_OWNER_BASE); + + /* Subscribe for message generation on update. */ + REQUIRE(poolOwner.subscribeWrapperSetUpdate(subscriberId) == returnvalue::OK); + /* Subscribe for an update message. */ + poolOwner.dataset.setChanged(true); + /* Now the update message should be generated. */ + REQUIRE(poolOwner.poolManager.performHkOperation() == returnvalue::OK); + REQUIRE(poolOwnerMock.wasMessageSent()); + + REQUIRE(poolOwnerMock.getNextSentMessage(subscriberId, messageSent) == returnvalue::OK); + CHECK(messageSent.getCommand() == + static_cast(HousekeepingMessage::UPDATE_NOTIFICATION_SET)); + + /* Should have been reset. */ + CHECK(poolOwner.dataset.hasChanged() == false); + poolOwnerMock.clearMessages(true); + /* Set changed again, result should be the same. */ + poolOwner.dataset.setChanged(true); + REQUIRE(poolOwner.poolManager.performHkOperation() == returnvalue::OK); + + REQUIRE(poolOwnerMock.wasMessageSent() == true); + CHECK(poolOwnerMock.numberOfSentMessages() == 1); + REQUIRE(poolOwnerMock.getNextSentMessage(subscriberId, messageSent) == returnvalue::OK); + CHECK(messageSent.getCommand() == + static_cast(HousekeepingMessage::UPDATE_NOTIFICATION_SET)); + + poolOwnerMock.clearMessages(true); + /* Now subscribe for set update HK as well. */ + REQUIRE(poolOwner.subscribeWrapperSetUpdateHk(false, &hkReceiver) == returnvalue::OK); + poolOwner.dataset.setChanged(true); + REQUIRE(poolOwner.poolManager.performHkOperation() == returnvalue::OK); + REQUIRE(poolOwnerMock.wasMessageSent() == true); + CHECK(poolOwnerMock.numberOfSentMessages() == 2); + // first message sent should be the update notification + REQUIRE(poolOwnerMock.getNextSentMessage(subscriberId, messageSent) == returnvalue::OK); + CHECK(messageSent.getCommand() == + static_cast(HousekeepingMessage::UPDATE_NOTIFICATION_SET)); + REQUIRE(poolOwnerMock.getNextSentMessage(messageSent) == returnvalue::OK); + CHECK(messageSent.getCommand() == static_cast(HousekeepingMessage::HK_REPORT)); + /* Clear message to avoid memory leak, our mock won't do it for us (yet) */ + CommandMessageCleaner::clearCommandMessage(&messageSent); + } + + SECTION("SetSnapshotUpdateTest") { + /* Set the variables in the set to certain values. These are checked later. */ + { + PoolReadGuard readHelper(&poolOwner.dataset); + REQUIRE(readHelper.getReadResult() == returnvalue::OK); + poolOwner.dataset.localPoolVarUint8.value = 5; + poolOwner.dataset.localPoolVarFloat.value = -12.242; + poolOwner.dataset.localPoolUint16Vec.value[0] = 2; + poolOwner.dataset.localPoolUint16Vec.value[1] = 32; + poolOwner.dataset.localPoolUint16Vec.value[2] = 42932; + } + + /* Subscribe for snapshot generation on update. */ + REQUIRE(poolOwner.subscribeWrapperSetUpdateSnapshot(subscriberId) == returnvalue::OK); + poolOwner.dataset.setChanged(true); + + /* Store current time, we are going to check the (approximate) time equality later */ + timeval now{}; + Clock::getClock_timeval(&now); + + /* Trigger generation of snapshot */ + REQUIRE(poolOwner.poolManager.performHkOperation() == returnvalue::OK); + REQUIRE(poolOwnerMock.wasMessageSent()); + CHECK(poolOwnerMock.numberOfSentMessages() == 1); + REQUIRE(poolOwnerMock.getNextSentMessage(subscriberId, messageSent) == returnvalue::OK); + /* Check that snapshot was generated */ + CHECK(messageSent.getCommand() == static_cast(HousekeepingMessage::UPDATE_SNAPSHOT_SET)); + /* Now we deserialize the snapshot into a new dataset instance */ + CCSDSTime::CDS_short cdsShort{}; + LocalPoolTestDataSet newSet; + HousekeepingSnapshot snapshot(&cdsShort, &newSet); + store_address_t storeId; + HousekeepingMessage::getUpdateSnapshotSetCommand(&messageSent, &storeId); + ConstAccessorPair accessorPair = tglob::getIpcStoreHandle()->getData(storeId); + REQUIRE(accessorPair.first == returnvalue::OK); + const uint8_t* readOnlyPtr = accessorPair.second.data(); + size_t sizeToDeserialize = accessorPair.second.size(); + CHECK(newSet.localPoolVarFloat.value == 0); + CHECK(newSet.localPoolVarUint8 == 0); + CHECK(newSet.localPoolUint16Vec.value[0] == 0); + CHECK(newSet.localPoolUint16Vec.value[1] == 0); + CHECK(newSet.localPoolUint16Vec.value[2] == 0); + /* Fill the dataset and timestamp */ + REQUIRE(snapshot.deSerialize(&readOnlyPtr, &sizeToDeserialize, + SerializeIF::Endianness::MACHINE) == returnvalue::OK); + /* Now we check that the snapshot is actually correct */ + CHECK(newSet.localPoolVarFloat.value == Catch::Approx(-12.242)); + CHECK(newSet.localPoolVarUint8 == 5); + CHECK(newSet.localPoolUint16Vec.value[0] == 2); + CHECK(newSet.localPoolUint16Vec.value[1] == 32); + CHECK(newSet.localPoolUint16Vec.value[2] == 42932); + + /* Now we check that both times are equal */ + timeval timeFromHK{}; + auto result = CCSDSTime::convertFromCDS(&timeFromHK, &cdsShort); + CHECK(result == returnvalue::OK); + timeval difference = timeFromHK - now; + CHECK(timevalOperations::toDouble(difference) < 1.0); + } + + SECTION("VariableSnapshotTest") { + /* Acquire subscription interface */ + ProvidesDataPoolSubscriptionIF* subscriptionIF = poolOwner.getSubscriptionInterface(); + REQUIRE(subscriptionIF != nullptr); + + /* Subscribe for variable snapshot */ + REQUIRE(poolOwner.subscribeWrapperVariableSnapshot(subscriberId, lpool::uint8VarId) == + returnvalue::OK); + auto poolVar = + dynamic_cast*>(poolOwner.getPoolObjectHandle(lpool::uint8VarId)); + REQUIRE(poolVar != nullptr); + + { + PoolReadGuard rg(poolVar); + CHECK(rg.getReadResult() == returnvalue::OK); + poolVar->value = 25; + } + + poolVar->setChanged(true); + /* Store current time, we are going to check the (approximate) time equality later */ + CCSDSTime::CDS_short timeCdsNow{}; + timeval now{}; + Clock::getClock_timeval(&now); + REQUIRE(poolOwner.poolManager.performHkOperation() == returnvalue::OK); + + /* Check update snapshot was sent. */ + REQUIRE(poolOwnerMock.wasMessageSent()); + CHECK(poolOwnerMock.numberOfSentMessages() == 1); + + /* Should have been reset. */ + CHECK(poolVar->hasChanged() == false); + REQUIRE(poolOwnerMock.getNextSentMessage(subscriberId, messageSent) == returnvalue::OK); + CHECK(messageSent.getCommand() == + static_cast(HousekeepingMessage::UPDATE_SNAPSHOT_VARIABLE)); + /* Now we deserialize the snapshot into a new dataset instance */ + CCSDSTime::CDS_short cdsShort{}; + lp_var_t varCopy = lp_var_t(lpool::uint8VarGpid); + HousekeepingSnapshot snapshot(&cdsShort, &varCopy); + store_address_t storeId; + HousekeepingMessage::getUpdateSnapshotVariableCommand(&messageSent, &storeId); + ConstAccessorPair accessorPair = tglob::getIpcStoreHandle()->getData(storeId); + REQUIRE(accessorPair.first == returnvalue::OK); + const uint8_t* readOnlyPtr = accessorPair.second.data(); + size_t sizeToDeserialize = accessorPair.second.size(); + CHECK(varCopy.value == 0); + /* Fill the dataset and timestamp */ + REQUIRE(snapshot.deSerialize(&readOnlyPtr, &sizeToDeserialize, + SerializeIF::Endianness::MACHINE) == returnvalue::OK); + CHECK(varCopy.value == 25); + + /* Now we check that both times are equal */ + timeval timeFromHK{}; + auto result = CCSDSTime::convertFromCDS(&timeFromHK, &cdsShort); + CHECK(result == returnvalue::OK); + timeval difference = timeFromHK - now; + CHECK(timevalOperations::toDouble(difference) < 1.0); + } + + SECTION("VariableNotificationTest") { + /* Acquire subscription interface */ + ProvidesDataPoolSubscriptionIF* subscriptionIF = poolOwner.getSubscriptionInterface(); + REQUIRE(subscriptionIF != nullptr); + + /* Subscribe for variable update */ + REQUIRE(poolOwner.subscribeWrapperVariableUpdate(subscriberId, lpool::uint8VarId) == + returnvalue::OK); + auto* poolVar = + dynamic_cast*>(poolOwner.getPoolObjectHandle(lpool::uint8VarId)); + REQUIRE(poolVar != nullptr); + poolVar->setChanged(true); + REQUIRE(poolVar->hasChanged() == true); + REQUIRE(poolOwner.poolManager.performHkOperation() == returnvalue::OK); + + /* Check update notification was sent. */ + REQUIRE(poolOwnerMock.wasMessageSent()); + CHECK(poolOwnerMock.numberOfSentMessages() == 1); + /* Should have been reset. */ + CHECK(poolVar->hasChanged() == false); + REQUIRE(poolOwnerMock.getNextSentMessage(subscriberId, messageSent) == returnvalue::OK); + CHECK(messageSent.getCommand() == + static_cast(HousekeepingMessage::UPDATE_NOTIFICATION_VARIABLE)); + /* Now subscribe for the dataset update (HK and update) again with subscription interface */ + REQUIRE(subscriptionIF->subscribeForSetUpdateMessage(lpool::testSetId, objects::NO_OBJECT, + subscriberId, false) == returnvalue::OK); + REQUIRE(poolOwner.subscribeWrapperSetUpdateHk(false, &hkReceiver) == returnvalue::OK); + + poolOwner.dataset.setChanged(true); + poolOwnerMock.clearMessages(); + REQUIRE(poolOwner.poolManager.performHkOperation() == returnvalue::OK); + /* Now two messages should be sent. */ + REQUIRE(poolOwnerMock.wasMessageSent()); + CHECK(poolOwnerMock.numberOfSentMessages() == 2); + poolOwnerMock.clearMessages(true); + + poolOwner.dataset.setChanged(true); + poolOwnerMock.clearMessages(true); + poolVar->setChanged(true); + REQUIRE(poolOwner.poolManager.performHkOperation() == returnvalue::OK); + /* Now three messages should be sent. */ + REQUIRE(poolOwnerMock.wasMessageSent()); + CHECK(poolOwnerMock.numberOfSentMessages() == 3); + CHECK(poolOwnerMock.numberOfSentMessagesToDest(subscriberId) == 2); + CHECK(poolOwnerMock.numberOfSentMessagesToDest(hkDest) == 1); + REQUIRE(poolOwnerMock.getNextSentMessage(subscriberId, messageSent) == returnvalue::OK); + CHECK(messageSent.getCommand() == + static_cast(HousekeepingMessage::UPDATE_NOTIFICATION_VARIABLE)); + REQUIRE(poolOwnerMock.clearLastSentMessage(subscriberId) == returnvalue::OK); + REQUIRE(poolOwnerMock.getNextSentMessage(subscriberId, messageSent) == returnvalue::OK); + CHECK(messageSent.getCommand() == + static_cast(HousekeepingMessage::UPDATE_NOTIFICATION_SET)); + REQUIRE(poolOwnerMock.clearLastSentMessage(subscriberId) == returnvalue::OK); + REQUIRE(poolOwnerMock.getNextSentMessage(messageSent) == returnvalue::OK); + CHECK(messageSent.getCommand() == static_cast(HousekeepingMessage::HK_REPORT)); + REQUIRE(poolOwnerMock.clearLastSentMessage() == returnvalue::OK); + REQUIRE(poolOwnerMock.getNextSentMessage(subscriberId, messageSent) == MessageQueueIF::EMPTY); + REQUIRE(poolOwnerMock.getNextSentMessage(messageSent) == MessageQueueIF::EMPTY); + } + + SECTION("PeriodicHKAndMessaging") { + /* Now we subcribe for a HK periodic generation. Even when it's difficult to simulate + the temporal behaviour correctly the HK manager should generate a HK packet + immediately and the periodic helper depends on HK op function calls anyway instead of + using the clock, so we could also just call performHkOperation multiple times */ + REQUIRE(poolOwner.subscribePeriodicHk(true) == returnvalue::OK); + REQUIRE(poolOwner.poolManager.performHkOperation() == returnvalue::OK); + /* Now HK packet should be sent as message immediately. */ + REQUIRE(poolOwnerMock.wasMessageSent()); + CHECK(poolOwnerMock.numberOfSentMessages() == 1); + CHECK(poolOwnerMock.clearLastSentMessage() == returnvalue::OK); + + LocalPoolDataSetBase* setHandle = poolOwner.getDataSetHandle(lpool::testSid); + REQUIRE(setHandle != nullptr); + CHECK(poolOwner.poolManager.generateHousekeepingPacket(lpool::testSid, setHandle, false) == + returnvalue::OK); + REQUIRE(poolOwnerMock.wasMessageSent()); + CHECK(poolOwnerMock.numberOfSentMessages() == 1); + CHECK(poolOwnerMock.clearLastSentMessage() == returnvalue::OK); + + CHECK(setHandle->getReportingEnabled() == true); + CommandMessage hkCmd; + HousekeepingMessage::setToggleReportingCommand(&hkCmd, lpool::testSid, false, false); + CHECK(poolOwner.poolManager.handleHousekeepingMessage(&hkCmd) == returnvalue::OK); + CHECK(setHandle->getReportingEnabled() == false); + REQUIRE(poolOwnerMock.wasMessageSent()); + CHECK(poolOwnerMock.numberOfSentMessages() == 1); + CHECK(poolOwnerMock.clearLastSentMessage() == returnvalue::OK); + + HousekeepingMessage::setToggleReportingCommand(&hkCmd, lpool::testSid, true, false); + CHECK(poolOwner.poolManager.handleHousekeepingMessage(&hkCmd) == returnvalue::OK); + CHECK(setHandle->getReportingEnabled() == true); + REQUIRE(poolOwnerMock.wasMessageSent()); + CHECK(poolOwnerMock.clearLastSentMessage() == returnvalue::OK); + + HousekeepingMessage::setToggleReportingCommand(&hkCmd, lpool::testSid, false, false); + CHECK(poolOwner.poolManager.handleHousekeepingMessage(&hkCmd) == returnvalue::OK); + CHECK(setHandle->getReportingEnabled() == false); + REQUIRE(poolOwnerMock.wasMessageSent()); + CHECK(poolOwnerMock.clearLastSentMessage() == returnvalue::OK); + + HousekeepingMessage::setCollectionIntervalModificationCommand(&hkCmd, lpool::testSid, 0.4, + false); + CHECK(poolOwner.poolManager.handleHousekeepingMessage(&hkCmd) == returnvalue::OK); + /* For non-diagnostics and a specified minimum frequency of 0.2 seconds, the + resulting collection interval should be 1.0 second */ + CHECK(poolOwner.dataset.getCollectionInterval() == 1.0); + REQUIRE(poolOwnerMock.wasMessageSent()); + REQUIRE(poolOwnerMock.numberOfSentMessages() == 1); + CHECK(poolOwnerMock.clearLastSentMessage() == returnvalue::OK); + + HousekeepingMessage::setStructureReportingCommand(&hkCmd, lpool::testSid, false); + REQUIRE(poolOwner.poolManager.performHkOperation() == returnvalue::OK); + CHECK(poolOwner.poolManager.handleHousekeepingMessage(&hkCmd) == returnvalue::OK); + /* Now HK packet should be sent as message. */ + REQUIRE(poolOwnerMock.wasMessageSent()); + REQUIRE(poolOwnerMock.numberOfSentMessages() == 1); + poolOwnerMock.clearMessages(); + + HousekeepingMessage::setOneShotReportCommand(&hkCmd, lpool::testSid, false); + CHECK(poolOwner.poolManager.handleHousekeepingMessage(&hkCmd) == returnvalue::OK); + REQUIRE(poolOwnerMock.wasMessageSent()); + REQUIRE(poolOwnerMock.numberOfSentMessages() == 1); + poolOwnerMock.clearMessages(); + + HousekeepingMessage::setUpdateNotificationSetCommand(&hkCmd, lpool::testSid); + sid_t sidToCheck; + store_address_t storeId; + CHECK(poolOwner.poolManager.handleHousekeepingMessage(&hkCmd) == returnvalue::OK); + CHECK(poolOwner.changedDataSetCallbackWasCalled(sidToCheck, storeId) == true); + CHECK(sidToCheck == lpool::testSid); + + /* Now we test the handling is the dataset is set to diagnostic */ + poolOwner.dataset.setDiagnostic(true); + + HousekeepingMessage::setStructureReportingCommand(&hkCmd, lpool::testSid, false); + CHECK(poolOwner.poolManager.handleHousekeepingMessage(&hkCmd) == + static_cast(LocalDataPoolManager::WRONG_HK_PACKET_TYPE)); + /* We still expect a failure message being sent */ + REQUIRE(poolOwnerMock.wasMessageSent()); + REQUIRE(poolOwnerMock.numberOfSentMessages() == 1); + CHECK(poolOwnerMock.clearLastSentMessage() == returnvalue::OK); + + HousekeepingMessage::setCollectionIntervalModificationCommand(&hkCmd, lpool::testSid, 0.4, + false); + CHECK(poolOwner.poolManager.handleHousekeepingMessage(&hkCmd) == + static_cast(LocalDataPoolManager::WRONG_HK_PACKET_TYPE)); + REQUIRE(poolOwnerMock.wasMessageSent()); + REQUIRE(poolOwnerMock.numberOfSentMessages() == 1); + CHECK(poolOwnerMock.clearLastSentMessage() == returnvalue::OK); + + HousekeepingMessage::setStructureReportingCommand(&hkCmd, lpool::testSid, false); + CHECK(poolOwner.poolManager.handleHousekeepingMessage(&hkCmd) == + static_cast(LocalDataPoolManager::WRONG_HK_PACKET_TYPE)); + REQUIRE(poolOwnerMock.wasMessageSent()); + REQUIRE(poolOwnerMock.numberOfSentMessages() == 1); + CHECK(poolOwnerMock.clearLastSentMessage() == returnvalue::OK); + + HousekeepingMessage::setStructureReportingCommand(&hkCmd, lpool::testSid, true); + CHECK(poolOwner.poolManager.handleHousekeepingMessage(&hkCmd) == returnvalue::OK); + REQUIRE(poolOwnerMock.wasMessageSent()); + REQUIRE(poolOwnerMock.numberOfSentMessages() == 1); + poolOwnerMock.clearMessages(); + + HousekeepingMessage::setCollectionIntervalModificationCommand(&hkCmd, lpool::testSid, 0.4, + true); + CHECK(poolOwner.poolManager.handleHousekeepingMessage(&hkCmd) == returnvalue::OK); + REQUIRE(poolOwnerMock.wasMessageSent()); + REQUIRE(poolOwnerMock.numberOfSentMessages() == 1); + poolOwnerMock.clearMessages(); + + HousekeepingMessage::setToggleReportingCommand(&hkCmd, lpool::testSid, true, true); + CHECK(poolOwner.poolManager.handleHousekeepingMessage(&hkCmd) == returnvalue::OK); + REQUIRE(poolOwnerMock.wasMessageSent()); + REQUIRE(poolOwnerMock.numberOfSentMessages() == 1); + poolOwnerMock.clearMessages(); + + HousekeepingMessage::setToggleReportingCommand(&hkCmd, lpool::testSid, false, true); + CHECK(poolOwner.poolManager.handleHousekeepingMessage(&hkCmd) == returnvalue::OK); + REQUIRE(poolOwnerMock.wasMessageSent()); + REQUIRE(poolOwnerMock.numberOfSentMessages() == 1); + poolOwnerMock.clearMessages(); + + HousekeepingMessage::setOneShotReportCommand(&hkCmd, lpool::testSid, false); + CHECK(poolOwner.poolManager.handleHousekeepingMessage(&hkCmd) == + static_cast(LocalDataPoolManager::WRONG_HK_PACKET_TYPE)); + REQUIRE(poolOwnerMock.wasMessageSent()); + REQUIRE(poolOwnerMock.numberOfSentMessages() == 1); + poolOwnerMock.clearMessages(); + + HousekeepingMessage::setOneShotReportCommand(&hkCmd, lpool::testSid, true); + CHECK(poolOwner.poolManager.handleHousekeepingMessage(&hkCmd) == returnvalue::OK); + REQUIRE(poolOwnerMock.wasMessageSent()); + REQUIRE(poolOwnerMock.numberOfSentMessages() == 1); + poolOwnerMock.clearMessages(); + + HousekeepingMessage::setUpdateNotificationVariableCommand(&hkCmd, lpool::uint8VarGpid); + gp_id_t gpidToCheck; + CHECK(poolOwner.poolManager.handleHousekeepingMessage(&hkCmd) == returnvalue::OK); + CHECK(poolOwner.changedVariableCallbackWasCalled(gpidToCheck, storeId) == true); + CHECK(gpidToCheck == lpool::uint8VarGpid); + + HousekeepingMessage::setUpdateSnapshotSetCommand(&hkCmd, lpool::testSid, + store_address_t::invalid()); + CHECK(poolOwner.poolManager.handleHousekeepingMessage(&hkCmd) == returnvalue::OK); + CHECK(poolOwner.changedDataSetCallbackWasCalled(sidToCheck, storeId) == true); + CHECK(sidToCheck == lpool::testSid); + + HousekeepingMessage::setUpdateSnapshotVariableCommand(&hkCmd, lpool::uint8VarGpid, + store_address_t::invalid()); + CHECK(poolOwner.poolManager.handleHousekeepingMessage(&hkCmd) == returnvalue::OK); + CHECK(poolOwner.changedVariableCallbackWasCalled(gpidToCheck, storeId) == true); + CHECK(gpidToCheck == lpool::uint8VarGpid); + + poolOwner.poolManager.printPoolEntry(lpool::uint8VarId); + } + + /* we need to reset the subscription list because the pool owner + is a global object. */ + CHECK(poolOwner.reset() == returnvalue::OK); + poolOwnerMock.clearMessages(true); +} diff --git a/unittests/datapoollocal/LocalPoolVariableTest.cpp b/unittests/datapoollocal/testLocalPoolVariable.cpp similarity index 92% rename from unittests/datapoollocal/LocalPoolVariableTest.cpp rename to unittests/datapoollocal/testLocalPoolVariable.cpp index ece01ca5..ce125029 100644 --- a/unittests/datapoollocal/LocalPoolVariableTest.cpp +++ b/unittests/datapoollocal/testLocalPoolVariable.cpp @@ -4,15 +4,16 @@ #include #include "CatchDefinitions.h" -#include "LocalPoolOwnerBase.h" +#include "mocks/LocalPoolOwnerBase.h" #include "tests/TestsConfig.h" +using namespace returnvalue; + TEST_CASE("LocalPoolVariable", "[LocPoolVarTest]") { - auto* poolOwner = - ObjectManager::instance()->get(objects::TEST_LOCAL_POOL_OWNER_BASE); - REQUIRE(poolOwner != nullptr); - REQUIRE(poolOwner->initializeHkManager() == returnvalue::OK); - REQUIRE(poolOwner->initializeHkManagerAfterTaskCreation() == returnvalue::OK); + auto queue = MessageQueueMock(1); + LocalPoolOwnerBase poolOwner(queue, objects::TEST_LOCAL_POOL_OWNER_BASE); + REQUIRE(poolOwner.initializeHkManager() == OK); + REQUIRE(poolOwner.initializeHkManagerAfterTaskCreation() == OK); SECTION("Basic Tests") { /* very basic test. */ @@ -106,6 +107,4 @@ TEST_CASE("LocalPoolVariable", "[LocPoolVarTest]") { lp_var_t invalidObjectVar2 = lp_var_t(globPoolId); lp_var_t invalidObjectVar3 = lp_var_t(nullptr, lpool::uint8VarId); } - - CHECK(poolOwner->reset() == returnvalue::OK); } diff --git a/unittests/datapoollocal/LocalPoolVectorTest.cpp b/unittests/datapoollocal/testLocalPoolVector.cpp similarity index 91% rename from unittests/datapoollocal/LocalPoolVectorTest.cpp rename to unittests/datapoollocal/testLocalPoolVector.cpp index fb75846b..69014e58 100644 --- a/unittests/datapoollocal/LocalPoolVectorTest.cpp +++ b/unittests/datapoollocal/testLocalPoolVector.cpp @@ -4,15 +4,16 @@ #include #include "CatchDefinitions.h" -#include "LocalPoolOwnerBase.h" +#include "mocks/LocalPoolOwnerBase.h" #include "tests/TestsConfig.h" +using namespace returnvalue; + TEST_CASE("LocalPoolVector", "[LocPoolVecTest]") { - LocalPoolOwnerBase* poolOwner = - ObjectManager::instance()->get(objects::TEST_LOCAL_POOL_OWNER_BASE); - REQUIRE(poolOwner != nullptr); - REQUIRE(poolOwner->initializeHkManager() == returnvalue::OK); - REQUIRE(poolOwner->initializeHkManagerAfterTaskCreation() == returnvalue::OK); + auto queue = MessageQueueMock(1); + LocalPoolOwnerBase poolOwner(queue, objects::TEST_LOCAL_POOL_OWNER_BASE); + REQUIRE(poolOwner.initializeHkManager() == OK); + REQUIRE(poolOwner.initializeHkManagerAfterTaskCreation() == OK); SECTION("BasicTest") { // very basic test. @@ -106,5 +107,4 @@ TEST_CASE("LocalPoolVector", "[LocPoolVecTest]") { objects::TEST_LOCAL_POOL_OWNER_BASE, lpool::uint16Vec3Id, nullptr, pool_rwm_t::VAR_READ); REQUIRE(readOnlyVec.commit() == static_cast(PoolVariableIF::INVALID_READ_WRITE_MODE)); } - poolOwner->reset(); } diff --git a/unittests/devicehandler/CMakeLists.txt b/unittests/devicehandler/CMakeLists.txt index 7ad5d316..5d4d9b06 100644 --- a/unittests/devicehandler/CMakeLists.txt +++ b/unittests/devicehandler/CMakeLists.txt @@ -1,8 +1,4 @@ target_sources(${FSFW_TEST_TGT} PRIVATE - CookieIFMock.cpp - ComIFMock.cpp DeviceHandlerCommander.cpp - DeviceHandlerMock.cpp - DeviceFdirMock.cpp TestDeviceHandlerBase.cpp ) diff --git a/unittests/devicehandler/TestDeviceHandlerBase.cpp b/unittests/devicehandler/TestDeviceHandlerBase.cpp index afa9d2ba..67c3cdaf 100644 --- a/unittests/devicehandler/TestDeviceHandlerBase.cpp +++ b/unittests/devicehandler/TestDeviceHandlerBase.cpp @@ -1,10 +1,10 @@ #include -#include "ComIFMock.h" -#include "DeviceFdirMock.h" #include "DeviceHandlerCommander.h" -#include "DeviceHandlerMock.h" -#include "devicehandler/CookieIFMock.h" +#include "mocks/ComIFMock.h" +#include "mocks/CookieIFMock.h" +#include "mocks/DeviceFdirMock.h" +#include "mocks/DeviceHandlerMock.h" #include "objects/systemObjectList.h" TEST_CASE("Device Handler Base", "[DeviceHandlerBase]") { diff --git a/unittests/hal/testCommandExecutor.cpp b/unittests/hal/testCommandExecutor.cpp index 04576f85..aecadd1b 100644 --- a/unittests/hal/testCommandExecutor.cpp +++ b/unittests/hal/testCommandExecutor.cpp @@ -78,7 +78,7 @@ TEST_CASE("Command Executor", "[cmd-exec]") { REQUIRE(result != CommandExecutor::COMMAND_ERROR); // This ensures that the tests do not block indefinitely usleep(500); - REQUIRE(limitIdx < 500); + REQUIRE(limitIdx < 50000); } limitIdx = 0; CHECK(bytesHaveBeenRead == true); diff --git a/unittests/internalerror/TestInternalErrorReporter.cpp b/unittests/internalerror/TestInternalErrorReporter.cpp index a23658c0..4562bab4 100644 --- a/unittests/internalerror/TestInternalErrorReporter.cpp +++ b/unittests/internalerror/TestInternalErrorReporter.cpp @@ -33,7 +33,7 @@ TEST_CASE("Internal Error Reporter", "[TestInternalError]") { MessageQueueIF* hkQueue = QueueFactory::instance()->createMessageQueue(1); internalErrorReporter->getSubscriptionInterface()->subscribeForSetUpdateMessage( InternalErrorDataset::ERROR_SET_ID, objects::NO_OBJECT, hkQueue->getId(), true); - StorageManagerIF* ipcStore = ObjectManager::instance()->get(objects::IPC_STORE); + auto* ipcStore = ObjectManager::instance()->get(objects::IPC_STORE); SECTION("MessageQueueFull") { CommandMessage message; ActionMessage::setCompletionReply(&message, 10, true); @@ -57,7 +57,7 @@ TEST_CASE("Internal Error Reporter", "[TestInternalError]") { REQUIRE(gpid.objectId == objects::INTERNAL_ERROR_REPORTER); // We need the object ID of the reporter here (NO_OBJECT) InternalErrorDataset dataset(objects::INTERNAL_ERROR_REPORTER); - CCSDSTime::CDS_short time; + CCSDSTime::CDS_short time{}; ConstAccessorPair data = ipcStore->getData(storeAddress); REQUIRE(data.first == returnvalue::OK); HousekeepingSnapshot hkSnapshot(&time, &dataset); @@ -107,10 +107,10 @@ TEST_CASE("Internal Error Reporter", "[TestInternalError]") { // Message Queue Id MessageQueueId_t id = internalErrorReporter->getCommandQueue(); REQUIRE(id != MessageQueueIF::NO_QUEUE); - CommandMessage message; + CommandMessage message2; sid_t sid(objects::INTERNAL_ERROR_REPORTER, InternalErrorDataset::ERROR_SET_ID); - HousekeepingMessage::setToggleReportingCommand(&message, sid, true, false); - result = hkQueue->sendMessage(id, &message); + HousekeepingMessage::setToggleReportingCommand(&message2, sid, true, false); + result = hkQueue->sendMessage(id, &message2); REQUIRE(result == returnvalue::OK); internalErrorReporter->performOperation(0); } diff --git a/unittests/mocks/AcceptsTmMock.cpp b/unittests/mocks/AcceptsTmMock.cpp new file mode 100644 index 00000000..5b1e0d05 --- /dev/null +++ b/unittests/mocks/AcceptsTmMock.cpp @@ -0,0 +1,11 @@ +#include "AcceptsTmMock.h" + +AcceptsTmMock::AcceptsTmMock(object_id_t registeredId, MessageQueueId_t queueToReturn) + : SystemObject(registeredId), returnedQueue(queueToReturn) {} + +AcceptsTmMock::AcceptsTmMock(MessageQueueId_t queueToReturn) + : SystemObject(objects::NO_OBJECT, false), returnedQueue(queueToReturn) {} + +MessageQueueId_t AcceptsTmMock::getReportReceptionQueue(uint8_t virtualChannel) { + return returnedQueue; +} diff --git a/unittests/mocks/AcceptsTmMock.h b/unittests/mocks/AcceptsTmMock.h new file mode 100644 index 00000000..a9422eb4 --- /dev/null +++ b/unittests/mocks/AcceptsTmMock.h @@ -0,0 +1,16 @@ +#ifndef FSFW_TESTS_ACCEPTSTMMOCK_H +#define FSFW_TESTS_ACCEPTSTMMOCK_H + +#include "fsfw/objectmanager/SystemObject.h" +#include "fsfw/tmtcservices/AcceptsTelemetryIF.h" + +class AcceptsTmMock : public SystemObject, public AcceptsTelemetryIF { + public: + AcceptsTmMock(object_id_t registeredId, MessageQueueId_t queueToReturn); + explicit AcceptsTmMock(MessageQueueId_t queueToReturn); + + MessageQueueId_t getReportReceptionQueue(uint8_t virtualChannel) override; + + MessageQueueId_t returnedQueue; +}; +#endif // FSFW_TESTS_ACCEPTSTMMOCK_H diff --git a/unittests/mocks/CMakeLists.txt b/unittests/mocks/CMakeLists.txt index 1b86547c..f3b50f62 100644 --- a/unittests/mocks/CMakeLists.txt +++ b/unittests/mocks/CMakeLists.txt @@ -1,3 +1,14 @@ target_sources(${FSFW_TEST_TGT} PRIVATE PowerSwitcherMock.cpp + DeviceHandlerMock.cpp + DeviceFdirMock.cpp + CookieIFMock.cpp + ComIFMock.cpp + MessageQueueMock.cpp + InternalErrorReporterMock.cpp + LocalPoolOwnerBase.cpp + PusVerificationReporterMock.cpp + PusServiceBaseMock.cpp + AcceptsTmMock.cpp + PusDistributorMock.cpp ) diff --git a/unittests/mocks/CdsShortTimestamperMock.h b/unittests/mocks/CdsShortTimestamperMock.h new file mode 100644 index 00000000..ca7a674c --- /dev/null +++ b/unittests/mocks/CdsShortTimestamperMock.h @@ -0,0 +1,86 @@ +#ifndef FSFW_TESTS_CDSSHORTTIMESTAMPERMOCK_H +#define FSFW_TESTS_CDSSHORTTIMESTAMPERMOCK_H + +#include + +#include "fsfw/timemanager/TimeReaderIF.h" +#include "fsfw/timemanager/TimeStamperIF.h" + +class CdsShortTimestamperMock : public TimeStamperIF, public TimeReaderIF { + public: + unsigned int serializeCallCount = 0; + unsigned int deserializeCallCount = 0; + ReturnValue_t lastDeserializeResult = returnvalue::OK; + ReturnValue_t lastSerializeResult = returnvalue::OK; + unsigned int getSizeCallCount = 0; + bool nextSerFails = false; + ReturnValue_t serFailRetval = returnvalue::FAILED; + bool nextDeserFails = false; + ReturnValue_t deserFailRetval = returnvalue::FAILED; + std::array valueToStamp{}; + + CdsShortTimestamperMock() = default; + + explicit CdsShortTimestamperMock(std::array valueToStamp) + : valueToStamp(valueToStamp) {} + + ReturnValue_t serialize(uint8_t **buffer, size_t *size, size_t maxSize, + Endianness streamEndianness) const override { + auto &thisNonConst = const_cast(*this); + thisNonConst.serializeCallCount += 1; + if (nextSerFails) { + return serFailRetval; + } + if (*size + getSerializedSize() > maxSize) { + thisNonConst.lastSerializeResult = SerializeIF::BUFFER_TOO_SHORT; + return lastSerializeResult; + } + std::copy(valueToStamp.begin(), valueToStamp.end(), *buffer); + thisNonConst.lastSerializeResult = returnvalue::OK; + *buffer += getSerializedSize(); + *size += getSerializedSize(); + return lastSerializeResult; + } + [[nodiscard]] size_t getSerializedSize() const override { + auto &thisNonConst = const_cast(*this); + thisNonConst.getSizeCallCount += 1; + return valueToStamp.size(); + } + ReturnValue_t deSerialize(const uint8_t **buffer, size_t *size, + Endianness streamEndianness) override { + deserializeCallCount += 1; + if (nextDeserFails) { + return deserFailRetval; + } + if (*size < 7) { + lastDeserializeResult = SerializeIF::STREAM_TOO_SHORT; + return lastDeserializeResult; + } + std::copy(*buffer, *buffer + getSerializedSize(), valueToStamp.begin()); + return lastDeserializeResult; + } + + [[nodiscard]] size_t getTimestampSize() const override { return getSerializedSize(); } + ReturnValue_t addTimeStamp(uint8_t *buffer, uint8_t maxSize) override { return 0; } + + void reset() { + serializeCallCount = 0; + getSizeCallCount = 0; + deserializeCallCount = 0; + nextSerFails = false; + nextDeserFails = false; + lastSerializeResult = returnvalue::OK; + lastDeserializeResult = returnvalue::OK; + deserFailRetval = returnvalue::FAILED; + serFailRetval = returnvalue::FAILED; + } + + ReturnValue_t readTimeStamp(const uint8_t *buffer, size_t maxSize) override { + return deSerialize(&buffer, &maxSize, SerializeIF::Endianness::NETWORK); + } + timeval &getTime() override { return dummyTime; } + + private: + timeval dummyTime{}; +}; +#endif // FSFW_TESTS_CDSSHORTTIMESTAMPERMOCK_H diff --git a/unittests/devicehandler/ComIFMock.cpp b/unittests/mocks/ComIFMock.cpp similarity index 100% rename from unittests/devicehandler/ComIFMock.cpp rename to unittests/mocks/ComIFMock.cpp diff --git a/unittests/devicehandler/ComIFMock.h b/unittests/mocks/ComIFMock.h similarity index 100% rename from unittests/devicehandler/ComIFMock.h rename to unittests/mocks/ComIFMock.h diff --git a/unittests/devicehandler/CookieIFMock.cpp b/unittests/mocks/CookieIFMock.cpp similarity index 100% rename from unittests/devicehandler/CookieIFMock.cpp rename to unittests/mocks/CookieIFMock.cpp diff --git a/unittests/devicehandler/CookieIFMock.h b/unittests/mocks/CookieIFMock.h similarity index 100% rename from unittests/devicehandler/CookieIFMock.h rename to unittests/mocks/CookieIFMock.h diff --git a/unittests/devicehandler/DeviceFdirMock.cpp b/unittests/mocks/DeviceFdirMock.cpp similarity index 86% rename from unittests/devicehandler/DeviceFdirMock.cpp rename to unittests/mocks/DeviceFdirMock.cpp index e3ac39ac..5dcd985d 100644 --- a/unittests/devicehandler/DeviceFdirMock.cpp +++ b/unittests/mocks/DeviceFdirMock.cpp @@ -1,11 +1,9 @@ #include "DeviceFdirMock.h" -#include "devicehandler/DeviceFdirMock.h" - DeviceFdirMock::DeviceFdirMock(object_id_t owner, object_id_t parent) : DeviceHandlerFailureIsolation(owner, parent) {} -DeviceFdirMock::~DeviceFdirMock() {} +DeviceFdirMock::~DeviceFdirMock() = default; uint32_t DeviceFdirMock::getMissedReplyCount() { ParameterWrapper parameterWrapper; diff --git a/unittests/devicehandler/DeviceFdirMock.h b/unittests/mocks/DeviceFdirMock.h similarity index 100% rename from unittests/devicehandler/DeviceFdirMock.h rename to unittests/mocks/DeviceFdirMock.h diff --git a/unittests/devicehandler/DeviceHandlerMock.cpp b/unittests/mocks/DeviceHandlerMock.cpp similarity index 98% rename from unittests/devicehandler/DeviceHandlerMock.cpp rename to unittests/mocks/DeviceHandlerMock.cpp index 3992d09c..ef0a23d8 100644 --- a/unittests/devicehandler/DeviceHandlerMock.cpp +++ b/unittests/mocks/DeviceHandlerMock.cpp @@ -8,7 +8,7 @@ DeviceHandlerMock::DeviceHandlerMock(object_id_t objectId, object_id_t deviceCom mode = MODE_ON; } -DeviceHandlerMock::~DeviceHandlerMock() {} +DeviceHandlerMock::~DeviceHandlerMock() = default; void DeviceHandlerMock::doStartUp() { setMode(_MODE_TO_ON); } diff --git a/unittests/devicehandler/DeviceHandlerMock.h b/unittests/mocks/DeviceHandlerMock.h similarity index 100% rename from unittests/devicehandler/DeviceHandlerMock.h rename to unittests/mocks/DeviceHandlerMock.h diff --git a/unittests/mocks/HkReceiverMock.h b/unittests/mocks/HkReceiverMock.h index 8d4b4983..33a43a81 100644 --- a/unittests/mocks/HkReceiverMock.h +++ b/unittests/mocks/HkReceiverMock.h @@ -2,13 +2,15 @@ #define FSFW_UNITTEST_TESTS_MOCKS_HKRECEIVERMOCK_H_ #include -#include -class HkReceiverMock : public SystemObject, public AcceptsHkPacketsIF { +class HkReceiverMock : public AcceptsHkPacketsIF { public: - HkReceiverMock(object_id_t objectId) : SystemObject(objectId) {} + explicit HkReceiverMock(MessageQueueId_t queueId) : queueId(queueId) {} - MessageQueueId_t getHkQueue() const { return MessageQueueIF::NO_QUEUE; } + [[nodiscard]] MessageQueueId_t getHkQueue() const override { return queueId; } + + private: + MessageQueueId_t queueId; }; #endif /* FSFW_UNITTEST_TESTS_MOCKS_HKRECEIVERMOCK_H_ */ diff --git a/unittests/mocks/InternalErrorReporterMock.cpp b/unittests/mocks/InternalErrorReporterMock.cpp new file mode 100644 index 00000000..f53a1ed4 --- /dev/null +++ b/unittests/mocks/InternalErrorReporterMock.cpp @@ -0,0 +1,13 @@ +#include "InternalErrorReporterMock.h" + +InternalErrorReporterMock::InternalErrorReporterMock() = default; + +void InternalErrorReporterMock::queueMessageNotSent() { queueMsgNotSentCallCnt++; } +void InternalErrorReporterMock::lostTm() { lostTmCallCnt++; } +void InternalErrorReporterMock::storeFull() { storeFullCallCnt++; } + +void InternalErrorReporterMock::reset() { + queueMsgNotSentCallCnt = 0; + lostTmCallCnt = 0; + storeFullCallCnt = 0; +} diff --git a/unittests/mocks/InternalErrorReporterMock.h b/unittests/mocks/InternalErrorReporterMock.h new file mode 100644 index 00000000..e1ad35ae --- /dev/null +++ b/unittests/mocks/InternalErrorReporterMock.h @@ -0,0 +1,19 @@ +#ifndef FSFW_TESTS_INTERNALERRORREPORTERMOCK_H +#define FSFW_TESTS_INTERNALERRORREPORTERMOCK_H + +#include "fsfw/internalerror/InternalErrorReporterIF.h" + +class InternalErrorReporterMock : public InternalErrorReporterIF { + public: + unsigned int queueMsgNotSentCallCnt = 0; + unsigned int lostTmCallCnt = 0; + unsigned int storeFullCallCnt = 0; + InternalErrorReporterMock(); + void reset(); + + private: + void queueMessageNotSent() override; + void lostTm() override; + void storeFull() override; +}; +#endif // FSFW_TESTS_INTERNALERRORREPORTERMOCK_H diff --git a/unittests/datapoollocal/LocalPoolOwnerBase.cpp b/unittests/mocks/LocalPoolOwnerBase.cpp similarity index 79% rename from unittests/datapoollocal/LocalPoolOwnerBase.cpp rename to unittests/mocks/LocalPoolOwnerBase.cpp index 07ede256..e1f2f0c5 100644 --- a/unittests/datapoollocal/LocalPoolOwnerBase.cpp +++ b/unittests/mocks/LocalPoolOwnerBase.cpp @@ -1,18 +1,17 @@ #include "LocalPoolOwnerBase.h" -LocalPoolOwnerBase::LocalPoolOwnerBase(object_id_t objectId) - : SystemObject(objectId), poolManager(this, messageQueue), dataset(this, lpool::testSetId) { - messageQueue = new MessageQueueMockBase(); -} +LocalPoolOwnerBase::LocalPoolOwnerBase(MessageQueueIF &queue, object_id_t objectId) + : SystemObject(objectId), + queue(queue), + poolManager(this, &queue), + dataset(this, lpool::testSetId) {} -LocalPoolOwnerBase::~LocalPoolOwnerBase() { - QueueFactory::instance()->deleteMessageQueue(messageQueue); -} +LocalPoolOwnerBase::~LocalPoolOwnerBase() = default; ReturnValue_t LocalPoolOwnerBase::initializeHkManager() { if (not initialized) { initialized = true; - return poolManager.initialize(messageQueue); + return poolManager.initialize(&queue); } return returnvalue::OK; } @@ -20,12 +19,12 @@ ReturnValue_t LocalPoolOwnerBase::initializeHkManager() { ReturnValue_t LocalPoolOwnerBase::initializeLocalDataPool(localpool::DataPool &localDataPoolMap, LocalDataPoolManager &poolManager) { // Default initialization empty for now. - localDataPoolMap.emplace(lpool::uint8VarId, new PoolEntry({0})); - localDataPoolMap.emplace(lpool::floatVarId, new PoolEntry({0})); - localDataPoolMap.emplace(lpool::uint32VarId, new PoolEntry({0})); + localDataPoolMap.emplace(lpool::uint8VarId, &u8PoolEntry); + localDataPoolMap.emplace(lpool::floatVarId, &floatPoolEntry); + localDataPoolMap.emplace(lpool::uint32VarId, &u32PoolEntry); - localDataPoolMap.emplace(lpool::uint16Vec3Id, new PoolEntry({0, 0, 0})); - localDataPoolMap.emplace(lpool::int64Vec2Id, new PoolEntry({0, 0})); + localDataPoolMap.emplace(lpool::uint16Vec3Id, &u16VecPoolEntry); + localDataPoolMap.emplace(lpool::int64Vec2Id, &i64VecPoolEntry); return returnvalue::OK; } @@ -90,7 +89,7 @@ bool LocalPoolOwnerBase::changedDataSetCallbackWasCalled(sid_t &sid, store_addre sid = changedDatasetSid; storeId = storeIdForChangedSet; this->changedDatasetSid.raw = sid_t::INVALID_SID; - this->storeIdForChangedSet = storeId::INVALID_STORE_ADDRESS; + this->storeIdForChangedSet = store_address_t::invalid(); return condition; } @@ -108,7 +107,7 @@ bool LocalPoolOwnerBase::changedVariableCallbackWasCalled(gp_id_t &gpid, store_a gpid = changedPoolVariableGpid; storeId = storeIdForChangedVariable; this->changedPoolVariableGpid.raw = gp_id_t::INVALID_GPID; - this->storeIdForChangedVariable = storeId::INVALID_STORE_ADDRESS; + this->storeIdForChangedVariable = store_address_t::invalid(); return condition; } @@ -125,3 +124,5 @@ void LocalPoolOwnerBase::handleChangedPoolVariable(gp_id_t globPoolId, store_add this->changedPoolVariableGpid = globPoolId; this->storeIdForChangedVariable = storeId; } + +void LocalPoolOwnerBase::setHkDestId(MessageQueueId_t id) { poolManager.setHkDestinationId(id); } diff --git a/unittests/datapoollocal/LocalPoolOwnerBase.h b/unittests/mocks/LocalPoolOwnerBase.h similarity index 64% rename from unittests/datapoollocal/LocalPoolOwnerBase.h rename to unittests/mocks/LocalPoolOwnerBase.h index 0bcebc00..f1d1225f 100644 --- a/unittests/datapoollocal/LocalPoolOwnerBase.h +++ b/unittests/mocks/LocalPoolOwnerBase.h @@ -10,7 +10,8 @@ #include #include -#include "../mocks/MessageQueueMockBase.h" +#include "fsfw/datapool/PoolEntry.h" +#include "mocks/MessageQueueMock.h" #include "tests/TestsConfig.h" namespace lpool { @@ -64,26 +65,29 @@ class LocalPoolTestDataSet : public LocalDataSet { class LocalPoolOwnerBase : public SystemObject, public HasLocalDataPoolIF { public: - LocalPoolOwnerBase(object_id_t objectId = objects::TEST_LOCAL_POOL_OWNER_BASE); + explicit LocalPoolOwnerBase(MessageQueueIF& queue, + object_id_t objectId = objects::TEST_LOCAL_POOL_OWNER_BASE); - ~LocalPoolOwnerBase(); + ~LocalPoolOwnerBase() override; - object_id_t getObjectId() const override { return SystemObject::getObjectId(); } + [[nodiscard]] object_id_t getObjectId() const override { return SystemObject::getObjectId(); } ReturnValue_t initializeHkManager(); + void setHkDestId(MessageQueueId_t id); + ReturnValue_t initializeHkManagerAfterTaskCreation(); /** Command queue for housekeeping messages. */ - MessageQueueId_t getCommandQueue() const override { return messageQueue->getId(); } + [[nodiscard]] MessageQueueId_t getCommandQueue() const override { return queue.getId(); } // This is called by initializeAfterTaskCreation of the HK manager. - virtual ReturnValue_t initializeLocalDataPool(localpool::DataPool& localDataPoolMap, - LocalDataPoolManager& poolManager) override; + ReturnValue_t initializeLocalDataPool(localpool::DataPool& localDataPoolMap, + LocalDataPoolManager& poolManager) override; LocalDataPoolManager* getHkManagerHandle() override { return &poolManager; } - dur_millis_t getPeriodicOperationFrequency() const override { return 200; } + [[nodiscard]] dur_millis_t getPeriodicOperationFrequency() const override { return 200; } /** * This function is used by the pool manager to get a valid dataset @@ -91,41 +95,54 @@ class LocalPoolOwnerBase : public SystemObject, public HasLocalDataPoolIF { * @param sid Corresponding structure ID * @return */ - virtual LocalPoolDataSetBase* getDataSetHandle(sid_t sid) override { return &dataset; } + LocalPoolDataSetBase* getDataSetHandle(sid_t sid) override { return &dataset; } - virtual LocalPoolObjectBase* getPoolObjectHandle(lp_id_t localPoolId) override; + LocalPoolObjectBase* getPoolObjectHandle(lp_id_t localPoolId) override; - MessageQueueMockBase* getMockQueueHandle() const { - return dynamic_cast(messageQueue); + [[nodiscard]] MessageQueueMock& getMockQueueHandle() const { + return dynamic_cast(queue); } ReturnValue_t subscribePeriodicHk(bool enableReporting) { - return poolManager.subscribeForPeriodicPacket(lpool::testSid, enableReporting, 0.2, false); + return poolManager.subscribeForRegularPeriodicPacket( + subdp::RegularHkPeriodicParams(lpool::testSid, enableReporting, 0.2)); } - ReturnValue_t subscribeWrapperSetUpdate() { + ReturnValue_t subscribeWrapperSetUpdate(MessageQueueId_t receiverId) { return poolManager.subscribeForSetUpdateMessage(lpool::testSetId, objects::NO_OBJECT, - objects::HK_RECEIVER_MOCK, false); + receiverId, false); } - ReturnValue_t subscribeWrapperSetUpdateSnapshot() { + ReturnValue_t subscribeWrapperSetUpdateSnapshot(MessageQueueId_t receiverId) { return poolManager.subscribeForSetUpdateMessage(lpool::testSetId, objects::NO_OBJECT, - objects::HK_RECEIVER_MOCK, true); + receiverId, true); } - ReturnValue_t subscribeWrapperSetUpdateHk(bool diagnostics = false) { - return poolManager.subscribeForUpdatePacket(lpool::testSid, diagnostics, false, - objects::HK_RECEIVER_MOCK); + ReturnValue_t subscribeWrapperSetUpdateHk(bool diagnostics = false, + AcceptsHkPacketsIF* receiver = nullptr) { + if (diagnostics) { + auto params = subdp::DiagnosticsHkUpdateParams(lpool::testSid, true); + if (receiver != nullptr) { + params.receiver = receiver->getHkQueue(); + } + return poolManager.subscribeForDiagUpdatePacket(params); + } else { + auto params = subdp::RegularHkUpdateParams(lpool::testSid, true); + if (receiver != nullptr) { + params.receiver = receiver->getHkQueue(); + } + return poolManager.subscribeForRegularUpdatePacket(params); + } } - ReturnValue_t subscribeWrapperVariableUpdate(lp_id_t localPoolId) { + ReturnValue_t subscribeWrapperVariableUpdate(MessageQueueId_t receiverId, lp_id_t localPoolId) { return poolManager.subscribeForVariableUpdateMessage(localPoolId, MessageQueueIF::NO_QUEUE, - objects::HK_RECEIVER_MOCK, false); + receiverId, false); } - ReturnValue_t subscribeWrapperVariableSnapshot(lp_id_t localPoolId) { + ReturnValue_t subscribeWrapperVariableSnapshot(MessageQueueId_t receiverId, lp_id_t localPoolId) { return poolManager.subscribeForVariableUpdateMessage(localPoolId, MessageQueueIF::NO_QUEUE, - objects::HK_RECEIVER_MOCK, true); + receiverId, true); } ReturnValue_t reset(); @@ -148,14 +165,19 @@ class LocalPoolOwnerBase : public SystemObject, public HasLocalDataPoolIF { gp_id_t changedPoolVariableGpid; store_address_t storeIdForChangedVariable; + PoolEntry u8PoolEntry = PoolEntry({0}); + PoolEntry floatPoolEntry = PoolEntry({0}); + PoolEntry u32PoolEntry = PoolEntry({0}); + PoolEntry u16VecPoolEntry = PoolEntry({0, 0, 0}); + PoolEntry i64VecPoolEntry = PoolEntry({0, 0}); + lp_var_t testUint8 = lp_var_t(this, lpool::uint8VarId); lp_var_t testFloat = lp_var_t(this, lpool::floatVarId); lp_var_t testUint32 = lp_var_t(this, lpool::uint32VarId); - lp_vec_t testUint16Vec = lp_vec_t(this, lpool::uint16Vec3Id); lp_vec_t testInt64Vec = lp_vec_t(this, lpool::int64Vec2Id); - MessageQueueIF* messageQueue = nullptr; + MessageQueueIF& queue; bool initialized = false; bool initializedAfterTaskCreation = false; diff --git a/unittests/mocks/MessageQueueMock.cpp b/unittests/mocks/MessageQueueMock.cpp new file mode 100644 index 00000000..cac5a0d9 --- /dev/null +++ b/unittests/mocks/MessageQueueMock.cpp @@ -0,0 +1,173 @@ +#include "MessageQueueMock.h" + +#include +#include + +MessageQueueMock::MessageQueueMock(MessageQueueId_t queueId) + : MessageQueueBase(queueId, MessageQueueIF::NO_QUEUE, nullptr) {} + +bool MessageQueueMock::wasMessageSent() const { + return std::any_of( + sendMap.begin(), sendMap.end(), + [](const std::pair& pair) { return pair.second.callCount > 0; }); +} + +size_t MessageQueueMock::numberOfSentMessages() const { + size_t callCount = 0; + for (auto& destInfo : sendMap) { + callCount += destInfo.second.callCount; + } + return callCount; +} + +size_t MessageQueueMock::numberOfSentMessagesToDest(MessageQueueId_t id) const { + auto iter = sendMap.find(id); + if (iter == sendMap.end()) { + return 0; + } + return iter->second.callCount; +} + +size_t MessageQueueMock::numberOfSentMessagesToDefault() const { + return numberOfSentMessagesToDest(MessageQueueBase::getDefaultDestination()); +} + +ReturnValue_t MessageQueueMock::clearLastReceivedMessage(bool clearCmdMsg) { + if (receivedMsgs.empty()) { + return MessageQueueIF::EMPTY; + } + if (clearCmdMsg) { + CommandMessage message; + std::memcpy(message.getBuffer(), receivedMsgs.front().getBuffer(), message.getMessageSize()); + message.clearCommandMessage(); + } + receivedMsgs.pop(); + return returnvalue::OK; +} + +ReturnValue_t MessageQueueMock::receiveMessage(MessageQueueMessageIF* message) { + if (receivedMsgs.empty()) { + return MessageQueueIF::EMPTY; + } + std::memcpy(message->getBuffer(), receivedMsgs.front().getBuffer(), message->getMessageSize()); + receivedMsgs.pop(); + return returnvalue::OK; +} + +ReturnValue_t MessageQueueMock::flush(uint32_t* count) { return returnvalue::FAILED; } + +ReturnValue_t MessageQueueMock::sendMessageFrom(MessageQueueId_t sendTo, + MessageQueueMessageIF* message, + MessageQueueId_t sentFrom, bool ignoreFault) { + if (message == nullptr) { + return returnvalue::FAILED; + } + if (nextSendFailsPair.first) { + nextSendFailsPair.first = false; + return nextSendFailsPair.second; + } + auto iter = sendMap.find(sendTo); + MessageQueueMessage messageCopy; + if (iter == sendMap.end()) { + createMsgCopy(messageCopy, *message); + sendMap.emplace(sendTo, SendInfo(messageCopy, 1)); + } else { + iter->second.callCount += 1; + createMsgCopy(messageCopy, *message); + iter->second.msgs.push(messageCopy); + } + return returnvalue::OK; +} + +ReturnValue_t MessageQueueMock::reply(MessageQueueMessageIF* message) { + return sendMessageFrom(MessageQueueIF::NO_QUEUE, message, this->getId(), false); +} + +void MessageQueueMock::clearMessages(bool clearCommandMessages) { + if (not clearCommandMessages) { + sendMap.clear(); + return; + } + for (auto& destInfo : sendMap) { + while (!destInfo.second.msgs.empty()) { + CommandMessage message; + std::memcpy(message.getBuffer(), destInfo.second.msgs.front().getBuffer(), + message.getMessageSize()); + message.clear(); + destInfo.second.msgs.pop(); + destInfo.second.callCount--; + } + } + sendMap.clear(); +} + +void MessageQueueMock::addReceivedMessage(MessageQueueMessageIF& msg) { + MessageQueueMessage messageCopy; + createMsgCopy(messageCopy, msg); + receivedMsgs.push(messageCopy); +} + +void MessageQueueMock::createMsgCopy(MessageQueueMessageIF& into, MessageQueueMessageIF& from) { + if (from.getMessageSize() > into.getMaximumDataSize()) { + throw std::invalid_argument("Passed message does not fit into message copy"); + } + std::memcpy(into.getBuffer(), from.getBuffer(), from.getMaximumDataSize()); +} + +ReturnValue_t MessageQueueMock::getNextSentMessage(MessageQueueId_t id, + MessageQueueMessageIF& message) { + auto iter = sendMap.find(id); + if (iter == sendMap.end() or iter->second.callCount == 0) { + return MessageQueueIF::EMPTY; + } + createMsgCopy(message, iter->second.msgs.front()); + return returnvalue::OK; +} + +ReturnValue_t MessageQueueMock::getNextSentMessage(MessageQueueMessageIF& message) { + return getNextSentMessage(MessageQueueBase::getDefaultDestination(), message); +} + +ReturnValue_t MessageQueueMock::clearLastSentMessage(MessageQueueId_t destId, bool clearCmdMsg) { + auto iter = sendMap.find(destId); + if (iter == sendMap.end()) { + return MessageQueueIF::EMPTY; + } + return clearLastSentMessage(iter, clearCmdMsg); +} + +ReturnValue_t MessageQueueMock::clearLastSentMessage(bool clearCmdMsg) { + auto iter = sendMap.find(getDefaultDestination()); + if (iter == sendMap.end()) { + return MessageQueueIF::EMPTY; + } + ReturnValue_t result = clearLastSentMessage(iter, clearCmdMsg); + clearEmptyEntries(); + return result; +} + +ReturnValue_t MessageQueueMock::clearLastSentMessage( + std::map::iterator& iter, bool clearCmdMsg) { + if (clearCmdMsg) { + CommandMessage message; + std::memcpy(message.getBuffer(), iter->second.msgs.front().getBuffer(), + message.getMessageSize()); + message.clear(); + } + iter->second.msgs.pop(); + iter->second.callCount--; + return returnvalue::OK; +} +void MessageQueueMock::clearEmptyEntries() { + for (auto it = sendMap.cbegin(); it != sendMap.cend();) { + if (it->second.callCount == 0) { + sendMap.erase(it++); + } else { + ++it; + } + } +} +void MessageQueueMock::makeNextSendFail(ReturnValue_t retval) { + nextSendFailsPair.first = true; + nextSendFailsPair.second = retval; +} diff --git a/unittests/mocks/MessageQueueMock.h b/unittests/mocks/MessageQueueMock.h new file mode 100644 index 00000000..52ba5dfe --- /dev/null +++ b/unittests/mocks/MessageQueueMock.h @@ -0,0 +1,64 @@ +#ifndef FSFW_UNITTEST_TESTS_MOCKS_MESSAGEQUEUEMOCKBASE_H_ +#define FSFW_UNITTEST_TESTS_MOCKS_MESSAGEQUEUEMOCKBASE_H_ + +#include +#include +#include + +#include "CatchDefinitions.h" +#include "fsfw/ipc/CommandMessage.h" +#include "fsfw/ipc/MessageQueueBase.h" +#include "fsfw/ipc/MessageQueueIF.h" +#include "fsfw/ipc/MessageQueueMessage.h" + +struct SendInfo { + explicit SendInfo(MessageQueueMessage& initMsg, unsigned int initCallCnt = 1) + : callCount(initCallCnt) { + msgs.push(initMsg); + } + unsigned int callCount = 0; + std::queue msgs; +}; + +class MessageQueueMock : public MessageQueueBase { + public: + void addReceivedMessage(MessageQueueMessageIF& msg); + explicit MessageQueueMock(MessageQueueId_t queueId); + + //! Get next message which was sent to the default destination + ReturnValue_t getNextSentMessage(MessageQueueMessageIF& message); + //! Get message which was sent to a specific ID + ReturnValue_t getNextSentMessage(MessageQueueId_t id, MessageQueueMessageIF& message); + [[nodiscard]] bool wasMessageSent() const; + void makeNextSendFail(ReturnValue_t retval); + [[nodiscard]] size_t numberOfSentMessages() const; + [[nodiscard]] size_t numberOfSentMessagesToDefault() const; + [[nodiscard]] size_t numberOfSentMessagesToDest(MessageQueueId_t id) const; + /** + * Pop a message, clearing it in the process. + * @return + */ + ReturnValue_t clearLastReceivedMessage(bool clearCmdMsg = true); + + ReturnValue_t flush(uint32_t* count) override; + ReturnValue_t sendMessageFrom(MessageQueueId_t sendTo, MessageQueueMessageIF* message, + MessageQueueId_t sentFrom, bool ignoreFault = false) override; + ReturnValue_t reply(MessageQueueMessageIF* message) override; + + ReturnValue_t clearLastSentMessage(MessageQueueId_t destId, bool clearCmdMsg = true); + ReturnValue_t clearLastSentMessage(bool clearCmdMsg = true); + void clearMessages(bool clearCmdMsg = true); + + private: + using SendMap = std::map; + SendMap sendMap; + std::queue receivedMsgs; + std::pair nextSendFailsPair; + + void clearEmptyEntries(); + ReturnValue_t receiveMessage(MessageQueueMessageIF* message) override; + static ReturnValue_t clearLastSentMessage(SendMap::iterator& iter, bool clearCmdMsg = true); + static void createMsgCopy(MessageQueueMessageIF& into, MessageQueueMessageIF& from); +}; + +#endif /* FSFW_UNITTEST_TESTS_MOCKS_MESSAGEQUEUEMOCKBASE_H_ */ diff --git a/unittests/mocks/MessageQueueMockBase.h b/unittests/mocks/MessageQueueMockBase.h deleted file mode 100644 index 22f66a54..00000000 --- a/unittests/mocks/MessageQueueMockBase.h +++ /dev/null @@ -1,84 +0,0 @@ -#ifndef FSFW_UNITTEST_TESTS_MOCKS_MESSAGEQUEUEMOCKBASE_H_ -#define FSFW_UNITTEST_TESTS_MOCKS_MESSAGEQUEUEMOCKBASE_H_ - -#include -#include - -#include "CatchDefinitions.h" -#include "fsfw/ipc/CommandMessage.h" -#include "fsfw/ipc/MessageQueueBase.h" -#include "fsfw/ipc/MessageQueueIF.h" -#include "fsfw/ipc/MessageQueueMessage.h" - -class MessageQueueMockBase : public MessageQueueBase { - public: - MessageQueueMockBase() - : MessageQueueBase(MessageQueueIF::NO_QUEUE, MessageQueueIF::NO_QUEUE, nullptr) {} - - uint8_t messageSentCounter = 0; - bool messageSent = false; - - bool wasMessageSent(uint8_t* messageSentCounter = nullptr, bool resetCounter = true) { - bool tempMessageSent = messageSent; - messageSent = false; - if (messageSentCounter != nullptr) { - *messageSentCounter = this->messageSentCounter; - } - if (resetCounter) { - this->messageSentCounter = 0; - } - return tempMessageSent; - } - - /** - * Pop a message, clearing it in the process. - * @return - */ - ReturnValue_t popMessage() { - CommandMessage message; - message.clear(); - return receiveMessage(&message); - } - - virtual ReturnValue_t receiveMessage(MessageQueueMessageIF* message) override { - if (messagesSentQueue.empty()) { - return MessageQueueIF::EMPTY; - } - this->last = message->getSender(); - std::memcpy(message->getBuffer(), messagesSentQueue.front().getBuffer(), - message->getMessageSize()); - messagesSentQueue.pop(); - return returnvalue::OK; - } - virtual ReturnValue_t flush(uint32_t* count) { return returnvalue::OK; } - virtual ReturnValue_t sendMessageFrom(MessageQueueId_t sendTo, MessageQueueMessageIF* message, - MessageQueueId_t sentFrom, - bool ignoreFault = false) override { - messageSent = true; - messageSentCounter++; - MessageQueueMessage& messageRef = *(dynamic_cast(message)); - messagesSentQueue.push(messageRef); - return returnvalue::OK; - } - - virtual ReturnValue_t reply(MessageQueueMessageIF* message) override { - return sendMessageFrom(MessageQueueIF::NO_QUEUE, message, this->getId(), false); - } - - void clearMessages(bool clearCommandMessages = true) { - while (not messagesSentQueue.empty()) { - if (clearCommandMessages) { - CommandMessage message; - std::memcpy(message.getBuffer(), messagesSentQueue.front().getBuffer(), - message.getMessageSize()); - message.clear(); - } - messagesSentQueue.pop(); - } - } - - private: - std::queue messagesSentQueue; -}; - -#endif /* FSFW_UNITTEST_TESTS_MOCKS_MESSAGEQUEUEMOCKBASE_H_ */ diff --git a/unittests/mocks/PusDistributorMock.cpp b/unittests/mocks/PusDistributorMock.cpp new file mode 100644 index 00000000..625dffc5 --- /dev/null +++ b/unittests/mocks/PusDistributorMock.cpp @@ -0,0 +1,12 @@ +#include "PusDistributorMock.h" + +PusDistributorMock::PusDistributorMock() : SystemObject(objects::NO_OBJECT, false) {} + +PusDistributorMock::PusDistributorMock(object_id_t registeredId) + : SystemObject(registeredId, true) {} + +ReturnValue_t PusDistributorMock::registerService(AcceptsTelecommandsIF *service) { + registerCallCount++; + lastServiceArg = service; + return returnvalue::OK; +} diff --git a/unittests/mocks/PusDistributorMock.h b/unittests/mocks/PusDistributorMock.h new file mode 100644 index 00000000..d5c7d96f --- /dev/null +++ b/unittests/mocks/PusDistributorMock.h @@ -0,0 +1,16 @@ +#ifndef FSFW_TESTS_PUSDISTRIBUTORMOCK_H +#define FSFW_TESTS_PUSDISTRIBUTORMOCK_H + +#include "fsfw/objectmanager/SystemObject.h" +#include "fsfw/tcdistribution/PUSDistributorIF.h" + +class PusDistributorMock : public SystemObject, public PUSDistributorIF { + public: + PusDistributorMock(); + explicit PusDistributorMock(object_id_t registeredId); + unsigned int registerCallCount = 0; + AcceptsTelecommandsIF* lastServiceArg = nullptr; + ReturnValue_t registerService(AcceptsTelecommandsIF* service) override; +}; + +#endif // FSFW_TESTS_PUSDISTRIBUTORMOCK_H diff --git a/unittests/mocks/PusServiceBaseMock.cpp b/unittests/mocks/PusServiceBaseMock.cpp new file mode 100644 index 00000000..91e745e9 --- /dev/null +++ b/unittests/mocks/PusServiceBaseMock.cpp @@ -0,0 +1,53 @@ +#include "PusServiceBaseMock.h" + +PsbMock::PsbMock(PsbParams params) : PusServiceBase(params) {} + +ReturnValue_t PsbMock::handleRequest(uint8_t subservice) { + handleRequestCallCnt++; + subserviceQueue.push(subservice); + if (handleReqFailPair.first) { + handleReqFailPair.first = false; + return handleReqFailPair.second; + } + return returnvalue::OK; +} + +ReturnValue_t PsbMock::performService() { + performServiceCallCnt++; + if (performServiceFailPair.first) { + performServiceFailPair.first = false; + return performServiceFailPair.second; + } + return returnvalue::OK; +} + +void PsbMock::reset() { + handleRequestCallCnt = 0; + performServiceCallCnt = 0; + std::queue().swap(subserviceQueue); +} + +void PsbMock::makeNextHandleReqCallFail(ReturnValue_t retval) { + handleReqFailPair.first = true; + handleReqFailPair.second = retval; +} +bool PsbMock::getAndPopNextSubservice(uint8_t& subservice) { + if (subserviceQueue.empty()) { + return false; + } + subservice = subserviceQueue.front(); + subserviceQueue.pop(); + return true; +} + +PsbParams& PsbMock::getParams() { return psbParams; } + +void PsbMock::setStaticPusDistributor(object_id_t pusDistributor) { + PUS_DISTRIBUTOR = pusDistributor; +} + +object_id_t PsbMock::getStaticPusDistributor() { return PUS_DISTRIBUTOR; } + +void PsbMock::setStaticTmDest(object_id_t tmDest) { PACKET_DESTINATION = tmDest; } + +object_id_t PsbMock::getStaticTmDest() { return PACKET_DESTINATION; } diff --git a/unittests/mocks/PusServiceBaseMock.h b/unittests/mocks/PusServiceBaseMock.h new file mode 100644 index 00000000..0aa6b406 --- /dev/null +++ b/unittests/mocks/PusServiceBaseMock.h @@ -0,0 +1,32 @@ +#ifndef FSFW_TESTS_PUSSERVICEBASEMOCK_H +#define FSFW_TESTS_PUSSERVICEBASEMOCK_H + +#include + +#include "fsfw/tmtcservices/PusServiceBase.h" + +class PsbMock : public PusServiceBase { + public: + explicit PsbMock(PsbParams params); + unsigned int handleRequestCallCnt = 0; + std::queue subserviceQueue; + unsigned int performServiceCallCnt = 0; + + static void setStaticPusDistributor(object_id_t pusDistributor); + static object_id_t getStaticPusDistributor(); + static void setStaticTmDest(object_id_t tmDest); + static object_id_t getStaticTmDest(); + + PsbParams& getParams(); + + std::pair handleReqFailPair; + std::pair performServiceFailPair; + ReturnValue_t handleRequest(uint8_t subservice) override; + ReturnValue_t performService() override; + + void makeNextHandleReqCallFail(ReturnValue_t retval); + bool getAndPopNextSubservice(uint8_t& subservice); + void reset(); +}; + +#endif // FSFW_TESTS_PUSSERVICEBASEMOCK_H diff --git a/unittests/mocks/PusVerificationReporterMock.cpp b/unittests/mocks/PusVerificationReporterMock.cpp new file mode 100644 index 00000000..07afd319 --- /dev/null +++ b/unittests/mocks/PusVerificationReporterMock.cpp @@ -0,0 +1,42 @@ +#include "PusVerificationReporterMock.h" + +#include "fsfw/objectmanager/frameworkObjects.h" + +PusVerificationReporterMock::PusVerificationReporterMock() + : SystemObject(objects::NO_OBJECT, false) {} + +PusVerificationReporterMock::PusVerificationReporterMock(object_id_t registeredId) + : SystemObject(registeredId) {} + +size_t PusVerificationReporterMock::successCallCount() const { return successParams.size(); } +size_t PusVerificationReporterMock::failCallCount() const { return failParams.size(); } + +VerifSuccessParams& PusVerificationReporterMock::getNextSuccessCallParams() { + return successParams.front(); +} + +void PusVerificationReporterMock::popNextFailParams() { + if (not failParams.empty()) { + failParams.pop(); + } +} + +VerifFailureParams& PusVerificationReporterMock::getNextFailCallParams() { + return failParams.front(); +} + +void PusVerificationReporterMock::popNextSuccessParams() { + if (not successParams.empty()) { + successParams.pop(); + } +} + +ReturnValue_t PusVerificationReporterMock::sendSuccessReport(VerifSuccessParams params) { + successParams.push(params); + return returnvalue::OK; +} + +ReturnValue_t PusVerificationReporterMock::sendFailureReport(VerifFailureParams params) { + failParams.push(params); + return returnvalue::OK; +} diff --git a/unittests/mocks/PusVerificationReporterMock.h b/unittests/mocks/PusVerificationReporterMock.h new file mode 100644 index 00000000..dedfd30e --- /dev/null +++ b/unittests/mocks/PusVerificationReporterMock.h @@ -0,0 +1,25 @@ +#ifndef FSFW_TESTS_PUSVERIFICATIONREPORTERMOCK_H +#define FSFW_TESTS_PUSVERIFICATIONREPORTERMOCK_H + +#include + +#include "fsfw/objectmanager/SystemObject.h" +#include "fsfw/tmtcservices/VerificationReporterIF.h" + +class PusVerificationReporterMock : public SystemObject, public VerificationReporterIF { + public: + std::queue successParams; + std::queue failParams; + PusVerificationReporterMock(); + explicit PusVerificationReporterMock(object_id_t registeredId); + [[nodiscard]] size_t successCallCount() const; + VerifSuccessParams& getNextSuccessCallParams(); + void popNextSuccessParams(); + [[nodiscard]] size_t failCallCount() const; + VerifFailureParams& getNextFailCallParams(); + void popNextFailParams(); + + ReturnValue_t sendSuccessReport(VerifSuccessParams params) override; + ReturnValue_t sendFailureReport(VerifFailureParams params) override; +}; +#endif // FSFW_TESTS_PUSVERIFICATIONREPORTERMOCK_H diff --git a/unittests/osal/CMakeLists.txt b/unittests/osal/CMakeLists.txt index 030d363b..0c93eba1 100644 --- a/unittests/osal/CMakeLists.txt +++ b/unittests/osal/CMakeLists.txt @@ -1,5 +1,5 @@ target_sources(${FSFW_TEST_TGT} PRIVATE - TestMessageQueue.cpp + testMq.cpp TestSemaphore.cpp TestClock.cpp ) diff --git a/unittests/osal/TestSemaphore.cpp b/unittests/osal/TestSemaphore.cpp index 376b08db..550c60b7 100644 --- a/unittests/osal/TestSemaphore.cpp +++ b/unittests/osal/TestSemaphore.cpp @@ -19,7 +19,7 @@ TEST_CASE("Binary Semaphore Test" , "[BinSemaphore]") { REQUIRE(binSemaph->release() == static_cast(SemaphoreIF::SEMAPHORE_NOT_OWNED)); REQUIRE(binSemaph->acquire(SemaphoreIF::POLLING) == - result::OK); + returnvalue::OK); { // not precise enough on linux.. should use clock instead.. //Stopwatch stopwatch(false); @@ -29,7 +29,7 @@ TEST_CASE("Binary Semaphore Test" , "[BinSemaphore]") { //CHECK(time == 5); } REQUIRE(binSemaph->getSemaphoreCounter() == 0); - REQUIRE(binSemaph->release() == result::OK); + REQUIRE(binSemaph->release() == returnvalue::OK); } SemaphoreFactory::instance()->deleteSemaphore(binSemaph); // perform tear-down here diff --git a/unittests/osal/TestMessageQueue.cpp b/unittests/osal/testMq.cpp similarity index 100% rename from unittests/osal/TestMessageQueue.cpp rename to unittests/osal/testMq.cpp diff --git a/unittests/storagemanager/CMakeLists.txt b/unittests/storagemanager/CMakeLists.txt index 7b6280df..d2bb4dbc 100644 --- a/unittests/storagemanager/CMakeLists.txt +++ b/unittests/storagemanager/CMakeLists.txt @@ -1,4 +1,4 @@ target_sources(${FSFW_TEST_TGT} PRIVATE - TestNewAccessor.cpp - TestPool.cpp + testAccessor.cpp + testPool.cpp ) diff --git a/unittests/storagemanager/TestNewAccessor.cpp b/unittests/storagemanager/testAccessor.cpp similarity index 97% rename from unittests/storagemanager/TestNewAccessor.cpp rename to unittests/storagemanager/testAccessor.cpp index c2c1dafd..d1c38f5d 100644 --- a/unittests/storagemanager/TestNewAccessor.cpp +++ b/unittests/storagemanager/testAccessor.cpp @@ -6,11 +6,11 @@ #include "CatchDefinitions.h" -TEST_CASE("New Accessor", "[NewAccessor]") { +TEST_CASE("Pool Accessor", "[pool-accessor]") { LocalPool::LocalPoolConfig poolCfg = {{1, 10}}; LocalPool SimplePool = LocalPool(0, poolCfg); - std::array testDataArray; - std::array receptionArray; + std::array testDataArray{}; + std::array receptionArray{}; store_address_t testStoreId; ReturnValue_t result = returnvalue::FAILED; @@ -162,7 +162,7 @@ TEST_CASE("New Accessor", "[NewAccessor]") { REQUIRE(result == returnvalue::OK); { StorageAccessor accessor(testStoreId); - StorageAccessor accessor2(0); + StorageAccessor accessor2(store_address_t::invalid()); accessor2 = std::move(accessor); REQUIRE(accessor.data() == nullptr); std::array data; diff --git a/unittests/storagemanager/TestPool.cpp b/unittests/storagemanager/testPool.cpp similarity index 96% rename from unittests/storagemanager/TestPool.cpp rename to unittests/storagemanager/testPool.cpp index 6bffa5de..49a097d0 100644 --- a/unittests/storagemanager/TestPool.cpp +++ b/unittests/storagemanager/testPool.cpp @@ -10,10 +10,10 @@ TEST_CASE("Local Pool Simple Tests [1 Pool]", "[TestPool]") { LocalPool::LocalPoolConfig config = {{1, 10}}; LocalPool simplePool(0, config); - std::array testDataArray; - std::array receptionArray; + std::array testDataArray{}; + std::array receptionArray{}; store_address_t testStoreId; - ReturnValue_t result = returnvalue::FAILED; + ReturnValue_t result; uint8_t* pointer = nullptr; const uint8_t* constPointer = nullptr; @@ -23,8 +23,10 @@ TEST_CASE("Local Pool Simple Tests [1 Pool]", "[TestPool]") { size_t size = 10; SECTION("Basic tests") { + REQUIRE(not simplePool.hasDataAtId(testStoreId)); result = simplePool.addData(&testStoreId, testDataArray.data(), size); REQUIRE(result == returnvalue::OK); + REQUIRE(simplePool.hasDataAtId(testStoreId)); result = simplePool.getData(testStoreId, &constPointer, &size); REQUIRE(result == returnvalue::OK); memcpy(receptionArray.data(), constPointer, size); @@ -40,6 +42,7 @@ TEST_CASE("Local Pool Simple Tests [1 Pool]", "[TestPool]") { } result = simplePool.deleteData(testStoreId); REQUIRE(result == returnvalue::OK); + REQUIRE(not simplePool.hasDataAtId(testStoreId)); result = simplePool.addData(&testStoreId, testDataArray.data(), 15); CHECK(result == (int)StorageManagerIF::DATA_TOO_LARGE); } @@ -138,8 +141,8 @@ TEST_CASE("Local Pool Extended Tests [3 Pools]", "[TestPool2]") { runIdx++; LocalPool simplePool(0, *config); - std::array testDataArray; - std::array receptionArray; + std::array testDataArray{}; + std::array receptionArray{}; store_address_t testStoreId; ReturnValue_t result = returnvalue::FAILED; for (size_t i = 0; i < testDataArray.size(); i++) { diff --git a/unittests/testcfg/objects/systemObjectList.h b/unittests/testcfg/objects/systemObjectList.h index 7d12e5c6..1e86d5f7 100644 --- a/unittests/testcfg/objects/systemObjectList.h +++ b/unittests/testcfg/objects/systemObjectList.h @@ -31,4 +31,4 @@ enum sourceObjects : uint32_t { }; } -#endif /* BSP_CONFIG_OBJECTS_SYSTEMOBJECTLIST_H_ */ +#endif /* HOSTED_CONFIG_OBJECTS_SYSTEMOBJECTLIST_H_ */ diff --git a/unittests/tmtcpacket/CMakeLists.txt b/unittests/tmtcpacket/CMakeLists.txt index 958bda40..5b53328f 100644 --- a/unittests/tmtcpacket/CMakeLists.txt +++ b/unittests/tmtcpacket/CMakeLists.txt @@ -1,3 +1,10 @@ target_sources(${FSFW_TEST_TGT} PRIVATE - testCcsds.cpp + testCcsdsCreator.cpp + testCcsdsReader.cpp + testPusTcCreator.cpp + testPusTcReader.cpp + testPusTmCreator.cpp + testPusTmReader.cpp + testCcsds.cpp + testZcTmWriter.cpp ) diff --git a/unittests/tmtcpacket/PusTmTest.cpp b/unittests/tmtcpacket/PusTmTest.cpp deleted file mode 100644 index 8b137891..00000000 --- a/unittests/tmtcpacket/PusTmTest.cpp +++ /dev/null @@ -1 +0,0 @@ - diff --git a/unittests/tmtcpacket/testCcsds.cpp b/unittests/tmtcpacket/testCcsds.cpp index d395449d..233e4ada 100644 --- a/unittests/tmtcpacket/testCcsds.cpp +++ b/unittests/tmtcpacket/testCcsds.cpp @@ -1,11 +1,134 @@ +#include #include +#include -#include "fsfw/tmtcpacket/SpacePacket.h" +#include "fsfw/tmtcpacket/ccsds/PacketId.h" +#include "fsfw/tmtcpacket/ccsds/PacketSeqCtrl.h" +#include "fsfw/tmtcpacket/ccsds/header.h" -TEST_CASE("CCSDS Test", "[ccsds]") { - REQUIRE(spacepacket::getTcSpacePacketIdFromApid(0x22) == 0x1822); - REQUIRE(spacepacket::getTmSpacePacketIdFromApid(0x22) == 0x0822); +TEST_CASE("CCSDS Low Level", "[ccsds-ll]") { + SECTION("Lowlevel Header Packet ID test") { + ccsds::PrimaryHeader header{}; + uint16_t packetIdRaw = 0x3ff; + ccsds::setPacketId(header, packetIdRaw); + REQUIRE(header.packetIdHAndVersion == 3); + REQUIRE(header.packetIdL == 0xff); + REQUIRE(ccsds::getPacketId(header) == 0x3ff); + header.packetIdHAndVersion |= 0b00100000; + REQUIRE(ccsds::getPacketId(header) == 0x3ff); + REQUIRE(ccsds::getVersion(header) == 0b001); + } - REQUIRE(spacepacket::getTcSpacePacketIdFromApid(0x7ff) == 0x1fff); - REQUIRE(spacepacket::getTmSpacePacketIdFromApid(0x7ff) == 0xfff); + SECTION("Lowlevel Header APID Test") { + ccsds::PrimaryHeader header{}; + uint16_t packetIdRaw = 0x3ff; + ccsds::setPacketId(header, packetIdRaw); + ccsds::setApid(header, 0x1ff); + REQUIRE(ccsds::getPacketId(header) == 0x3ff); + } + + SECTION("Lowlevel Packet Length Test") { + ccsds::PrimaryHeader header{}; + header.packetLenH = 0x02; + header.packetLenL = 0x03; + REQUIRE(ccsds::getPacketLen(header) == 0x0203); + } +} + +TEST_CASE("CCSDS Packet ID", "[ccsds-packet-id]") { + PacketId packetId; + std::array buf{}; + SECTION("Basic") { + packetId.apid = 0x1ff; + packetId.secHeaderFlag = false; + packetId.packetType = ccsds::PacketType::TM; + size_t serLen = 0; + REQUIRE(packetId.raw() == 0x1ff); + REQUIRE(packetId.SerializeIF::serializeBe(buf.data(), serLen, buf.size()) == returnvalue::OK); + CHECK(buf[0] == 0x1); + CHECK(buf[1] == 0xff); + } + + SECTION("Invalid Ser") { + size_t serLen = 0; + REQUIRE(packetId.SerializeIF::serializeBe(buf.data(), serLen, 0) == + SerializeIF::BUFFER_TOO_SHORT); + REQUIRE(packetId.SerializeIF::serializeBe(buf.data(), serLen, 1) == + SerializeIF::BUFFER_TOO_SHORT); + } + + SECTION("Invalid Deser") { + size_t deserLen = 0; + REQUIRE(packetId.deSerialize(buf.data(), deserLen, 1, SerializeIF::Endianness::NETWORK) == + SerializeIF::STREAM_TOO_SHORT); + REQUIRE(packetId.deSerialize(buf.data(), deserLen, 0, SerializeIF::Endianness::NETWORK) == + SerializeIF::STREAM_TOO_SHORT); + } + + SECTION("From Raw") { + auto newId = PacketId(ccsds::PacketType::TC, true, 0x2ff); + uint16_t rawId = newId.raw(); + CHECK(rawId == 0x1aff); + CHECK(PacketId::fromRaw(rawId) == newId); + } + + SECTION("Deserialize") { + buf[0] = 0x1a; + buf[1] = 0xff; + size_t deserLen = 0xff; + REQUIRE(packetId.deSerialize(buf.data(), deserLen, buf.size(), + SerializeIF::Endianness::NETWORK) == returnvalue::OK); + CHECK(packetId.apid == 0x2ff); + CHECK(deserLen == 2); + CHECK(packetId.packetType == ccsds::PacketType::TC); + CHECK(packetId.secHeaderFlag == true); + } +} + +TEST_CASE("CCSDS Packet Seq Ctrl", "[ccsds-packet-seq-ctrl]") { + PacketSeqCtrl psc; + std::array buf{}; + SECTION("Basic") { + size_t serLen = 0xff; + psc.seqFlags = ccsds::SequenceFlags::FIRST_SEGMENT; + psc.seqCount = static_cast(std::round(std::pow(2, 14) - 1)); + REQUIRE(psc.raw() == 0x7fff); + REQUIRE(psc.SerializeIF::serializeBe(buf.data(), serLen, buf.size()) == returnvalue::OK); + CHECK(buf[0] == 0x7f); + CHECK(buf[1] == 0xff); + CHECK(serLen == 2); + } + + SECTION("From Raw") { + auto newId = PacketSeqCtrl(ccsds::SequenceFlags::LAST_SEGMENT, + static_cast(std::round(std::pow(2, 14) - 2))); + uint16_t rawId = newId.raw(); + REQUIRE(rawId == 0xbffe); + CHECK(PacketSeqCtrl::fromRaw(rawId) == newId); + } + + SECTION("Deserialize") { + buf[0] = 0xbf; + buf[1] = 0xfe; + size_t deserLen = 0xff; + REQUIRE(psc.deSerialize(buf.data(), deserLen, buf.size(), SerializeIF::Endianness::NETWORK) == + returnvalue::OK); + CHECK(psc.seqFlags == ccsds::SequenceFlags::LAST_SEGMENT); + CHECK(deserLen == 2); + CHECK(psc.seqCount == static_cast(std::round(std::pow(2, 14) - 2))); + } + + SECTION("Invalid Ser") { + size_t deserLen = 0; + REQUIRE(psc.SerializeIF::serializeBe(buf.data(), deserLen, 0) == SerializeIF::BUFFER_TOO_SHORT); + REQUIRE(psc.SerializeIF::serializeBe(buf.data(), deserLen, 1) == SerializeIF::BUFFER_TOO_SHORT); + } + + SECTION("Invalid Deser") { + size_t deserLen = 0; + REQUIRE(psc.deSerialize(buf.data(), deserLen, 1, SerializeIF::Endianness::NETWORK) == + SerializeIF::STREAM_TOO_SHORT); + REQUIRE(psc.deSerialize(buf.data(), deserLen, 0, SerializeIF::Endianness::NETWORK) == + SerializeIF::STREAM_TOO_SHORT); + } } diff --git a/unittests/tmtcpacket/testCcsdsCreator.cpp b/unittests/tmtcpacket/testCcsdsCreator.cpp new file mode 100644 index 00000000..2b043717 --- /dev/null +++ b/unittests/tmtcpacket/testCcsdsCreator.cpp @@ -0,0 +1,107 @@ +#include +#include +#include + +#include "fsfw/tmtcpacket/ccsds/SpacePacketCreator.h" + +TEST_CASE("CCSDS Creator", "[ccsds-creator]") { + auto packetId = PacketId(ccsds::PacketType::TC, true, 0x02); + auto psc = PacketSeqCtrl(ccsds::SequenceFlags::FIRST_SEGMENT, 0x34); + auto params = SpacePacketParams(packetId, psc, 0x16); + SpacePacketCreator base = SpacePacketCreator(params); + std::array buf{}; + uint8_t* bufPtr = buf.data(); + size_t serLen = 0; + + SECTION("Constexpr Helpers") { + REQUIRE(ccsds::getTcSpacePacketIdFromApid(0x22) == 0x1822); + REQUIRE(ccsds::getTmSpacePacketIdFromApid(0x22) == 0x0822); + + REQUIRE(ccsds::getTcSpacePacketIdFromApid(0x7ff) == 0x1fff); + REQUIRE(ccsds::getTmSpacePacketIdFromApid(0x7ff) == 0xfff); + } + + SECTION("Basic Test") { + CHECK(base.isValid()); + CHECK(base); + CHECK(base.getApid() == 0x02); + CHECK(base.getSequenceFlags() == ccsds::SequenceFlags::FIRST_SEGMENT); + CHECK(base.getVersion() == 0b000); + CHECK(base.getSequenceCount() == 0x34); + CHECK(base.getPacketDataLen() == 0x16); + CHECK(base.getPacketType() == ccsds::PacketType::TC); + CHECK(base.getPacketIdRaw() == 0x1802); + CHECK(base.getSerializedSize() == 6); + CHECK(base.getPacketSeqCtrl() == psc); + CHECK(base.getPacketId() == packetId); + } + + SECTION("Deserialization Fails") { + serLen = 6; + const uint8_t* readOnlyPtr = buf.data(); + REQUIRE(base.deSerialize(&readOnlyPtr, &serLen, SerializeIF::Endianness::BIG) == + returnvalue::FAILED); + } + + SECTION("Raw Output") { + REQUIRE(base.serializeBe(&bufPtr, &serLen, buf.size()) == returnvalue::OK); + // TC, and secondary header flag is set -> 0b0001100 -> 0x18 + CHECK(buf[0] == 0x18); + // APID 0x02 + CHECK(buf[1] == 0x02); + // Sequence count is one byte value, so the only set bit here is the bit + // from the Sequence flag argument, which is the second bit for + // SequenceFlags.FIRST_SEGMENT + CHECK(buf[2] == 0x40); + // Sequence Count specified above + CHECK(buf[3] == 0x34); + // This byte and the next byte should be 22 big endian (packet length) + CHECK(buf[4] == 0x00); + CHECK(buf[5] == 0x16); + } + + SECTION("All Ones Output") { + base.setApid(static_cast(std::pow(2, 11)) - 1); + base.setSeqCount(static_cast(std::pow(2, 14)) - 1); + base.setSeqFlags(ccsds::SequenceFlags::UNSEGMENTED); + base.setDataLen(static_cast(std::pow(2, 16)) - 1); + REQUIRE(base.isValid()); + REQUIRE(base.serializeBe(&bufPtr, &serLen, buf.size()) == returnvalue::OK); + CHECK(buf[0] == 0x1F); + CHECK(buf[1] == 0xFF); + CHECK(buf[2] == 0xFF); + CHECK(buf[3] == 0xFF); + CHECK(buf[4] == 0xFF); + CHECK(buf[5] == 0xFF); + } + + SECTION("Invalid APID") { + SpacePacketCreator creator = SpacePacketCreator( + ccsds::PacketType::TC, true, 0xFFFF, ccsds::SequenceFlags::FIRST_SEGMENT, 0x34, 0x16); + REQUIRE(not creator.isValid()); + REQUIRE(not creator); + REQUIRE(creator.serializeBe(&bufPtr, &serLen, buf.size()) == returnvalue::FAILED); + } + + SECTION("Invalid Seq Count") { + SpacePacketCreator invalid = SpacePacketCreator( + ccsds::PacketType::TC, true, 0x02, ccsds::SequenceFlags::FIRST_SEGMENT, 0xFFFF, 0x16); + REQUIRE(not invalid.isValid()); + REQUIRE(invalid.serializeBe(&bufPtr, &serLen, buf.size()) == returnvalue::FAILED); + } + + SECTION("Invalid Buf Size 1") { + serLen = 2; + REQUIRE(base.serializeBe(&bufPtr, &serLen, buf.size()) == SerializeIF::BUFFER_TOO_SHORT); + } + + SECTION("Invalid Buf Size 2") { + serLen = 4; + REQUIRE(base.serializeBe(&bufPtr, &serLen, buf.size()) == SerializeIF::BUFFER_TOO_SHORT); + } + + SECTION("Invalid Buf Size 3") { + serLen = 6; + REQUIRE(base.serializeBe(&bufPtr, &serLen, buf.size()) == SerializeIF::BUFFER_TOO_SHORT); + } +} diff --git a/unittests/tmtcpacket/testCcsdsReader.cpp b/unittests/tmtcpacket/testCcsdsReader.cpp new file mode 100644 index 00000000..519ef08b --- /dev/null +++ b/unittests/tmtcpacket/testCcsdsReader.cpp @@ -0,0 +1,71 @@ +#include +#include + +#include "fsfw/tmtcpacket/ccsds/SpacePacketCreator.h" +#include "fsfw/tmtcpacket/ccsds/SpacePacketReader.h" + +#define FULL_PACKET_LEN 29 + +TEST_CASE("CCSDS Reader", "[ccsds-reader]") { + auto params = SpacePacketParams(PacketId(ccsds::PacketType::TC, true, 0x02), + PacketSeqCtrl(ccsds::SequenceFlags::FIRST_SEGMENT, 0x34), 0x16); + SpacePacketCreator base = SpacePacketCreator(params); + // This is enough to hold 0x16 (22) bytes + 6 (SP header length) + 1 as defined as the full packet + // length derived from the length field + std::array buf{}; + uint8_t* bufPtr = buf.data(); + size_t serLen = 0; + SpacePacketReader reader; + + auto checkReader = [&](SpacePacketReader& reader) { + REQUIRE(reader.getPacketDataLen() == 0x16); + REQUIRE(reader.getBufSize() == SpacePacketIF::getHeaderLen()); + REQUIRE(reader.getFullData() == buf.data()); + REQUIRE(reader.getFullPacketLen() == 0x16 + SpacePacketReader::getHeaderLen() + 1); + REQUIRE(reader.getPacketIdRaw() == 0x1802); + REQUIRE(reader.getSequenceFlags() == ccsds::SequenceFlags::FIRST_SEGMENT); + REQUIRE(reader.getSequenceCount() == 0x34); + REQUIRE(reader.getPacketSeqCtrlRaw() == 0x4034); + REQUIRE(reader.hasSecHeader()); + REQUIRE(reader.getApid() == 0x02); + REQUIRE(not reader.isNull()); + // We only serialized the 6 bytes of the header, so the packer data should be invalid + REQUIRE(reader.getPacketData() == nullptr); + }; + + SECTION("Empty Reader") { + REQUIRE(SpacePacketIF::getHeaderLen() == 6); + REQUIRE(reader.isNull()); + REQUIRE(reader.checkSize() == returnvalue::FAILED); + } + + SECTION("Basic Read") { + REQUIRE(base.serialize(&bufPtr, &serLen, buf.size(), SerializeIF::Endianness::NETWORK) == + returnvalue::OK); + SECTION("Setter") { + reader.setReadOnlyData(buf.data(), SpacePacketIF::getHeaderLen()); + checkReader(reader); + } + SECTION("Direct Construction") { + SpacePacketReader secondReader(buf.data(), serLen); + checkReader(secondReader); + } + } + + SECTION("Read with additional data") { + REQUIRE(base.serialize(&bufPtr, &serLen, buf.size(), SerializeIF::Endianness::NETWORK) == + returnvalue::OK); + REQUIRE(reader.setReadOnlyData(buf.data(), buf.size()) == returnvalue::OK); + REQUIRE(reader.getBufSize() == buf.size()); + REQUIRE(reader.getFullPacketLen() == FULL_PACKET_LEN); + REQUIRE(reader.getPacketData() == buf.data() + SpacePacketIF::getHeaderLen()); + } + + SECTION("Invalid Size") { + for (size_t i = 0; i < 5; i++) { + REQUIRE(reader.setReadOnlyData(buf.data(), i) == SerializeIF::STREAM_TOO_SHORT); + REQUIRE(not reader.isNull()); + REQUIRE(reader.getPacketData() == nullptr); + } + } +} \ No newline at end of file diff --git a/unittests/tmtcpacket/testPusTcCreator.cpp b/unittests/tmtcpacket/testPusTcCreator.cpp new file mode 100644 index 00000000..b18c4717 --- /dev/null +++ b/unittests/tmtcpacket/testPusTcCreator.cpp @@ -0,0 +1,132 @@ +#include +#include + +#include "fsfw/globalfunctions/CRC.h" +#include "fsfw/tmtcpacket/pus/tc.h" +#include "mocks/SimpleSerializable.h" + +TEST_CASE("PUS TC Creator", "[pus-tc-creator]") { + auto packetId = PacketId(ccsds::PacketType::TC, true, 0x02); + auto spParams = + SpacePacketParams(packetId, PacketSeqCtrl(ccsds::SequenceFlags::UNSEGMENTED, 0x34), 0x00); + auto pusParams = PusTcParams(17, 1); + PusTcCreator creator(spParams, pusParams); + std::array buf{}; + uint8_t* dataPtr = buf.data(); + size_t serLen = 0; + + SECTION("State") { + CHECK(creator.isTc()); + CHECK(creator.hasSecHeader()); + CHECK(creator.getService() == 17); + CHECK(creator.getSubService() == 1); + CHECK(creator.getApid() == 0x02); + CHECK(creator.getPusVersion() == 2); + CHECK(creator.getAcknowledgeFlags() == 0b1111); + CHECK(creator.getSourceId() == 0x00); + CHECK(creator.getPacketSeqCtrlRaw() == 0xc034); + // bytes CCSDS header, 5 bytes secondary header, 2 bytes CRC, 3 bytes app data + CHECK(creator.getFullPacketLen() == 13); + // The data length field is the full packet length minus the primary header minus 1 + CHECK(creator.getPacketDataLen() == 6); + auto& paramsLocal = creator.getSpParams(); + CHECK(paramsLocal.packetId == packetId); + } + + SECTION("Serialized") { + REQUIRE(creator.serializeBe(&dataPtr, &serLen, buf.size()) == returnvalue::OK); + REQUIRE(serLen == 13); + REQUIRE(buf[0] == 0x18); + REQUIRE(buf[1] == 0x02); + // Unsegmented, first 2 bits 11 + REQUIRE(buf[2] == 0xc0); + // Packet Sequence count only occupies lower byte of packet sequence control + REQUIRE(buf[3] == 0x34); + // Data length packed big endian + REQUIRE(buf[4] == 0x00); + REQUIRE(buf[5] == 0x06); + // PUS Version C (2) + REQUIRE(((buf[6] >> 4) & 0b1111) == 2); + // All Ack Fields is default + REQUIRE((buf[6] & 0b1111) == 0b1111); + // Service and subservice + REQUIRE(buf[7] == 17); + REQUIRE(buf[8] == 1); + // Source ID is 0 + REQUIRE(((buf[9] << 8) | buf[10]) == 0); + // CRC16 check + REQUIRE(CRC::crc16ccitt(buf.data(), serLen) == 0); + REQUIRE(buf[11] == 0xee); + REQUIRE(buf[12] == 0x63); + } + + SECTION("Custom Source ID") { + auto& params = creator.getPusParams(); + params.sourceId = 0x5ff; + REQUIRE(creator.getSourceId() == 0x5ff); + REQUIRE(creator.serializeBe(&dataPtr, &serLen, buf.size()) == returnvalue::OK); + REQUIRE(((buf[9] << 8) | buf[10]) == 0x5ff); + } + + SECTION("Test with Application Data Raw") { + auto& params = creator.getPusParams(); + std::array data{1, 2, 3}; + params.dataWrapper.setRawData({data.data(), data.size()}); + // To get correct size information, the SP length field needs to be updated automatically + REQUIRE(creator.getSerializedSize() == 13); + creator.updateSpLengthField(); + REQUIRE(creator.getSerializedSize() == 16); + REQUIRE(creator.serializeBe(&dataPtr, &serLen, buf.size()) == returnvalue::OK); + REQUIRE(serLen == 16); + REQUIRE(buf[11] == 1); + REQUIRE(buf[12] == 2); + REQUIRE(buf[13] == 3); + } + + SECTION("Test with Application Data Serializable") { + auto& params = creator.getPusParams(); + auto simpleSer = SimpleSerializable(); + creator.setSerializableUserData(simpleSer); + REQUIRE(creator.getSerializedSize() == 16); + REQUIRE(creator.serializeBe(&dataPtr, &serLen, buf.size()) == returnvalue::OK); + REQUIRE(serLen == 16); + REQUIRE(buf[11] == 1); + REQUIRE(buf[12] == 2); + REQUIRE(buf[13] == 3); + } + + SECTION("Test with Application Data Serializable Simple Ser API") { + auto& params = creator.getPusParams(); + auto simpleSer = SimpleSerializable(); + creator.setSerializableUserData(simpleSer); + REQUIRE(creator.getSerializedSize() == 16); + REQUIRE(creator.serializeBe(dataPtr, serLen, buf.size()) == returnvalue::OK); + REQUIRE(serLen == 16); + REQUIRE(buf[11] == 1); + REQUIRE(buf[12] == 2); + REQUIRE(buf[13] == 3); + } + + SECTION("Deserialization Fails") { + SerializeIF& deser = creator; + size_t deserLen = buf.size(); + const uint8_t* roPtr = buf.data(); + REQUIRE(deser.deSerialize(&roPtr, &deserLen, SerializeIF::Endianness::NETWORK) == + returnvalue::FAILED); + } + + SECTION("Serialize with invalid buffer length") { + size_t reqSize = creator.getSerializedSize(); + for (size_t maxSize = 0; maxSize < reqSize; maxSize++) { + dataPtr = buf.data(); + serLen = 0; + REQUIRE(creator.serializeBe(&dataPtr, &serLen, maxSize) == SerializeIF::BUFFER_TOO_SHORT); + } + } + + SECTION("Invalid PUS Version") { + auto& params = creator.getPusParams(); + params.pusVersion = 0; + REQUIRE(creator.serializeBe(&dataPtr, &serLen, buf.size()) == PusIF::INVALID_PUS_VERSION); + } +} \ No newline at end of file diff --git a/unittests/tmtcpacket/testPusTcReader.cpp b/unittests/tmtcpacket/testPusTcReader.cpp new file mode 100644 index 00000000..3dbb8f81 --- /dev/null +++ b/unittests/tmtcpacket/testPusTcReader.cpp @@ -0,0 +1,85 @@ +#include +#include + +#include "fsfw/tmtcpacket/pus/tc/PusTcCreator.h" +#include "fsfw/tmtcpacket/pus/tc/PusTcReader.h" + +TEST_CASE("PUS TC Reader", "[pus-tc-reader]") { + auto packetId = PacketId(ccsds::PacketType::TC, true, 0x02); + auto spParams = + SpacePacketParams(packetId, PacketSeqCtrl(ccsds::SequenceFlags::UNSEGMENTED, 0x34), 0x00); + auto pusParams = PusTcParams(17, 1); + PusTcCreator creator(spParams, pusParams); + std::array buf{}; + uint8_t* dataPtr = buf.data(); + size_t serLen = 0; + PusTcReader reader; + + SECTION("State") { + REQUIRE(creator.serializeBe(&dataPtr, &serLen, buf.size()) == returnvalue::OK); + REQUIRE(reader.isNull()); + REQUIRE(not reader); + PusTcReader* readerPtr = nullptr; + bool callDelete = false; + SECTION("Setter") { + readerPtr = &reader; + REQUIRE(readerPtr->setReadOnlyData(buf.data(), serLen) == returnvalue::OK); + REQUIRE(readerPtr->parseDataWithCrcCheck() == returnvalue::OK); + } + SECTION("Directly Constructed") { + callDelete = true; + readerPtr = new PusTcReader(buf.data(), serLen); + REQUIRE(not readerPtr->isNull()); + REQUIRE(readerPtr->parseDataWithCrcCheck() == returnvalue::OK); + } + REQUIRE(not readerPtr->isNull()); + REQUIRE(*readerPtr); + REQUIRE(readerPtr->getPacketType() == ccsds::PacketType::TC); + REQUIRE(readerPtr->getApid() == 0x02); + REQUIRE(readerPtr->getService() == 17); + REQUIRE(readerPtr->getSubService() == 1); + REQUIRE(readerPtr->getFullPacketLen() == 13); + REQUIRE(readerPtr->getPacketDataLen() == 6); + REQUIRE(readerPtr->getPusVersion() == 2); + REQUIRE(readerPtr->getSequenceCount() == 0x34); + REQUIRE(readerPtr->getUserData() == nullptr); + REQUIRE(readerPtr->getUserDataLen() == 0); + REQUIRE(readerPtr->getFullData() == buf.data()); + REQUIRE(readerPtr->getSourceId() == 0x00); + REQUIRE(readerPtr->getAcknowledgeFlags() == 0b1111); + // This value was verified to be correct + REQUIRE(readerPtr->getErrorControl() == 0xee63); + if (callDelete) { + delete readerPtr; + } + } + + SECTION("Invalid CRC") { + REQUIRE(creator.serializeBe(&dataPtr, &serLen, buf.size()) == returnvalue::OK); + REQUIRE(reader.setReadOnlyData(buf.data(), serLen) == returnvalue::OK); + buf[11] = 0x00; + REQUIRE(reader.parseDataWithCrcCheck() == PusIF::INVALID_CRC_16); + } + + SECTION("Invalid CRC but no check") { + REQUIRE(creator.serializeBe(&dataPtr, &serLen, buf.size()) == returnvalue::OK); + REQUIRE(reader.setReadOnlyData(buf.data(), serLen) == returnvalue::OK); + buf[11] = 0x00; + REQUIRE(reader.parseDataWithoutCrcCheck() == returnvalue::OK); + } + + SECTION("With application data") { + auto& params = creator.getPusParams(); + std::array data{1, 2, 3}; + creator.setRawUserData(data.data(), data.size()); + REQUIRE(creator.serializeBe(&dataPtr, &serLen, buf.size()) == returnvalue::OK); + REQUIRE(reader.setReadOnlyData(buf.data(), serLen) == returnvalue::OK); + REQUIRE(reader.parseDataWithCrcCheck() == returnvalue::OK); + const uint8_t* userDataPtr = reader.getUserData(); + REQUIRE(userDataPtr != nullptr); + REQUIRE(reader.getUserDataLen() == 3); + REQUIRE(userDataPtr[0] == 1); + REQUIRE(userDataPtr[1] == 2); + REQUIRE(userDataPtr[2] == 3); + } +} \ No newline at end of file diff --git a/unittests/tmtcpacket/testPusTmCreator.cpp b/unittests/tmtcpacket/testPusTmCreator.cpp new file mode 100644 index 00000000..fc86dcbe --- /dev/null +++ b/unittests/tmtcpacket/testPusTmCreator.cpp @@ -0,0 +1,158 @@ +#include + +#include "fsfw/globalfunctions/CRC.h" +#include "fsfw/globalfunctions/arrayprinter.h" +#include "fsfw/tmtcpacket/pus/tm.h" +#include "mocks/CdsShortTimestamperMock.h" +#include "mocks/SimpleSerializable.h" + +TEST_CASE("PUS TM Creator", "[pus-tm-creator]") { + auto packetId = PacketId(ccsds::PacketType::TC, true, 0xef); + auto spParams = + SpacePacketParams(packetId, PacketSeqCtrl(ccsds::SequenceFlags::UNSEGMENTED, 22), 0x00); + auto timeStamper = CdsShortTimestamperMock(); + auto pusTmParams = PusTmParams(17, 2, &timeStamper); + timeStamper.valueToStamp = {1, 2, 3, 4, 5, 6, 7}; + PusTmCreator creator(spParams, pusTmParams); + std::array buf{}; + uint8_t* dataPtr = buf.data(); + size_t serLen = 0; + + SECTION("State") { + CHECK(creator.isTm()); + CHECK(creator.hasSecHeader()); + CHECK(creator.getApid() == 0xef); + CHECK(creator.getPusVersion() == 2); + CHECK(creator.getScTimeRefStatus() == 0); + CHECK(creator.getService() == 17); + CHECK(creator.getSubService() == 2); + CHECK(creator.getTimestamper() == &timeStamper); + CHECK(creator.getSequenceFlags() == ccsds::SequenceFlags::UNSEGMENTED); + CHECK(creator.getSequenceCount() == 22); + // 6 bytes CCSDS header, 7 bytes secondary header, 7 bytes CDS short timestamp, + // 0 bytes application data, 2 bytes CRC + CHECK(creator.getFullPacketLen() == 22); + // As specified in standard, the data length fields is the total size of the packet without + // the primary header minus 1 + CHECK(creator.getPacketDataLen() == 15); + CHECK(timeStamper.getSizeCallCount == 1); + } + + SECTION("SP Params") { + auto& spParamsRef = creator.getSpParams(); + REQUIRE(spParamsRef.dataLen == 15); + REQUIRE(spParamsRef.packetId.apid == 0xef); + } + + SECTION("Serialization") { + REQUIRE(creator.SerializeIF::serializeBe(&dataPtr, &serLen, buf.size()) == returnvalue::OK); + REQUIRE(buf[0] == 0x08); + REQUIRE(buf[1] == 0xef); + // Unsegmented is the default + REQUIRE(buf[2] == 0xc0); + REQUIRE(buf[3] == 22); + REQUIRE(buf[4] == 0); + REQUIRE(buf[5] == 15); + REQUIRE(((buf[6] >> 4) & 0b1111) == ecss::PusVersion::PUS_C); + // SC time reference field + REQUIRE((buf[6] & 0b1111) == 0); + // Service and subservice field + REQUIRE(buf[7] == 17); + REQUIRE(buf[8] == 2); + // Message Sequence Count + REQUIRE(((buf[9] << 8) | buf[10]) == 0); + // Destination ID + REQUIRE(((buf[11] << 8) | buf[12]) == 0); + // Custom timestamp + for (size_t i = 1; i < 8; i++) { + REQUIRE(buf[12 + i] == i); + } + REQUIRE(serLen == 22); + REQUIRE(CRC::crc16ccitt(buf.data(), serLen) == 0); + REQUIRE(buf[20] == 0x03); + REQUIRE(buf[21] == 0x79); + REQUIRE(timeStamper.serializeCallCount == 1); + } + + SECTION("Custom Fields") { + creator.setApid(0x3ff); + SECTION("Using Params") { + auto& pusParams = creator.getParams(); + pusParams.secHeader.destId = 0xfff; + pusParams.secHeader.messageTypeCounter = 0x313; + } + SECTION("Using Setters") { + auto& pusParams = creator.getParams(); + creator.setDestId(0xfff); + creator.setMessageTypeCounter(0x313); + } + REQUIRE(creator.getApid() == 0x3ff); + REQUIRE(creator.getDestId() == 0xfff); + REQUIRE(creator.getMessageTypeCounter() == 0x313); + REQUIRE(creator.serializeBe(&dataPtr, &serLen, buf.size()) == returnvalue::OK); + // Message Sequence Count + REQUIRE(((buf[9] << 8) | buf[10]) == 0x313); + // Destination ID + REQUIRE(((buf[11] << 8) | buf[12]) == 0xfff); + } + + SECTION("Deserialization fails") { + SerializeIF& deser = creator; + const uint8_t* roDataPtr = nullptr; + REQUIRE(deser.deSerialize(&roDataPtr, &serLen, SerializeIF::Endianness::NETWORK) == + returnvalue::FAILED); + } + + SECTION("Serialize with Raw Data") { + std::array data{1, 2, 3}; + creator.setRawUserData(data.data(), data.size()); + REQUIRE(creator.getFullPacketLen() == 25); + REQUIRE(creator.serializeBe(&dataPtr, &serLen, buf.size()) == returnvalue::OK); + REQUIRE(buf[20] == 1); + REQUIRE(buf[21] == 2); + REQUIRE(buf[22] == 3); + } + + SECTION("Serialize with Serializable") { + auto simpleSer = SimpleSerializable(); + creator.setSerializableUserData(simpleSer); + REQUIRE(creator.getFullPacketLen() == 25); + REQUIRE(creator.serialize(&dataPtr, &serLen, buf.size(), SerializeIF::Endianness::NETWORK) == + returnvalue::OK); + REQUIRE(buf[20] == 1); + REQUIRE(buf[21] == 2); + REQUIRE(buf[22] == 3); + } + + SECTION("Empty Ctor") { + PusTmCreator creatorFromEmptyCtor; + // 6 bytes CCSDS header, 7 bytes secondary header, no timestamp (IF is null), + // 0 bytes application data, 2 bytes CRC + REQUIRE(creatorFromEmptyCtor.getFullPacketLen() == 15); + // As specified in standard, the data length fields is the total size of the packet without + // the primary header minus 1 + REQUIRE(creatorFromEmptyCtor.getPacketDataLen() == 8); + creatorFromEmptyCtor.setTimeStamper(timeStamper); + REQUIRE(creatorFromEmptyCtor.getFullPacketLen() == 22); + REQUIRE(creatorFromEmptyCtor.getPacketDataLen() == 15); + } + + SECTION("Invalid Buffer Sizes") { + size_t reqSize = creator.getSerializedSize(); + for (size_t maxSize = 0; maxSize < reqSize; maxSize++) { + dataPtr = buf.data(); + serLen = 0; + REQUIRE(creator.serialize(&dataPtr, &serLen, maxSize, SerializeIF::Endianness::NETWORK) == + SerializeIF::BUFFER_TOO_SHORT); + } + } + + SECTION("No CRC Generation") { + creator.disableCrcCalculation(); + REQUIRE(not creator.crcCalculationEnabled()); + REQUIRE(creator.serializeBe(dataPtr, serLen, buf.size()) == returnvalue::OK); + REQUIRE(serLen == 22); + REQUIRE(buf[20] == 0x00); + REQUIRE(buf[21] == 0x00); + } +} \ No newline at end of file diff --git a/unittests/tmtcpacket/testPusTmReader.cpp b/unittests/tmtcpacket/testPusTmReader.cpp new file mode 100644 index 00000000..1180fd23 --- /dev/null +++ b/unittests/tmtcpacket/testPusTmReader.cpp @@ -0,0 +1,109 @@ +#include + +#include "fsfw/tmtcpacket/pus/tm/PusTmCreator.h" +#include "fsfw/tmtcpacket/pus/tm/PusTmReader.h" +#include "mocks/CdsShortTimestamperMock.h" + +TEST_CASE("PUS TM Reader", "[pus-tm-reader]") { + auto packetId = PacketId(ccsds::PacketType::TC, true, 0xef); + auto spParams = + SpacePacketParams(packetId, PacketSeqCtrl(ccsds::SequenceFlags::UNSEGMENTED, 22), 0x00); + auto timeStamperAndReader = CdsShortTimestamperMock(); + auto pusTmParams = PusTmParams(17, 2, &timeStamperAndReader); + timeStamperAndReader.valueToStamp = {1, 2, 3, 4, 5, 6, 7}; + PusTmCreator creator(spParams, pusTmParams); + PusTmReader reader(&timeStamperAndReader); + std::array buf{}; + uint8_t* dataPtr = buf.data(); + size_t serLen = 0; + + SECTION("Basic") { + PusTmReader* readerPtr = &reader; + bool deleteReader = false; + dataPtr = buf.data(); + serLen = 0; + REQUIRE(creator.serializeBe(&dataPtr, &serLen, buf.size()) == returnvalue::OK); + REQUIRE(not(*readerPtr)); + REQUIRE(readerPtr->isNull()); + + SECTION("Setter") { + REQUIRE(readerPtr->setReadOnlyData(buf.data(), serLen) == returnvalue::OK); + } + SECTION("Full Construction") { + readerPtr = new PusTmReader(&timeStamperAndReader, buf.data(), serLen); + deleteReader = true; + } + SECTION("Time Stamper set manually") { + readerPtr = new PusTmReader(buf.data(), serLen); + readerPtr->setTimeReader(&timeStamperAndReader); + deleteReader = true; + } + REQUIRE(not *readerPtr); + REQUIRE(readerPtr->isNull()); + REQUIRE(readerPtr->parseDataWithCrcCheck() == returnvalue::OK); + REQUIRE(not readerPtr->isNull()); + REQUIRE(readerPtr->getService() == 17); + REQUIRE(readerPtr->getSubService() == 2); + REQUIRE(readerPtr->getApid() == 0xef); + REQUIRE(readerPtr->getSequenceFlags() == ccsds::SequenceFlags::UNSEGMENTED); + REQUIRE(readerPtr->getScTimeRefStatus() == 0); + REQUIRE(readerPtr->getDestId() == 0); + REQUIRE(readerPtr->getMessageTypeCounter() == 0); + REQUIRE(readerPtr->getTimeReader() == &timeStamperAndReader); + REQUIRE(readerPtr->getPusVersion() == 2); + REQUIRE(readerPtr->getPacketDataLen() == 15); + REQUIRE(readerPtr->getFullPacketLen() == 22); + REQUIRE(readerPtr->getUserDataLen() == 0); + REQUIRE(readerPtr->getUserData() == nullptr); + REQUIRE(readerPtr->getFullData() == buf.data()); + if (deleteReader) { + delete readerPtr; + } + } + + SECTION("Invalid CRC") { + REQUIRE(creator.serializeBe(&dataPtr, &serLen, buf.size()) == returnvalue::OK); + buf[20] = 0; + REQUIRE(reader.setReadOnlyData(buf.data(), serLen) == returnvalue::OK); + REQUIRE(reader.parseDataWithCrcCheck() == PusIF::INVALID_CRC_16); + } + + SECTION("Set Time Reader") { + reader.setTimeReader(nullptr); + REQUIRE(reader.getTimeReader() == nullptr); + } + + SECTION("Invalid CRC ignored") { + REQUIRE(creator.serializeBe(&dataPtr, &serLen, buf.size()) == returnvalue::OK); + buf[20] = 0; + REQUIRE(reader.setReadOnlyData(buf.data(), serLen) == returnvalue::OK); + REQUIRE(reader.parseDataWithoutCrcCheck() == returnvalue::OK); + } + + SECTION("Read with source data") { + std::array data{1, 2, 3}; + creator.setRawUserData(data.data(), data.size()); + REQUIRE(creator.serializeBe(&dataPtr, &serLen, buf.size()) == returnvalue::OK); + REQUIRE(reader.setReadOnlyData(buf.data(), serLen) == returnvalue::OK); + REQUIRE(reader.parseDataWithCrcCheck() == returnvalue::OK); + REQUIRE(reader.getUserDataLen() == 3); + const uint8_t* roData = reader.getUserData(); + REQUIRE(roData[0] == 1); + REQUIRE(roData[1] == 2); + REQUIRE(roData[2] == 3); + } + + SECTION("Invalid stream lengths") { + REQUIRE(creator.serializeBe(&dataPtr, &serLen, buf.size()) == returnvalue::OK); + for (size_t i = 0; i < serLen - 1; i++) { + REQUIRE(reader.setReadOnlyData(buf.data(), i) == SerializeIF::STREAM_TOO_SHORT); + } + } + + SECTION("Reading timestamp fails") { + timeStamperAndReader.nextDeserFails = true; + REQUIRE(creator.serializeBe(&dataPtr, &serLen, buf.size()) == returnvalue::OK); + REQUIRE(reader.setReadOnlyData(buf.data(), serLen) == returnvalue::OK); + REQUIRE(reader.parseDataWithCrcCheck() == returnvalue::FAILED); + } +} \ No newline at end of file diff --git a/unittests/tmtcpacket/testZcTmWriter.cpp b/unittests/tmtcpacket/testZcTmWriter.cpp new file mode 100644 index 00000000..12e88ea1 --- /dev/null +++ b/unittests/tmtcpacket/testZcTmWriter.cpp @@ -0,0 +1,42 @@ +#include + +#include "fsfw/globalfunctions/CRC.h" +#include "fsfw/tmtcpacket/pus/tm.h" +#include "fsfw/tmtcpacket/pus/tm/PusTmZcWriter.h" +#include "mocks/CdsShortTimestamperMock.h" + +TEST_CASE("TM ZC Helper", "[tm-zc-helper]") { + auto packetId = PacketId(ccsds::PacketType::TC, true, 0xef); + auto spParams = + SpacePacketParams(packetId, PacketSeqCtrl(ccsds::SequenceFlags::UNSEGMENTED, 22), 0x00); + auto timeStamper = CdsShortTimestamperMock(); + auto pusTmParams = PusTmParams(17, 2, &timeStamper); + timeStamper.valueToStamp = {1, 2, 3, 4, 5, 6, 7}; + PusTmCreator creator(spParams, pusTmParams); + std::array buf{}; + uint8_t* dataPtr = buf.data(); + size_t serLen = 0; + + SECTION("No Crash For Uninitialized Object") { + REQUIRE(creator.serializeBe(dataPtr, serLen, buf.size()) == returnvalue::OK); + PusTmZeroCopyWriter writer(timeStamper, dataPtr, serLen); + REQUIRE(writer.getSequenceCount() == 22); + writer.setSequenceCount(23); + // Can't set anything, parse function was not called + REQUIRE(writer.getSequenceCount() == 22); + writer.updateErrorControl(); + } + + SECTION("Basic") { + REQUIRE(creator.serializeBe(dataPtr, serLen, buf.size()) == returnvalue::OK); + PusTmZeroCopyWriter writer(timeStamper, dataPtr, serLen); + REQUIRE(writer.parseDataWithoutCrcCheck() == returnvalue::OK); + REQUIRE(writer.getSequenceCount() == 22); + writer.setSequenceCount(23); + REQUIRE(writer.getSequenceCount() == 23); + // CRC is invalid now + REQUIRE(CRC::crc16ccitt(dataPtr, serLen) != 0); + writer.updateErrorControl(); + REQUIRE(CRC::crc16ccitt(dataPtr, serLen) == 0); + } +} \ No newline at end of file diff --git a/unittests/tmtcservices/CMakeLists.txt b/unittests/tmtcservices/CMakeLists.txt new file mode 100644 index 00000000..9e60ced1 --- /dev/null +++ b/unittests/tmtcservices/CMakeLists.txt @@ -0,0 +1,6 @@ +target_sources(${FSFW_TEST_TGT} PRIVATE + testStoreHelper.cpp + testSendHelper.cpp + testStoreAndSendHelper.cpp + testPsb.cpp +) diff --git a/unittests/tmtcservices/testPsb.cpp b/unittests/tmtcservices/testPsb.cpp new file mode 100644 index 00000000..ec252da6 --- /dev/null +++ b/unittests/tmtcservices/testPsb.cpp @@ -0,0 +1,247 @@ +#include + +#include "fsfw/ipc/QueueFactory.h" +#include "fsfw/storagemanager/LocalPool.h" +#include "fsfw/storagemanager/PoolManager.h" +#include "mocks/AcceptsTmMock.h" +#include "mocks/CdsShortTimestamperMock.h" +#include "mocks/InternalErrorReporterMock.h" +#include "mocks/MessageQueueMock.h" +#include "mocks/PusDistributorMock.h" +#include "mocks/PusServiceBaseMock.h" +#include "mocks/PusVerificationReporterMock.h" + +TEST_CASE("Pus Service Base", "[pus-service-base]") { + uint16_t apid = 2; + auto verificationReporter = PusVerificationReporterMock(); + auto msgQueue = MessageQueueMock(1); + auto tmReceiver = AcceptsTmMock(2); + auto psbParams = PsbParams(0, apid, 17); + + LocalPool::LocalPoolConfig cfg = {{5, 32}, {2, 64}}; + LocalPool pool(objects::NO_OBJECT, cfg); + + psbParams.verifReporter = &verificationReporter; + psbParams.reqQueue = &msgQueue; + psbParams.tmReceiver = &tmReceiver; + psbParams.tcPool = &pool; + auto psb = PsbMock(psbParams); + + store_address_t storeId; + TmTcMessage tmtcMsg; + + // Components to create valid PUS packets + auto packetId = PacketId(ccsds::PacketType::TC, true, 0x02); + auto spParams = + SpacePacketParams(packetId, PacketSeqCtrl(ccsds::SequenceFlags::UNSEGMENTED, 0x34), 0x00); + auto pusParams = PusTcParams(17, 1); + PusTcCreator creator(spParams, pusParams); + + REQUIRE(psb.initialize() == returnvalue::OK); + + SECTION("State") { + REQUIRE(psb.getIdentifier() == 17); + REQUIRE(psb.getObjectId() == 0); + REQUIRE(psb.getRequestQueue() == msgQueue.getId()); + auto psbParamsLocal = psb.getParams(); + REQUIRE(psbParamsLocal.errReporter == nullptr); + } + + SECTION("Perform Service") { + REQUIRE(psb.performServiceCallCnt == 0); + REQUIRE(psb.performOperation(0) == returnvalue::OK); + REQUIRE(psb.performServiceCallCnt == 1); + } + + SECTION("Send Request with Successful Handling") { + REQUIRE(psb.performServiceCallCnt == 0); + uint8_t* dataPtr; + REQUIRE(pool.getFreeElement(&storeId, creator.getSerializedSize(), &dataPtr) == + returnvalue::OK); + size_t serLen = 0; + REQUIRE(creator.serializeBe(dataPtr, serLen, creator.getSerializedSize()) == returnvalue::OK); + tmtcMsg.setStorageId(storeId); + msgQueue.addReceivedMessage(tmtcMsg); + REQUIRE(psb.performOperation(0) == returnvalue::OK); + uint8_t subservice = 0; + REQUIRE(psb.getAndPopNextSubservice(subservice)); + REQUIRE(subservice == 1); + REQUIRE(psb.performServiceCallCnt == 1); + // PSB should take care of freeing the pool slot + REQUIRE(not pool.hasDataAtId(storeId)); + REQUIRE(verificationReporter.successCallCount() == 1); + REQUIRE(verificationReporter.failCallCount() == 0); + auto verifParams = verificationReporter.getNextSuccessCallParams(); + REQUIRE(verifParams.tcPacketId == creator.getPacketIdRaw()); + REQUIRE(verifParams.tcPsc == creator.getPacketSeqCtrlRaw()); + } + + SECTION("Send Request with Failed Handling") { + uint8_t* dataPtr; + REQUIRE(pool.getFreeElement(&storeId, creator.getSerializedSize(), &dataPtr) == + returnvalue::OK); + size_t serLen = 0; + REQUIRE(creator.serializeBe(dataPtr, serLen, creator.getSerializedSize()) == returnvalue::OK); + tmtcMsg.setStorageId(storeId); + msgQueue.addReceivedMessage(tmtcMsg); + psb.makeNextHandleReqCallFail(3); + REQUIRE(psb.performOperation(0) == returnvalue::OK); + uint8_t subservice = 0; + REQUIRE(psb.getAndPopNextSubservice(subservice)); + REQUIRE(subservice == 1); + REQUIRE(psb.performServiceCallCnt == 1); + // PSB should take care of freeing the pool slot + REQUIRE(not pool.hasDataAtId(storeId)); + REQUIRE(verificationReporter.successCallCount() == 0); + REQUIRE(verificationReporter.failCallCount() == 1); + auto verifParams = verificationReporter.getNextFailCallParams(); + REQUIRE(verifParams.tcPacketId == creator.getPacketIdRaw()); + REQUIRE(verifParams.tcPsc == creator.getPacketSeqCtrlRaw()); + } + + SECTION("Invalid Packet Sent") { + tmtcMsg.setStorageId(store_address_t::invalid()); + msgQueue.addReceivedMessage(tmtcMsg); + REQUIRE(psb.performOperation(0) == returnvalue::OK); + REQUIRE(verificationReporter.failCallCount() == 1); + auto verifParams = verificationReporter.getNextFailCallParams(); + REQUIRE(verifParams.tcPacketId == 0); + REQUIRE(verifParams.tcPsc == 0); + } + + SECTION("Set Verif Reporter") { + auto verificationReporter2 = PusVerificationReporterMock(); + psb.setVerificationReporter(verificationReporter2); + auto& p = psb.getParams(); + REQUIRE(p.verifReporter == &verificationReporter2); + } + + SECTION("Set Request Queue") { + auto msgQueueMock = MessageQueueMock(2); + psb.setRequestQueue(msgQueueMock); + auto& p = psb.getParams(); + REQUIRE(p.reqQueue == &msgQueueMock); + } + + SECTION("Set TM Receiver") { + auto tmReceiver2 = AcceptsTmMock(3); + psb.setTmReceiver(tmReceiver2); + auto& p = psb.getParams(); + REQUIRE(p.tmReceiver == &tmReceiver2); + } + + SECTION("Set TC Store") { + LocalPool tcStore2(5, cfg); + psb.setTcPool(tcStore2); + auto& p = psb.getParams(); + REQUIRE(p.tcPool == &tcStore2); + } + + SECTION("Set error reporter") { + auto errReporter = InternalErrorReporterMock(); + psb.setErrorReporter(errReporter); + auto& p = psb.getParams(); + REQUIRE(p.errReporter == &errReporter); + } + SECTION("Owner Queue") { + // This will cause the initialize function to create a new owner queue + psbParams.reqQueue = nullptr; + psbParams.objectId = 1; + auto mockWithOwnerQueue = PsbMock(psbParams); + REQUIRE(mockWithOwnerQueue.getRequestQueue() == MessageQueueIF::NO_QUEUE); + REQUIRE(mockWithOwnerQueue.initialize() == returnvalue::OK); + REQUIRE(mockWithOwnerQueue.getRequestQueue() != MessageQueueIF::NO_QUEUE); + } + + SECTION("TM Store Helper Initializer") { + TmStoreHelper storeHelper(0); + psb.initializeTmStoreHelper(storeHelper); + REQUIRE(storeHelper.getApid() == apid); + } + + SECTION("TM Send Helper Initializer") { + TmSendHelper sendHelper; + psb.initializeTmSendHelper(sendHelper); + REQUIRE(sendHelper.getMsgQueue() == &msgQueue); + REQUIRE(sendHelper.getDefaultDestination() == msgQueue.getDefaultDestination()); + } + + SECTION("TM Store And Send Helper Initializer") { + TmStoreHelper storeHelper(0); + TmSendHelper sendHelper; + psb.initializeTmHelpers(sendHelper, storeHelper); + REQUIRE(sendHelper.getMsgQueue() == &msgQueue); + REQUIRE(sendHelper.getDefaultDestination() == msgQueue.getDefaultDestination()); + REQUIRE(storeHelper.getApid() == apid); + } + + SECTION("TM Send Helper Initializer With Error Reporter") { + TmSendHelper sendHelper; + auto errReporter = InternalErrorReporterMock(); + psb.setErrorReporter(errReporter); + psb.initializeTmSendHelper(sendHelper); + REQUIRE(sendHelper.getMsgQueue() == &msgQueue); + REQUIRE(sendHelper.getDefaultDestination() == msgQueue.getDefaultDestination()); + REQUIRE(sendHelper.getInternalErrorReporter() == &errReporter); + } + + SECTION("Auto Initialize PUS Distributor") { + psbParams.objectId = 1; + object_id_t distributorId = 3; + auto psb2 = PsbMock(psbParams); + auto pusDistrib = PusDistributorMock(distributorId); + PsbMock::setStaticPusDistributor(distributorId); + REQUIRE(PsbMock::getStaticPusDistributor() == distributorId); + REQUIRE(psb2.initialize() == returnvalue::OK); + REQUIRE(pusDistrib.registerCallCount == 1); + REQUIRE(pusDistrib.lastServiceArg == &psb2); + } + + SECTION("Auto Initialize Packet Destination") { + psbParams.tmReceiver = nullptr; + psbParams.objectId = 1; + object_id_t destId = 3; + auto psb2 = PsbMock(psbParams); + auto packetDest = AcceptsTmMock(destId, 2); + PsbMock::setStaticTmDest(destId); + REQUIRE(PsbMock::getStaticTmDest() == destId); + REQUIRE(psb2.initialize() == returnvalue::OK); + auto& p = psb2.getParams(); + REQUIRE(p.tmReceiver == &packetDest); + } + + SECTION("Auto Initialize Verification Reporter") { + psbParams.verifReporter = nullptr; + psbParams.objectId = 1; + object_id_t reporterId = objects::VERIFICATION_REPORTER; + PusVerificationReporterMock otherReporter(reporterId); + auto psb2 = PsbMock(psbParams); + REQUIRE(psb2.initialize() == returnvalue::OK); + auto& p = psb2.getParams(); + REQUIRE(p.verifReporter == &otherReporter); + } + + SECTION("Auto Initialize TC Pool") { + PoolManager tcStoreGlobal(objects::TC_STORE, cfg); + psbParams.tcPool = nullptr; + psbParams.objectId = 1; + auto psb2 = PsbMock(psbParams); + REQUIRE(psb2.initialize() == returnvalue::OK); + auto& p = psb2.getParams(); + REQUIRE(p.tcPool == &tcStoreGlobal); + } + + SECTION("Invalid Verification Reporter") { + psbParams.verifReporter = nullptr; + psbParams.objectId = 1; + auto psb2 = PsbMock(psbParams); + REQUIRE(psb2.initialize() == ObjectManagerIF::CHILD_INIT_FAILED); + } + + SECTION("Invalid TC Store") { + psbParams.tcPool = nullptr; + psbParams.objectId = 1; + auto psb2 = PsbMock(psbParams); + REQUIRE(psb2.initialize() == ObjectManagerIF::CHILD_INIT_FAILED); + } +} diff --git a/unittests/tmtcservices/testSendHelper.cpp b/unittests/tmtcservices/testSendHelper.cpp new file mode 100644 index 00000000..43816835 --- /dev/null +++ b/unittests/tmtcservices/testSendHelper.cpp @@ -0,0 +1,106 @@ +#include + +#include "fsfw/storagemanager/LocalPool.h" +#include "fsfw/tmtcservices/TmSendHelper.h" +#include "fsfw/tmtcservices/TmStoreHelper.h" +#include "mocks/CdsShortTimestamperMock.h" +#include "mocks/InternalErrorReporterMock.h" +#include "mocks/MessageQueueMock.h" + +TEST_CASE("TM Send Helper", "[tm-send-helper]") { + MessageQueueId_t destId = 2; + auto errReporter = InternalErrorReporterMock(); + auto msgQueue = MessageQueueMock(1); + msgQueue.setDefaultDestination(destId); + TmSendHelper sendHelper(msgQueue, errReporter, destId); + auto timeStamper = CdsShortTimestamperMock(); + LocalPool::LocalPoolConfig cfg = {{5, 32}, {2, 64}}; + LocalPool pool(objects::NO_OBJECT, cfg); + auto storeHelper = TmStoreHelper(2, pool, timeStamper); + + SECTION("State and Setters") { + REQUIRE(sendHelper.getInternalErrorReporter() == &errReporter); + REQUIRE(sendHelper.getDefaultDestination() == destId); + REQUIRE(sendHelper.getMsgQueue() == &msgQueue); + } + + SECTION("Setters") { + REQUIRE(not sendHelper.areFaultsIgnored()); + sendHelper.ignoreFaults(); + REQUIRE(sendHelper.areFaultsIgnored()); + sendHelper.dontIgnoreFaults(); + REQUIRE(not sendHelper.areFaultsIgnored()); + REQUIRE(sendHelper.getDefaultDestination() == destId); + sendHelper.setDefaultDestination(destId + 1); + REQUIRE(sendHelper.getDefaultDestination() == destId + 1); + auto errReporter2 = InternalErrorReporterMock(); + sendHelper.setInternalErrorReporter(errReporter2); + REQUIRE(sendHelper.getInternalErrorReporter() == &errReporter2); + } + + SECTION("Default CTOR") { + TmSendHelper emptyHelper; + REQUIRE(emptyHelper.getInternalErrorReporter() == nullptr); + REQUIRE(emptyHelper.getDefaultDestination() == MessageQueueIF::NO_QUEUE); + store_address_t dummy; + // basic robustness + REQUIRE(emptyHelper.sendPacket(dummy) == returnvalue::FAILED); + } + + SECTION("One Arg CTOR") { + TmSendHelper helper(errReporter); + REQUIRE(helper.getInternalErrorReporter() == &errReporter); + REQUIRE(helper.getDefaultDestination() == MessageQueueIF::NO_QUEUE); + REQUIRE(helper.getMsgQueue() == nullptr); + } + + SECTION("Two Arg CTOR") { + TmSendHelper helper(msgQueue, errReporter); + REQUIRE(helper.getInternalErrorReporter() == &errReporter); + REQUIRE(helper.getDefaultDestination() == 2); + REQUIRE(helper.getMsgQueue() == &msgQueue); + } + SECTION("Send") { + REQUIRE(storeHelper.preparePacket(17, 2, 0) == returnvalue::OK); + store_address_t storeId; + SECTION("Separate Helpers") { + REQUIRE(storeHelper.addPacketToStore() == returnvalue::OK); + storeId = storeHelper.getCurrentAddr(); + REQUIRE(sendHelper.sendPacket(storeId) == returnvalue::OK); + } + REQUIRE(msgQueue.wasMessageSent()); + REQUIRE(msgQueue.numberOfSentMessagesToDefault() == 1); + TmTcMessage msg; + REQUIRE(msgQueue.getNextSentMessage(msg) == returnvalue::OK); + REQUIRE(msg.getStorageId() == storeId); + REQUIRE(pool.hasDataAtId(msg.getStorageId())); + } + + SECTION("Send to Non-Default") { + storeHelper.preparePacket(17, 2, 0); + REQUIRE(storeHelper.addPacketToStore() == returnvalue::OK); + store_address_t storeId = storeHelper.getCurrentAddr(); + REQUIRE(sendHelper.sendPacket(destId + 1, storeId) == returnvalue::OK); + REQUIRE(msgQueue.wasMessageSent()); + REQUIRE(msgQueue.numberOfSentMessagesToDest(destId + 1) == 1); + } + + SECTION("Sending fails, errors not ignored") { + msgQueue.makeNextSendFail(returnvalue::FAILED); + storeHelper.preparePacket(17, 2, 0); + REQUIRE(storeHelper.addPacketToStore() == returnvalue::OK); + store_address_t storeId = storeHelper.getCurrentAddr(); + REQUIRE(sendHelper.sendPacket(destId + 1, storeId) == returnvalue::FAILED); + REQUIRE(errReporter.lostTmCallCnt == 1); + } + + SECTION("Sending fails, errors ignored") { + msgQueue.makeNextSendFail(returnvalue::FAILED); + storeHelper.preparePacket(17, 2, 0); + sendHelper.ignoreFaults(); + REQUIRE(storeHelper.addPacketToStore() == returnvalue::OK); + store_address_t storeId = storeHelper.getCurrentAddr(); + REQUIRE(sendHelper.sendPacket(destId + 1, storeId) == returnvalue::FAILED); + REQUIRE(errReporter.lostTmCallCnt == 0); + } +} \ No newline at end of file diff --git a/unittests/tmtcservices/testStoreAndSendHelper.cpp b/unittests/tmtcservices/testStoreAndSendHelper.cpp new file mode 100644 index 00000000..2731b28f --- /dev/null +++ b/unittests/tmtcservices/testStoreAndSendHelper.cpp @@ -0,0 +1,94 @@ +#include + +#include "fsfw/storagemanager/LocalPool.h" +#include "fsfw/tmtcservices/TmSendHelper.h" +#include "fsfw/tmtcservices/TmStoreAndSendHelper.h" +#include "fsfw/tmtcservices/TmStoreHelper.h" +#include "mocks/CdsShortTimestamperMock.h" +#include "mocks/InternalErrorReporterMock.h" +#include "mocks/MessageQueueMock.h" +#include "mocks/SimpleSerializable.h" + +TEST_CASE("TM Store And Send Helper", "[tm-store-send-helper]") { + auto timeStamper = CdsShortTimestamperMock(); + LocalPool::LocalPoolConfig cfg = {{5, 32}, {2, 64}}; + LocalPool pool(objects::NO_OBJECT, cfg); + auto storeHelper = TmStoreHelper(2, pool, timeStamper); + + MessageQueueId_t destId = 1; + auto errReporter = InternalErrorReporterMock(); + auto msgQueue = MessageQueueMock(2); + msgQueue.setDefaultDestination(destId); + TmSendHelper sendHelper(msgQueue, errReporter, destId); + TmStoreAndSendWrapper tmHelper(17, storeHelper, sendHelper); + + SECTION("State") { + CHECK(tmHelper.sendCounter == 0); + CHECK(tmHelper.defaultService == 17); + CHECK(tmHelper.delOnFailure); + CHECK(tmHelper.incrementSendCounter); + CHECK(&tmHelper.sendHelper == &sendHelper); + CHECK(&tmHelper.storeHelper == &storeHelper); + } + + SECTION("Storage Fails") { + // Too large to fit in store + std::array data{}; + REQUIRE(storeHelper.setSourceDataRaw(data.data(), data.size()) == returnvalue::OK); + REQUIRE(tmHelper.storeAndSendTmPacket() == StorageManagerIF::DATA_TOO_LARGE); + } + + SECTION("Base Test") { + tmHelper.prepareTmPacket(2); + auto& creator = storeHelper.getCreatorRef(); + REQUIRE(creator.getSubService() == 2); + REQUIRE(creator.getService() == 17); + auto& params = creator.getParams(); + REQUIRE(params.dataWrapper.type == util::DataTypes::RAW); + REQUIRE(params.dataWrapper.dataUnion.raw.data == nullptr); + REQUIRE(params.dataWrapper.dataUnion.raw.len == 0); + REQUIRE(tmHelper.sendCounter == 0); + REQUIRE(tmHelper.storeAndSendTmPacket() == returnvalue::OK); + REQUIRE(tmHelper.sendCounter == 1); + auto storeId = storeHelper.getCurrentAddr(); + REQUIRE(msgQueue.wasMessageSent()); + REQUIRE(msgQueue.numberOfSentMessagesToDefault() == 1); + TmTcMessage msg; + REQUIRE(msgQueue.getNextSentMessage(msg) == returnvalue::OK); + REQUIRE(msg.getStorageId() == storeId); + REQUIRE(pool.hasDataAtId(msg.getStorageId())); + storeHelper.deletePacket(); + } + + SECTION("Raw Data Helper") { + std::array data = {1, 2, 3}; + REQUIRE(tmHelper.prepareTmPacket(2, data.data(), data.size()) == returnvalue::OK); + auto& creator = storeHelper.getCreatorRef(); + auto& params = creator.getParams(); + REQUIRE(params.dataWrapper.type == util::DataTypes::RAW); + REQUIRE(params.dataWrapper.dataUnion.raw.data == data.data()); + REQUIRE(params.dataWrapper.dataUnion.raw.len == data.size()); + } + + SECTION("Serializable Helper") { + auto simpleSer = SimpleSerializable(); + REQUIRE(tmHelper.prepareTmPacket(2, simpleSer) == returnvalue::OK); + auto& creator = storeHelper.getCreatorRef(); + auto& params = creator.getParams(); + REQUIRE(params.dataWrapper.type == util::DataTypes::SERIALIZABLE); + REQUIRE(params.dataWrapper.dataUnion.serializable == &simpleSer); + } + + SECTION("Object ID prefix Helper") { + uint32_t objectId = 0x01020304; + std::array data = {1, 2, 3}; + telemetry::DataWithObjectIdPrefix dataWithObjId(objectId, data.data(), data.size()); + REQUIRE(tmHelper.prepareTmPacket(2, dataWithObjId) == returnvalue::OK); + auto& creator = storeHelper.getCreatorRef(); + auto& params = creator.getParams(); + REQUIRE(params.dataWrapper.type == util::DataTypes::SERIALIZABLE); + REQUIRE(params.dataWrapper.dataUnion.serializable == &dataWithObjId); + } + + // TODO: Error handling +} diff --git a/unittests/tmtcservices/testStoreHelper.cpp b/unittests/tmtcservices/testStoreHelper.cpp new file mode 100644 index 00000000..dd73305d --- /dev/null +++ b/unittests/tmtcservices/testStoreHelper.cpp @@ -0,0 +1,110 @@ +#include + +#include "fsfw/storagemanager/LocalPool.h" +#include "fsfw/tmtcservices/TmStoreHelper.h" +#include "fsfw/tmtcservices/tmHelpers.h" +#include "mocks/CdsShortTimestamperMock.h" +#include "mocks/SimpleSerializable.h" + +TEST_CASE("TM Store Helper", "[tm-store-helper]") { + auto timeStamper = CdsShortTimestamperMock(); + LocalPool::LocalPoolConfig cfg = {{5, 32}, {2, 64}}; + LocalPool pool(objects::NO_OBJECT, cfg); + auto storeHelper = TmStoreHelper(2, pool, timeStamper); + + SECTION("State") { + REQUIRE(storeHelper.getCurrentAddr() == store_address_t::invalid()); + REQUIRE(storeHelper.getTimeStamper() == &timeStamper); + REQUIRE(storeHelper.getTmStore() == &pool); + REQUIRE(storeHelper.preparePacket(17, 1, 1) == returnvalue::OK); + auto& creator = storeHelper.getCreatorRef(); + REQUIRE(creator.getApid() == 2); + REQUIRE(creator.getService() == 17); + REQUIRE(creator.getSubService() == 1); + REQUIRE(creator.getSequenceCount() == 0); + REQUIRE(creator.getMessageTypeCounter() == 1); + } + + SECTION("Timestamper Setter") { + auto timeStamper2 = CdsShortTimestamperMock(); + storeHelper.setTimeStamper(timeStamper2); + REQUIRE(storeHelper.getTimeStamper() == &timeStamper2); + } + + SECTION("Pool Setter") { + LocalPool::LocalPoolConfig cfg2 = {{10, 32}, {5, 64}}; + LocalPool pool2(objects::NO_OBJECT, cfg); + storeHelper.setTmStore(pool2); + REQUIRE(storeHelper.getTmStore() == &pool2); + } + + SECTION("APID Setter") { + storeHelper.setApid(3); + auto& creator = storeHelper.getCreatorRef(); + REQUIRE(creator.getApid() == 3); + } + + SECTION("Basic") { + REQUIRE(storeHelper.preparePacket(17, 1, 1) == returnvalue::OK); + REQUIRE(storeHelper.addPacketToStore() == returnvalue::OK); + REQUIRE(storeHelper.getCurrentAddr() != store_address_t::invalid()); + auto accessor = pool.getData(storeHelper.getCurrentAddr()); + REQUIRE(accessor.first == returnvalue::OK); + // Not going to verify individual fields, the creator was unittested separately + REQUIRE(accessor.second.size() == 22); + } + + SECTION("Deletion") { + REQUIRE(storeHelper.preparePacket(17, 1, 1) == returnvalue::OK); + REQUIRE(storeHelper.addPacketToStore() == returnvalue::OK); + REQUIRE(storeHelper.getCurrentAddr() != store_address_t::invalid()); + { + auto accessor = pool.getData(storeHelper.getCurrentAddr()); + REQUIRE(accessor.first == returnvalue::OK); + REQUIRE(accessor.second.size() == 22); + accessor.second.release(); + } + REQUIRE(storeHelper.deletePacket() == returnvalue::OK); + REQUIRE(storeHelper.getCurrentAddr() == store_address_t::invalid()); + auto accessor = pool.getData(storeHelper.getCurrentAddr()); + REQUIRE(accessor.first != returnvalue::OK); + } + + SECTION("With App Data Raw") { + REQUIRE(storeHelper.preparePacket(17, 1, 1) == returnvalue::OK); + std::array data = {1, 2, 3}; + REQUIRE(storeHelper.setSourceDataRaw(data.data(), data.size()) == returnvalue::OK); + REQUIRE(storeHelper.addPacketToStore() == returnvalue::OK); + REQUIRE(storeHelper.getCurrentAddr() != store_address_t::invalid()); + auto accessor = pool.getData(storeHelper.getCurrentAddr()); + REQUIRE(accessor.first == returnvalue::OK); + // Not going to verify individual fields, the creator was unittested separately + REQUIRE(accessor.second.size() == 25); + } + + SECTION("With App Data Serializable") { + REQUIRE(storeHelper.preparePacket(17, 1, 1) == returnvalue::OK); + auto serializable = SimpleSerializable(); + REQUIRE(storeHelper.setSourceDataSerializable(serializable) == returnvalue::OK); + REQUIRE(storeHelper.addPacketToStore() == returnvalue::OK); + REQUIRE(storeHelper.getCurrentAddr() != store_address_t::invalid()); + auto accessor = pool.getData(storeHelper.getCurrentAddr()); + REQUIRE(accessor.first == returnvalue::OK); + // Not going to verify individual fields, the creator was unittested separately + REQUIRE(accessor.second.size() == 25); + } + + SECTION("APID Only CTOR") { + auto storeHelperApidOnly = TmStoreHelper(2); + REQUIRE(storeHelperApidOnly.getApid() == 2); + REQUIRE(storeHelperApidOnly.getTmStore() == nullptr); + REQUIRE(storeHelperApidOnly.getTimeStamper() == nullptr); + } + + SECTION("APID and TM Store Only CTOR") { + auto storeHelperApidOnly = TmStoreHelper(2, pool); + REQUIRE(storeHelperApidOnly.getApid() == 2); + REQUIRE(storeHelperApidOnly.getTmStore() == &pool); + REQUIRE(storeHelperApidOnly.getTimeStamper() == nullptr); + } +} \ No newline at end of file diff --git a/unittests/util/CMakeLists.txt b/unittests/util/CMakeLists.txt index d4caa4d5..dd9f6dc1 100644 --- a/unittests/util/CMakeLists.txt +++ b/unittests/util/CMakeLists.txt @@ -1,3 +1,4 @@ target_sources(${FSFW_TEST_TGT} PRIVATE testUnsignedByteField.cpp + testDataWrapper.cpp ) diff --git a/unittests/util/testDataWrapper.cpp b/unittests/util/testDataWrapper.cpp new file mode 100644 index 00000000..72931d90 --- /dev/null +++ b/unittests/util/testDataWrapper.cpp @@ -0,0 +1,59 @@ +#include +#include + +#include "fsfw/util/dataWrapper.h" +#include "mocks/SimpleSerializable.h" + +TEST_CASE("Data Wrapper", "[util]") { + util::DataWrapper wrapper; + SECTION("State") { + REQUIRE(wrapper.isNull()); + REQUIRE(wrapper.type == util::DataTypes::NONE); + } + + SECTION("Set Raw Data") { + util::DataWrapper* instance = &wrapper; + bool deleteInst = false; + REQUIRE(wrapper.isNull()); + std::array data = {1, 2, 3, 4}; + SECTION("Setter") { + wrapper.setRawData({data.data(), data.size()}); + } + SECTION("Direct Construction Pair") { + instance = new util::DataWrapper(util::BufPair(data.data(), data.size())); + deleteInst = true; + } + SECTION("Direct Construction Single Args") { + instance = new util::DataWrapper(data.data(), data.size()); + deleteInst = true; + } + REQUIRE(not instance->isNull()); + REQUIRE(instance->type == util::DataTypes::RAW); + REQUIRE(instance->dataUnion.raw.data == data.data()); + REQUIRE(instance->dataUnion.raw.len == data.size()); + if(deleteInst) { + delete instance; + } + } + + SECTION("Simple Serializable") { + util::DataWrapper* instance = &wrapper; + bool deleteInst = false; + REQUIRE(instance->isNull()); + SimpleSerializable serializable; + SECTION("Setter") { + wrapper.setSerializable(serializable); + } + SECTION("Direct Construction") { + instance = new util::DataWrapper(serializable); + deleteInst = true; + } + + REQUIRE(not instance->isNull()); + REQUIRE(instance->type == util::DataTypes::SERIALIZABLE); + REQUIRE(instance->dataUnion.serializable == &serializable); + if(deleteInst) { + delete instance; + } + } +} \ No newline at end of file diff --git a/unittests/util/testUnsignedByteField.cpp b/unittests/util/testUnsignedByteField.cpp index df1ff483..58a87a7d 100644 --- a/unittests/util/testUnsignedByteField.cpp +++ b/unittests/util/testUnsignedByteField.cpp @@ -4,7 +4,7 @@ #include "fsfw/util/UnsignedByteField.h" -TEST_CASE("Unsigned Byte Field", "[unsigned-byte-field]") { +TEST_CASE("Unsigned Byte Field", "[util]") { auto testByteField = UnsignedByteField(10); auto u32ByteField = U32ByteField(10); auto u16ByteField = U16ByteField(5);