Compare commits

..

1 Commits

Author SHA1 Message Date
04122ffec5 dumb bug 2022-09-28 17:00:28 +02:00
544 changed files with 6733 additions and 12935 deletions

2
.gitignore vendored
View File

@ -1,5 +1,5 @@
# PyCharm and CLion # PyCharm and CLion
.idea/* /.idea/*
!/.idea/runConfigurations !/.idea/runConfigurations
!/.idea/cmake.xml !/.idea/cmake.xml
!/.idea/codeStyles !/.idea/codeStyles

View File

@ -1,8 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="CMakeSharedSettings">
<configurations>
<configuration PROFILE_NAME="Debug Test" ENABLED="true" CONFIG_NAME="Debug" GENERATION_OPTIONS="-DFSFW_OSAL=host -DFSFW_BUILD_TESTS=ON" NO_GENERATOR="true" />
</configurations>
</component>
</project>

View File

@ -8,169 +8,23 @@ and this project adheres to [Semantic Versioning](http://semver.org/).
# [unreleased] # [unreleased]
## Fixes # [v6.0.0]
- The `PusTmCreator` API only accepted 255 bytes of source data. It can now accept source
data with a size limited only by the size of `size_t`.
- Important bugfix in CFDP PDU header format: The entity length field and the transaction sequence
number fields stored the actual length of the field instead of the length minus 1 like specified
in the CFDP standard.
- PUS Health Service: Size check for set health command.
Perform operation completion for announce health command.
https://egit.irs.uni-stuttgart.de/fsfw/fsfw/pulls/746
- Linux OSAL `getUptime` fix: Check validity of `/proc/uptime` file before reading uptime.
https://egit.irs.uni-stuttgart.de/fsfw/fsfw/pulls/745
- Small tweak for version getter
https://egit.irs.uni-stuttgart.de/fsfw/fsfw/pulls/744
## Added ## Added
- add CFDP subsystem ID - DHB TM handler `handleDeviceTM` renamed to `handleDeviceTm` and now takes
https://egit.irs.uni-stuttgart.de/fsfw/fsfw/pulls/742 `util::DataWrapper` as the data input argument. This allows more flexibility in the possible
- `PusTmZcWriter` now exposes API to set message counter field. types of telemetry.
- Relative timeshift in the PUS time service. 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
## Changed to specify raw data either as a classic C-style raw pointer and size or as a `SerializeIF`
pointer.
- The PUS time service now dumps the time before setting a new time and after having set the PR: https://egit.irs.uni-stuttgart.de/fsfw/fsfw/pulls/668
time.
- HK generation is now countdown based.
- Bump ETL version to 20.35.14
https://egit.irs.uni-stuttgart.de/fsfw/fsfw/pulls/748
- Renamed `PCDU_2` subsystem ID to `POWER_SWITCH_IF`.
https://egit.irs.uni-stuttgart.de/fsfw/fsfw/pulls/743
- Add new `PowerSwitchIF::SWITCH_UNKNOWN` returnvalue.
https://egit.irs.uni-stuttgart.de/fsfw/fsfw/pulls/743
- Assert that `FixedArrayList` is larger than 0 at compile time.
https://egit.irs.uni-stuttgart.de/fsfw/fsfw/pulls/740
- Health functions are virtual now.
- PUS Service Base request queue depth and maximum number of handled packets per cycle is now
configurable.
# [v6.0.0] 2023-02-10
## Fixes
- Mode Service: Add allowed subservice
PR: https://egit.irs.uni-stuttgart.de/fsfw/fsfw/pulls/739
- `CService200ModeManagement`: Various bugfixes which lead to now execution complete being generated
on mode announcements, duplicate mode reply generated on announce commands, and the mode read
subservice not working properly.
PR: https://egit.irs.uni-stuttgart.de/fsfw/fsfw/pulls/736
- Memory leak fixes for the TCP/IP TMTC bridge.
PR: https://egit.irs.uni-stuttgart.de/fsfw/fsfw/pulls/737
- `Service9TimeManagement`: Fix the time dump at the `SET_TIME` subservice: Include clock timeval
seconds instead of uptime.
PR: https://egit.irs.uni-stuttgart.de/fsfw/fsfw/pulls/726
- HAL MGM3100 Handler: Use axis specific gain/scaling factors. Previously,
only the X scaling factor was used.
PR: https://egit.irs.uni-stuttgart.de/fsfw/fsfw/pulls/724
- HAL MGM3100 Handler: Z value was previously calculated with bytes of the X value.
PR: https://egit.irs.uni-stuttgart.de/fsfw/fsfw/pulls/733
- DHB `setNormalDatapoolEntriesInvalid`: The default implementation did not set the validity
to false correctly because the `read` and `write` calls were missing.
PR: https://egit.irs.uni-stuttgart.de/fsfw/fsfw/pulls/728
- PUS TMTC creator module: Sequence flags were set to continuation segment (0b00) instead
of the correct unsegmented flags (0b11) as specified in the standard.
PR: https://egit.irs.uni-stuttgart.de/fsfw/fsfw/pulls/727
- TC Scheduler Service 11: Add size and CRC check for contained TC.
Bug: https://egit.irs.uni-stuttgart.de/fsfw/fsfw/issues/719
PR: https://egit.irs.uni-stuttgart.de/fsfw/fsfw/pulls/720
- Only delete health table entry in `HealthHelper` destructor if
health table was set.
PR: https://egit.irs.uni-stuttgart.de/fsfw/fsfw/pulls/710
- I2C Bugfixes: Do not keep iterator as member and fix some incorrect handling with the iterator.
Also properly reset the reply size for successfull transfers and erroneous transfers.
PR: https://egit.irs.uni-stuttgart.de/fsfw/fsfw/pulls/700
- Bugfix for Serial Buffer Stream: Setting `doActive` to false now
actually fully disables printing.
PR: https://egit.irs.uni-stuttgart.de/fsfw/fsfw/pulls/680
- `TcpTmTcServer.cpp`: The server was actually not able to handle
CCSDS packets which were clumped together. This has been fixed now.
PR: https://egit.irs.uni-stuttgart.de/fsfw/fsfw/pulls/673
- `CServiceHealthCommanding`: Add announce all health info implementation
PR: https://egit.irs.uni-stuttgart.de/fsfw/fsfw/pulls/725
- various fixes related to linux Unittests and memory leaks
PR: https://egit.irs.uni-stuttgart.de/fsfw/fsfw/pulls/715
- small fix to allow teardown handling
PR: https://egit.irs.uni-stuttgart.de/fsfw/fsfw/pulls/713
- fix compiler warning for fixed array list copy ctor
PR: https://egit.irs.uni-stuttgart.de/fsfw/fsfw/pulls/704
- missing include
PR: https://egit.irs.uni-stuttgart.de/fsfw/fsfw/pulls/703
- defaultconfig did not build anymore
PR: https://egit.irs.uni-stuttgart.de/fsfw/fsfw/pulls/702
- hotfix
PR: https://egit.irs.uni-stuttgart.de/fsfw/fsfw/pulls/699
- small fix for helper
PR: https://egit.irs.uni-stuttgart.de/fsfw/fsfw/pulls/698
- missing retval conv
PR: https://egit.irs.uni-stuttgart.de/fsfw/fsfw/pulls/697
- DHB Countdown Bug
PR: https://egit.irs.uni-stuttgart.de/fsfw/fsfw/pulls/693
- doc corrections
PR: https://egit.irs.uni-stuttgart.de/fsfw/fsfw/pulls/687
- better error printout
PR: https://egit.irs.uni-stuttgart.de/fsfw/fsfw/pulls/686
- include correction
PR: https://egit.irs.uni-stuttgart.de/fsfw/fsfw/pulls/683
- better warning for missing include paths
PR: https://egit.irs.uni-stuttgart.de/fsfw/fsfw/pulls/676
- Service 11 regression
PR: https://egit.irs.uni-stuttgart.de/fsfw/fsfw/pulls/670
## Added
- `CServiceHealthCommanding`: Add announce all health info implementation
PR: https://egit.irs.uni-stuttgart.de/eive/fsfw/pulls/122
- Empty constructor for `CdsShortTimeStamper` which does not do an object manager registration.
PR: https://egit.irs.uni-stuttgart.de/fsfw/fsfw/pulls/730
- `Service9TimeManagement`: Add `DUMP_TIME` (129) subservice.
- `TcpTmTcServer`: Allow setting the `SO_REUSEADDR` and `SO_REUSEPORT`
option on the TCP server. CTOR prototype has changed and expects an explicit
TCP configuration struct to be passed.
PR: https://egit.irs.uni-stuttgart.de/fsfw/fsfw/pulls/722
- `DleParser` helper class to parse DLE encoded packets from a byte stream.
PR: https://egit.irs.uni-stuttgart.de/fsfw/fsfw/pulls/711
- `UioMapper` is able to resolve symlinks now.
PR: https://egit.irs.uni-stuttgart.de/fsfw/fsfw/pulls/709
- Add new `UnsignedByteField` class - Add new `UnsignedByteField` class
PR: https://egit.irs.uni-stuttgart.de/fsfw/fsfw/pulls/660 PR: https://egit.irs.uni-stuttgart.de/fsfw/fsfw/pulls/660
- publish documentation for development and master branch
PR: https://egit.irs.uni-stuttgart.de/fsfw/fsfw/pulls/681
- Add Linux HAL options
PR: https://egit.irs.uni-stuttgart.de/fsfw/fsfw/pulls/663
- Expand SerializeIF
PR: https://egit.irs.uni-stuttgart.de/fsfw/fsfw/pulls/656
- PUS Service 11: Additional Safety Check
PR: https://egit.irs.uni-stuttgart.de/fsfw/fsfw/pulls/666
- improvements for auto-formatter script
PR: https://egit.irs.uni-stuttgart.de/fsfw/fsfw/pulls/665
- provide a weak print char impl
PR: https://egit.irs.uni-stuttgart.de/fsfw/fsfw/pulls/674
## Removed
- now that doc server is up, remove markdown files
PR: https://egit.irs.uni-stuttgart.de/fsfw/fsfw/pulls/688
- remove bsp specific code
PR: https://egit.irs.uni-stuttgart.de/fsfw/fsfw/pulls/679
## Changes ## Changes
- `CService201HealthCommanding` renamed to `CServiceHealthCommanding`,
service ID customizable now. `CServiceHealthCommanding` expects configuration struct
`HealthServiceCfg` now
PR: https://egit.irs.uni-stuttgart.de/fsfw/fsfw/pulls/725
- `AcceptsTelemetryIF`: `getReportReceptionQueue` is const now
PR: https://egit.irs.uni-stuttgart.de/fsfw/fsfw/pulls/712
- Moved some container returnvalues to dedicated header and namespace
so they can be used without template specification.
PR: https://egit.irs.uni-stuttgart.de/fsfw/fsfw/pulls/707
- Remove default secondary header argument for
`uint16_t getTcSpacePacketIdFromApid(uint16_t apid, bool secondaryHeaderFlag)` and
`uint16_t getTmSpacePacketIdFromApid(uint16_t apid, bool secondaryHeaderFlag)`
PR: https://egit.irs.uni-stuttgart.de/fsfw/fsfw/pulls/689
- Removed `HasReturnvaluesIF` class in favor of `returnvalue` namespace with `OK` and `FAILED` - Removed `HasReturnvaluesIF` class in favor of `returnvalue` namespace with `OK` and `FAILED`
constants. constants.
PR: https://egit.irs.uni-stuttgart.de/fsfw/fsfw/pulls/659 PR: https://egit.irs.uni-stuttgart.de/fsfw/fsfw/pulls/659
@ -178,78 +32,8 @@ and this project adheres to [Semantic Versioning](http://semver.org/).
for other modules for other modules
PR: https://egit.irs.uni-stuttgart.de/fsfw/fsfw/pulls/655 PR: https://egit.irs.uni-stuttgart.de/fsfw/fsfw/pulls/655
which also includes a migration guide which also includes a migration guide
- Bump Catch2 dependency to regular version `v3.1.0`
PR: https://egit.irs.uni-stuttgart.de/fsfw/fsfw/pulls/678
- `SerialBufferAdapter`: Rename `setBuffer` to `setConstBuffer` and update
API to expect `const uint8_t*` accordingly.
PR: https://egit.irs.uni-stuttgart.de/fsfw/fsfw/pulls/677
- Remove the following user includes from `fsfw/events/Event.h` and
`fsfw/returnvalues/returnvalue.h`:
- `#include "events/subsystemIdRanges.h"`
- `#include "returnvalues/classIds.h"`
The user has to include those themselves now
PR: https://egit.irs.uni-stuttgart.de/fsfw/fsfw/pulls/675
- `DeviceHandlerBase`: Set command sender before calling `buildCommandFromCommand`.
This allows finishing action commands immediately inside the function.
PR: https://egit.irs.uni-stuttgart.de/fsfw/fsfw/pulls/672
- `DeviceHandlerBase`: New signature of `handleDeviceTm` which expects
a `const SerializeIF&` and additional helper variant which expects `const uint8_t*`
PR: https://egit.irs.uni-stuttgart.de/fsfw/fsfw/pulls/671
- Improvements for `AcceptsTelemetryIF` and `AcceptsTelecommandsIF`:
- Make functions `const` where it makes sense
- Add `const char* getName const` abstract function
PR: https://egit.irs.uni-stuttgart.de/fsfw/fsfw/pulls/684
- Generic TMTC Bridge Update
PR: https://egit.irs.uni-stuttgart.de/fsfw/fsfw/pulls/734
- comment tweak to event parser can read everything
PR: https://egit.irs.uni-stuttgart.de/fsfw/fsfw/pulls/732
- CMakeLists file updates
PR: https://egit.irs.uni-stuttgart.de/fsfw/fsfw/pulls/731
- improve srv20 error messages
PR: https://egit.irs.uni-stuttgart.de/fsfw/fsfw/pulls/723
- I2C Linux: remove duplicate printout
PR: https://egit.irs.uni-stuttgart.de/fsfw/fsfw/pulls/718
- printout handling improvements
PR: https://egit.irs.uni-stuttgart.de/fsfw/fsfw/pulls/717
- vec getter, reset for content
PR: https://egit.irs.uni-stuttgart.de/fsfw/fsfw/pulls/716
- updates for source sequence counter
PR: https://egit.irs.uni-stuttgart.de/fsfw/fsfw/pulls/714
- SP reader getPacketData is const now
PR: https://egit.irs.uni-stuttgart.de/fsfw/fsfw/pulls/708
- refactoring of serial drivers for linux
PR: https://egit.irs.uni-stuttgart.de/fsfw/fsfw/pulls/705
- Local Pool Update Remove Add Data Ignore Fault Argument
PR: https://egit.irs.uni-stuttgart.de/fsfw/fsfw/pulls/701
- Switch to new documentation server
PR: https://egit.irs.uni-stuttgart.de/fsfw/fsfw/pulls/694
- Windows Tweaks
PR: https://egit.irs.uni-stuttgart.de/fsfw/fsfw/pulls/691
- Refactor Local Pool API
PR: https://egit.irs.uni-stuttgart.de/fsfw/fsfw/pulls/667
- group MGM data in local pool vectors
PR: https://egit.irs.uni-stuttgart.de/fsfw/fsfw/pulls/664
# [v5.0.0] 25.07.2022
## CFDP
- Refactoring of CFDP stack which was done during implementation of the CFDP source and destination
handlers.
- New filesystem module, changes for filesystem abstraction `HasFileSystemIF` to better
fit requirements of CFDP
- New `HostFilesystem` implementation of the `HasFileSystemIF`
- New `cfdp::UserBase` class which is the abstraction for the CFDP user in an OBSW context.
- mib module for the CFDP stack
- PDU classes renamed from `...Serializer`/`...Deserializer` to `...Creator`/`...Reader`
respetively
- Renamed `TcDistributor` to `TcDistributorBase` to prevent confusion
- Refactored `TcDisitributorBase` to be more flexible and usable for CFDP distribution
- Renamed `CCSDSDistributor` to `CcsdsDistributor` and add feature which allows it
to remove the CCSDS header when routing a packet. This allows CCSDS agnostic receiver
implementation without an extra component
PR: https://egit.irs.uni-stuttgart.de/fsfw/fsfw/pulls/682
# [v5.0.0] 2022-07-25
## Changes ## Changes
@ -382,7 +166,6 @@ https://egit.irs.uni-stuttgart.de/fsfw/fsfw/pulls/593
- https://gitlab.kitware.com/cmake/cmake/-/issues/21696 - https://gitlab.kitware.com/cmake/cmake/-/issues/21696
Easiest solution for now: Keep this option OFF by default. Easiest solution for now: Keep this option OFF by default.
PR: https://egit.irs.uni-stuttgart.de/fsfw/fsfw/pulls/616 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 - Dedicated Version class and constant `fsfw::FSFW_VERSION` containing version information
inside `fsfw/version.h` inside `fsfw/version.h`
PR: https://egit.irs.uni-stuttgart.de/fsfw/fsfw/pulls/559 PR: https://egit.irs.uni-stuttgart.de/fsfw/fsfw/pulls/559
@ -397,6 +180,17 @@ https://egit.irs.uni-stuttgart.de/fsfw/fsfw/pulls/593
PR: https://egit.irs.uni-stuttgart.de/fsfw/fsfw/pulls/590 PR: https://egit.irs.uni-stuttgart.de/fsfw/fsfw/pulls/590
- `Subsystem`: New API to add table and sequence entries - `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 ## Fixed
- TCP TMTC Server: `MutexGuard` was not created properly in - TCP TMTC Server: `MutexGuard` was not created properly in

View File

@ -13,7 +13,7 @@ list(APPEND CMAKE_MODULE_PATH
# Version file handling # # Version file handling #
# ############################################################################## # ##############################################################################
set(FSFW_VERSION_IF_GIT_FAILS 6) set(FSFW_VERSION_IF_GIT_FAILS 5)
set(FSFW_SUBVERSION_IF_GIT_FAILS 0) set(FSFW_SUBVERSION_IF_GIT_FAILS 0)
set(FSFW_REVISION_IF_GIT_FAILS 0) set(FSFW_REVISION_IF_GIT_FAILS 0)
@ -72,7 +72,7 @@ set(FSFW_ETL_LIB_MAJOR_VERSION
20 20
CACHE STRING "ETL library major version requirement") CACHE STRING "ETL library major version requirement")
set(FSFW_ETL_LIB_VERSION set(FSFW_ETL_LIB_VERSION
${FSFW_ETL_LIB_MAJOR_VERSION}.35.14 ${FSFW_ETL_LIB_MAJOR_VERSION}.28.0
CACHE STRING "ETL library exact version requirement") CACHE STRING "ETL library exact version requirement")
set(FSFW_ETL_LINK_TARGET etl::etl) set(FSFW_ETL_LINK_TARGET etl::etl)
@ -80,7 +80,7 @@ set(FSFW_CATCH2_LIB_MAJOR_VERSION
3 3
CACHE STRING "Catch2 library major version requirement") CACHE STRING "Catch2 library major version requirement")
set(FSFW_CATCH2_LIB_VERSION set(FSFW_CATCH2_LIB_VERSION
v${FSFW_CATCH2_LIB_MAJOR_VERSION}.1.0 v${FSFW_CATCH2_LIB_MAJOR_VERSION}.0.0-preview5
CACHE STRING "Catch2 library exact version requirement") CACHE STRING "Catch2 library exact version requirement")
# Keep this off by default for now. See PR: # Keep this off by default for now. See PR:
@ -104,8 +104,7 @@ if(FSFW_GENERATE_SECTIONS)
option(FSFW_REMOVE_UNUSED_CODE "Remove unused code" ON) option(FSFW_REMOVE_UNUSED_CODE "Remove unused code" ON)
endif() endif()
option(FSFW_BUILD_TESTS option(FSFW_BUILD_TESTS "Build unittest binary in addition to static library"
"Build unittest binary in addition to static library. Requires Catch2"
OFF) OFF)
option(FSFW_CICD_BUILD "Build for CI/CD. This can disable problematic test" OFF) option(FSFW_CICD_BUILD "Build for CI/CD. This can disable problematic test" OFF)
option(FSFW_BUILD_DOCS "Build documentation with Sphinx and Doxygen" OFF) option(FSFW_BUILD_DOCS "Build documentation with Sphinx and Doxygen" OFF)
@ -116,13 +115,13 @@ endif()
option(FSFW_WARNING_SHADOW_LOCAL_GCC "Enable -Wshadow=local warning in GCC" ON) option(FSFW_WARNING_SHADOW_LOCAL_GCC "Enable -Wshadow=local warning in GCC" ON)
# Options to exclude parts of the FSFW from compilation. # Options to exclude parts of the FSFW from compilation.
option(FSFW_ADD_INTERNAL_TESTS "Add internal unit tests" ON) option(FSFW_ADD_INTERNAL_TESTS "Add internal unit tests" ON)
option(FSFW_ADD_UNITTESTS "Add regular unittests. Requires Catch2" OFF)
option(FSFW_ADD_HAL "Add Hardware Abstraction Layer" ON) option(FSFW_ADD_HAL "Add Hardware Abstraction Layer" ON)
if(UNIX) if(UNIX)
option(FSFW_HAL_LINUX_ADD_PERIPHERAL_DRIVERS "Add Linux peripheral drivers" option(FSFW_HAL_LINUX_ADD_PERIPHERAL_DRIVERS "Add Linux peripheral drivers"
OFF) OFF)
option(FSFW_HAL_LINUX_ADD_LIBGPIOD "Attempt to add Linux GPIOD drivers" OFF) option(FSFW_HAL_LINUX_ADD_LIBGPIOD "Attempt to add Linux GPIOD drivers" OFF)
option(FSFW_HAL_LINUX_ADD_SERIAL_DRIVERS "Add serial drivers" ON)
endif() endif()
# Optional sources # Optional sources
@ -153,12 +152,12 @@ if(FSFW_BUILD_TESTS)
"${MSG_PREFIX} Building the FSFW unittests in addition to the static library" "${MSG_PREFIX} Building the FSFW unittests in addition to the static library"
) )
# Check whether the user has already installed Catch2 first # Check whether the user has already installed Catch2 first
find_package(Catch2 ${FSFW_CATCH2_LIB_MAJOR_VERSION} QUIET) find_package(Catch2 ${FSFW_CATCH2_LIB_MAJOR_VERSION})
# Not installed, so use FetchContent to download and provide Catch2 # Not installed, so use FetchContent to download and provide Catch2
if(NOT Catch2_FOUND) if(NOT Catch2_FOUND)
message( message(
STATUS STATUS
"${MSG_PREFIX} Catch2 installation not found. Downloading Catch2 library with FetchContent." "${MSG_PREFIX} Catch2 installation not found. Downloading Catch2 library with FetchContent"
) )
include(FetchContent) include(FetchContent)
@ -196,13 +195,13 @@ message(
) )
# Check whether the user has already installed ETL first # 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 # Not installed, so use FetchContent to download and provide etl
if(NOT ${FSFW_ETL_LIB_NAME}_FOUND) if(NOT ${FSFW_ETL_LIB_NAME}_FOUND)
message( message(
STATUS STATUS
"${MSG_PREFIX} ETL installation not found. Downloading ETL with FetchContent." "${MSG_PREFIX} No ETL installation was found with find_package. Installing and providing "
) "etl with FindPackage")
include(FetchContent) include(FetchContent)
FetchContent_Declare( FetchContent_Declare(
@ -327,8 +326,7 @@ if(FSFW_BUILD_TESTS)
"/usr/local/include/*" "/usr/local/include/*"
"*/fsfw_tests/*" "*/fsfw_tests/*"
"*/catch2-src/*" "*/catch2-src/*"
"*/fsfw_hal/*" "*/fsfw_hal/*")
"unittests/*")
endif() endif()
target_link_options(${FSFW_TEST_TGT} PRIVATE -fprofile-arcs target_link_options(${FSFW_TEST_TGT} PRIVATE -fprofile-arcs
@ -346,15 +344,8 @@ if(FSFW_BUILD_TESTS)
DEPENDENCIES ${FSFW_TEST_TGT}) DEPENDENCIES ${FSFW_TEST_TGT})
else() else()
setup_target_for_coverage_lcov( setup_target_for_coverage_lcov(
NAME NAME ${FSFW_TEST_TGT}_coverage EXECUTABLE ${FSFW_TEST_TGT}
${FSFW_TEST_TGT}_coverage DEPENDENCIES ${FSFW_TEST_TGT})
EXECUTABLE
${FSFW_TEST_TGT}
DEPENDENCIES
${FSFW_TEST_TGT}
GENHTML_ARGS
--html-epilog
${CMAKE_SOURCE_DIR}/unittests/lcov_epilog.html)
endif() endif()
endif() endif()
endif() endif()
@ -369,8 +360,7 @@ if(NOT FSFW_CONFIG_PATH)
if(NOT FSFW_BUILD_DOCS) if(NOT FSFW_BUILD_DOCS)
message( message(
WARNING WARNING
"${MSG_PREFIX} Flight Software Framework configuration path FSFW_CONFIG_PATH not set" "${MSG_PREFIX} Flight Software Framework configuration path not set")
)
message( message(
WARNING WARNING
"${MSG_PREFIX} Setting default configuration from ${DEF_CONF_PATH} ..") "${MSG_PREFIX} Setting default configuration from ${DEF_CONF_PATH} ..")

View File

@ -175,7 +175,7 @@ cmake -DFSFW_BUILD_DOCS=ON -DFSFW_OSAL=host ..
Then you can generate the documentation using Then you can generate the documentation using
```sh ```sh
cmake --build . -- Sphinx -j cmake --build . -j
``` ```
You can find the generated documentation inside the `docs/sphinx` folder inside the build You can find the generated documentation inside the `docs/sphinx` folder inside the build

View File

@ -5,13 +5,11 @@ RUN apt-get --yes upgrade
#tzdata is a dependency, won't install otherwise #tzdata is a dependency, won't install otherwise
ARG DEBIAN_FRONTEND=noninteractive ARG DEBIAN_FRONTEND=noninteractive
RUN apt-get --yes install gcc g++ cmake make lcov git valgrind nano iputils-ping python3 pip doxygen graphviz rsync RUN apt-get --yes install gcc g++ cmake make lcov git valgrind nano iputils-ping
RUN python3 -m pip install sphinx breathe
RUN git clone https://github.com/catchorg/Catch2.git && \ RUN git clone https://github.com/catchorg/Catch2.git && \
cd Catch2 && \ cd Catch2 && \
git checkout v3.1.0 && \ git checkout v3.0.0-preview5 && \
cmake -Bbuild -H. -DBUILD_TESTING=OFF && \ cmake -Bbuild -H. -DBUILD_TESTING=OFF && \
cmake --build build/ --target install cmake --build build/ --target install
@ -20,10 +18,3 @@ RUN git clone https://github.com/ETLCPP/etl.git && \
git checkout 20.28.0 && \ git checkout 20.28.0 && \
cmake -B build . && \ cmake -B build . && \
cmake --install build/ cmake --install build/
#ssh needs a valid user to work
RUN adduser --uid 114 jenkins
#add documentation server to known hosts
RUN echo "|1|/LzCV4BuTmTb2wKnD146l9fTKgQ=|NJJtVjvWbtRt8OYqFgcYRnMQyVw= ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBNL8ssTonYtgiR/6RRlSIK9WU1ywOcJmxFTLcEblAwH7oifZzmYq3XRfwXrgfMpylEfMFYfCU8JRqtmi19xc21A=" >> /etc/ssh/ssh_known_hosts
RUN echo "|1|CcBvBc3EG03G+XM5rqRHs6gK/Gg=|oGeJQ+1I8NGI2THIkJsW92DpTzs= ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBNL8ssTonYtgiR/6RRlSIK9WU1ywOcJmxFTLcEblAwH7oifZzmYq3XRfwXrgfMpylEfMFYfCU8JRqtmi19xc21A=" >> /etc/ssh/ssh_known_hosts

View File

@ -1,125 +1,41 @@
pipeline { pipeline {
environment { environment {
BUILDDIR_HOST = 'cmake-build-tests-host' BUILDDIR = 'cmake-build-tests'
BUILDDIR_LINUX = 'cmake-build-tests-linux'
DOCDDIR = 'cmake-build-documentation'
} }
agent { agent {
docker { docker { image 'fsfw-ci:d3'}
image 'fsfw-ci:d6'
args '--network host --sysctl fs.mqueue.msg_max=100'
}
} }
stages { stages {
stage('Host') {
stages{
stage('Clean') { stage('Clean') {
steps { steps {
sh 'rm -rf $BUILDDIR_HOST' sh 'rm -rf $BUILDDIR'
} }
} }
stage('Configure') { stage('Configure') {
steps { steps {
dir(BUILDDIR_HOST) { dir(BUILDDIR) {
sh 'cmake -DFSFW_OSAL=host -DFSFW_BUILD_TESTS=ON -DFSFW_CICD_BUILD=ON ..' sh 'cmake -DFSFW_OSAL=host -DFSFW_BUILD_TESTS=ON -DFSFW_CICD_BUILD=ON ..'
} }
} }
} }
stage('Build') { stage('Build') {
steps { steps {
dir(BUILDDIR_HOST) { dir(BUILDDIR) {
sh 'cmake --build . -j4' sh 'cmake --build . -j4'
} }
} }
} }
stage('Unittests') { stage('Unittests') {
steps { steps {
dir(BUILDDIR_HOST) { dir(BUILDDIR) {
sh 'cmake --build . -- fsfw-tests_coverage -j4' sh 'cmake --build . -- fsfw-tests_coverage -j4'
} }
} }
} }
stage('Valgrind') { stage('Valgrind') {
steps { steps {
dir(BUILDDIR_HOST) {
sh 'valgrind --leak-check=full --error-exitcode=1 ./fsfw-tests'
}
}
}
}
}
stage('Linux') {
stages{
stage('Clean') {
steps {
sh 'rm -rf $BUILDDIR_LINUX'
}
}
stage('Configure') {
steps {
dir(BUILDDIR_LINUX) {
sh 'cmake -DFSFW_OSAL=linux -DFSFW_BUILD_TESTS=ON -DFSFW_CICD_BUILD=ON ..'
}
}
}
stage('Build') {
steps {
dir(BUILDDIR_LINUX) {
sh 'cmake --build . -j4'
}
}
}
stage('Unittests') {
steps {
dir(BUILDDIR_LINUX) {
sh 'cmake --build . -- fsfw-tests_coverage -j4'
}
}
}
stage('Valgrind') {
steps {
dir(BUILDDIR_LINUX) {
sh 'valgrind --leak-check=full --error-exitcode=1 ./fsfw-tests'
}
}
}
}
}
stage('Documentation') {
when {
branch 'development'
}
steps {
dir(DOCDDIR) {
sh 'cmake -DFSFW_BUILD_DOCS=ON -DFSFW_OSAL=host ..'
sh 'make Sphinx'
sshagent(credentials: ['documentation-buildfix']) {
sh 'rsync -r --delete docs/sphinx/* buildfix@documentation.irs.uni-stuttgart.de:/fsfw/development'
}
}
dir(BUILDDIR) { dir(BUILDDIR) {
sshagent(credentials: ['documentation-buildfix']) { sh 'valgrind --leak-check=full --error-exitcode=1 ./fsfw-tests'
sh 'rsync -r --delete fsfw-tests_coverage/* buildfix@documentation.irs.uni-stuttgart.de:/fsfw/coverage/development'
}
}
}
}
stage('Master Documentation') {
when {
branch 'master'
}
steps {
dir(DOCDDIR) {
sh 'cmake -DFSFW_BUILD_DOCS=ON -DFSFW_OSAL=host ..'
sh 'make Sphinx'
sshagent(credentials: ['documentation-buildfix']) {
sh 'rsync -r --delete docs/sphinx/* buildfix@documentation.irs.uni-stuttgart.de:/fsfw/master'
}
}
dir(BUILDDIR) {
sshagent(credentials: ['documentation-buildfix']) {
sh 'rsync -r --delete fsfw-tests_coverage/* buildfix@documentation.irs.uni-stuttgart.de:/fsfw/coverage/master'
}
} }
} }
} }

View File

@ -140,7 +140,7 @@ find_program( GCOV_PATH gcov )
find_program( LCOV_PATH NAMES lcov lcov.bat lcov.exe lcov.perl) find_program( LCOV_PATH NAMES lcov lcov.bat lcov.exe lcov.perl)
find_program( FASTCOV_PATH NAMES fastcov fastcov.py ) find_program( FASTCOV_PATH NAMES fastcov fastcov.py )
find_program( GENHTML_PATH NAMES genhtml genhtml.perl genhtml.bat ) find_program( GENHTML_PATH NAMES genhtml genhtml.perl genhtml.bat )
find_program( GCOVR_PATH gcovr ) find_program( GCOVR_PATH gcovr PATHS ${CMAKE_SOURCE_DIR}/scripts/test)
find_program( CPPFILT_PATH NAMES c++filt ) find_program( CPPFILT_PATH NAMES c++filt )
if(NOT GCOV_PATH) if(NOT GCOV_PATH)

40
docs/README-config.md Normal file
View File

@ -0,0 +1,40 @@
Configuring the FSFW
======
The FSFW can be configured via the `fsfwconfig` folder. A template folder has
been provided to have a starting point for this. The folder should be added
to the include path. The primary configuration file is the `FSFWConfig.h` folder. Some
of the available options will be explained in more detail here.
# Auto-Translation of Events
The FSFW allows the automatic translation of events, which allows developers to track triggered
events directly via console output. Using this feature requires:
1. `FSFW_OBJ_EVENT_TRANSLATION` set to 1 in the configuration file.
2. Special auto-generated translation files which translate event IDs and object IDs into
human readable strings. These files can be generated using the
[modgen Python scripts](https://git.ksat-stuttgart.de/source/modgen.git).
3. The generated translation files for the object IDs should be named `translatesObjects.cpp`
and `translateObjects.h` and should be copied to the `fsfwconfig/objects` folder
4. The generated translation files for the event IDs should be named `translateEvents.cpp` and
`translateEvents.h` and should be copied to the `fsfwconfig/events` folder
An example implementations of these translation file generators can be found as part
of the [SOURCE project here](https://git.ksat-stuttgart.de/source/sourceobsw/-/tree/development/generators)
or the [FSFW example](https://egit.irs.uni-stuttgart.de/fsfw/fsfw_example_public/src/branch/master/generators)
## Configuring the Event Manager
The number of allowed subscriptions can be modified with the following
parameters:
``` c++
namespace fsfwconfig {
//! Configure the allocated pool sizes for the event manager.
static constexpr size_t FSFW_EVENTMGMR_MATCHTREE_NODES = 240;
static constexpr size_t FSFW_EVENTMGMT_EVENTIDMATCHERS = 120;
static constexpr size_t FSFW_EVENTMGMR_RANGEMATCHERS = 120;
}
```

View File

@ -0,0 +1 @@
## Controllers

55
docs/README-core.md Normal file
View File

@ -0,0 +1,55 @@
## FSFW Core Modules
These core modules provide the most important functionalities of the
Flight Software Framework
### Clock
* This is a class of static functions that can be used at anytime
* Leap Seconds must be set if any time conversions from UTC to other times is used
### ObjectManager
* Must be created during program startup
* The component which handles all references. All SystemObjects register at this component.
* Any SystemObject needs to have a unique ObjectId. Those can be managed like objects::framework_objects.
* A reference to an object can be get by calling the following function. T must be the specific Interface you want to call.
A nullptr check of the returning Pointer must be done. This function is based on Run-time type information.
```cpp
template <typename T> T* ObjectManagerIF::get( object_id_t id )
```
* A typical way to create all objects on startup is a handing a static produce function to the
ObjectManager on creation. By calling objectManager->initialize() the produce function will be
called and all SystemObjects will be initialized afterwards.
### Event Manager
* Component which allows routing of events
* Other objects can subscribe to specific events, ranges of events or all events of an object.
* Subscriptions can be done during runtime but should be done during initialization
* Amounts of allowed subscriptions can be configured in `FSFWConfig.h`
### Health Table
* A component which holds every health state
* Provides a thread safe way to access all health states without the need of message exchanges
### Stores
* The message based communication can only exchange a few bytes of information inside the message
itself. Therefore, additional information can be exchanged with Stores. With this, only the
store address must be exchanged in the message.
* Internally, the FSFW uses an IPC Store to exchange data between processes. For incoming TCs a TC
Store is used. For outgoing TM a TM store is used.
* All of them should use the Thread Safe Class storagemanager/PoolManager
### Tasks
There are two different types of tasks:
* The PeriodicTask just executes objects that are of type ExecutableObjectIF in the order of the
insertion to the Tasks.
* FixedTimeslotTask executes a list of calls in the order of the given list. This is intended for
DeviceHandlers, where polling should be in a defined order. An example can be found in
`defaultcfg/fsfwconfig/pollingSequence` folder

View File

@ -0,0 +1 @@
## Device Handlers

135
docs/README-highlevel.md Normal file
View File

@ -0,0 +1,135 @@
High-level overview
======
# Structure
The general structure is driven by the usage of interfaces provided by objects.
The FSFW uses C++11 as baseline. The intention behind this is that this C++ Standard should be
widely available, even with older compilers.
The FSFW uses dynamic allocation during the initialization but provides static containers during runtime.
This simplifies the instantiation of objects and allows the usage of some standard containers.
Dynamic Allocation after initialization is discouraged and different solutions are provided in the
FSFW to achieve that. The fsfw uses run-time type information but exceptions are not allowed.
# Failure Handling
Functions should return a defined `ReturnValue_t` to signal to the caller that something has
gone wrong. Returnvalues must be unique. For this the function `returnvalue::makeCode`
or the macro `MAKE_RETURN` can be used. The `CLASS_ID` is a unique id for that type of object.
See `returnvalues/FwClassIds` folder. The user can add custom `CLASS_ID`s via the
`fsfwconfig` folder.
# OSAL
The FSFW provides operation system abstraction layers for Linux, FreeRTOS and RTEMS.
The OSAL provides periodic tasks, message queues, clocks and semaphores as well as mutexes.
The [OSAL README](doc/README-osal.md#top) provides more detailed information on provided components
and how to use them.
# Core Components
The FSFW has following core components. More detailed informations can be found in the
[core component section](doc/README-core.md#top):
1. Tasks: Abstraction for different (periodic) task types like periodic tasks or tasks
with fixed timeslots
2. ObjectManager: This module stores all `SystemObjects` by mapping a provided unique object ID
to the object handles.
3. Static Stores: Different stores are provided to store data of variable size (like telecommands
or small telemetry) in a pool structure without using dynamic memory allocation.
These pools are allocated up front.
3. Clock: This module provided common time related functions
4. EventManager: This module allows routing of events generated by `SystemObjects`
5. HealthTable: A component which stores the health states of objects
# Static IDs in the framework
Some parts of the framework use a static routing address for communication.
An example setup of ids can be found in the example config in `defaultcft/fsfwconfig/objects`
inside the function `Factory::setStaticFrameworkObjectIds()`.
# Events
Events are tied to objects. EventIds can be generated by calling the Macro MAKE_EVENT.
This works analog to the returnvalues. Every object that needs own EventIds has to get a
unique SUBSYSTEM_ID. Every SystemObject can call triggerEvent from the parent class.
Therefore, event messages contain the specific EventId and the objectId of the object that
has triggered.
# Internal Communication
Components communicate mostly via Messages through Queues.
Those queues are created by calling the singleton `QueueFactory::instance()->create()` which
will create `MessageQueue` instances for the used OSAL.
# External Communication
The external communication with the mission control system is mostly up to the user implementation.
The FSFW provides PUS Services which can be used to but don't need to be used.
The services can be seen as a conversion from a TC to a message based communication and back.
## TMTC Communication
The FSFW provides some components to facilitate TMTC handling via the PUS commands.
For example, a UDP or TCP PUS server socket can be opened on a specific port using the
files located in `osal/common`. The FSFW example uses this functionality to allow sending telecommands
and receiving telemetry using the [TMTC commander application](https://github.com/spacefisch/tmtccmd).
Simple commands like the PUS Service 17 ping service can be tested by simply running the
`tmtc_client_cli.py` or `tmtc_client_gui.py` utility in
the [example tmtc folder](https://egit.irs.uni-stuttgart.de/fsfw/fsfw_example_public/src/branch/master/tmtc)
while the `fsfw_example` application is running.
More generally, any class responsible for handling incoming telecommands and sending telemetry
can implement the generic `TmTcBridge` class located in `tmtcservices`. Many applications
also use a dedicated polling task for reading telecommands which passes telecommands
to the `TmTcBridge` implementation.
## CCSDS Frames, CCSDS Space Packets and PUS
If the communication is based on CCSDS Frames and Space Packets, several classes can be used to
distributed the packets to the corresponding services. Those can be found in `tcdistribution`.
If Space Packets are used, a timestamper has to be provided by the user.
An example can be found in the `timemanager` folder, which uses `CCSDSTime::CDS_short`.
# Device Handlers
DeviceHandlers are another important component of the FSFW.
The idea is, to have a software counterpart of every physical device to provide a simple mode,
health and commanding interface. By separating the underlying Communication Interface with
`DeviceCommunicationIF`, a device handler (DH) can be tested on different hardware.
The DH has mechanisms to monitor the communication with the physical device which allow
for FDIR reaction. Device Handlers can be created by implementing `DeviceHandlerBase`.
A standard FDIR component for the DH will be created automatically but can
be overwritten by the user. More information on DeviceHandlers can be found in the
related [documentation section](doc/README-devicehandlers.md#top).
# Modes and Health
The two interfaces `HasModesIF` and `HasHealthIF` provide access for commanding and monitoring
of components. On-board Mode Management is implement in hierarchy system.
DeviceHandlers and Controllers are the lowest part of the hierarchy.
The next layer are Assemblies. Those assemblies act as a component which handle
redundancies of handlers. Assemblies share a common core with the next level which
are the Subsystems.
Those Assemblies are intended to act as auto-generated components from a database which describes
the subsystem modes. The definitions contain transition and target tables which contain the DH,
Assembly and Controller Modes to be commanded.
Transition tables contain as many steps as needed to reach the mode from any other mode, e.g. a
switch into any higher AOCS mode might first turn on the sensors, than the actuators and the
controller as last component.
The target table is used to describe the state that is checked continuously by the subsystem.
All of this allows System Modes to be generated as Subsystem object as well from the same database.
This System contains list of subsystem modes in the transition and target tables.
Therefore, it allows a modular system to create system modes and easy commanding of those, because
only the highest components must be commanded.
The health state represents if the component is able to perform its tasks.
This can be used to signal the system to avoid using this component instead of a redundant one.
The on-board FDIR uses the health state for isolation and recovery.
# Unit Tests
Unit Tests are provided in the unittest folder. Those use the catch2 framework but do not include
catch2 itself. More information on how to run these tests can be found in the separate
[`fsfw_tests` reposoitory](https://egit.irs.uni-stuttgart.de/fsfw/fsfw_tests)

174
docs/README-localpools.md Normal file
View File

@ -0,0 +1,174 @@
## Local Data Pools Developer Information
The following text is targeted towards mission software developers which would like
to use the local data pools provided by the FSFW to store data like sensor values so they can be
used by other software objects like controllers as well. If a custom class should have a local
pool which can be used by other software objects as well, following steps have to be performed:
1. Create a `LocalDataPoolManager` member object in the custom class
2. Implement the `HasLocalDataPoolIF` with specifies the interface between the local pool manager
and the class owning the local pool.
The local data pool manager is also able to process housekeeping service requests in form
of messages, generate periodic housekeeping packet, generate notification and snapshots of changed
variables and datasets and process notifications and snapshots coming from other objects.
The two former tasks are related to the external interface using telemetry and telecommands (TMTC)
while the later two are related to data consumers like controllers only acting on data change
detected by the data creator instead of checking the data manually each cycle. Two important
framework classes `DeviceHandlerBase` and `ExtendedControllerBase` already perform the two steps
shown above so the steps required are altered slightly.
### Storing and Accessing pool data
The pool manager is responsible for thread-safe access of the pool data, but the actual
access to the pool data from the point of view of a mission software developer happens via proxy
classes like pool variable classes. These classes store a copy
of the pool variable with the matching datatype and copy the actual data from the local pool
on a `read` call. Changed variables can then be written to the local pool with a `commit` call.
The `read` and `commit` calls are thread-safe and can be called concurrently from data creators
and data consumers. Generally, a user will create a dataset class which in turn groups all
cohesive pool variables. These sets simply iterator over the list of variables and call the
`read` and `commit` functions of each variable. The following diagram shows the
high-level architecture of the local data pools.
.. image:: ../misc/logo/FSFW_Logo_V3_bw.png
:alt: FSFW Logo
An example is shown for using the local data pools with a Gyroscope.
For example, the following code shows an implementation to access data from a Gyroscope taken
from the SOURCE CubeSat project:
```cpp
class GyroPrimaryDataset: public StaticLocalDataSet<3 * sizeof(float)> {
public:
/**
* Constructor for data users
* @param gyroId
*/
GyroPrimaryDataset(object_id_t gyroId):
StaticLocalDataSet(sid_t(gyroId, gyrodefs::GYRO_DATA_SET_ID)) {
setAllVariablesReadOnly();
}
lp_var_t<float> angVelocityX = lp_var_t<float>(sid.objectId,
gyrodefs::ANGULAR_VELOCITY_X, this);
lp_var_t<float> angVelocityY = lp_var_t<float>(sid.objectId,
gyrodefs::ANGULAR_VELOCITY_Y, this);
lp_var_t<float> angVelocityZ = lp_var_t<float>(sid.objectId,
gyrodefs::ANGULAR_VELOCITY_Z, this);
private:
friend class GyroHandler;
/**
* Constructor for data creator
* @param hkOwner
*/
GyroPrimaryDataset(HasLocalDataPoolIF* hkOwner):
StaticLocalDataSet(hkOwner, gyrodefs::GYRO_DATA_SET_ID) {}
};
```
There is a public constructor for users which sets all variables to read-only and there is a
constructor for the GyroHandler data creator by marking it private and declaring the `GyroHandler`
as a friend class. Both the atittude controller and the `GyroHandler` can now
use the same class definition to access the pool variables with `read` and `commit` semantics
in a thread-safe way. Generally, each class requiring access will have the set class as a member
class. The data creator will also be generally a `DeviceHandlerBase` subclass and some additional
steps are necessary to expose the set for housekeeping purposes.
### Using the local data pools in a `DeviceHandlerBase` subclass
It is very common to store data generated by devices like a sensor into a pool which can
then be used by other objects. Therefore, the `DeviceHandlerBase` already has a
local pool. Using the aforementioned example, our `GyroHandler` will now have the set class
as a member:
```cpp
class GyroHandler: ... {
public:
...
private:
...
GyroPrimaryDataset gyroData;
...
};
```
The constructor used for the creators expects the owner class as a parameter, so we initialize
the object in the `GyroHandler` constructor like this:
```cpp
GyroHandler::GyroHandler(object_id_t objectId, object_id_t comIF,
CookieIF *comCookie, uint8_t switchId):
DeviceHandlerBase(objectId, comIF, comCookie), switchId(switchId),
gyroData(this) {}
```
We need to assign the set to a reply ID used in the `DeviceHandlerBase`.
The combination of the `GyroHandler` object ID and the reply ID will be the 64-bit structure ID
`sid_t` and is used to globally identify the set, for example when requesting housekeeping data or
generating update messages. We need to assign our custom set class in some way so that the local
pool manager can access the custom data sets as well.
By default, the `getDataSetHandle` will take care of this tasks. The default implementation for a
`DeviceHandlerBase` subclass will use the internal command map to retrieve
a handle to a dataset from a given reply ID. Therefore,
we assign the set in the `fillCommandAndReplyMap` function:
```cpp
void GyroHandler::fillCommandAndReplyMap() {
...
this->insertInCommandAndReplyMap(gyrodefs::GYRO_DATA, 3, &gyroData);
...
}
```
Now, we need to create the actual pool entries as well, using the `initializeLocalDataPool`
function. Here, we also immediately subscribe for periodic housekeeping packets
with an interval of 4 seconds. They are still disabled in this example and can be enabled
with a housekeeping service command.
```cpp
ReturnValue_t GyroHandler::initializeLocalDataPool(localpool::DataPool &localDataPoolMap,
LocalDataPoolManager &poolManager) {
localDataPoolMap.emplace(gyrodefs::ANGULAR_VELOCITY_X,
new PoolEntry<float>({0.0}));
localDataPoolMap.emplace(gyrodefs::ANGULAR_VELOCITY_Y,
new PoolEntry<float>({0.0}));
localDataPoolMap.emplace(gyrodefs::ANGULAR_VELOCITY_Z,
new PoolEntry<float>({0.0}));
localDataPoolMap.emplace(gyrodefs::GENERAL_CONFIG_REG42,
new PoolEntry<uint8_t>({0}));
localDataPoolMap.emplace(gyrodefs::RANGE_CONFIG_REG43,
new PoolEntry<uint8_t>({0}));
poolManager.subscribeForPeriodicPacket(gyroData.getSid(), false, 4.0, false);
return returnvalue::OK;
}
```
Now, if we receive some sensor data and converted them into the right format,
we can write it into the pool like this, using a guard class to ensure the set is commited back
in any case:
```cpp
PoolReadGuard readHelper(&gyroData);
if(readHelper.getReadResult() == returnvalue::OK) {
if(not gyroData.isValid()) {
gyroData.setValidity(true, true);
}
gyroData.angVelocityX = angularVelocityX;
gyroData.angVelocityY = angularVelocityY;
gyroData.angVelocityZ = angularVelocityZ;
}
```
The guard class will commit the changed data on destruction automatically.
### Using the local data pools in a `ExtendedControllerBase` subclass
Coming soon

32
docs/README-osal.md Normal file
View File

@ -0,0 +1,32 @@
# Operating System Abstraction Layer (OSAL)
Some specific information on the provided OSALs are provided.
## Linux OSAL
This OSAL can be used to compile for Linux host systems like Ubuntu 20.04 or for
embedded Linux targets like the Raspberry Pi. This OSAL generally requires threading support
and real-time functionalities. For most UNIX systems, this is done by adding `-lrt` and `-lpthread` to the linked libraries in the compilation process. The CMake build support provided will do this automatically for the `fsfw` target. It should be noted that most UNIX systems need to be configured specifically to allow the real-time functionalities required by the FSFW.
More information on how to set up a Linux system accordingly can be found in the
[Linux README of the FSFW example application](https://egit.irs.uni-stuttgart.de/fsfw/fsfw_example/src/branch/master/doc/README-linux.md#top)
## Hosted OSAL
This is the newest OSAL. Support for Semaphores has not been implemented yet and will propably be implemented as soon as C++20 with Semaphore support has matured. This OSAL can be used to run the FSFW on any host system, but currently has only been tested on Windows 10 and Ubuntu 20.04. Unlike the other OSALs, it uses dynamic memory allocation (e.g. for the message queue implementation). Cross-platform serial port (USB) support might be added soon.
## FreeRTOS OSAL
FreeRTOS is not included and the developer needs to take care of compiling the FreeRTOS sources and adding the `FreeRTOSConfig.h` file location to the include path. This OSAL has only been tested extensively with the pre-emptive scheduler configuration so far but it should in principle also be possible to use a cooperative scheduler. It is recommended to use the `heap_4` allocation scheme. When using newlib (nano), it is also recommended to add `#define configUSE_NEWLIB_REENTRANT` to the FreeRTOS configuration file to ensure thread-safety.
When using this OSAL, developers also need to provide an implementation for the `vRequestContextSwitchFromISR` function. This has been done because the call to request a context switch from an ISR is generally located in the `portmacro.h` header and is different depending on the target architecture or device.
## RTEMS OSAL
The RTEMS OSAL was the first implemented OSAL which is also used on the active satellite Flying Laptop.
## TCP/IP socket abstraction
The Linux and Host OSAL provide abstraction layers for the socket API. Currently, only UDP sockets have been imlemented. This is very useful to test TMTC handling either on the host computer directly (targeting localhost with a TMTC application) or on embedded Linux devices, sending TMTC packets via Ethernet.

1
docs/README-pus.md Normal file
View File

@ -0,0 +1 @@
## PUS Services

View File

@ -4,7 +4,6 @@ API
.. toctree:: .. toctree::
:maxdepth: 4 :maxdepth: 4
api/cfdp
api/objectmanager api/objectmanager
api/task api/task
api/ipc api/ipc

View File

@ -1,8 +0,0 @@
CFDP API
=================
``UserBase``
-----------------
.. doxygenclass:: cfdp::UserBase
:members:

View File

@ -17,12 +17,12 @@
# -- Project information ----------------------------------------------------- # -- Project information -----------------------------------------------------
project = "Flight Software Framework" project = 'Flight Software Framework'
copyright = "2021, Institute of Space Systems (IRS)" copyright = '2021, Institute of Space Systems (IRS)'
author = "Institute of Space Systems (IRS)" author = 'Institute of Space Systems (IRS)'
# The full version, including alpha/beta/rc tags # The full version, including alpha/beta/rc tags
release = "5.0.0" release = '2.0.1'
# -- General configuration --------------------------------------------------- # -- General configuration ---------------------------------------------------
@ -30,17 +30,17 @@ release = "5.0.0"
# Add any Sphinx extension module names here, as strings. They can be # Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones. # ones.
extensions = ["breathe"] extensions = [ "breathe" ]
breathe_default_project = "fsfw" breathe_default_project = "fsfw"
# Add any paths that contain templates here, relative to this directory. # Add any paths that contain templates here, relative to this directory.
templates_path = ["_templates"] templates_path = ['_templates']
# List of patterns, relative to source directory, that match files and # List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files. # directories to ignore when looking for source files.
# This pattern also affects html_static_path and html_extra_path. # This pattern also affects html_static_path and html_extra_path.
exclude_patterns = ["_build", "Thumbs.db", ".DS_Store"] exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store']
# -- Options for HTML output ------------------------------------------------- # -- Options for HTML output -------------------------------------------------
@ -48,15 +48,7 @@ exclude_patterns = ["_build", "Thumbs.db", ".DS_Store"]
# The theme to use for HTML and HTML Help pages. See the documentation for # The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes. # a list of builtin themes.
# #
html_theme = "alabaster" html_theme = 'alabaster'
html_theme_options = {
"extra_nav_links": {
"Impressum": "https://www.uni-stuttgart.de/impressum",
"Datenschutz": "https://info.irs.uni-stuttgart.de/datenschutz/datenschutzWebmit.html",
}
}
# Add any paths that contain custom static files (such as style sheets) here, # Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files, # relative to this directory. They are copied after the builtin static files,

View File

@ -7,13 +7,12 @@ Structure
---------- ----------
The general structure is driven by the usage of interfaces provided by objects. The general structure is driven by the usage of interfaces provided by objects.
The FSFW uses C++17 as baseline. Most modern compilers like GCC should have support for this The FSFW uses C++11 as baseline. The intention behind this is that this C++ Standard should be
standard, even for micocontrollers. widely available, even with older compilers.
The FSFW uses dynamic allocation during the initialization but provides static containers during runtime.
The FSFW might use dynamic allocation during program initialization but not during runtime. This simplifies the instantiation of objects and allows the usage of some standard containers.
It offers pool objects, static containers and it also exposes the Dynamic Allocation after initialization is discouraged and different solutions are provided in the
`Embedded Template Library <https://www.etlcpp.com/>`_ to allow writing code which does not perform FSFW to achieve that. The fsfw uses run-time type information but exceptions are not allowed.
allocation during runtime. The fsfw uses run-time type information but will not throw exceptions.
Failure Handling Failure Handling
----------------- -----------------

View File

@ -4,10 +4,6 @@
#include <cstddef> #include <cstddef>
#include <cstdint> #include <cstdint>
// It is assumed the user has a subsystem and class ID list in some user header files.
// #include "events/subsystemIdRanges.h"
// #include "returnvalues/classIds.h"
//! Used to determine whether C++ ostreams are used which can increase //! Used to determine whether C++ ostreams are used which can increase
//! the binary size significantly. If this is disabled, //! the binary size significantly. If this is disabled,
//! the C stdio functions can be used alternatively //! the C stdio functions can be used alternatively

View File

@ -4,6 +4,7 @@
#include <fsfw/devicehandlers/DeviceHandlerBase.h> #include <fsfw/devicehandlers/DeviceHandlerBase.h>
#include <fsfw/events/EventManager.h> #include <fsfw/events/EventManager.h>
#include <fsfw/health/HealthTable.h> #include <fsfw/health/HealthTable.h>
#include <fsfw/tmtcpacket/pus/tm/TmPacketStored.h>
#include <fsfw/tmtcservices/CommandingServiceBase.h> #include <fsfw/tmtcservices/CommandingServiceBase.h>
#include <fsfw/tmtcservices/PusServiceBase.h> #include <fsfw/tmtcservices/PusServiceBase.h>
#include <fsfw/internalerror/InternalErrorReporter.h> #include <fsfw/internalerror/InternalErrorReporter.h>
@ -40,9 +41,13 @@ void Factory::setStaticFrameworkObjectIds() {
CommandingServiceBase::defaultPacketSource = objects::NO_OBJECT; CommandingServiceBase::defaultPacketSource = objects::NO_OBJECT;
CommandingServiceBase::defaultPacketDestination = objects::NO_OBJECT; CommandingServiceBase::defaultPacketDestination = objects::NO_OBJECT;
VerificationReporter::messageReceiver = objects::PUS_SERVICE_1_VERIFICATION;
DeviceHandlerBase::powerSwitcherId = objects::NO_OBJECT; DeviceHandlerBase::powerSwitcherId = objects::NO_OBJECT;
DeviceHandlerBase::rawDataReceiverId = objects::PUS_SERVICE_2_DEVICE_ACCESS; DeviceHandlerBase::rawDataReceiverId = objects::PUS_SERVICE_2_DEVICE_ACCESS;
DeviceHandlerFailureIsolation::powerConfirmationId = objects::NO_OBJECT; DeviceHandlerFailureIsolation::powerConfirmationId = objects::NO_OBJECT;
TmPacketBase::timeStamperId = objects::NO_OBJECT;
} }

View File

@ -13,7 +13,6 @@ file_selectors="-iname CMakeLists.txt"
if command -v ${cmake_fmt} &> /dev/null; then if command -v ${cmake_fmt} &> /dev/null; then
${cmake_fmt} -i CMakeLists.txt ${cmake_fmt} -i CMakeLists.txt
find ./src ${file_selectors} | xargs ${cmake_fmt} -i find ./src ${file_selectors} | xargs ${cmake_fmt} -i
find ./unittests ${file_selectors} | xargs ${cmake_fmt} -i
else else
echo "No ${cmake_fmt} tool found, not formatting CMake files" echo "No ${cmake_fmt} tool found, not formatting CMake files"
fi fi

View File

@ -1,110 +0,0 @@
#! /bin/python
import argparse
import json
import urllib.request
import re
from pathlib import Path
def main() -> None:
parser = argparse.ArgumentParser(
description="List undocumented PRs"
)
parser.add_argument("-v", "--version", type=str, required=True)
args = parser.parse_args()
match = re.search("([0-9]+\.[0-9]+\.[0-9]+)", args.version)
if not match:
print("invalid version")
exit(1)
version = "v" + match.group(1)
print("looking for milestone for " + version + " ...")
with urllib.request.urlopen("https://egit.irs.uni-stuttgart.de/api/v1/repos/fsfw/fsfw/milestones?name=" + version) as milestone_json:
milestones = json.load(milestone_json)
if (len(milestones) == 0):
print("did not find any milestone")
exit(1)
if (len(milestones) > 1):
print("found multiple milestons")
milestone_title = milestones[0]['title']
milestone = str(milestones[0]['id'])
print("Using Milestone \""+ milestone_title + "\" with id " + milestone)
milestone_prs = []
page = 1
last_count = 1;
while last_count != 0:
with urllib.request.urlopen("https://egit.irs.uni-stuttgart.de/api/v1/repos/fsfw/fsfw/pulls?state=closed&milestone=" + str(milestone) + "&limit=100&page=" + str(page)) as pull_requests_json:
pull_requests = json.load(pull_requests_json)
for pr in pull_requests:
milestone_prs.append({'number': str(pr['number']), 'title' : pr['title']})
page += 1
last_count = len(pull_requests)
print("Found " + str(len(milestone_prs)) + " closed PRs in Milestone")
print("looking for CHANGELOG.md ...")
path = Path(".")
files = list(path.glob("CHANGELOG.md"))
if (len(files) != 1):
files = list(path.glob("../CHANGELOG.md"))
if (len(files) != 1):
print("did not find CHANGELOG.md. Run script in either root directory or scripts subfolder.")
exit(1)
print("Scanning CHANGELOG.md ...")
changelog_prs = []
with open(files[0]) as changelog:
line = changelog.readline()
while (line):
#print("line: " + line)
match = re.search("\#.+(v[0-9]+\.[0-9]+\.[0-9]+)", line)
if (match):
if match.group(1) == version:
#print("found version")
line = changelog.readline()
continue
else:
#print("done with " + match.group(1))
break
match = re.search("PR: https://egit\.irs\.uni-stuttgart\.de/fsfw/fsfw/pulls/([0-9]+)", line)
if match:
changelog_prs.append(match.group(1))
line = changelog.readline()
print("Found " + str(len(changelog_prs)) + " PRs in CHANGELOG.md")
print("")
copy_array = changelog_prs.copy()
print("PRs in CHANGELOG.md that are not in Milestone:")
for pr in milestone_prs:
if pr['number'] in copy_array:
copy_array.remove(pr['number'])
for pr in copy_array:
print("https://egit.irs.uni-stuttgart.de/fsfw/fsfw/pulls/" + pr)
print("")
print("PRs in milestone that are not in CHANGELOG.md:")
for pr in milestone_prs:
if pr['number'] not in changelog_prs:
print("- " + pr['title'] + "\n PR: https://egit.irs.uni-stuttgart.de/fsfw/fsfw/pulls/" + pr['number'])
main()

View File

@ -51,7 +51,7 @@ def main():
parser.add_argument( parser.add_argument(
"-g", "-g",
"--generators", "--generators",
default="Ninja", default = "Ninja",
action="store", action="store",
help="CMake generators", help="CMake generators",
) )
@ -165,18 +165,10 @@ def create_tests_build_cfg(args):
os.mkdir(UNITTEST_FOLDER_NAME) os.mkdir(UNITTEST_FOLDER_NAME)
os.chdir(UNITTEST_FOLDER_NAME) os.chdir(UNITTEST_FOLDER_NAME)
if args.windows: if args.windows:
cmake_cmd = ( cmake_cmd = 'cmake -G "' + args.generators + '" -DFSFW_OSAL=host -DFSFW_BUILD_TESTS=ON \
'cmake -G "'
+ args.generators
+ '" -DFSFW_OSAL=host -DFSFW_BUILD_TESTS=ON \
-DGCOVR_PATH="py -m gcovr" ..' -DGCOVR_PATH="py -m gcovr" ..'
)
else: else:
cmake_cmd = ( cmake_cmd = 'cmake -G "' + args.generators + '" -DFSFW_OSAL=host -DFSFW_BUILD_TESTS=ON ..'
'cmake -G "'
+ args.generators
+ '" -DFSFW_OSAL=host -DFSFW_BUILD_TESTS=ON ..'
)
cmd_runner(cmake_cmd) cmd_runner(cmake_cmd)
os.chdir("..") os.chdir("..")
@ -207,7 +199,7 @@ def check_for_cmake_build_dir(build_dir_list: list) -> list:
def perform_lcov_operation(directory: str, chdir: bool): def perform_lcov_operation(directory: str, chdir: bool):
if chdir: if chdir:
os.chdir(directory) os.chdir(directory)
cmd_runner("cmake --build . -j -- fsfw-tests_coverage") cmd_runner("cmake --build . -- fsfw-tests_coverage -j")
def determine_build_dir(build_dir_list: List[str]): def determine_build_dir(build_dir_list: List[str]):

View File

@ -31,8 +31,6 @@ add_subdirectory(thermal)
add_subdirectory(timemanager) add_subdirectory(timemanager)
add_subdirectory(tmtcpacket) add_subdirectory(tmtcpacket)
add_subdirectory(tmtcservices) add_subdirectory(tmtcservices)
add_subdirectory(filesystem)
add_subdirectory(util)
# Optional # Optional

View File

@ -59,12 +59,8 @@ void ActionHelper::setQueueToUse(MessageQueueIF* queue) { queueToUse = queue; }
void ActionHelper::prepareExecution(MessageQueueId_t commandedBy, ActionId_t actionId, void ActionHelper::prepareExecution(MessageQueueId_t commandedBy, ActionId_t actionId,
store_address_t dataAddress) { store_address_t dataAddress) {
bool hasAdditionalData = false;
const uint8_t* dataPtr = nullptr; const uint8_t* dataPtr = nullptr;
size_t size = 0; size_t size = 0;
ReturnValue_t result;
if (dataAddress != store_address_t::invalid()) {
hasAdditionalData = true;
ReturnValue_t result = ipcStore->getData(dataAddress, &dataPtr, &size); ReturnValue_t result = ipcStore->getData(dataAddress, &dataPtr, &size);
if (result != returnvalue::OK) { if (result != returnvalue::OK) {
CommandMessage reply; CommandMessage reply;
@ -72,11 +68,8 @@ void ActionHelper::prepareExecution(MessageQueueId_t commandedBy, ActionId_t act
queueToUse->sendMessage(commandedBy, &reply); queueToUse->sendMessage(commandedBy, &reply);
return; return;
} }
}
result = owner->executeAction(actionId, commandedBy, dataPtr, size); result = owner->executeAction(actionId, commandedBy, dataPtr, size);
if (hasAdditionalData) {
ipcStore->deleteData(dataAddress); ipcStore->deleteData(dataAddress);
}
if (result == HasActionsIF::EXECUTION_FINISHED) { if (result == HasActionsIF::EXECUTION_FINISHED) {
CommandMessage reply; CommandMessage reply;
ActionMessage::setCompletionReply(&reply, actionId, true, result); ActionMessage::setCompletionReply(&reply, actionId, true, result);

View File

@ -1,12 +0,0 @@
#ifndef FSFW_CFDP_H
#define FSFW_CFDP_H
#include "cfdp/definitions.h"
#include "cfdp/handler/DestHandler.h"
#include "cfdp/handler/FaultHandlerBase.h"
#include "cfdp/helpers.h"
#include "cfdp/tlv/Lv.h"
#include "cfdp/tlv/StringLv.h"
#include "cfdp/tlv/Tlv.h"
#endif // FSFW_CFDP_H

View File

@ -1,6 +1,4 @@
target_sources(${LIB_FSFW_NAME} PRIVATE CfdpMessage.cpp CfdpDistributor.cpp target_sources(${LIB_FSFW_NAME} PRIVATE CfdpHandler.cpp CfdpMessage.cpp)
VarLenFields.cpp helpers.cpp)
add_subdirectory(pdu) add_subdirectory(pdu)
add_subdirectory(tlv) add_subdirectory(tlv)
add_subdirectory(handler)

View File

@ -1,55 +0,0 @@
#include "CfdpDistributor.h"
#include "fsfw/tcdistribution/definitions.h"
CfdpDistributor::CfdpDistributor(CfdpDistribCfg cfg)
: TcDistributorBase(cfg.objectId, cfg.tcQueue), cfg(cfg) {}
ReturnValue_t CfdpDistributor::registerTcDestination(const cfdp::EntityId& address,
AcceptsTelecommandsIF& tcDest) {
for (const auto& dest : tcDestinations) {
if (dest.id == address) {
return returnvalue::FAILED;
}
}
tcDestinations.emplace_back(address, tcDest.getName(), tcDest.getRequestQueue());
return returnvalue::OK;
}
ReturnValue_t CfdpDistributor::selectDestination(MessageQueueId_t& destId) {
auto accessorPair = cfg.tcStore.getData(currentMessage.getStorageId());
if (accessorPair.first != returnvalue::OK) {
return accessorPair.first;
}
ReturnValue_t result =
pduReader.setReadOnlyData(accessorPair.second.data(), accessorPair.second.size());
if (result != returnvalue::OK) {
return result;
}
result = pduReader.parseData();
if (result != returnvalue::OK) {
return result;
}
cfdp::EntityId foundId;
pduReader.getDestId(foundId);
bool destFound = false;
for (const auto& dest : tcDestinations) {
if (dest.id == foundId) {
destId = dest.queueId;
destFound = true;
}
}
if (not destFound) {
// TODO: Warning and event?
return tmtcdistrib::NO_DESTINATION_FOUND;
}
// Packet was forwarded successfully, so do not delete it.
accessorPair.second.release();
return returnvalue::OK;
}
const char* CfdpDistributor::getName() const { return "CFDP Distributor"; }
uint32_t CfdpDistributor::getIdentifier() const { return 0; }
MessageQueueId_t CfdpDistributor::getRequestQueue() const { return tcQueue->getId(); }

View File

@ -1,76 +0,0 @@
#ifndef FSFW_TCDISTRIBUTION_CFDPDISTRIBUTOR_H_
#define FSFW_TCDISTRIBUTION_CFDPDISTRIBUTOR_H_
#include <utility>
#include <vector>
#include "fsfw/cfdp/pdu/PduHeaderReader.h"
#include "fsfw/returnvalues/returnvalue.h"
#include "fsfw/tcdistribution/CfdpPacketChecker.h"
#include "fsfw/tcdistribution/TcDistributorBase.h"
#include "fsfw/tmtcpacket/cfdp/CfdpPacketStored.h"
#include "fsfw/tmtcservices/AcceptsTelecommandsIF.h"
#include "fsfw/tmtcservices/VerificationReporter.h"
struct CfdpDistribCfg {
CfdpDistribCfg(object_id_t objectId, StorageManagerIF& tcStore, MessageQueueIF* tcQueue)
: objectId(objectId), tcStore(tcStore), tcQueue(tcQueue) {}
object_id_t objectId;
StorageManagerIF& tcStore;
MessageQueueIF* tcQueue;
};
/**
* This will be the primary component to perform PDU forwading procedures. This includes forwarding
* CFDP TC packets to registered source or destination handlers, and forwarding all telemetry
* generated by them to registered TM sinks.
* @ingroup tc_distribution
*/
class CfdpDistributor : public TcDistributorBase, public AcceptsTelecommandsIF {
public:
/**
* The ctor passes @c set_apid to the checker class and calls the
* TcDistribution ctor with a certain object id.
* @param setApid The APID of this receiving Application.
* @param setObjectId Object ID of the distributor itself
* @param setPacketSource Object ID of the source of TC packets.
* Must implement CcsdsDistributorIF.
*/
explicit CfdpDistributor(CfdpDistribCfg cfg);
[[nodiscard]] const char* getName() const override;
[[nodiscard]] uint32_t getIdentifier() const override;
[[nodiscard]] MessageQueueId_t getRequestQueue() const override;
/**
* Register a new CFDP entity which can receive PDUs.
* @param address
* @param tcDest
* @return
* - @c RETURN_FAILED: Entry already exists for the given address
*/
ReturnValue_t registerTcDestination(const cfdp::EntityId& address, AcceptsTelecommandsIF& tcDest);
protected:
struct EntityInfo {
EntityInfo(cfdp::EntityId id, const char* name, MessageQueueId_t queueId)
: id(std::move(id)), name(name), queueId(queueId) {}
cfdp::EntityId id;
const char* name;
MessageQueueId_t queueId;
};
PduHeaderReader pduReader;
ReturnValue_t lastTcError = returnvalue::OK;
ReturnValue_t lastTmError = returnvalue::OK;
// I don't think a regular OBSW will have more than 1 or 2 of these destinations, so I think
// it is okay to accept the overhead here
std::vector<EntityInfo> tcDestinations;
CfdpDistribCfg cfg;
ReturnValue_t selectDestination(MessageQueueId_t& destId) override;
private:
};
#endif /* FSFW_TCDISTRIBUTION_CFDPDISTRIBUTOR_H_ */

View File

@ -0,0 +1,58 @@
#include "fsfw/cfdp/CfdpHandler.h"
#include "fsfw/cfdp/CfdpMessage.h"
#include "fsfw/ipc/CommandMessage.h"
#include "fsfw/ipc/QueueFactory.h"
#include "fsfw/storagemanager/storeAddress.h"
#include "fsfw/tmtcservices/AcceptsTelemetryIF.h"
object_id_t CfdpHandler::packetSource = 0;
object_id_t CfdpHandler::packetDestination = 0;
CfdpHandler::CfdpHandler(object_id_t setObjectId, CFDPDistributor* dist)
: SystemObject(setObjectId) {
auto mqArgs = MqArgs(setObjectId, static_cast<void*>(this));
requestQueue = QueueFactory::instance()->createMessageQueue(
CFDP_HANDLER_MAX_RECEPTION, MessageQueueMessage::MAX_MESSAGE_SIZE, &mqArgs);
distributor = dist;
}
CfdpHandler::~CfdpHandler() = default;
ReturnValue_t CfdpHandler::initialize() {
ReturnValue_t result = SystemObject::initialize();
if (result != returnvalue::OK) {
return result;
}
this->distributor->registerHandler(this);
return returnvalue::OK;
}
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;
#else
sif::printDebug("CFDPHandler::handleRequest\n");
#endif /* !FSFW_CPP_OSTREAM_ENABLED == 1 */
#endif
// TODO read out packet from store using storeId
return returnvalue::OK;
}
ReturnValue_t CfdpHandler::performOperation(uint8_t opCode) {
ReturnValue_t status = returnvalue::OK;
CommandMessage currentMessage;
for (status = this->requestQueue->receiveMessage(&currentMessage); status == returnvalue::OK;
status = this->requestQueue->receiveMessage(&currentMessage)) {
store_address_t storeId = CfdpMessage::getStoreId(&currentMessage);
this->handleRequest(storeId);
}
return returnvalue::OK;
}
uint16_t CfdpHandler::getIdentifier() { return 0; }
MessageQueueId_t CfdpHandler::getRequestQueue() { return this->requestQueue->getId(); }

View File

@ -0,0 +1,60 @@
#ifndef FSFW_CFDP_CFDPHANDLER_H_
#define FSFW_CFDP_CFDPHANDLER_H_
#include "fsfw/ipc/MessageQueueIF.h"
#include "fsfw/objectmanager/SystemObject.h"
#include "fsfw/returnvalues/returnvalue.h"
#include "fsfw/tasks/ExecutableObjectIF.h"
#include "fsfw/tcdistribution/CFDPDistributor.h"
#include "fsfw/tmtcservices/AcceptsTelecommandsIF.h"
namespace Factory {
void setStaticFrameworkObjectIds();
}
class CfdpHandler : public ExecutableObjectIF, public AcceptsTelecommandsIF, public SystemObject {
friend void(Factory::setStaticFrameworkObjectIds)();
public:
CfdpHandler(object_id_t setObjectId, CFDPDistributor* distributor);
/**
* The destructor is empty.
*/
virtual ~CfdpHandler();
virtual ReturnValue_t handleRequest(store_address_t storeId);
virtual ReturnValue_t initialize() override;
virtual uint16_t getIdentifier() override;
MessageQueueId_t getRequestQueue() override;
ReturnValue_t performOperation(uint8_t opCode) override;
protected:
/**
* This is a complete instance of the telecommand reception queue
* of the class. It is initialized on construction of the class.
*/
MessageQueueIF* requestQueue = nullptr;
CFDPDistributor* distributor = nullptr;
/**
* The current CFDP packet to be processed.
* It is deleted after handleRequest was executed.
*/
CfdpPacketStored currentPacket;
static object_id_t packetSource;
static object_id_t packetDestination;
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 CFDP_HANDLER_MAX_RECEPTION = 100;
};
#endif /* FSFW_CFDP_CFDPHANDLER_H_ */

View File

@ -4,9 +4,8 @@ CfdpMessage::CfdpMessage() = default;
CfdpMessage::~CfdpMessage() = default; CfdpMessage::~CfdpMessage() = default;
void CfdpMessage::setPutRequest(CommandMessage *message, store_address_t putRequest) { void CfdpMessage::setCommand(CommandMessage *message, store_address_t cfdpPacket) {
message->setCommand(PUT_REQUEST); message->setParameter(cfdpPacket.raw);
message->setParameter(putRequest.raw);
} }
store_address_t CfdpMessage::getStoreId(const CommandMessage *message) { store_address_t CfdpMessage::getStoreId(const CommandMessage *message) {

View File

@ -11,11 +11,9 @@ class CfdpMessage {
public: public:
static const uint8_t MESSAGE_ID = messagetypes::CFDP; static const uint8_t MESSAGE_ID = messagetypes::CFDP;
static const Command_t PUT_REQUEST = MAKE_COMMAND_ID(1);
static const Command_t CANCEL_REQUEST = MAKE_COMMAND_ID(1);
virtual ~CfdpMessage(); virtual ~CfdpMessage();
static void setPutRequest(CommandMessage* message, store_address_t putRequest); static void setCommand(CommandMessage* message, store_address_t cfdpPacket);
static store_address_t getStoreId(const CommandMessage* message); static store_address_t getStoreId(const CommandMessage* message);

View File

@ -1,23 +1,16 @@
#ifndef FSFW_CFDP_FILESIZE_H_ #ifndef FSFW_SRC_FSFW_CFDP_FILESIZE_H_
#define FSFW_CFDP_FILESIZE_H_ #define FSFW_SRC_FSFW_CFDP_FILESIZE_H_
#include <optional>
#include "fsfw/serialize/SerializeAdapter.h" #include "fsfw/serialize/SerializeAdapter.h"
#include "fsfw/serialize/SerializeIF.h" #include "fsfw/serialize/SerializeIF.h"
namespace cfdp { namespace cfdp {
/** struct FileSize : public SerializeIF {
* Helper type for the CFDP File Size Sensitive (FSS) fields.
*/
struct Fss : public SerializeIF {
public: public:
Fss() = default; FileSize() : largeFile(false){};
explicit Fss(uint64_t fileSize, bool isLarge = false) { setFileSize(fileSize, isLarge); }; FileSize(uint64_t fileSize, bool isLarge = false) { setFileSize(fileSize, isLarge); };
[[nodiscard]] uint64_t value() const { return fileSize; }
ReturnValue_t serialize(bool isLarge, uint8_t **buffer, size_t *size, size_t maxSize, ReturnValue_t serialize(bool isLarge, uint8_t **buffer, size_t *size, size_t maxSize,
Endianness streamEndianness) { Endianness streamEndianness) {
@ -34,7 +27,7 @@ struct Fss : public SerializeIF {
return SerializeAdapter::serialize(&fileSize, buffer, size, maxSize, streamEndianness); return SerializeAdapter::serialize(&fileSize, buffer, size, maxSize, streamEndianness);
} }
[[nodiscard]] size_t getSerializedSize() const override { size_t getSerializedSize() const override {
if (largeFile) { if (largeFile) {
return 8; return 8;
} else { } else {
@ -57,22 +50,20 @@ struct Fss : public SerializeIF {
} }
} }
ReturnValue_t setFileSize(uint64_t fileSize_, std::optional<bool> largeFile_) { ReturnValue_t setFileSize(uint64_t fileSize, bool largeFile) {
if (largeFile_) {
largeFile = largeFile_.value();
}
if (not largeFile and fileSize > UINT32_MAX) { if (not largeFile and fileSize > UINT32_MAX) {
// TODO: emit warning here // TODO: emit warning here
return returnvalue::FAILED; return returnvalue::FAILED;
} }
this->fileSize = fileSize_; this->fileSize = fileSize;
this->largeFile = largeFile;
return returnvalue::OK; return returnvalue::OK;
} }
[[nodiscard]] bool isLargeFile() const { return largeFile; } bool isLargeFile() const { return largeFile; }
uint64_t getSize(bool *largeFile_ = nullptr) const { uint64_t getSize(bool *largeFile = nullptr) const {
if (largeFile_ != nullptr) { if (largeFile != nullptr) {
*largeFile_ = this->largeFile; *largeFile = this->largeFile;
} }
return fileSize; return fileSize;
} }
@ -84,4 +75,4 @@ struct Fss : public SerializeIF {
} // namespace cfdp } // namespace cfdp
#endif /* FSFW_CFDP_FILESIZE_H_ */ #endif /* FSFW_SRC_FSFW_CFDP_FILESIZE_H_ */

View File

@ -1,135 +0,0 @@
#ifndef FSFW_CFDP_PDU_VARLENFIELD_H_
#define FSFW_CFDP_PDU_VARLENFIELD_H_
#include <cstddef>
#include <cstdint>
#include <utility>
#include "fsfw/cfdp/definitions.h"
#include "fsfw/serialize/SerializeIF.h"
#include "fsfw/serviceinterface.h"
#include "fsfw/util/UnsignedByteField.h"
namespace cfdp {
class VarLenField : public SerializeIF {
public:
union LengthFieldLen {
uint8_t oneByte;
uint16_t twoBytes;
uint32_t fourBytes;
uint64_t eightBytes;
};
VarLenField();
template <typename T>
explicit VarLenField(UnsignedByteField<T> byteField);
VarLenField(cfdp::WidthInBytes width, uint64_t value);
bool operator==(const VarLenField &other) const;
bool operator!=(const VarLenField &other) const;
bool operator<(const VarLenField &other) const;
ReturnValue_t setValueAndWidth(cfdp::WidthInBytes width, uint64_t value);
void setWidth(cfdp::WidthInBytes width);
ReturnValue_t setValue(uint64_t value);
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(cfdp::WidthInBytes width, const uint8_t **buffer, size_t *size,
Endianness streamEndianness);
[[nodiscard]] cfdp::WidthInBytes getWidth() const;
[[nodiscard]] uint64_t getValue() const;
#if FSFW_CPP_OSTREAM_ENABLED == 1
friend std::ostream &operator<<(std::ostream &os, const VarLenField &id) {
os << "dec: " << id.getValue() << ", hex: " << std::hex << std::setw(id.getWidth())
<< std::setfill('0') << id.getValue() << std::dec << std::setfill('0');
return os;
}
#endif
private:
ReturnValue_t deSerialize(const uint8_t **buffer, size_t *size,
Endianness streamEndianness) override;
cfdp::WidthInBytes width;
LengthFieldLen value{};
};
template <typename T>
cfdp::VarLenField::VarLenField(UnsignedByteField<T> byteField)
: width(static_cast<cfdp::WidthInBytes>(sizeof(T))) {
static_assert((sizeof(T) % 2) == 0);
setValueAndWidth(width, byteField.getValue());
}
struct EntityId : public VarLenField {
public:
EntityId() : VarLenField() {}
template <typename T>
explicit EntityId(UnsignedByteField<T> byteField) : VarLenField(byteField) {}
EntityId(cfdp::WidthInBytes width, size_t entityId) : VarLenField(width, entityId) {}
ReturnValue_t serializeAsLv(uint8_t **buffer, size_t *size, size_t maxSize) const {
if (buffer == nullptr or size == nullptr) {
return returnvalue::FAILED;
}
if (*size + 1 + getWidth() > maxSize) {
return SerializeIF::BUFFER_TOO_SHORT;
}
**buffer = getWidth();
*buffer += 1;
*size += 1;
return serialize(buffer, size, maxSize, SerializeIF::Endianness::NETWORK);
}
ReturnValue_t deSerializeFromLv(const uint8_t **buffer, size_t *deserLen) {
if (buffer == nullptr or deserLen == nullptr) {
return returnvalue::FAILED;
}
if (*deserLen < 2) {
return SerializeIF::STREAM_TOO_SHORT;
}
auto width = static_cast<WidthInBytes>(**buffer);
*buffer += 1;
*deserLen -= 1;
return VarLenField::deSerialize(width, buffer, deserLen, SerializeIF::Endianness::NETWORK);
}
};
struct TransactionSeqNum : public VarLenField {
public:
TransactionSeqNum() : VarLenField() {}
template <typename T>
explicit TransactionSeqNum(UnsignedByteField<T> byteField) : VarLenField(byteField) {}
TransactionSeqNum(cfdp::WidthInBytes width, size_t seqNum) : VarLenField(width, seqNum) {}
};
struct TransactionId {
TransactionId() = default;
TransactionId(EntityId entityId, TransactionSeqNum seqNum)
: entityId(std::move(entityId)), seqNum(std::move(seqNum)) {}
bool operator==(const TransactionId &other) const {
return entityId == other.entityId and seqNum == other.seqNum;
}
#if FSFW_CPP_OSTREAM_ENABLED == 1
friend std::ostream &operator<<(std::ostream &os, const TransactionId &id) {
os << "Source ID { " << id.entityId << " }, Sequence Number " << id.seqNum.getValue();
return os;
}
#endif
EntityId entityId;
TransactionSeqNum seqNum;
};
} // namespace cfdp
#endif /* FSFW_CFDP_PDU_VARLENFIELD_H_ */

View File

@ -11,16 +11,12 @@
namespace cfdp { namespace cfdp {
static constexpr char CFDP_VERSION_2_NAME[] = "CCSDS 727.0-B-5"; static constexpr uint8_t VERSION_BITS = 0b00100000;
// Second version of the protocol, only this one is supported here static constexpr uint8_t CFDP_CLASS_ID = CLASS_ID::CFDP;
static constexpr uint8_t CFDP_VERSION_2 = 0b001;
static constexpr uint8_t VERSION_BITS = CFDP_VERSION_2 << 5;
static constexpr uint8_t CFDP_CLASS_ID = CLASS_ID::CFDP_BASE;
static constexpr ReturnValue_t INVALID_TLV_TYPE = returnvalue::makeCode(CFDP_CLASS_ID, 1); static constexpr ReturnValue_t INVALID_TLV_TYPE = returnvalue::makeCode(CFDP_CLASS_ID, 1);
static constexpr ReturnValue_t INVALID_DIRECTIVE_FIELD = returnvalue::makeCode(CFDP_CLASS_ID, 2); static constexpr ReturnValue_t INVALID_DIRECTIVE_FIELDS = returnvalue::makeCode(CFDP_CLASS_ID, 2);
static constexpr ReturnValue_t INVALID_PDU_DATAFIELD_LEN = returnvalue::makeCode(CFDP_CLASS_ID, 3); static constexpr ReturnValue_t INVALID_PDU_DATAFIELD_LEN = returnvalue::makeCode(CFDP_CLASS_ID, 3);
static constexpr ReturnValue_t INVALID_ACK_DIRECTIVE_FIELDS = static constexpr ReturnValue_t INVALID_ACK_DIRECTIVE_FIELDS =
returnvalue::makeCode(CFDP_CLASS_ID, 4); returnvalue::makeCode(CFDP_CLASS_ID, 4);
@ -30,14 +26,13 @@ static constexpr ReturnValue_t METADATA_CANT_PARSE_OPTIONS =
returnvalue::makeCode(CFDP_CLASS_ID, 5); returnvalue::makeCode(CFDP_CLASS_ID, 5);
static constexpr ReturnValue_t NAK_CANT_PARSE_OPTIONS = returnvalue::makeCode(CFDP_CLASS_ID, 6); static constexpr ReturnValue_t NAK_CANT_PARSE_OPTIONS = returnvalue::makeCode(CFDP_CLASS_ID, 6);
static constexpr ReturnValue_t FINISHED_CANT_PARSE_FS_RESPONSES = static constexpr ReturnValue_t FINISHED_CANT_PARSE_FS_RESPONSES =
returnvalue::makeCode(CFDP_CLASS_ID, 7); returnvalue::makeCode(CFDP_CLASS_ID, 6);
static constexpr ReturnValue_t FILESTORE_REQUIRES_SECOND_FILE = static constexpr ReturnValue_t FILESTORE_REQUIRES_SECOND_FILE =
returnvalue::makeCode(CFDP_CLASS_ID, 8); returnvalue::makeCode(CFDP_CLASS_ID, 8);
//! Can not parse filestore response because user did not pass a valid instance //! Can not parse filestore response because user did not pass a valid instance
//! or remaining size is invalid //! or remaining size is invalid
static constexpr ReturnValue_t FILESTORE_RESPONSE_CANT_PARSE_FS_MESSAGE = static constexpr ReturnValue_t FILESTORE_RESPONSE_CANT_PARSE_FS_MESSAGE =
returnvalue::makeCode(CFDP_CLASS_ID, 9); returnvalue::makeCode(CFDP_CLASS_ID, 9);
static constexpr ReturnValue_t INVALID_PDU_FORMAT = returnvalue::makeCode(CFDP_CLASS_ID, 10);
//! Checksum types according to the SANA Checksum Types registry //! Checksum types according to the SANA Checksum Types registry
//! https://sanaregistry.org/r/checksum_identifiers/ //! https://sanaregistry.org/r/checksum_identifiers/
@ -50,17 +45,17 @@ enum ChecksumType {
NULL_CHECKSUM = 15 NULL_CHECKSUM = 15
}; };
enum PduType : uint8_t { FILE_DIRECTIVE = 0, FILE_DATA = 1 }; enum PduType : bool { FILE_DIRECTIVE = 0, FILE_DATA = 1 };
enum TransmissionMode : uint8_t { ACKNOWLEDGED = 0, UNACKNOWLEDGED = 1 }; enum TransmissionModes : bool { ACKNOWLEDGED = 0, UNACKNOWLEDGED = 1 };
enum SegmentMetadataFlag : bool { NOT_PRESENT = false, PRESENT = true }; enum SegmentMetadataFlag : bool { NOT_PRESENT = 0, PRESENT = 1 };
enum Direction : uint8_t { TOWARDS_RECEIVER = 0, TOWARDS_SENDER = 1 }; enum Direction : bool { TOWARDS_RECEIVER = 0, TOWARDS_SENDER = 1 };
enum SegmentationControl : bool { enum SegmentationControl : bool {
NO_RECORD_BOUNDARIES_PRESERVATION = false, NO_RECORD_BOUNDARIES_PRESERVATION = 0,
RECORD_BOUNDARIES_PRESERVATION = true RECORD_BOUNDARIES_PRESERVATION = 1
}; };
enum WidthInBytes : uint8_t { enum WidthInBytes : uint8_t {
@ -68,12 +63,10 @@ enum WidthInBytes : uint8_t {
ONE_BYTE = 1, ONE_BYTE = 1,
TWO_BYTES = 2, TWO_BYTES = 2,
FOUR_BYTES = 4, FOUR_BYTES = 4,
EIGHT_BYTES = 8
}; };
enum FileDirective : uint8_t { enum FileDirectives : uint8_t {
INVALID_DIRECTIVE = 0x0f, INVALID_DIRECTIVE = 0x0f,
// The _DIRECTIVE suffix is mandatory here because of some nameclash!
EOF_DIRECTIVE = 0x04, EOF_DIRECTIVE = 0x04,
FINISH = 0x05, FINISH = 0x05,
ACK = 0x06, ACK = 0x06,
@ -100,14 +93,6 @@ enum ConditionCode : uint8_t {
CANCEL_REQUEST_RECEIVED = 0b1111 CANCEL_REQUEST_RECEIVED = 0b1111
}; };
enum FaultHandlerCode {
RESERVED = 0b0000,
NOTICE_OF_CANCELLATION = 0b0001,
NOTICE_OF_SUSPENSION = 0b0010,
IGNORE_ERROR = 0b0011,
ABANDON_TRANSACTION = 0b0100
};
enum AckTransactionStatus { enum AckTransactionStatus {
UNDEFINED = 0b00, UNDEFINED = 0b00,
ACTIVE = 0b01, ACTIVE = 0b01,
@ -115,18 +100,18 @@ enum AckTransactionStatus {
UNRECOGNIZED = 0b11 UNRECOGNIZED = 0b11
}; };
enum FileDeliveryCode { DATA_COMPLETE = 0, DATA_INCOMPLETE = 1 }; enum FinishedDeliveryCode { DATA_COMPLETE = 0, DATA_INCOMPLETE = 1 };
enum FileDeliveryStatus { enum FinishedFileStatus {
DISCARDED_DELIBERATELY = 0, DISCARDED_DELIBERATELY = 0,
DISCARDED_FILESTORE_REJECTION = 1, DISCARDED_FILESTORE_REJECTION = 1,
RETAINED_IN_FILESTORE = 2, RETAINED_IN_FILESTORE = 2,
FILE_STATUS_UNREPORTED = 3 FILE_STATUS_UNREPORTED = 3
}; };
enum PromptResponseRequired : uint8_t { PROMPT_NAK = 0, PROMPT_KEEP_ALIVE = 1 }; enum PromptResponseRequired : bool { PROMPT_NAK = 0, PROMPT_KEEP_ALIVE = 1 };
enum TlvType : uint8_t { enum TlvTypes : uint8_t {
FILESTORE_REQUEST = 0x00, FILESTORE_REQUEST = 0x00,
FILESTORE_RESPONSE = 0x01, FILESTORE_RESPONSE = 0x01,
MSG_TO_USER = 0x02, MSG_TO_USER = 0x02,
@ -143,20 +128,6 @@ enum RecordContinuationState {
CONTAINS_START_AND_END = 0b11 CONTAINS_START_AND_END = 0b11
}; };
enum class ProxyOpMessageType : uint8_t {
PUT_REQUEST = 0x00,
MSG_TO_USR = 0x01,
FS_REQUEST = 0x02,
FAULT_HANDLER_OVERRIDE = 0x03,
TRANSMISSION_MODE = 0x04,
FLOW_LABEL = 0x05,
SEG_CTRL = 0x06,
PUT_RESPONSE = 0x07,
FS_RESPONSE = 0x08,
PUT_CANCEL = 0x09,
CLOSURE = 0x0b
};
} // namespace cfdp } // namespace cfdp
#endif /* FSFW_SRC_FSFW_CFDP_PDU_DEFINITIONS_H_ */ #endif /* FSFW_SRC_FSFW_CFDP_PDU_DEFINITIONS_H_ */

View File

@ -1,4 +0,0 @@
target_sources(
${LIB_FSFW_NAME}
PRIVATE SourceHandler.cpp DestHandler.cpp PutRequest.cpp
ReservedMessageParser.cpp FaultHandlerBase.cpp UserBase.cpp)

View File

@ -1,574 +0,0 @@
#include "DestHandler.h"
#include <etl/crc32.h>
#include <utility>
#include "fsfw/FSFW.h"
#include "fsfw/cfdp/pdu/EofPduReader.h"
#include "fsfw/cfdp/pdu/FileDataReader.h"
#include "fsfw/cfdp/pdu/FinishedPduCreator.h"
#include "fsfw/cfdp/pdu/PduHeaderReader.h"
#include "fsfw/objectmanager.h"
#include "fsfw/tmtcservices/TmTcMessage.h"
using namespace returnvalue;
cfdp::DestHandler::DestHandler(DestHandlerParams params, FsfwParams fsfwParams)
: tlvVec(params.maxTlvsInOnePdu),
msgToUserVec(params.maxTlvsInOnePdu),
transactionParams(params.maxFilenameLen),
destParams(std::move(params)),
fsfwParams(fsfwParams) {
transactionParams.pduConf.direction = cfdp::Direction::TOWARDS_SENDER;
}
const cfdp::DestHandler::FsmResult& cfdp::DestHandler::stateMachine() {
ReturnValue_t result;
uint8_t errorIdx = 0;
fsmRes.resetOfIteration();
if (fsmRes.step == TransactionStep::IDLE) {
for (auto infoIter = destParams.packetListRef.begin();
infoIter != destParams.packetListRef.end();) {
if (infoIter->pduType == PduType::FILE_DIRECTIVE and
infoIter->directiveType == FileDirective::METADATA) {
result = handleMetadataPdu(*infoIter);
checkAndHandleError(result, errorIdx);
// Store data was deleted in PDU handler because a store guard is used
destParams.packetListRef.erase(infoIter++);
} else {
infoIter++;
}
}
if (fsmRes.step == TransactionStep::IDLE) {
// To decrease the already high complexity of the software, all packets arriving before
// a metadata PDU are deleted.
for (auto infoIter = destParams.packetListRef.begin();
infoIter != destParams.packetListRef.end();) {
fsfwParams.tcStore->deleteData(infoIter->storeId);
infoIter++;
}
destParams.packetListRef.clear();
}
if (fsmRes.step != TransactionStep::IDLE) {
fsmRes.callStatus = CallStatus::CALL_AGAIN;
}
return updateFsmRes(errorIdx);
}
if (fsmRes.state == CfdpState::BUSY_CLASS_1_NACKED) {
if (fsmRes.step == TransactionStep::RECEIVING_FILE_DATA_PDUS) {
for (auto infoIter = destParams.packetListRef.begin();
infoIter != destParams.packetListRef.end();) {
if (infoIter->pduType == PduType::FILE_DATA) {
result = handleFileDataPdu(*infoIter);
checkAndHandleError(result, errorIdx);
// Store data was deleted in PDU handler because a store guard is used
destParams.packetListRef.erase(infoIter++);
} else if (infoIter->pduType == PduType::FILE_DIRECTIVE and
infoIter->directiveType == FileDirective::EOF_DIRECTIVE) {
// TODO: Support for check timer missing
result = handleEofPdu(*infoIter);
checkAndHandleError(result, errorIdx);
// Store data was deleted in PDU handler because a store guard is used
destParams.packetListRef.erase(infoIter++);
} else {
infoIter++;
}
}
}
if (fsmRes.step == TransactionStep::TRANSFER_COMPLETION) {
result = handleTransferCompletion();
checkAndHandleError(result, errorIdx);
}
if (fsmRes.step == TransactionStep::SENDING_FINISHED_PDU) {
result = sendFinishedPdu();
checkAndHandleError(result, errorIdx);
finish();
}
return updateFsmRes(errorIdx);
}
if (fsmRes.state == CfdpState::BUSY_CLASS_2_ACKED) {
// TODO: Will be implemented at a later stage
#if FSFW_CPP_OSTREAM_ENABLED == 1
sif::warning << "CFDP state machine for acknowledged mode not implemented yet" << std::endl;
#endif
}
return updateFsmRes(errorIdx);
}
ReturnValue_t cfdp::DestHandler::passPacket(PacketInfo packet) {
if (destParams.packetListRef.full()) {
return FAILED;
}
destParams.packetListRef.push_back(packet);
return OK;
}
ReturnValue_t cfdp::DestHandler::initialize() {
if (fsfwParams.tmStore == nullptr) {
fsfwParams.tmStore = ObjectManager::instance()->get<StorageManagerIF>(objects::TM_STORE);
if (fsfwParams.tmStore == nullptr) {
return FAILED;
}
}
if (fsfwParams.tcStore == nullptr) {
fsfwParams.tcStore = ObjectManager::instance()->get<StorageManagerIF>(objects::TC_STORE);
if (fsfwParams.tcStore == nullptr) {
return FAILED;
}
}
if (fsfwParams.msgQueue == nullptr) {
return FAILED;
}
return OK;
}
ReturnValue_t cfdp::DestHandler::handleMetadataPdu(const PacketInfo& info) {
// Process metadata PDU
auto constAccessorPair = fsfwParams.tcStore->getData(info.storeId);
if (constAccessorPair.first != OK) {
// TODO: This is not a CFDP error. Event and/or warning?
return constAccessorPair.first;
}
cfdp::StringLv sourceFileName;
cfdp::StringLv destFileName;
MetadataGenericInfo metadataInfo(transactionParams.fileSize);
MetadataPduReader reader(constAccessorPair.second.data(), constAccessorPair.second.size(),
metadataInfo, tlvVec.data(), tlvVec.size());
ReturnValue_t result = reader.parseData();
// TODO: The standard does not really specify what happens if this kind of error happens
// I think it might be a good idea to cache some sort of error code, which
// is translated into a warning and/or event by an upper layer
if (result != OK) {
return handleMetadataParseError(result, constAccessorPair.second.data(),
constAccessorPair.second.size());
}
return startTransaction(reader);
}
ReturnValue_t cfdp::DestHandler::handleFileDataPdu(const cfdp::PacketInfo& info) {
// Process file data PDU
auto constAccessorPair = fsfwParams.tcStore->getData(info.storeId);
if (constAccessorPair.first != OK) {
// TODO: This is not a CFDP error. Event and/or warning?
return constAccessorPair.first;
}
FileDataInfo fdInfo;
FileDataReader reader(constAccessorPair.second.data(), constAccessorPair.second.size(), fdInfo);
ReturnValue_t result = reader.parseData();
if (result != OK) {
return result;
}
size_t fileSegmentLen = 0;
const uint8_t* fileData = fdInfo.getFileData(&fileSegmentLen);
FileOpParams fileOpParams(transactionParams.destName.data(), fileSegmentLen);
fileOpParams.offset = fdInfo.getOffset().value();
if (destParams.cfg.indicCfg.fileSegmentRecvIndicRequired) {
FileSegmentRecvdParams segParams;
segParams.offset = fdInfo.getOffset().value();
segParams.id = transactionParams.transactionId;
segParams.length = fileSegmentLen;
segParams.recContState = fdInfo.getRecordContinuationState();
size_t segmentMetadatLen = 0;
auto* segMetadata = fdInfo.getSegmentMetadata(&segmentMetadatLen);
segParams.segmentMetadata = {segMetadata, segmentMetadatLen};
destParams.user.fileSegmentRecvdIndication(segParams);
}
result = destParams.user.vfs.writeToFile(fileOpParams, fileData);
if (result != returnvalue::OK) {
// TODO: Proper Error handling
#if FSFW_CPP_OSTREAM_ENABLED == 1
sif::error << "cfdp::DestHandler: VFS file write error with code 0x" << std::hex << std::setw(2)
<< result << std::endl;
#endif
transactionParams.vfsErrorCount++;
if (transactionParams.vfsErrorCount < 3) {
// TODO: Provide execution step as parameter
fsfwParams.eventReporter->forwardEvent(events::FILESTORE_ERROR,
static_cast<uint8_t>(fsmRes.step), result);
}
return result;
} else {
transactionParams.deliveryStatus = FileDeliveryStatus::RETAINED_IN_FILESTORE;
transactionParams.vfsErrorCount = 0;
}
if (fdInfo.getOffset().value() + fileSegmentLen > transactionParams.progress) {
transactionParams.progress = fdInfo.getOffset().value() + fileSegmentLen;
}
return result;
}
ReturnValue_t cfdp::DestHandler::handleEofPdu(const cfdp::PacketInfo& info) {
// Process EOF PDU
auto constAccessorPair = fsfwParams.tcStore->getData(info.storeId);
if (constAccessorPair.first != OK) {
// TODO: This is not a CFDP error. Event and/or warning?
return constAccessorPair.first;
}
EofInfo eofInfo(nullptr);
EofPduReader reader(constAccessorPair.second.data(), constAccessorPair.second.size(), eofInfo);
ReturnValue_t result = reader.parseData();
if (result != OK) {
return result;
}
// TODO: Error handling
if (eofInfo.getConditionCode() == ConditionCode::NO_ERROR) {
transactionParams.crc = eofInfo.getChecksum();
uint64_t fileSizeFromEof = eofInfo.getFileSize().value();
// CFDP 4.6.1.2.9: Declare file size error if progress exceeds file size
if (fileSizeFromEof > transactionParams.progress) {
// TODO: File size error
}
transactionParams.fileSize.setFileSize(fileSizeFromEof, std::nullopt);
}
if (destParams.cfg.indicCfg.eofRecvIndicRequired) {
destParams.user.eofRecvIndication(getTransactionId());
}
if (fsmRes.step == TransactionStep::RECEIVING_FILE_DATA_PDUS) {
if (fsmRes.state == CfdpState::BUSY_CLASS_1_NACKED) {
fsmRes.step = TransactionStep::TRANSFER_COMPLETION;
} else if (fsmRes.state == CfdpState::BUSY_CLASS_2_ACKED) {
fsmRes.step = TransactionStep::SENDING_ACK_PDU;
}
}
return returnvalue::OK;
}
ReturnValue_t cfdp::DestHandler::handleMetadataParseError(ReturnValue_t result,
const uint8_t* rawData, size_t maxSize) {
// TODO: try to extract destination ID for error
// TODO: Invalid metadata PDU.
#if FSFW_CPP_OSTREAM_ENABLED == 1
sif::warning << "Parsing Metadata PDU failed with code " << result << std::endl;
#else
#endif
PduHeaderReader headerReader(rawData, maxSize);
result = headerReader.parseData();
if (result != OK) {
// TODO: Now this really should not happen. Warning or error,
// yield or cache appropriate returnvalue
#if FSFW_CPP_OSTREAM_ENABLED == 1
sif::warning << "Parsing Header failed" << std::endl;
#else
#endif
// TODO: Trigger appropriate event
return result;
}
cfdp::EntityId destId;
headerReader.getDestId(destId);
RemoteEntityCfg* remoteCfg;
if (not destParams.remoteCfgTable.getRemoteCfg(destId, &remoteCfg)) {
// TODO: No remote config for dest ID. I consider this a configuration error, which is not
// covered by the standard.
// Warning or error, yield or cache appropriate returnvalue
#if FSFW_CPP_OSTREAM_ENABLED == 1
sif::warning << "No remote config exists for destination ID" << std::endl;
#else
#endif
// TODO: Trigger appropriate event
}
// TODO: Appropriate returnvalue?
return returnvalue::FAILED;
}
ReturnValue_t cfdp::DestHandler::startTransaction(const MetadataPduReader& reader) {
if (fsmRes.state != CfdpState::IDLE) {
// According to standard, discard metadata PDU if we are busy
return OK;
}
ReturnValue_t result = OK;
size_t sourceNameSize = 0;
if (not reader.getSourceFileName().isEmpty()) {
const uint8_t* sourceNamePtr = reader.getSourceFileName().getValue(&sourceNameSize);
if (sourceNameSize + 1 > transactionParams.sourceName.size()) {
fileErrorHandler(events::FILENAME_TOO_LARGE_ERROR, 0, "source filename too large");
return FAILED;
}
std::memcpy(transactionParams.sourceName.data(), sourceNamePtr, sourceNameSize);
transactionParams.sourceName[sourceNameSize] = '\0';
}
size_t destNameSize = 0;
if (not reader.getDestFileName().isEmpty()) {
const uint8_t* destNamePtr = reader.getDestFileName().getValue(&destNameSize);
if (destNameSize + 1 > transactionParams.destName.size()) {
fileErrorHandler(events::FILENAME_TOO_LARGE_ERROR, 0, "dest filename too large");
return FAILED;
}
std::memcpy(transactionParams.destName.data(), destNamePtr, destNameSize);
transactionParams.destName[destNameSize] = '\0';
}
transactionParams.metadataOnly = true;
// If both dest name size and source name size are 0, we are dealing with a metadata only PDU,
// so there is no need to create a file or truncate an existing file
if (destNameSize > 0 and sourceNameSize > 0) {
transactionParams.metadataOnly = false;
FilesystemParams fparams(transactionParams.destName.data());
// handling to allow only specifying target directory. Example:
// Source path /test/hello.txt, dest path /tmp -> dest path /tmp/hello.txt
if (destParams.user.vfs.isDirectory(transactionParams.destName.data())) {
result = tryBuildingAbsoluteDestName(destNameSize);
if (result != OK) {
return result;
}
}
if (destParams.user.vfs.fileExists(fparams)) {
result = destParams.user.vfs.truncateFile(fparams);
if (result != returnvalue::OK) {
fileErrorHandler(events::FILESTORE_ERROR, result, "file truncation error");
return FAILED;
// TODO: Relevant for filestore rejection error?
}
} else {
result = destParams.user.vfs.createFile(fparams);
if (result != OK) {
fileErrorHandler(events::FILESTORE_ERROR, result, "file creation error");
return FAILED;
// TODO: Relevant for filestore rejection error?
}
}
}
EntityId sourceId;
reader.getSourceId(sourceId);
if (not destParams.remoteCfgTable.getRemoteCfg(sourceId, &transactionParams.remoteCfg)) {
// TODO: Warning, event etc.
#if FSFW_CPP_OSTREAM_ENABLED == 1
sif::warning << "cfdp::DestHandler" << __func__
<< ": No remote configuration found for destination ID "
<< transactionParams.pduConf.sourceId.getValue() << std::endl;
#endif
return FAILED;
}
if (reader.getTransmissionMode() == TransmissionMode::UNACKNOWLEDGED) {
fsmRes.state = CfdpState::BUSY_CLASS_1_NACKED;
} else if (reader.getTransmissionMode() == TransmissionMode::ACKNOWLEDGED) {
fsmRes.state = CfdpState::BUSY_CLASS_2_ACKED;
}
if (transactionParams.metadataOnly) {
fsmRes.step = TransactionStep::TRANSFER_COMPLETION;
} else {
// Kind of ugly, make FSM working on packet per packet basis..
fsmRes.step = TransactionStep::TRANSACTION_START;
fsmRes.step = TransactionStep::RECEIVING_FILE_DATA_PDUS;
}
auto& info = reader.getGenericInfo();
transactionParams.checksumType = info.getChecksumType();
transactionParams.closureRequested = info.isClosureRequested();
reader.fillConfig(transactionParams.pduConf);
transactionParams.pduConf.direction = Direction::TOWARDS_SENDER;
transactionParams.transactionId.entityId = transactionParams.pduConf.sourceId;
transactionParams.transactionId.seqNum = transactionParams.pduConf.seqNum;
transactionParams.fileSize = info.getFileSize();
MetadataRecvdParams params(transactionParams.transactionId, transactionParams.pduConf.sourceId,
transactionParams.fileSize);
params.destFileName = transactionParams.destName.data();
params.sourceFileName = transactionParams.sourceName.data();
params.numberOfMsgsToUser = 0;
for (const auto& opt : tlvVec) {
if (opt.getType() == TlvType::MSG_TO_USER) {
msgToUserVec[params.numberOfMsgsToUser] =
MessageToUserTlv(opt.getValue(), opt.getLengthField());
params.numberOfMsgsToUser++;
}
}
params.msgsToUserArray = msgToUserVec.data();
destParams.user.metadataRecvdIndication(params);
return result;
}
cfdp::CfdpState cfdp::DestHandler::getCfdpState() const { return fsmRes.state; }
ReturnValue_t cfdp::DestHandler::handleTransferCompletion() {
ReturnValue_t result;
if (transactionParams.checksumType != ChecksumType::NULL_CHECKSUM) {
result = checksumVerification();
if (result != OK) {
// TODO: Warning / error handling?
}
} else {
transactionParams.conditionCode = ConditionCode::NO_ERROR;
}
result = noticeOfCompletion();
if (result != OK) {
}
if (fsmRes.state == CfdpState::BUSY_CLASS_1_NACKED) {
if (transactionParams.closureRequested) {
fsmRes.step = TransactionStep::SENDING_FINISHED_PDU;
} else {
finish();
}
} else if (fsmRes.state == CfdpState::BUSY_CLASS_2_ACKED) {
fsmRes.step = TransactionStep::SENDING_FINISHED_PDU;
}
return OK;
}
ReturnValue_t cfdp::DestHandler::tryBuildingAbsoluteDestName(size_t destNameSize) {
// A path may only have a maximum of 256 characters in CFDP, so this buffer should be sufficient
// for all use-cases.
char baseNameBuf[512]{};
FilesystemParams fparamsSrc(transactionParams.sourceName.data());
size_t baseNameLen = 0;
ReturnValue_t result = destParams.user.vfs.getBaseFilename(fparamsSrc, baseNameBuf,
sizeof(baseNameBuf), baseNameLen);
if (result != returnvalue::OK or baseNameLen == 0) {
fileErrorHandler(events::FILENAME_TOO_LARGE_ERROR, 0, "error retrieving source base name");
return FAILED;
}
// Destination name + slash + base name + null termination
if (destNameSize + 1 + baseNameLen + 1 > transactionParams.destName.size()) {
fileErrorHandler(events::FILENAME_TOO_LARGE_ERROR, 0,
"dest filename too large after adding source base name");
return FAILED;
}
transactionParams.destName[destNameSize++] = '/';
std::memcpy(transactionParams.destName.data() + destNameSize, baseNameBuf, baseNameLen);
destNameSize += baseNameLen;
transactionParams.destName[destNameSize++] = '\0';
return OK;
}
void cfdp::DestHandler::fileErrorHandler(Event event, ReturnValue_t result,
const char* info) const {
fsfwParams.eventReporter->forwardEvent(event, static_cast<uint8_t>(fsmRes.step), result);
#if FSFW_CPP_OSTREAM_ENABLED == 1
sif::warning << "cfdp::DestHandler: " << info << std::endl;
#endif
}
void cfdp::DestHandler::finish() {
transactionParams.reset();
destParams.packetListRef.clear();
fsmRes.state = CfdpState::IDLE;
fsmRes.step = TransactionStep::IDLE;
}
ReturnValue_t cfdp::DestHandler::checksumVerification() {
std::array<uint8_t, 1024> buf{};
etl::crc32 crcCalc;
uint64_t currentOffset = 0;
FileOpParams params(transactionParams.destName.data(), transactionParams.fileSize.value());
while (currentOffset < transactionParams.fileSize.value()) {
uint64_t readLen;
if (currentOffset + buf.size() > transactionParams.fileSize.value()) {
readLen = transactionParams.fileSize.value() - currentOffset;
} else {
readLen = buf.size();
}
if (readLen > 0) {
params.offset = currentOffset;
params.size = readLen;
auto result = destParams.user.vfs.readFromFile(params, buf.data(), buf.size());
if (result != OK) {
// TODO: I think this is a case for a filestore rejection, but it might sense to print
// a warning or trigger an event because this should generally not happen
return FAILED;
}
crcCalc.add(buf.begin(), buf.begin() + readLen);
}
currentOffset += readLen;
}
uint32_t value = crcCalc.value();
if (value == transactionParams.crc) {
transactionParams.conditionCode = ConditionCode::NO_ERROR;
transactionParams.deliveryCode = FileDeliveryCode::DATA_COMPLETE;
} else {
// TODO: Proper error handling
#if FSFW_CPP_OSTREAM_ENABLED == 1
sif::warning << "CRC check for file " << transactionParams.destName.data() << " failed"
<< std::endl;
#endif
transactionParams.conditionCode = ConditionCode::FILE_CHECKSUM_FAILURE;
}
return OK;
}
ReturnValue_t cfdp::DestHandler::noticeOfCompletion() {
if (destParams.cfg.indicCfg.transactionFinishedIndicRequired) {
TransactionFinishedParams params(
transactionParams.transactionId, transactionParams.conditionCode,
transactionParams.deliveryCode, transactionParams.deliveryStatus);
destParams.user.transactionFinishedIndication(params);
}
return OK;
}
ReturnValue_t cfdp::DestHandler::sendFinishedPdu() {
FinishedInfo info(transactionParams.conditionCode, transactionParams.deliveryCode,
transactionParams.deliveryStatus);
FinishPduCreator finishedPdu(transactionParams.pduConf, info);
store_address_t storeId;
uint8_t* dataPtr = nullptr;
ReturnValue_t result =
fsfwParams.tmStore->getFreeElement(&storeId, finishedPdu.getSerializedSize(), &dataPtr);
if (result != OK) {
#if FSFW_CPP_OSTREAM_ENABLED == 1
sif::warning << "cfdp::DestHandler:sendFinishedPdu: Getting store slot failed" << std::endl;
#endif
fsfwParams.eventReporter->forwardEvent(events::STORE_ERROR, result, 0);
return result;
}
size_t serLen = 0;
result = finishedPdu.serialize(dataPtr, serLen, finishedPdu.getSerializedSize());
if (result != OK) {
#if FSFW_CPP_OSTREAM_ENABLED == 1
sif::warning << "cfdp::DestHandler::sendFinishedPdu: Serializing Finished PDU failed"
<< std::endl;
#endif
fsfwParams.eventReporter->forwardEvent(events::SERIALIZATION_ERROR, result, 0);
return result;
}
TmTcMessage msg(storeId);
result = fsfwParams.msgQueue->sendMessage(fsfwParams.packetDest.getReportReceptionQueue(), &msg);
if (result != OK) {
#if FSFW_CPP_OSTREAM_ENABLED == 1
sif::warning << "cfdp::DestHandler::sendFinishedPdu: Sending PDU failed" << std::endl;
#endif
fsfwParams.eventReporter->forwardEvent(events::MSG_QUEUE_ERROR, result, 0);
return result;
}
fsmRes.packetsSent++;
return OK;
}
cfdp::DestHandler::TransactionStep cfdp::DestHandler::getTransactionStep() const {
return fsmRes.step;
}
const cfdp::DestHandler::FsmResult& cfdp::DestHandler::updateFsmRes(uint8_t errors) {
fsmRes.errors = errors;
fsmRes.result = OK;
if (fsmRes.errors > 0) {
fsmRes.result = FAILED;
}
return fsmRes;
}
const cfdp::TransactionId& cfdp::DestHandler::getTransactionId() const {
return transactionParams.transactionId;
}
void cfdp::DestHandler::checkAndHandleError(ReturnValue_t result, uint8_t& errorIdx) {
if (result != OK and errorIdx < 3) {
fsmRes.errorCodes[errorIdx] = result;
errorIdx++;
}
}
void cfdp::DestHandler::setMsgQueue(MessageQueueIF& queue) { fsfwParams.msgQueue = &queue; }
void cfdp::DestHandler::setEventReporter(EventReportingProxyIF& reporter) {
fsfwParams.eventReporter = &reporter;
}
const cfdp::DestHandlerParams& cfdp::DestHandler::getDestHandlerParams() const {
return destParams;
}
StorageManagerIF* cfdp::DestHandler::getTmStore() const { return fsfwParams.tmStore; }
StorageManagerIF* cfdp::DestHandler::getTcStore() const { return fsfwParams.tcStore; }

View File

@ -1,177 +0,0 @@
#ifndef FSFW_CFDP_CFDPDESTHANDLER_H
#define FSFW_CFDP_CFDPDESTHANDLER_H
#include <etl/list.h>
#include <etl/set.h>
#include <optional>
#include <utility>
#include "RemoteConfigTableIF.h"
#include "UserBase.h"
#include "defs.h"
#include "fsfw/cfdp/handler/mib.h"
#include "fsfw/cfdp/pdu/MetadataPduReader.h"
#include "fsfw/cfdp/pdu/PduConfig.h"
#include "fsfw/cfdp/tlv/MessageToUserTlv.h"
#include "fsfw/container/DynamicFIFO.h"
#include "fsfw/storagemanager/StorageManagerIF.h"
#include "fsfw/storagemanager/storeAddress.h"
#include "fsfw/tmtcservices/AcceptsTelemetryIF.h"
namespace cfdp {
template <size_t SIZE>
using LostSegmentsList = etl::set<etl::pair<uint64_t, uint64_t>, SIZE>;
using LostSegmentsListBase = etl::iset<etl::pair<uint64_t, uint64_t>>;
struct DestHandlerParams {
DestHandlerParams(LocalEntityCfg cfg, UserBase& user, RemoteConfigTableIF& remoteCfgTable,
PacketInfoListBase& packetList,
// TODO: This container can potentially take tons of space. For a better
// memory efficient implementation, an additional abstraction could be
// be used so users can use uint32_t as the pair type
// TODO: Actually, we can provide a better abstraction via interface, which
// allows using something like a bounded map. This simplifies
// the implementation significantly.
LostSegmentsListBase& lostSegmentsContainer)
: cfg(std::move(cfg)),
user(user),
remoteCfgTable(remoteCfgTable),
packetListRef(packetList),
lostSegmentsContainer(lostSegmentsContainer) {}
LocalEntityCfg cfg;
UserBase& user;
RemoteConfigTableIF& remoteCfgTable;
PacketInfoListBase& packetListRef;
LostSegmentsListBase& lostSegmentsContainer;
uint8_t maxTlvsInOnePdu = 20;
size_t maxFilenameLen = 255;
};
class DestHandler {
public:
enum class TransactionStep : uint8_t {
IDLE = 0,
TRANSACTION_START = 1,
RECEIVING_FILE_DATA_PDUS = 2,
SENDING_ACK_PDU = 3,
TRANSFER_COMPLETION = 4,
SENDING_FINISHED_PDU = 5
};
struct FsmResult {
public:
ReturnValue_t result = returnvalue::OK;
CallStatus callStatus = CallStatus::CALL_AFTER_DELAY;
TransactionStep step = TransactionStep::IDLE;
CfdpState state = CfdpState::IDLE;
uint32_t packetsSent = 0;
uint8_t errors = 0;
std::array<ReturnValue_t, 3> errorCodes = {};
void resetOfIteration() {
result = returnvalue::OK;
callStatus = CallStatus::CALL_AFTER_DELAY;
packetsSent = 0;
errors = 0;
errorCodes.fill(returnvalue::OK);
}
};
/**
* Will be returned if it is advisable to call the state machine operation call again
*/
ReturnValue_t PARTIAL_SUCCESS = returnvalue::makeCode(0, 2);
ReturnValue_t FAILURE = returnvalue::makeCode(0, 3);
explicit DestHandler(DestHandlerParams handlerParams, FsfwParams fsfwParams);
/**
*
* @return
* - @c returnvalue::OK State machine OK for this execution cycle
* - @c CALL_FSM_AGAIN State machine should be called again.
*/
const FsmResult& stateMachine();
void setMsgQueue(MessageQueueIF& queue);
void setEventReporter(EventReportingProxyIF& reporter);
ReturnValue_t passPacket(PacketInfo packet);
ReturnValue_t initialize();
[[nodiscard]] CfdpState getCfdpState() const;
[[nodiscard]] TransactionStep getTransactionStep() const;
[[nodiscard]] const TransactionId& getTransactionId() const;
[[nodiscard]] const DestHandlerParams& getDestHandlerParams() const;
[[nodiscard]] StorageManagerIF* getTcStore() const;
[[nodiscard]] StorageManagerIF* getTmStore() const;
private:
struct TransactionParams {
// Initialize char vectors with length + 1 for 0 termination
explicit TransactionParams(size_t maxFileNameLen)
: sourceName(maxFileNameLen + 1), destName(maxFileNameLen + 1) {}
void reset() {
pduConf = PduConfig();
transactionId = TransactionId();
std::fill(sourceName.begin(), sourceName.end(), '\0');
std::fill(destName.begin(), destName.end(), '\0');
fileSize.setFileSize(0, false);
conditionCode = ConditionCode::NO_ERROR;
deliveryCode = FileDeliveryCode::DATA_INCOMPLETE;
deliveryStatus = FileDeliveryStatus::DISCARDED_DELIBERATELY;
crc = 0;
progress = 0;
remoteCfg = nullptr;
metadataOnly = false;
closureRequested = false;
vfsErrorCount = 0;
checksumType = ChecksumType::NULL_CHECKSUM;
}
bool metadataOnly = false;
ChecksumType checksumType = ChecksumType::NULL_CHECKSUM;
bool closureRequested = false;
uint16_t vfsErrorCount = 0;
std::vector<char> sourceName;
std::vector<char> destName;
cfdp::Fss fileSize;
TransactionId transactionId;
PduConfig pduConf;
ConditionCode conditionCode = ConditionCode::NO_ERROR;
FileDeliveryCode deliveryCode = FileDeliveryCode::DATA_INCOMPLETE;
FileDeliveryStatus deliveryStatus = FileDeliveryStatus::DISCARDED_DELIBERATELY;
uint32_t crc = 0;
uint64_t progress = 0;
RemoteEntityCfg* remoteCfg = nullptr;
};
std::vector<cfdp::Tlv> tlvVec;
std::vector<MessageToUserTlv> msgToUserVec;
TransactionParams transactionParams;
DestHandlerParams destParams;
cfdp::FsfwParams fsfwParams;
FsmResult fsmRes;
ReturnValue_t startTransaction(const MetadataPduReader& reader);
ReturnValue_t handleMetadataPdu(const PacketInfo& info);
ReturnValue_t handleFileDataPdu(const PacketInfo& info);
ReturnValue_t handleEofPdu(const PacketInfo& info);
ReturnValue_t handleMetadataParseError(ReturnValue_t result, const uint8_t* rawData,
size_t maxSize);
ReturnValue_t handleTransferCompletion();
ReturnValue_t tryBuildingAbsoluteDestName(size_t destNameSize);
ReturnValue_t sendFinishedPdu();
ReturnValue_t noticeOfCompletion();
ReturnValue_t checksumVerification();
void fileErrorHandler(Event event, ReturnValue_t result, const char* info) const;
const FsmResult& updateFsmRes(uint8_t errors);
void checkAndHandleError(ReturnValue_t result, uint8_t& errorIdx);
void finish();
};
} // namespace cfdp
#endif // FSFW_CFDP_CFDPDESTHANDLER_H

View File

@ -1,51 +0,0 @@
#include "FaultHandlerBase.h"
namespace cfdp {
FaultHandlerBase::FaultHandlerBase() = default;
FaultHandlerBase::~FaultHandlerBase() = default;
bool FaultHandlerBase::getFaultHandler(cfdp::ConditionCode code,
cfdp::FaultHandlerCode& handler) const {
auto iter = faultHandlerMap.find(code);
if (iter == faultHandlerMap.end()) {
return false;
}
handler = iter->second;
return true;
}
bool FaultHandlerBase::setFaultHandler(cfdp::ConditionCode code, cfdp::FaultHandlerCode handler) {
if (not faultHandlerMap.contains(code)) {
return false;
}
if (handler != FaultHandlerCode::NOTICE_OF_SUSPENSION and
handler != FaultHandlerCode::ABANDON_TRANSACTION and
handler != FaultHandlerCode::NOTICE_OF_CANCELLATION and
handler != FaultHandlerCode::IGNORE_ERROR) {
return false;
}
faultHandlerMap[code] = handler;
return true;
}
bool FaultHandlerBase::reportFault(cfdp::TransactionId& id, cfdp::ConditionCode code) {
if (not faultHandlerMap.contains(code)) {
return false;
}
cfdp::FaultHandlerCode fh = faultHandlerMap[code];
if (fh == cfdp::FaultHandlerCode::IGNORE_ERROR) {
ignoreCb(id, code);
} else if (fh == cfdp::FaultHandlerCode::ABANDON_TRANSACTION) {
abandonCb(id, code);
} else if (fh == cfdp::FaultHandlerCode::NOTICE_OF_CANCELLATION) {
noticeOfCancellationCb(id, code);
} else if (fh == cfdp::FaultHandlerCode::NOTICE_OF_SUSPENSION) {
noticeOfSuspensionCb(id, code);
} else {
// Should never happen, but use defensive programming
return false;
}
return true;
}
} // namespace cfdp

View File

@ -1,77 +0,0 @@
#ifndef FSFW_CFDP_FAULTHANDLERBASE_H
#define FSFW_CFDP_FAULTHANDLERBASE_H
#include <etl/flat_map.h>
#include "fsfw/cfdp/VarLenFields.h"
#include "fsfw/cfdp/definitions.h"
namespace cfdp {
/**
* @brief Provides a way to implement the fault handling procedures as specified
* in chapter 4.8 of the CFDP standard.
*
* @details
* It is passed into the CFDP handlers as part of the local entity configuration and provides
* a way to specify custom user error handlers.
*
* It does so by mapping each applicable CFDP condition code to a fault handler which
* is denoted by the four @cfdp::FaultHandlerCodes. This code is used to dispatch
* to a user-provided callback function:
*
* 1. @FaultHandlerCodes::IGNORE_ERROR -> @ignore_cb
* 2. @FaultHandlerCodes::NOTICE_OF_CANCELLATION` -> @notice_of_cancellation_cb
* 3. @FaultHandlerCodes::NOTICE_OF_SUSPENSION` -> @notice_of_suspension_cb
* 4. @FaultHandlerCodes::ABANDON_TRANSACTION` -> @abandon_transaction_cb
*
* For each error reported by @reportError, the appropriate fault handler callback
* will be called. The user provides the callbacks by providing a custom class which implements
* these base class and all abstract fault handler callbacks.
*/
class FaultHandlerBase {
public:
virtual ~FaultHandlerBase();
FaultHandlerBase();
/**
* Get the fault handler code for the given condition code
* @param code
* @param handler [out] Will be set to the approrpiate handler for the condition code if
* it is valid
* @return
* - true if the condition code is valid
* - false otherwise
*/
bool getFaultHandler(cfdp::ConditionCode code, cfdp::FaultHandlerCode& handler) const;
bool setFaultHandler(cfdp::ConditionCode code, cfdp::FaultHandlerCode handler);
bool reportFault(cfdp::TransactionId& id, cfdp::ConditionCode code);
virtual void noticeOfSuspensionCb(cfdp::TransactionId& id, cfdp::ConditionCode code) = 0;
virtual void noticeOfCancellationCb(cfdp::TransactionId& id, cfdp::ConditionCode code) = 0;
virtual void abandonCb(cfdp::TransactionId& id, cfdp::ConditionCode code) = 0;
virtual void ignoreCb(cfdp::TransactionId& id, cfdp::ConditionCode code) = 0;
private:
etl::flat_map<cfdp::ConditionCode, cfdp::FaultHandlerCode, 10> faultHandlerMap = {
etl::pair{cfdp::ConditionCode::POSITIVE_ACK_LIMIT_REACHED,
cfdp::FaultHandlerCode::IGNORE_ERROR},
etl::pair{cfdp::ConditionCode::KEEP_ALIVE_LIMIT_REACHED,
cfdp::FaultHandlerCode::IGNORE_ERROR},
etl::pair{cfdp::ConditionCode::INVALID_TRANSMISSION_MODE,
cfdp::FaultHandlerCode::IGNORE_ERROR},
etl::pair{cfdp::ConditionCode::FILE_CHECKSUM_FAILURE, cfdp::FaultHandlerCode::IGNORE_ERROR},
etl::pair{cfdp::ConditionCode::FILE_SIZE_ERROR, cfdp::FaultHandlerCode::IGNORE_ERROR},
etl::pair{cfdp::ConditionCode::NAK_LIMIT_REACHED, cfdp::FaultHandlerCode::IGNORE_ERROR},
etl::pair{cfdp::ConditionCode::INACTIVITY_DETECTED, cfdp::FaultHandlerCode::IGNORE_ERROR},
etl::pair{cfdp::ConditionCode::UNSUPPORTED_CHECKSUM_TYPE,
cfdp::FaultHandlerCode::IGNORE_ERROR},
etl::pair{cfdp::ConditionCode::FILESTORE_REJECTION, cfdp::FaultHandlerCode::IGNORE_ERROR},
etl::pair{cfdp::ConditionCode::CHECK_LIMIT_REACHED, cfdp::FaultHandlerCode::IGNORE_ERROR}};
};
} // namespace cfdp
#endif // FSFW_CFDP_FAULTHANDLERBASE_H

View File

@ -1,201 +0,0 @@
#include "PutRequest.h"
using namespace returnvalue;
cfdp::PutRequest::PutRequest(cfdp::EntityId destId, const uint8_t *msgsToUser,
size_t msgsToUserTotalSize, const uint8_t *fsRequests,
size_t fsRequestsSize)
: destId(std::move(destId)),
metadataOnly(true),
msgsToUsersTotalSize(msgsToUserTotalSize),
msgsToUserStartPtr(msgsToUser),
fsRequestsTotalSize(fsRequestsSize),
fsRequestStartPtr(fsRequests) {}
cfdp::PutRequest::PutRequest(cfdp::EntityId destId, cfdp::StringLv &sourceName,
cfdp::StringLv &destName)
: destId(std::move(destId)), sourceName(std::move(sourceName)), destName(std::move(destName)) {}
[[nodiscard]] bool cfdp::PutRequest::isMetadataOnly() const { return metadataOnly; }
ReturnValue_t cfdp::PutRequest::serialize(uint8_t **buffer, size_t *size, size_t maxSize,
SerializeIF::Endianness streamEndianness) const {
if (buffer == nullptr or size == nullptr) {
return FAILED;
}
if (*size + getSerializedSize() > maxSize) {
return SerializeIF::BUFFER_TOO_SHORT;
}
ReturnValue_t result = destId.serializeAsLv(buffer, size, maxSize);
if (result != OK) {
return result;
}
result = SerializeAdapter::serialize(&metadataOnly, buffer, size, maxSize, streamEndianness);
if (result != OK) {
return result;
}
if (!metadataOnly) {
result = sourceName.serialize(buffer, size, maxSize, streamEndianness);
if (result != OK) {
return result;
}
result = destName.serialize(buffer, size, maxSize, streamEndianness);
if (result != OK) {
return result;
}
result =
SerializeAdapter::serialize(&hasTransmissionMode, buffer, size, maxSize, streamEndianness);
if (result != OK) {
return result;
}
result =
SerializeAdapter::serialize(&transmissionMode, buffer, size, maxSize, streamEndianness);
if (result != OK) {
return result;
}
result =
SerializeAdapter::serialize(&hasClosureRequested, buffer, size, maxSize, streamEndianness);
if (result != OK) {
return result;
}
result =
SerializeAdapter::serialize(&closureRequested, buffer, size, maxSize, streamEndianness);
if (result != OK) {
return result;
}
}
result =
SerializeAdapter::serialize(&msgsToUsersTotalSize, buffer, size, maxSize, streamEndianness);
if (result != OK) {
return result;
}
std::memcpy(*buffer, msgsToUserStartPtr, msgsToUsersTotalSize);
*buffer += msgsToUsersTotalSize;
*size += msgsToUsersTotalSize;
result =
SerializeAdapter::serialize(&fsRequestsTotalSize, buffer, size, maxSize, streamEndianness);
if (result != OK) {
return result;
}
std::memcpy(*buffer, fsRequestStartPtr, fsRequestsTotalSize);
*buffer += fsRequestsTotalSize;
*size += fsRequestsTotalSize;
return OK;
}
ReturnValue_t cfdp::PutRequest::deSerialize(const uint8_t **buffer, size_t *size,
SerializeIF::Endianness streamEndianness) {
if (buffer == nullptr or size == nullptr) {
return FAILED;
}
ReturnValue_t result = destId.deSerializeFromLv(buffer, size);
if (result != OK) {
return result;
}
result = SerializeAdapter::deSerialize(&metadataOnly, buffer, size, streamEndianness);
if (result != OK) {
return result;
}
if (!metadataOnly) {
result = sourceName.deSerialize(buffer, size, streamEndianness);
if (result != OK) {
return result;
}
result = destName.deSerialize(buffer, size, streamEndianness);
if (result != OK) {
return result;
}
result = SerializeAdapter::deSerialize(&hasTransmissionMode, buffer, size, streamEndianness);
if (result != OK) {
return result;
}
result = SerializeAdapter::deSerialize(&transmissionMode, buffer, size, streamEndianness);
if (result != OK) {
return result;
}
result = SerializeAdapter::deSerialize(&hasClosureRequested, buffer, size, streamEndianness);
if (result != OK) {
return result;
}
result = SerializeAdapter::deSerialize(&closureRequested, buffer, size, streamEndianness);
if (result != OK) {
return result;
}
}
result = SerializeAdapter::deSerialize(&msgsToUsersTotalSize, buffer, size, streamEndianness);
if (result != OK) {
return result;
}
msgsToUserStartPtr = *buffer;
*buffer += msgsToUsersTotalSize;
*size += msgsToUsersTotalSize;
result = SerializeAdapter::deSerialize(&fsRequestsTotalSize, buffer, size, streamEndianness);
if (result != OK) {
return result;
}
fsRequestStartPtr = *buffer;
*buffer += fsRequestsTotalSize;
*size += fsRequestsTotalSize;
return OK;
}
size_t cfdp::PutRequest::getSerializedSize() const {
// Entity ID LV (1 leading size byte) and the metadata only flag.
size_t baseSize = 1 + destId.getSerializedSize() + 1;
if (!metadataOnly) {
baseSize += sourceName.getSerializedSize() + destName.getSerializedSize() + 4;
}
baseSize += sizeof(msgsToUsersTotalSize) + msgsToUsersTotalSize + sizeof(fsRequestsTotalSize) +
fsRequestsTotalSize;
return baseSize;
}
void cfdp::PutRequest::setSourceAndDestName(cfdp::StringLv &sourceName_,
cfdp::StringLv &destName_) {
metadataOnly = false;
this->sourceName = std::move(sourceName_);
this->destName = std::move(destName_);
}
const cfdp::StringLv &cfdp::PutRequest::getSourceName() const { return sourceName; }
const cfdp::StringLv &cfdp::PutRequest::getDestName() const { return destName; }
const cfdp::EntityId &cfdp::PutRequest::getDestId() const { return destId; }
void cfdp::PutRequest::setDestId(cfdp::EntityId id) { destId = std::move(id); }
void cfdp::PutRequest::setTransmissionMode(cfdp::TransmissionMode transmissionMode_) {
this->transmissionMode = transmissionMode_;
hasTransmissionMode = true;
}
void cfdp::PutRequest::clearTransmissionMode() { hasTransmissionMode = false; }
void cfdp::PutRequest::clearClosureRequest() { hasClosureRequested = false; }
void cfdp::PutRequest::setClosureRequest(bool closureRequested_) {
this->closureRequested = closureRequested_;
hasClosureRequested = true;
}
const uint8_t *cfdp::PutRequest::getMessagesToUser(size_t &totalSize) {
totalSize = this->msgsToUsersTotalSize;
return msgsToUserStartPtr;
}
bool cfdp::PutRequest::getClosureRequested(bool &closureRequested_) const {
if (hasClosureRequested) {
closureRequested_ = this->closureRequested;
}
return hasClosureRequested;
}
bool cfdp::PutRequest::getTransmissionMode(cfdp::TransmissionMode &mode) const {
if (hasTransmissionMode) {
mode = static_cast<cfdp::TransmissionMode>(this->transmissionMode);
}
return hasTransmissionMode;
}

View File

@ -1,82 +0,0 @@
#pragma once
#include <optional>
#include <vector>
#include "fsfw/cfdp/VarLenFields.h"
#include "fsfw/cfdp/tlv/FilestoreRequestTlv.h"
#include "fsfw/cfdp/tlv/MessageToUserTlv.h"
namespace cfdp {
class PutRequest : public SerializeIF {
public:
/**
* Metadata only constructor.
* @param destId
* @param msgsToUser
* @param msgsToUserTotalSize
* @param fsRequests
* @param fsRequestsSize
*/
PutRequest(EntityId destId, const uint8_t* msgsToUser, size_t msgsToUserTotalSize,
const uint8_t* fsRequests, size_t fsRequestsSize);
/**
* Put request to initiate file transfers. By default, the transmission mode and closure requested
* parameter are not present, thereby being derived from the remote configuration for a
* particular destination ID.
* @param destId
* @param sourceName
* @param destName
*/
PutRequest(EntityId destId, cfdp::StringLv& sourceName, cfdp::StringLv& destName);
/**
* Default constructor for deserialization.
*/
PutRequest() = default;
[[nodiscard]] ReturnValue_t serialize(uint8_t** buffer, size_t* size, size_t maxSize,
Endianness streamEndianness) const override;
ReturnValue_t deSerialize(const uint8_t** buffer, size_t* size,
Endianness streamEndianness) override;
[[nodiscard]] size_t getSerializedSize() const override;
void setSourceAndDestName(cfdp::StringLv& sourceName, cfdp::StringLv& destName);
[[nodiscard]] const cfdp::StringLv& getSourceName() const;
[[nodiscard]] const cfdp::StringLv& getDestName() const;
void setTransmissionMode(cfdp::TransmissionMode transmissionMode);
void clearTransmissionMode();
void setClosureRequest(bool closureRequested);
void clearClosureRequest();
const uint8_t* getMessagesToUser(size_t& msgSize);
[[nodiscard]] bool isMetadataOnly() const;
bool getTransmissionMode(TransmissionMode& mode) const;
bool getClosureRequested(bool& closureRequested) const;
[[nodiscard]] const EntityId& getDestId() const;
void setDestId(EntityId id);
private:
EntityId destId;
uint8_t metadataOnly = true;
// Transaction parameters. Omitted if the put request is metadata only.
cfdp::StringLv sourceName;
cfdp::StringLv destName;
bool hasTransmissionMode = false;
uint8_t transmissionMode = TransmissionMode::UNACKNOWLEDGED;
bool hasClosureRequested = false;
uint8_t closureRequested = false;
// Metadata
size_t msgsToUsersTotalSize = 0;
const uint8_t* msgsToUserStartPtr = nullptr;
size_t fsRequestsTotalSize = 0;
const uint8_t* fsRequestStartPtr = nullptr;
};
} // namespace cfdp

View File

@ -1,35 +0,0 @@
#ifndef FSFW_CFDP_HANDLER_REMOTECONFIGTABLEIF_H
#define FSFW_CFDP_HANDLER_REMOTECONFIGTABLEIF_H
#include "fsfw/cfdp/handler/mib.h"
namespace cfdp {
class RemoteConfigTableIF {
public:
virtual ~RemoteConfigTableIF() = default;
virtual bool getRemoteCfg(const cfdp::EntityId& remoteId, cfdp::RemoteEntityCfg** cfg) = 0;
};
/**
* Helper class for the common case that there is exactly one remote entity
*/
class OneRemoteConfigProvider : public RemoteConfigTableIF {
public:
explicit OneRemoteConfigProvider(RemoteEntityCfg& cfg) : cfg(cfg) {}
bool getRemoteCfg(const EntityId& remoteId, cfdp::RemoteEntityCfg** cfg_) override {
if (remoteId != cfg.remoteId) {
return false;
}
*cfg_ = &cfg;
return true;
}
private:
RemoteEntityCfg& cfg;
};
} // namespace cfdp
#endif // FSFW_CFDP_HANDLER_REMOTECONFIGTABLEIF_H

View File

@ -1,74 +0,0 @@
#include "ReservedMessageParser.h"
#include "fsfw/cfdp/CfdpMessage.h"
#include "fsfw/cfdp/handler/PutRequest.h"
#include "fsfw/cfdp/tlv/MessageToUserTlv.h"
#include "fsfw/ipc/CommandMessage.h"
#include "fsfw/ipc/QueueFactory.h"
using namespace returnvalue;
cfdp::ReservedMessageParser::ReservedMessageParser(StorageManagerIF& ipcStore,
MessageQueueIF& msgQueue,
MessageQueueId_t userDestination)
: msgQueue(msgQueue), ipcStore(ipcStore), userDestination(userDestination) {}
ReturnValue_t cfdp::ReservedMessageParser::parse(const MessageToUserTlv* msgsToUserArray,
size_t numMsgToUser) {
ReturnValue_t result = returnvalue::OK;
cfdp::StringLv sourceFileName;
cfdp::StringLv destFileName;
PutRequest putRequest;
const uint8_t* currentPtr = nullptr;
size_t deserSize = 0;
bool needToSendPutRequest = false;
for (size_t idx = 0; idx < numMsgToUser; idx++) {
if (&msgsToUserArray[idx] == nullptr) {
continue;
}
uint8_t messageType = 0;
if (msgsToUserArray[idx].isReservedCfdpMessage(messageType, &currentPtr, deserSize)) {
if (messageType == static_cast<uint8_t>(ProxyOpMessageType::PUT_REQUEST)) {
EntityId entityIdLv;
result = entityIdLv.deSerializeFromLv(&currentPtr, &deserSize);
if (result != returnvalue::OK) {
return result;
}
putRequest.setDestId(entityIdLv);
result =
sourceFileName.deSerialize(&currentPtr, &deserSize, SerializeIF::Endianness::NETWORK);
if (result != OK) {
return result;
}
result =
destFileName.deSerialize(&currentPtr, &deserSize, SerializeIF::Endianness::NETWORK);
if (result != OK) {
return result;
}
putRequest.setSourceAndDestName(sourceFileName, destFileName);
needToSendPutRequest = true;
}
}
}
if (needToSendPutRequest) {
store_address_t storeId;
uint8_t* dataPtr;
result = ipcStore.getFreeElement(&storeId, putRequest.getSerializedSize(), &dataPtr);
if (result != OK) {
return result;
}
size_t serLen = 0;
result = putRequest.serialize(&dataPtr, &serLen, putRequest.getSerializedSize(),
SerializeIF::Endianness::MACHINE);
if (result != OK) {
return result;
}
CommandMessage msg;
CfdpMessage::setPutRequest(&msg, storeId);
result = msgQueue.sendMessage(userDestination, &msg);
if (result != OK) {
return result;
}
}
return OK;
}

View File

@ -1,27 +0,0 @@
#pragma once
#include "fsfw/cfdp/tlv/MessageToUserTlv.h"
#include "fsfw/ipc/MessageQueueIF.h"
#include "fsfw/storagemanager/StorageManagerIF.h"
namespace cfdp {
/**
* This class parses messages to user for special CFDP messages and converts them to appropriate
* CFDP requests sent via the IPC store where applicable. It also provides an API to retrieve
* custom messages which are not special CFDP messages from a provided bytestream.
*/
class ReservedMessageParser {
public:
ReservedMessageParser(StorageManagerIF& ipcStore, MessageQueueIF& msgQueue,
MessageQueueId_t userDestination);
ReturnValue_t parse(const MessageToUserTlv* msgsToUserArray, size_t numMsgsToUser);
private:
MessageQueueIF& msgQueue;
StorageManagerIF& ipcStore;
MessageQueueId_t userDestination;
};
} // namespace cfdp

View File

@ -1,376 +0,0 @@
#include "SourceHandler.h"
#include <etl/crc32.h>
#include <array>
#include "fsfw/cfdp/pdu/EofPduCreator.h"
#include "fsfw/cfdp/pdu/FileDataCreator.h"
#include "fsfw/cfdp/pdu/MetadataPduCreator.h"
#include "fsfw/filesystem/HasFileSystemIF.h"
#include "fsfw/globalfunctions/arrayprinter.h"
#include "fsfw/objectmanager.h"
#include "fsfw/serviceinterface.h"
#include "fsfw/tasks/TaskFactory.h"
#include "fsfw/tmtcservices/TmTcMessage.h"
using namespace returnvalue;
cfdp::SourceHandler::SourceHandler(SourceHandlerParams params, FsfwParams fsfwParams)
: sourceParams(std::move(params)), fsfwParams(fsfwParams) {
// The entity ID portion of the transaction ID will always remain fixed.
transactionParams.id.entityId = sourceParams.cfg.localId;
transactionParams.pduConf.sourceId = sourceParams.cfg.localId;
if (sourceParams.seqCountProvider.bitWidth() == 8) {
transactionParams.pduConf.seqNum.setWidth(cfdp::WidthInBytes::ONE_BYTE);
} else if (sourceParams.seqCountProvider.bitWidth() == 16) {
transactionParams.pduConf.seqNum.setWidth(cfdp::WidthInBytes::TWO_BYTES);
} else if (sourceParams.seqCountProvider.bitWidth() == 32) {
transactionParams.pduConf.seqNum.setWidth(cfdp::WidthInBytes::FOUR_BYTES);
} else if (sourceParams.seqCountProvider.bitWidth() == 64) {
transactionParams.pduConf.seqNum.setWidth(cfdp::WidthInBytes::EIGHT_BYTES);
} else {
#if FSFW_CPP_OSTREAM_ENABLED == 1
sif::error << "cfdp::SourceHandler: Seq count provider bit width "
<< sourceParams.seqCountProvider.bitWidth() << " not allowed" << std::endl;
#else
sif::printError("cfdp::SourceHandler: Seq count provider bit width %d not allowed\n",
sourceParams.seqCountProvider.bitWidth());
#endif
// Yeah, what am I supposed to do here? Can't throw an exception in the FSFW..
transactionParams.pduConf.seqNum.setWidth(cfdp::WidthInBytes::ONE_BYTE);
}
transactionParams.pduConf.seqNum.setValue(0);
}
cfdp::SourceHandler::FsmResult& cfdp::SourceHandler::fsmNacked() {
ReturnValue_t result;
if (step == TransactionStep::IDLE) {
step = TransactionStep::TRANSACTION_START;
}
if (step == TransactionStep::TRANSACTION_START) {
sourceParams.user.transactionIndication(transactionParams.id);
result = checksumGeneration();
if (result != OK) {
addError(result);
}
step = TransactionStep::SENDING_METADATA;
}
if (step == TransactionStep::SENDING_METADATA) {
result = prepareAndSendMetadataPdu();
if (result != OK) {
addError(result);
}
fsmResult.callStatus = CallStatus::CALL_AGAIN;
return fsmResult;
}
if (step == TransactionStep::SENDING_FILE_DATA) {
bool noFdPdu = false;
result = prepareAndSendNextFileDataPdu(noFdPdu);
if (result == OK and !noFdPdu) {
fsmResult.callStatus = CallStatus::CALL_AGAIN;
return fsmResult;
}
}
if (step == TransactionStep::SENDING_EOF) {
result = prepareAndSendEofPdu();
if (result != OK) {
addError(result);
}
if (sourceParams.cfg.indicCfg.eofSentIndicRequired) {
sourceParams.user.eofSentIndication(transactionParams.id);
}
if (transactionParams.closureRequested) {
step = TransactionStep::WAIT_FOR_FINISH;
fsmResult.callStatus = CallStatus::CALL_AFTER_DELAY;
} else {
step = TransactionStep::NOTICE_OF_COMPLETION;
fsmResult.callStatus = CallStatus::CALL_AGAIN;
}
return fsmResult;
}
if (step == TransactionStep::WAIT_FOR_FINISH) {
// TODO: In case this is a request with closure, wait for finish.
// Done, issue notice of completion
step = TransactionStep::NOTICE_OF_COMPLETION;
}
if (step == TransactionStep::NOTICE_OF_COMPLETION) {
noticeOfCompletion();
reset();
}
return fsmResult;
}
const cfdp::SourceHandler::FsmResult& cfdp::SourceHandler::stateMachine() {
fsmResult.packetsSent = 0;
fsmResult.errors = 0;
fsmResult.callStatus = CallStatus::DONE;
if (state == cfdp::CfdpState::IDLE) {
return fsmResult;
}
if (state == cfdp::CfdpState::BUSY_CLASS_1_NACKED) {
return fsmNacked();
}
return fsmResult;
}
ReturnValue_t cfdp::SourceHandler::checksumGeneration() {
if (transactionParams.fileSize.value() == 0) {
// NULL checksum for empty file.
transactionParams.crc = 0;
return OK;
}
std::array<uint8_t, 1024> buf{};
etl::crc32 crcCalc;
uint64_t currentOffset = 0;
FileOpParams params(transactionParams.sourceName.data(), transactionParams.fileSize.value());
while (currentOffset < transactionParams.fileSize.value()) {
uint64_t readLen;
if (currentOffset + buf.size() > transactionParams.fileSize.value()) {
readLen = transactionParams.fileSize.value() - currentOffset;
} else {
readLen = buf.size();
}
if (readLen > 0) {
params.offset = currentOffset;
params.size = readLen;
auto result = sourceParams.user.vfs.readFromFile(params, buf.data(), buf.size());
if (result != OK) {
addError(result);
return FAILED;
}
crcCalc.add(buf.begin(), buf.begin() + readLen);
}
currentOffset += readLen;
}
transactionParams.crc = crcCalc.value();
return OK;
}
ReturnValue_t cfdp::SourceHandler::transactionStart(PutRequest& putRequest, RemoteEntityCfg& cfg) {
if (state != CfdpState::IDLE) {
return SOURCE_TRANSACTION_PENDING;
}
if (cfg.remoteId != putRequest.getDestId()) {
return WRONG_REMOTE_CFG_ENTITY_ID;
}
if (putRequest.getSourceName().getValueLen() == 0) {
return SOURCE_NAME_EMPTY;
}
if (putRequest.getDestName().getValueLen() == 0) {
return DEST_NAME_EMPTY;
}
const char* srcNamePtr = putRequest.getSourceName().getCString(transactionParams.sourceNameSize);
const char* destNamePtr = putRequest.getDestName().getCString(transactionParams.destNameSize);
std::strncpy(transactionParams.sourceName.data(), srcNamePtr, transactionParams.sourceNameSize);
std::strncpy(transactionParams.destName.data(), destNamePtr, transactionParams.destNameSize);
// Add 0 termination. The source and dest name size can not be larger than UINT8_MAX, so this
// operation is safe.
transactionParams.sourceName[transactionParams.sourceNameSize] = '\0';
transactionParams.destName[transactionParams.destNameSize] = '\0';
FilesystemParams params(transactionParams.sourceName.data());
if (!sourceParams.user.vfs.fileExists(params)) {
return FILE_DOES_NOT_EXIST;
}
if (cfg.maxFileSegmentLen > fileBuf.size() or cfg.maxFileSegmentLen == 0) {
return FILE_SEGMENT_LEN_INVALID;
}
// If transmission mode is not set, use default transmission mode for the remote entity.
if (not putRequest.getTransmissionMode(transactionParams.pduConf.mode)) {
transactionParams.pduConf.mode = cfg.defaultTransmissionMode;
}
// If closure request field is not set, use default option for the remote entity.
if (not putRequest.getClosureRequested(transactionParams.closureRequested)) {
transactionParams.closureRequested = cfg.closureRequested;
}
const EntityId& destId = putRequest.getDestId();
// The width of the source and destination ID must be the same. Use the larger ID value to
// ensure the width is large enough for both IDs
if (destId.getWidth() > transactionParams.pduConf.sourceId.getWidth()) {
transactionParams.pduConf.destId = destId;
transactionParams.pduConf.sourceId.setWidth(destId.getWidth());
} else {
transactionParams.pduConf.destId.setValueAndWidth(transactionParams.pduConf.sourceId.getWidth(),
destId.getValue());
}
// Only used for PDU forwarding, file is sent to file receiver regularly here.
transactionParams.pduConf.direction = Direction::TOWARDS_RECEIVER;
transactionParams.pduConf.seqNum.setValue(sourceParams.seqCountProvider.getAndIncrement());
transactionParams.id.seqNum = transactionParams.pduConf.seqNum;
if (transactionParams.pduConf.mode == TransmissionMode::ACKNOWLEDGED) {
state = cfdp::CfdpState::BUSY_CLASS_2_ACKED;
} else if (transactionParams.pduConf.mode == TransmissionMode::UNACKNOWLEDGED) {
state = cfdp::CfdpState::BUSY_CLASS_1_NACKED;
}
step = TransactionStep::IDLE;
uint64_t fileSize = 0;
sourceParams.user.vfs.getFileSize(params, fileSize);
transactionParams.pduConf.largeFile = false;
if (fileSize > UINT32_MAX) {
transactionParams.pduConf.largeFile = true;
}
if (fileSize == 0) {
transactionParams.checksumType = ChecksumType::NULL_CHECKSUM;
} else {
transactionParams.checksumType = ChecksumType::CRC_32;
}
transactionParams.fileSize.setFileSize(fileSize, transactionParams.pduConf.largeFile);
transactionParams.progress = 0;
transactionParams.remoteCfg = cfg;
return OK;
}
ReturnValue_t cfdp::SourceHandler::prepareAndSendMetadataPdu() {
cfdp::StringLv sourceName(transactionParams.sourceName.data(), transactionParams.sourceNameSize);
cfdp::StringLv destName(transactionParams.destName.data(), transactionParams.destNameSize);
auto metadataInfo =
MetadataGenericInfo(transactionParams.closureRequested, transactionParams.checksumType,
transactionParams.fileSize);
auto metadataPdu =
MetadataPduCreator(transactionParams.pduConf, metadataInfo, sourceName, destName, nullptr, 0);
ReturnValue_t result = sendGenericPdu(metadataPdu);
if (result != OK) {
return result;
}
// Advance FSM if everything works
step = TransactionStep::SENDING_FILE_DATA;
return OK;
}
ReturnValue_t cfdp::SourceHandler::prepareAndSendNextFileDataPdu(bool& noFileDataPdu) {
cfdp::Fss offset(transactionParams.progress);
uint64_t readLen;
uint64_t fileSize = transactionParams.fileSize.value();
noFileDataPdu = false;
if (fileSize == 0) {
// We are done, no need to send file data PDUs for an empty file.
step = TransactionStep::SENDING_EOF;
noFileDataPdu = true;
return OK;
}
if (fileSize < transactionParams.remoteCfg.maxFileSegmentLen) {
readLen = transactionParams.fileSize.value();
} else {
if (transactionParams.progress + transactionParams.remoteCfg.maxFileSegmentLen > fileSize) {
readLen = fileSize - transactionParams.progress;
} else {
readLen = transactionParams.remoteCfg.maxFileSegmentLen;
}
}
FileOpParams fileParams(transactionParams.sourceName.data(), readLen);
fileParams.offset = transactionParams.progress;
ReturnValue_t result =
sourceParams.user.vfs.readFromFile(fileParams, fileBuf.data(), fileBuf.size());
if (result != returnvalue::OK) {
addError(result);
return result;
}
auto fileDataInfo = FileDataInfo(offset, fileBuf.data(), readLen);
auto fileDataPdu = FileDataCreator(transactionParams.pduConf, fileDataInfo);
result = sendGenericPdu(fileDataPdu);
if (result != OK) {
return result;
}
transactionParams.progress += readLen;
if (transactionParams.progress >= fileSize) {
// Advance FSM after all file data PDUs were sent.
step = TransactionStep::SENDING_EOF;
}
return OK;
}
ReturnValue_t cfdp::SourceHandler::prepareAndSendEofPdu() {
auto eofInfo =
EofInfo(ConditionCode::NO_ERROR, transactionParams.crc, transactionParams.fileSize);
auto eofPdu = EofPduCreator(transactionParams.pduConf, eofInfo);
ReturnValue_t result = sendGenericPdu(eofPdu);
if (result != OK) {
return result;
}
return OK;
}
ReturnValue_t cfdp::SourceHandler::initialize() {
if (fsfwParams.tmStore == nullptr) {
fsfwParams.tmStore = ObjectManager::instance()->get<StorageManagerIF>(objects::TM_STORE);
if (fsfwParams.tmStore == nullptr) {
return FAILED;
}
}
if (fsfwParams.tcStore == nullptr) {
fsfwParams.tcStore = ObjectManager::instance()->get<StorageManagerIF>(objects::TC_STORE);
if (fsfwParams.tcStore == nullptr) {
return FAILED;
}
}
if (fsfwParams.msgQueue == nullptr) {
return FAILED;
}
return OK;
}
ReturnValue_t cfdp::SourceHandler::sendGenericPdu(const SerializeIF& pdu) {
uint8_t* dataPtr;
store_address_t storeId;
ReturnValue_t result =
fsfwParams.tmStore->getFreeElement(&storeId, pdu.getSerializedSize(), &dataPtr);
if (result != OK) {
addError(result);
fsmResult.callStatus = CallStatus::CALL_AFTER_DELAY;
if (result == StorageManagerIF::DATA_STORAGE_FULL) {
return TM_STORE_FULL;
}
return result;
}
size_t serializedLen = 0;
result = pdu.serializeBe(dataPtr, serializedLen, pdu.getSerializedSize());
if (result != OK) {
addError(result);
return result;
}
TmTcMessage tmMsg(storeId);
result =
fsfwParams.msgQueue->sendMessage(fsfwParams.packetDest.getReportReceptionQueue(), &tmMsg);
if (result != OK) {
fsmResult.callStatus = CallStatus::CALL_AFTER_DELAY;
}
if (result == MessageQueueIF::FULL) {
return TARGET_MSG_QUEUE_FULL;
} else if (result == OK) {
fsmResult.packetsSent += 1;
}
return result;
}
ReturnValue_t cfdp::SourceHandler::noticeOfCompletion() {
if (sourceParams.cfg.indicCfg.transactionFinishedIndicRequired) {
cfdp::TransactionFinishedParams params(transactionParams.id, ConditionCode::NO_ERROR,
FileDeliveryCode::DATA_COMPLETE,
FileDeliveryStatus::RETAINED_IN_FILESTORE);
sourceParams.user.transactionFinishedIndication(params);
}
return OK;
}
ReturnValue_t cfdp::SourceHandler::reset() {
step = TransactionStep::IDLE;
state = cfdp::CfdpState::IDLE;
fsmResult.callStatus = CallStatus::DONE;
transactionParams.reset();
return OK;
}
cfdp::CfdpState cfdp::SourceHandler::getState() const { return state; }
cfdp::SourceHandler::TransactionStep cfdp::SourceHandler::getStep() const { return step; }
void cfdp::SourceHandler::addError(ReturnValue_t error) {
if (fsmResult.errors < fsmResult.errorCodes.size()) {
fsmResult.errorCodes[fsmResult.errors] = error;
fsmResult.errors++;
fsmResult.result = error;
}
}

View File

@ -1,110 +0,0 @@
#ifndef FSFW_CFDP_CFDPSOURCEHANDLER_H
#define FSFW_CFDP_CFDPSOURCEHANDLER_H
#include <cstdint>
#include <vector>
#include "UserBase.h"
#include "defs.h"
#include "fsfw/cfdp/Fss.h"
#include "fsfw/cfdp/handler/PutRequest.h"
#include "fsfw/cfdp/handler/mib.h"
#include "fsfw/events/EventReportingProxyIF.h"
#include "fsfw/storagemanager/StorageManagerIF.h"
#include "fsfw/tmtcservices/AcceptsTelemetryIF.h"
#include "fsfw/util/ProvidesSeqCountIF.h"
namespace cfdp {
struct SourceHandlerParams {
SourceHandlerParams(LocalEntityCfg cfg, UserBase& user, ProvidesSeqCountIF& seqCountProvider)
: cfg(std::move(cfg)), user(user), seqCountProvider(seqCountProvider) {}
LocalEntityCfg cfg;
UserBase& user;
ProvidesSeqCountIF& seqCountProvider;
};
class SourceHandler {
public:
enum class TransactionStep : uint8_t {
IDLE = 0,
TRANSACTION_START = 1,
SENDING_METADATA = 3,
SENDING_FILE_DATA = 4,
SENDING_EOF = 5,
WAIT_FOR_ACK = 6,
WAIT_FOR_FINISH = 7,
NOTICE_OF_COMPLETION = 8
};
struct FsmResult {
public:
ReturnValue_t result = returnvalue::OK;
CallStatus callStatus = CallStatus::CALL_AFTER_DELAY;
CfdpState state = CfdpState::IDLE;
uint32_t packetsSent = 0;
uint8_t errors = 0;
std::array<ReturnValue_t, 3> errorCodes = {};
};
SourceHandler(SourceHandlerParams params, FsfwParams fsfwParams);
[[nodiscard]] CfdpState getState() const;
[[nodiscard]] TransactionStep getStep() const;
/**
* Pass a put request to the source handler, which might initiate a CFDP transaction and start
* the state machine
* @return
*/
ReturnValue_t transactionStart(PutRequest& putRequest, RemoteEntityCfg& cfg);
const FsmResult& stateMachine();
ReturnValue_t initialize();
private:
struct TransactionParams {
uint32_t crc{};
std::array<char, UINT8_MAX + 1> sourceName{};
size_t sourceNameSize = 0;
std::array<char, UINT8_MAX + 1> destName{};
size_t destNameSize = 0;
cfdp::Fss fileSize;
size_t progress = 0;
bool closureRequested = false;
ChecksumType checksumType = ChecksumType::NULL_CHECKSUM;
RemoteEntityCfg remoteCfg;
PduConfig pduConf;
cfdp::TransactionId id{};
void reset() {
sourceNameSize = 0;
destNameSize = 0;
fileSize.setFileSize(0, false);
progress = 0;
closureRequested = false;
}
} transactionParams;
cfdp::CfdpState state = cfdp::CfdpState::IDLE;
TransactionStep step = TransactionStep::IDLE;
std::array<uint8_t, 4096> fileBuf{};
SourceHandlerParams sourceParams;
cfdp::FsfwParams fsfwParams;
FsmResult fsmResult;
FsmResult& fsmNacked();
ReturnValue_t checksumGeneration();
ReturnValue_t prepareAndSendMetadataPdu();
ReturnValue_t prepareAndSendNextFileDataPdu(bool& noFileDataPdu);
ReturnValue_t prepareAndSendEofPdu();
ReturnValue_t noticeOfCompletion();
ReturnValue_t reset();
[[nodiscard]] ReturnValue_t sendGenericPdu(const SerializeIF& pdu);
void addError(ReturnValue_t error);
};
} // namespace cfdp
#endif // FSFW_CFDP_CFDPSOURCEHANDLER_H

View File

@ -1,12 +0,0 @@
#ifndef FSFW_CFDP_HANDLER_STATUSREPORTIF_H
#define FSFW_CFDP_HANDLER_STATUSREPORTIF_H
namespace cfdp {
class StatusReportIF {
virtual ~StatusReportIF() = default;
};
} // namespace cfdp
#endif // FSFW_CFDP_HANDLER_STATUSREPORTIF_H

View File

@ -1,3 +0,0 @@
#include "UserBase.h"
cfdp::UserBase::UserBase(HasFileSystemIF& vfs) : vfs(vfs) {}

View File

@ -1,103 +0,0 @@
#ifndef FSFW_CFDP_USERBASE_H
#define FSFW_CFDP_USERBASE_H
#include <optional>
#include <utility>
#include <vector>
#include "StatusReportIF.h"
#include "fsfw/cfdp/Fss.h"
#include "fsfw/cfdp/VarLenFields.h"
#include "fsfw/cfdp/tlv/FilestoreResponseTlv.h"
#include "fsfw/cfdp/tlv/MessageToUserTlv.h"
#include "fsfw/filesystem/HasFileSystemIF.h"
namespace cfdp {
struct TransactionFinishedParams {
TransactionFinishedParams(const TransactionId& id, ConditionCode code, FileDeliveryCode delivCode,
FileDeliveryStatus status)
: id(id), condCode(code), status(status), deliveryCode(delivCode) {}
const TransactionId& id;
ConditionCode condCode;
FileDeliveryStatus status;
FileDeliveryCode deliveryCode;
std::vector<FilestoreResponseTlv*> fsResponses;
StatusReportIF* statusReport = nullptr;
};
struct MetadataRecvdParams {
MetadataRecvdParams(const TransactionId& id, const EntityId& sourceId, Fss fileSize)
: id(id), sourceId(sourceId), fileSize(std::move(fileSize)) {}
const TransactionId& id;
const EntityId& sourceId;
Fss fileSize{};
const char* sourceFileName = "";
const char* destFileName = "";
size_t numberOfMsgsToUser = 0;
const MessageToUserTlv* msgsToUserArray = nullptr;
};
struct FileSegmentRecvdParams {
TransactionId id;
size_t offset;
size_t length;
std::optional<RecordContinuationState> recContState = std::nullopt;
std::pair<const uint8_t*, size_t> segmentMetadata;
};
/**
* @brief Base class which provides a user interface to interact with CFDP handlers.
*
* @details
* This class is also used to pass the Virtual Filestore (VFS) Implementation to the CFDP
* handlers so the filestore operations can be mapped to the underlying filestore.
*
* It is used by implementing it in a child class and then passing it to the CFDP
* handler objects. The base class provides default implementation for the user indication
* primitives specified in the CFDP standard. The user can override these implementations
* to provide custom indication handlers.
*
* Please note that for all indication callbacks, the passed transaction ID reference will
* become invalid shortly after the function has been executed. If the transaction ID is to be
* cached or used, create an own copy of it.
* @param vfs Virtual Filestore Object. Will be used for all file operations
*/
class UserBase {
friend class DestHandler;
friend class SourceHandler;
public:
explicit UserBase(HasFileSystemIF& vfs);
virtual void transactionIndication(const TransactionId& id) = 0;
virtual void eofSentIndication(const TransactionId& id) = 0;
virtual void transactionFinishedIndication(const TransactionFinishedParams& params) = 0;
/**
* Will be called if metadata was received.
*
* IMPORTANT: The passed struct contains the messages to the user in form of a raw C array.
* The TLVs in these arrays are zero-copy types, which means that they point to the raw data
* inside the metadata packet directly. The metadata packet will be deleted from the TC store
* shortly after it was processed. If some of the data is to be cached and/or used after the
* function call, it needs to be copied into another user-provided buffer.
* @param params
*/
virtual void metadataRecvdIndication(const MetadataRecvdParams& params) = 0;
virtual void fileSegmentRecvdIndication(const FileSegmentRecvdParams& params) = 0;
virtual void reportIndication(const TransactionId& id, StatusReportIF& report) = 0;
virtual void suspendedIndication(const TransactionId& id, ConditionCode code) = 0;
virtual void resumedIndication(const TransactionId& id, size_t progress) = 0;
virtual void faultIndication(const TransactionId& id, ConditionCode code, size_t progress) = 0;
virtual void abandonedIndication(const TransactionId& id, ConditionCode code,
size_t progress) = 0;
virtual void eofRecvIndication(const TransactionId& id) = 0;
private:
HasFileSystemIF& vfs;
};
} // namespace cfdp
#endif // FSFW_CFDP_USERBASE_H

View File

@ -1,76 +0,0 @@
#ifndef FSFW_CFDP_HANDLER_DEFS_H
#define FSFW_CFDP_HANDLER_DEFS_H
#include <etl/list.h>
#include "fsfw/storagemanager/StorageManagerIF.h"
#include "fsfw/storagemanager/storeAddress.h"
#include "fsfw/tmtcservices/AcceptsTelemetryIF.h"
namespace cfdp {
enum class CfdpState { IDLE, BUSY_CLASS_1_NACKED, BUSY_CLASS_2_ACKED, SUSPENDED };
static constexpr uint8_t SSID = SUBSYSTEM_ID::CFDP;
static constexpr uint8_t CID = CLASS_ID::CFDP_HANDLER;
struct PacketInfo {
PacketInfo(PduType type, store_address_t storeId,
std::optional<FileDirective> directive = std::nullopt)
: pduType(type), directiveType(directive), storeId(storeId) {}
PduType pduType = PduType::FILE_DATA;
std::optional<FileDirective> directiveType = FileDirective::INVALID_DIRECTIVE;
store_address_t storeId = store_address_t::invalid();
PacketInfo() = default;
};
struct FsfwParams {
FsfwParams(AcceptsTelemetryIF& packetDest, MessageQueueIF* msgQueue,
EventReportingProxyIF* eventReporter, StorageManagerIF& tcStore,
StorageManagerIF& tmStore)
: FsfwParams(packetDest, msgQueue, eventReporter) {
this->tcStore = &tcStore;
this->tmStore = &tmStore;
}
FsfwParams(AcceptsTelemetryIF& packetDest, MessageQueueIF* msgQueue,
EventReportingProxyIF* eventReporter)
: packetDest(packetDest), msgQueue(msgQueue), eventReporter(eventReporter) {}
AcceptsTelemetryIF& packetDest;
MessageQueueIF* msgQueue;
EventReportingProxyIF* eventReporter = nullptr;
StorageManagerIF* tcStore = nullptr;
StorageManagerIF* tmStore = nullptr;
};
template <size_t SIZE>
using PacketInfoList = etl::list<PacketInfo, SIZE>;
using PacketInfoListBase = etl::ilist<PacketInfo>;
enum class CallStatus { DONE, CALL_AFTER_DELAY, CALL_AGAIN };
namespace events {
static constexpr Event STORE_ERROR = event::makeEvent(SSID, 0, severity::LOW);
static constexpr Event MSG_QUEUE_ERROR = event::makeEvent(SSID, 1, severity::LOW);
static constexpr Event SERIALIZATION_ERROR = event::makeEvent(SSID, 2, severity::LOW);
static constexpr Event FILESTORE_ERROR = event::makeEvent(SSID, 3, severity::LOW);
//! [EXPORT] : [COMMENT] P1: Transaction step ID, P2: 0 for source file name, 1 for dest file name
static constexpr Event FILENAME_TOO_LARGE_ERROR = event::makeEvent(SSID, 4, severity::LOW);
//! [EXPORT] : [COMMENT] CFDP request handling failed. P2: Returncode.
static constexpr Event HANDLING_CFDP_REQUEST_FAILED = event::makeEvent(SSID, 5, severity::LOW);
} // namespace events
static constexpr ReturnValue_t SOURCE_TRANSACTION_PENDING = returnvalue::makeCode(CID, 0);
static constexpr ReturnValue_t FILE_DOES_NOT_EXIST = returnvalue::makeCode(CID, 1);
static constexpr ReturnValue_t FILE_SEGMENT_LEN_INVALID = returnvalue::makeCode(CID, 2);
static constexpr ReturnValue_t SOURCE_NAME_EMPTY = returnvalue::makeCode(CID, 3);
static constexpr ReturnValue_t DEST_NAME_EMPTY = returnvalue::makeCode(CID, 4);
static constexpr ReturnValue_t WRONG_REMOTE_CFG_ENTITY_ID = returnvalue::makeCode(CID, 5);
static constexpr ReturnValue_t TARGET_MSG_QUEUE_FULL = returnvalue::makeCode(CID, 6);
static constexpr ReturnValue_t TM_STORE_FULL = returnvalue::makeCode(CID, 7);
} // namespace cfdp
#endif // FSFW_CFDP_HANDLER_DEFS_H

View File

@ -1,43 +0,0 @@
#ifndef FSFW_CFDP_MIB_H
#define FSFW_CFDP_MIB_H
#include <utility>
#include "FaultHandlerBase.h"
#include "fsfw/cfdp/pdu/PduConfig.h"
namespace cfdp {
struct IndicationCfg {
bool eofSentIndicRequired = true;
bool eofRecvIndicRequired = true;
bool fileSegmentRecvIndicRequired = true;
bool transactionFinishedIndicRequired = true;
bool suspendedIndicRequired = true;
bool resumedIndicRequired = true;
};
struct LocalEntityCfg {
LocalEntityCfg(EntityId localId, IndicationCfg indicationCfg, FaultHandlerBase& fhBase)
: localId(std::move(localId)), indicCfg(indicationCfg), fhBase(fhBase) {}
EntityId localId;
IndicationCfg indicCfg;
FaultHandlerBase& fhBase;
};
struct RemoteEntityCfg {
RemoteEntityCfg() = default;
explicit RemoteEntityCfg(EntityId id) : remoteId(std::move(id)) {}
EntityId remoteId;
size_t maxFileSegmentLen = 1024;
bool closureRequested = false;
bool crcOnTransmission = false;
TransmissionMode defaultTransmissionMode = TransmissionMode::UNACKNOWLEDGED;
ChecksumType defaultChecksum = ChecksumType::NULL_CHECKSUM;
uint8_t version = CFDP_VERSION_2;
};
} // namespace cfdp
#endif // FSFW_CFDP_MIB_H

View File

@ -1,50 +0,0 @@
#include "helpers.h"
const char* COND_CODE_STRINGS[14] = {"Unknown",
"No Error",
"Positive ACK Limit Reached",
"Keep Alive Limit Reached",
"Invalid Transmission Mode",
"Filestore Rejection",
"File Checksum Failure",
"File Size Error",
"NAK limit reached",
"Inactivity Detected",
"Check Limit Reached",
"Unsupported Checksum Type",
"Suspend Request Received",
"Cancel Request Received"};
const char* cfdp::getConditionCodeString(cfdp::ConditionCode code) {
switch (code) {
case NO_CONDITION_FIELD:
return COND_CODE_STRINGS[0];
case NO_ERROR:
return COND_CODE_STRINGS[1];
case POSITIVE_ACK_LIMIT_REACHED:
return COND_CODE_STRINGS[2];
case KEEP_ALIVE_LIMIT_REACHED:
return COND_CODE_STRINGS[3];
case INVALID_TRANSMISSION_MODE:
return COND_CODE_STRINGS[4];
case FILESTORE_REJECTION:
return COND_CODE_STRINGS[5];
case FILE_CHECKSUM_FAILURE:
return COND_CODE_STRINGS[6];
case FILE_SIZE_ERROR:
return COND_CODE_STRINGS[7];
case NAK_LIMIT_REACHED:
return COND_CODE_STRINGS[8];
case INACTIVITY_DETECTED:
return COND_CODE_STRINGS[9];
case CHECK_LIMIT_REACHED:
return COND_CODE_STRINGS[10];
case UNSUPPORTED_CHECKSUM_TYPE:
return COND_CODE_STRINGS[11];
case SUSPEND_REQUEST_RECEIVED:
return COND_CODE_STRINGS[12];
case CANCEL_REQUEST_RECEIVED:
return COND_CODE_STRINGS[13];
}
return "Unknown";
}

View File

@ -1,11 +0,0 @@
#ifndef FSFW_EXAMPLE_HOSTED_HELPER_H
#define FSFW_EXAMPLE_HOSTED_HELPER_H
#include "definitions.h"
namespace cfdp {
const char* getConditionCodeString(cfdp::ConditionCode code);
}
#endif // FSFW_EXAMPLE_HOSTED_HELPER_H

View File

@ -1,12 +1,12 @@
#include "AckInfo.h" #include "AckInfo.h"
AckInfo::AckInfo(cfdp::FileDirective ackedDirective, cfdp::ConditionCode ackedConditionCode, AckInfo::AckInfo(cfdp::FileDirectives ackedDirective, cfdp::ConditionCode ackedConditionCode,
cfdp::AckTransactionStatus transactionStatus, uint8_t directiveSubtypeCode) cfdp::AckTransactionStatus transactionStatus, uint8_t directiveSubtypeCode)
: ackedDirective(ackedDirective), : ackedDirective(ackedDirective),
ackedConditionCode(ackedConditionCode), ackedConditionCode(ackedConditionCode),
transactionStatus(transactionStatus), transactionStatus(transactionStatus),
directiveSubtypeCode(directiveSubtypeCode) { directiveSubtypeCode(directiveSubtypeCode) {
if (ackedDirective == cfdp::FileDirective::FINISH) { if (ackedDirective == cfdp::FileDirectives::FINISH) {
this->directiveSubtypeCode = 0b0001; this->directiveSubtypeCode = 0b0001;
} else { } else {
this->directiveSubtypeCode = 0b0000; this->directiveSubtypeCode = 0b0000;
@ -17,16 +17,16 @@ cfdp::ConditionCode AckInfo::getAckedConditionCode() const { return ackedConditi
void AckInfo::setAckedConditionCode(cfdp::ConditionCode ackedConditionCode) { void AckInfo::setAckedConditionCode(cfdp::ConditionCode ackedConditionCode) {
this->ackedConditionCode = ackedConditionCode; this->ackedConditionCode = ackedConditionCode;
if (ackedDirective == cfdp::FileDirective::FINISH) { if (ackedDirective == cfdp::FileDirectives::FINISH) {
this->directiveSubtypeCode = 0b0001; this->directiveSubtypeCode = 0b0001;
} else { } else {
this->directiveSubtypeCode = 0b0000; this->directiveSubtypeCode = 0b0000;
} }
} }
cfdp::FileDirective AckInfo::getAckedDirective() const { return ackedDirective; } cfdp::FileDirectives AckInfo::getAckedDirective() const { return ackedDirective; }
void AckInfo::setAckedDirective(cfdp::FileDirective ackedDirective) { void AckInfo::setAckedDirective(cfdp::FileDirectives ackedDirective) {
this->ackedDirective = ackedDirective; this->ackedDirective = ackedDirective;
} }

View File

@ -6,14 +6,14 @@
class AckInfo { class AckInfo {
public: public:
AckInfo(); AckInfo();
AckInfo(cfdp::FileDirective ackedDirective, cfdp::ConditionCode ackedConditionCode, AckInfo(cfdp::FileDirectives ackedDirective, cfdp::ConditionCode ackedConditionCode,
cfdp::AckTransactionStatus transactionStatus, uint8_t directiveSubtypeCode = 0); cfdp::AckTransactionStatus transactionStatus, uint8_t directiveSubtypeCode = 0);
cfdp::ConditionCode getAckedConditionCode() const; cfdp::ConditionCode getAckedConditionCode() const;
void setAckedConditionCode(cfdp::ConditionCode ackedConditionCode); void setAckedConditionCode(cfdp::ConditionCode ackedConditionCode);
cfdp::FileDirective getAckedDirective() const; cfdp::FileDirectives getAckedDirective() const;
void setAckedDirective(cfdp::FileDirective ackedDirective); void setAckedDirective(cfdp::FileDirectives ackedDirective);
uint8_t getDirectiveSubtypeCode() const; uint8_t getDirectiveSubtypeCode() const;
void setDirectiveSubtypeCode(uint8_t directiveSubtypeCode); void setDirectiveSubtypeCode(uint8_t directiveSubtypeCode);
@ -22,7 +22,7 @@ class AckInfo {
void setTransactionStatus(cfdp::AckTransactionStatus transactionStatus); void setTransactionStatus(cfdp::AckTransactionStatus transactionStatus);
private: private:
cfdp::FileDirective ackedDirective = cfdp::FileDirective::INVALID_DIRECTIVE; cfdp::FileDirectives ackedDirective = cfdp::FileDirectives::INVALID_DIRECTIVE;
cfdp::ConditionCode ackedConditionCode = cfdp::ConditionCode::NO_CONDITION_FIELD; cfdp::ConditionCode ackedConditionCode = cfdp::ConditionCode::NO_CONDITION_FIELD;
cfdp::AckTransactionStatus transactionStatus = cfdp::AckTransactionStatus::UNDEFINED; cfdp::AckTransactionStatus transactionStatus = cfdp::AckTransactionStatus::UNDEFINED;
uint8_t directiveSubtypeCode = 0; uint8_t directiveSubtypeCode = 0;

View File

@ -1,33 +0,0 @@
#include "AckPduCreator.h"
AckPduCreator::AckPduCreator(AckInfo &ackInfo, PduConfig &pduConf)
: FileDirectiveCreator(pduConf, cfdp::FileDirective::ACK, 2), ackInfo(ackInfo) {}
size_t AckPduCreator::getSerializedSize() const { return FileDirectiveCreator::getWholePduSize(); }
ReturnValue_t AckPduCreator::serialize(uint8_t **buffer, size_t *size, size_t maxSize,
Endianness streamEndianness) const {
ReturnValue_t result = FileDirectiveCreator::serialize(buffer, size, maxSize, streamEndianness);
if (result != returnvalue::OK) {
return result;
}
cfdp::FileDirective ackedDirective = ackInfo.getAckedDirective();
uint8_t directiveSubtypeCode = ackInfo.getDirectiveSubtypeCode();
cfdp::ConditionCode ackedConditionCode = ackInfo.getAckedConditionCode();
cfdp::AckTransactionStatus transactionStatus = ackInfo.getTransactionStatus();
if (ackedDirective != cfdp::FileDirective::FINISH and
ackedDirective != cfdp::FileDirective::EOF_DIRECTIVE) {
// TODO: better returncode
return returnvalue::FAILED;
}
if (*size + 2 > maxSize) {
return SerializeIF::BUFFER_TOO_SHORT;
}
**buffer = ackedDirective << 4 | directiveSubtypeCode;
*buffer += 1;
*size += 1;
**buffer = ackedConditionCode << 4 | transactionStatus;
*buffer += 1;
*size += 1;
return returnvalue::OK;
}

View File

@ -0,0 +1,37 @@
#include "AckPduDeserializer.h"
AckPduDeserializer::AckPduDeserializer(const uint8_t* pduBuf, size_t maxSize, AckInfo& info)
: FileDirectiveDeserializer(pduBuf, maxSize), info(info) {}
ReturnValue_t AckPduDeserializer::parseData() {
ReturnValue_t result = FileDirectiveDeserializer::parseData();
if (result != returnvalue::OK) {
return result;
}
size_t currentIdx = FileDirectiveDeserializer::getHeaderSize();
if (currentIdx + 2 > this->maxSize) {
return SerializeIF::BUFFER_TOO_SHORT;
}
if (not checkAndSetCodes(rawPtr[currentIdx], rawPtr[currentIdx + 1])) {
return cfdp::INVALID_ACK_DIRECTIVE_FIELDS;
}
return returnvalue::OK;
}
bool AckPduDeserializer::checkAndSetCodes(uint8_t firstByte, uint8_t secondByte) {
uint8_t ackedDirective = static_cast<cfdp::FileDirectives>(firstByte >> 4);
if (ackedDirective != cfdp::FileDirectives::EOF_DIRECTIVE and
ackedDirective != cfdp::FileDirectives::FINISH) {
return false;
}
this->info.setAckedDirective(static_cast<cfdp::FileDirectives>(ackedDirective));
uint8_t directiveSubtypeCode = firstByte & 0x0f;
if (directiveSubtypeCode != 0b0000 and directiveSubtypeCode != 0b0001) {
return false;
}
this->info.setDirectiveSubtypeCode(directiveSubtypeCode);
this->info.setAckedConditionCode(static_cast<cfdp::ConditionCode>(secondByte >> 4));
this->info.setTransactionStatus(static_cast<cfdp::AckTransactionStatus>(secondByte & 0x0f));
return true;
}

View File

@ -2,21 +2,18 @@
#define FSFW_SRC_FSFW_CFDP_PDU_ACKPDUDESERIALIZER_H_ #define FSFW_SRC_FSFW_CFDP_PDU_ACKPDUDESERIALIZER_H_
#include "AckInfo.h" #include "AckInfo.h"
#include "fsfw/cfdp/pdu/FileDirectiveReader.h" #include "fsfw/cfdp/pdu/FileDirectiveDeserializer.h"
class AckPduReader : public FileDirectiveReader { class AckPduDeserializer : public FileDirectiveDeserializer {
public: public:
AckPduReader(const uint8_t* pduBuf, size_t maxSize, AckInfo& info); AckPduDeserializer(const uint8_t* pduBuf, size_t maxSize, AckInfo& info);
/** /**
* *
* @return * @return
* - cfdp::INVALID_DIRECTIVE_FIELDS: Invalid fields * - cfdp::INVALID_DIRECTIVE_FIELDS: Invalid fields
*/ */
ReturnValue_t parseData() override; ReturnValue_t parseData();
static bool checkAckedDirectiveField(uint8_t firstPduDataByte,
cfdp::FileDirective& ackedDirective);
private: private:
bool checkAndSetCodes(uint8_t rawAckedByte, uint8_t rawAckedConditionCode); bool checkAndSetCodes(uint8_t rawAckedByte, uint8_t rawAckedConditionCode);

View File

@ -1,45 +0,0 @@
#include "AckPduReader.h"
AckPduReader::AckPduReader(const uint8_t* pduBuf, size_t maxSize, AckInfo& info)
: FileDirectiveReader(pduBuf, maxSize), info(info) {}
ReturnValue_t AckPduReader::parseData() {
ReturnValue_t result = FileDirectiveReader::parseData();
if (result != returnvalue::OK) {
return result;
}
size_t currentIdx = FileDirectiveReader::getHeaderSize();
if (currentIdx + 2 > this->maxSize) {
return SerializeIF::BUFFER_TOO_SHORT;
}
if (not checkAndSetCodes(pointers.rawPtr[currentIdx], pointers.rawPtr[currentIdx + 1])) {
return cfdp::INVALID_ACK_DIRECTIVE_FIELDS;
}
return returnvalue::OK;
}
bool AckPduReader::checkAndSetCodes(uint8_t firstByte, uint8_t secondByte) {
cfdp::FileDirective directive;
if (not checkAckedDirectiveField(firstByte, directive)) {
return false;
}
this->info.setAckedDirective(directive);
uint8_t directiveSubtypeCode = firstByte & 0x0f;
if (directiveSubtypeCode != 0b0000 and directiveSubtypeCode != 0b0001) {
return false;
}
this->info.setDirectiveSubtypeCode(directiveSubtypeCode);
this->info.setAckedConditionCode(static_cast<cfdp::ConditionCode>(secondByte >> 4));
this->info.setTransactionStatus(static_cast<cfdp::AckTransactionStatus>(secondByte & 0x0f));
return true;
}
bool AckPduReader::checkAckedDirectiveField(uint8_t firstPduDataByte,
cfdp::FileDirective& ackedDirective) {
uint8_t ackedDirectiveRaw = static_cast<cfdp::FileDirective>(firstPduDataByte >> 4);
if (ackedDirectiveRaw != cfdp::FileDirective::EOF_DIRECTIVE and
ackedDirectiveRaw != cfdp::FileDirective::FINISH) {
return false;
}
ackedDirective = (static_cast<cfdp::FileDirective>(ackedDirectiveRaw));
return true;
}

View File

@ -0,0 +1,36 @@
#include "AckPduSerializer.h"
AckPduSerializer::AckPduSerializer(AckInfo &ackInfo, PduConfig &pduConf)
: FileDirectiveSerializer(pduConf, cfdp::FileDirectives::ACK, 2), ackInfo(ackInfo) {}
size_t AckPduSerializer::getSerializedSize() const {
return FileDirectiveSerializer::getWholePduSize();
}
ReturnValue_t AckPduSerializer::serialize(uint8_t **buffer, size_t *size, size_t maxSize,
Endianness streamEndianness) const {
ReturnValue_t result =
FileDirectiveSerializer::serialize(buffer, size, maxSize, streamEndianness);
if (result != returnvalue::OK) {
return result;
}
cfdp::FileDirectives ackedDirective = ackInfo.getAckedDirective();
uint8_t directiveSubtypeCode = ackInfo.getDirectiveSubtypeCode();
cfdp::ConditionCode ackedConditionCode = ackInfo.getAckedConditionCode();
cfdp::AckTransactionStatus transactionStatus = ackInfo.getTransactionStatus();
if (ackedDirective != cfdp::FileDirectives::FINISH and
ackedDirective != cfdp::FileDirectives::EOF_DIRECTIVE) {
// TODO: better returncode
return returnvalue::FAILED;
}
if (*size + 2 > maxSize) {
return SerializeIF::BUFFER_TOO_SHORT;
}
**buffer = ackedDirective << 4 | directiveSubtypeCode;
*buffer += 1;
*size += 1;
**buffer = ackedConditionCode << 4 | transactionStatus;
*buffer += 1;
*size += 1;
return returnvalue::OK;
}

View File

@ -1,11 +1,11 @@
#ifndef FSFW_CFDP_PDU_ACKPDUSERIALIZER_H_ #ifndef FSFW_SRC_FSFW_CFDP_PDU_ACKPDUSERIALIZER_H_
#define FSFW_CFDP_PDU_ACKPDUSERIALIZER_H_ #define FSFW_SRC_FSFW_CFDP_PDU_ACKPDUSERIALIZER_H_
#include "AckInfo.h" #include "AckInfo.h"
#include "FileDirectiveCreator.h" #include "FileDirectiveDeserializer.h"
#include "FileDirectiveReader.h" #include "FileDirectiveSerializer.h"
class AckPduCreator : public FileDirectiveCreator { class AckPduSerializer : public FileDirectiveSerializer {
public: public:
/** /**
* @brief Serializer to pack ACK PDUs * @brief Serializer to pack ACK PDUs
@ -16,9 +16,9 @@ class AckPduCreator : public FileDirectiveCreator {
* @param transactionStatus * @param transactionStatus
* @param pduConf * @param pduConf
*/ */
AckPduCreator(AckInfo& ackInfo, PduConfig& pduConf); AckPduSerializer(AckInfo& ackInfo, PduConfig& pduConf);
[[nodiscard]] size_t getSerializedSize() const override; size_t getSerializedSize() const override;
ReturnValue_t serialize(uint8_t** buffer, size_t* size, size_t maxSize, ReturnValue_t serialize(uint8_t** buffer, size_t* size, size_t maxSize,
Endianness streamEndianness) const override; Endianness streamEndianness) const override;
@ -27,4 +27,4 @@ class AckPduCreator : public FileDirectiveCreator {
AckInfo& ackInfo; AckInfo& ackInfo;
}; };
#endif /* FSFW_CFDP_PDU_ACKPDUSERIALIZER_H_ */ #endif /* FSFW_SRC_FSFW_CFDP_PDU_ACKPDUSERIALIZER_H_ */

View File

@ -1,29 +1,30 @@
target_sources( target_sources(
${LIB_FSFW_NAME} ${LIB_FSFW_NAME}
PRIVATE PduConfig.cpp PRIVATE PduConfig.cpp
HeaderCreator.cpp VarLenField.cpp
HeaderReader.cpp HeaderSerializer.cpp
FileDirectiveReader.cpp HeaderDeserializer.cpp
FileDirectiveCreator.cpp FileDirectiveDeserializer.cpp
FileDirectiveSerializer.cpp
AckInfo.cpp AckInfo.cpp
AckPduCreator.cpp AckPduSerializer.cpp
AckPduReader.cpp AckPduDeserializer.cpp
EofInfo.cpp EofInfo.cpp
EofPduCreator.cpp EofPduSerializer.cpp
EofPduReader.cpp EofPduDeserializer.cpp
NakInfo.cpp NakInfo.cpp
NakPduCreator.cpp NakPduSerializer.cpp
NakPduReader.cpp NakPduDeserializer.cpp
FinishedInfo.cpp FinishedInfo.cpp
FinishedPduCreator.cpp FinishedPduSerializer.cpp
FinishedPduReader.cpp FinishedPduDeserializer.cpp
MetadataGenericInfo.cpp MetadataInfo.cpp
MetadataPduCreator.cpp MetadataPduSerializer.cpp
MetadataPduReader.cpp MetadataPduDeserializer.cpp
KeepAlivePduCreator.cpp KeepAlivePduSerializer.cpp
KeepAlivePduReader.cpp KeepAlivePduDeserializer.cpp
PromptPduCreator.cpp PromptPduSerializer.cpp
PromptPduReader.cpp PromptPduDeserializer.cpp
FileDataCreator.cpp FileDataSerializer.cpp
FileDataReader.cpp FileDataDeserializer.cpp
FileDataInfo.cpp) FileDataInfo.cpp)

View File

@ -1,13 +1,8 @@
#include "EofInfo.h" #include "EofInfo.h"
#include <utility> EofInfo::EofInfo(cfdp::ConditionCode conditionCode, uint32_t checksum, cfdp::FileSize fileSize,
EofInfo::EofInfo(cfdp::ConditionCode conditionCode, uint32_t checksum, cfdp::Fss fileSize,
EntityIdTlv* faultLoc) EntityIdTlv* faultLoc)
: conditionCode(conditionCode), : conditionCode(conditionCode), checksum(checksum), fileSize(fileSize), faultLoc(faultLoc) {}
checksum(checksum),
fileSize(std::move(fileSize)),
faultLoc(faultLoc) {}
EofInfo::EofInfo(EntityIdTlv* faultLoc) EofInfo::EofInfo(EntityIdTlv* faultLoc)
: conditionCode(cfdp::ConditionCode::NO_CONDITION_FIELD), : conditionCode(cfdp::ConditionCode::NO_CONDITION_FIELD),
@ -21,15 +16,15 @@ cfdp::ConditionCode EofInfo::getConditionCode() const { return conditionCode; }
EntityIdTlv* EofInfo::getFaultLoc() const { return faultLoc; } EntityIdTlv* EofInfo::getFaultLoc() const { return faultLoc; }
cfdp::Fss& EofInfo::getFileSize() { return fileSize; } cfdp::FileSize& EofInfo::getFileSize() { return fileSize; }
void EofInfo::setChecksum(uint32_t checksum_) { this->checksum = checksum_; } void EofInfo::setChecksum(uint32_t checksum) { this->checksum = checksum; }
void EofInfo::setConditionCode(cfdp::ConditionCode conditionCode_) { void EofInfo::setConditionCode(cfdp::ConditionCode conditionCode) {
this->conditionCode = conditionCode_; this->conditionCode = conditionCode;
} }
void EofInfo::setFaultLoc(EntityIdTlv* faultLoc_) { this->faultLoc = faultLoc_; } void EofInfo::setFaultLoc(EntityIdTlv* faultLoc) { this->faultLoc = faultLoc; }
size_t EofInfo::getSerializedSize(bool fssLarge) { size_t EofInfo::getSerializedSize(bool fssLarge) {
// Condition code + spare + 4 byte checksum // Condition code + spare + 4 byte checksum
@ -47,6 +42,6 @@ size_t EofInfo::getSerializedSize(bool fssLarge) {
return size; return size;
} }
ReturnValue_t EofInfo::setFileSize(size_t fileSize_, bool isLarge) { ReturnValue_t EofInfo::setFileSize(size_t fileSize, bool isLarge) {
return this->fileSize.setFileSize(fileSize_, isLarge); return this->fileSize.setFileSize(fileSize, isLarge);
} }

View File

@ -1,23 +1,23 @@
#ifndef FSFW_SRC_FSFW_CFDP_PDU_EOFINFO_H_ #ifndef FSFW_SRC_FSFW_CFDP_PDU_EOFINFO_H_
#define FSFW_SRC_FSFW_CFDP_PDU_EOFINFO_H_ #define FSFW_SRC_FSFW_CFDP_PDU_EOFINFO_H_
#include "../Fss.h" #include "../FileSize.h"
#include "../definitions.h" #include "../definitions.h"
#include "fsfw/cfdp/tlv/EntityIdTlv.h" #include "fsfw/cfdp/tlv/EntityIdTlv.h"
struct EofInfo { struct EofInfo {
public: public:
explicit EofInfo(EntityIdTlv* faultLoc = nullptr); EofInfo(EntityIdTlv* faultLoc = nullptr);
EofInfo(cfdp::ConditionCode conditionCode, uint32_t checksum, cfdp::Fss fileSize, EofInfo(cfdp::ConditionCode conditionCode, uint32_t checksum, cfdp::FileSize fileSize,
EntityIdTlv* faultLoc = nullptr); EntityIdTlv* faultLoc = nullptr);
size_t getSerializedSize(bool fssLarge = false); size_t getSerializedSize(bool fssLarge = false);
[[nodiscard]] uint32_t getChecksum() const; uint32_t getChecksum() const;
[[nodiscard]] cfdp::ConditionCode getConditionCode() const; cfdp::ConditionCode getConditionCode() const;
[[nodiscard]] EntityIdTlv* getFaultLoc() const; EntityIdTlv* getFaultLoc() const;
cfdp::Fss& getFileSize(); cfdp::FileSize& getFileSize();
void setChecksum(uint32_t checksum); void setChecksum(uint32_t checksum);
void setConditionCode(cfdp::ConditionCode conditionCode); void setConditionCode(cfdp::ConditionCode conditionCode);
void setFaultLoc(EntityIdTlv* faultLoc); void setFaultLoc(EntityIdTlv* faultLoc);
@ -26,7 +26,7 @@ struct EofInfo {
private: private:
cfdp::ConditionCode conditionCode; cfdp::ConditionCode conditionCode;
uint32_t checksum; uint32_t checksum;
cfdp::Fss fileSize; cfdp::FileSize fileSize;
EntityIdTlv* faultLoc = nullptr; EntityIdTlv* faultLoc = nullptr;
}; };

View File

@ -1,23 +1,23 @@
#include "EofPduReader.h" #include "EofPduDeserializer.h"
#include "fsfw/FSFW.h" #include "fsfw/FSFW.h"
#include "fsfw/serviceinterface.h" #include "fsfw/serviceinterface.h"
EofPduReader::EofPduReader(const uint8_t* pduBuf, size_t maxSize, EofInfo& eofInfo) EofPduDeserializer::EofPduDeserializer(const uint8_t* pduBuf, size_t maxSize, EofInfo& eofInfo)
: FileDirectiveReader(pduBuf, maxSize), info(eofInfo) {} : FileDirectiveDeserializer(pduBuf, maxSize), info(eofInfo) {}
ReturnValue_t EofPduReader::parseData() { ReturnValue_t EofPduDeserializer::parseData() {
ReturnValue_t result = FileDirectiveReader::parseData(); ReturnValue_t result = FileDirectiveDeserializer::parseData();
if (result != returnvalue::OK) { if (result != returnvalue::OK) {
return result; return result;
} }
const uint8_t* bufPtr = pointers.rawPtr; const uint8_t* bufPtr = rawPtr;
size_t expectedFileFieldLen = 4; size_t expectedFileFieldLen = 4;
if (this->getLargeFileFlag()) { if (this->getLargeFileFlag()) {
expectedFileFieldLen = 8; expectedFileFieldLen = 8;
} }
size_t currentIdx = FileDirectiveReader::getHeaderSize(); size_t currentIdx = FileDirectiveDeserializer::getHeaderSize();
size_t deserLen = maxSize; size_t deserLen = maxSize;
if (maxSize < currentIdx + 5 + expectedFileFieldLen) { if (maxSize < currentIdx + 5 + expectedFileFieldLen) {
return SerializeIF::STREAM_TOO_SHORT; return SerializeIF::STREAM_TOO_SHORT;

View File

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

View File

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

View File

@ -1,17 +1,21 @@
#include "EofPduCreator.h" #include "EofPduSerializer.h"
#include "fsfw/FSFW.h" #include "fsfw/FSFW.h"
#include "fsfw/serviceinterface.h"
EofPduCreator::EofPduCreator(PduConfig &conf, EofInfo &info) EofPduSerializer::EofPduSerializer(PduConfig &conf, EofInfo &info)
: FileDirectiveCreator(conf, cfdp::FileDirective::EOF_DIRECTIVE, 9), info(info) { : FileDirectiveSerializer(conf, cfdp::FileDirectives::EOF_DIRECTIVE, 9), info(info) {
setDirectiveDataFieldLen(info.getSerializedSize(HeaderCreator::getLargeFileFlag())); setDirectiveDataFieldLen(info.getSerializedSize(getLargeFileFlag()));
} }
size_t EofPduCreator::getSerializedSize() const { return FileDirectiveCreator::getWholePduSize(); } size_t EofPduSerializer::getSerializedSize() const {
return FileDirectiveSerializer::getWholePduSize();
}
ReturnValue_t EofPduCreator::serialize(uint8_t **buffer, size_t *size, size_t maxSize, ReturnValue_t EofPduSerializer::serialize(uint8_t **buffer, size_t *size, size_t maxSize,
Endianness streamEndianness) const { Endianness streamEndianness) const {
ReturnValue_t result = FileDirectiveCreator::serialize(buffer, size, maxSize, streamEndianness); ReturnValue_t result =
FileDirectiveSerializer::serialize(buffer, size, maxSize, streamEndianness);
if (result != returnvalue::OK) { if (result != returnvalue::OK) {
return result; return result;
} }

View File

@ -2,20 +2,18 @@
#define FSFW_SRC_FSFW_CFDP_PDU_EOFPDUSERIALIZER_H_ #define FSFW_SRC_FSFW_CFDP_PDU_EOFPDUSERIALIZER_H_
#include "EofInfo.h" #include "EofInfo.h"
#include "fsfw/cfdp/pdu/FileDirectiveCreator.h" #include "fsfw/cfdp/pdu/FileDirectiveSerializer.h"
#include "fsfw/cfdp/tlv/EntityIdTlv.h" #include "fsfw/cfdp/tlv/EntityIdTlv.h"
class EofPduCreator : public FileDirectiveCreator { class EofPduSerializer : public FileDirectiveSerializer {
public: public:
EofPduCreator(PduConfig& conf, EofInfo& info); EofPduSerializer(PduConfig& conf, EofInfo& info);
[[nodiscard]] size_t getSerializedSize() const override; size_t getSerializedSize() const override;
ReturnValue_t serialize(uint8_t** buffer, size_t* size, size_t maxSize, ReturnValue_t serialize(uint8_t** buffer, size_t* size, size_t maxSize,
Endianness streamEndianness) const override; Endianness streamEndianness) const override;
using FileDirectiveCreator::serialize;
private: private:
EofInfo& info; EofInfo& info;
}; };

View File

@ -1,27 +0,0 @@
#ifndef FSFW_CFDP_PDU_FILEDATASERIALIZER_H_
#define FSFW_CFDP_PDU_FILEDATASERIALIZER_H_
#include "../definitions.h"
#include "FileDataInfo.h"
#include "HeaderCreator.h"
class FileDataCreator : public HeaderCreator {
public:
FileDataCreator(PduConfig& conf, FileDataInfo& info);
void update();
ReturnValue_t serialize(uint8_t* buf, size_t& serLen, size_t maxSize) const {
return SerializeIF::serialize(buf, serLen, maxSize, SerializeIF::Endianness::NETWORK);
}
ReturnValue_t serialize(uint8_t** buffer, size_t* size, size_t maxSize,
Endianness streamEndianness) const override;
[[nodiscard]] size_t getSerializedSize() const override;
private:
FileDataInfo& info;
};
#endif /* FSFW_CFDP_PDU_FILEDATASERIALIZER_H_ */

View File

@ -1,16 +1,17 @@
#include "FileDataReader.h" #include "FileDataDeserializer.h"
FileDataReader::FileDataReader(const uint8_t* pduBuf, size_t maxSize, FileDataInfo& info) FileDataDeserializer::FileDataDeserializer(const uint8_t* pduBuf, size_t maxSize,
: PduHeaderReader(pduBuf, maxSize), info(info) {} FileDataInfo& info)
: HeaderDeserializer(pduBuf, maxSize), info(info) {}
ReturnValue_t FileDataReader::parseData() { ReturnValue_t FileDataDeserializer::parseData() {
ReturnValue_t result = PduHeaderReader::parseData(); ReturnValue_t result = HeaderDeserializer::parseData();
if (result != returnvalue::OK) { if (result != returnvalue::OK) {
return result; return result;
} }
size_t currentIdx = PduHeaderReader::getHeaderSize(); size_t currentIdx = HeaderDeserializer::getHeaderSize();
const uint8_t* buf = pointers.rawPtr + currentIdx; const uint8_t* buf = rawPtr + currentIdx;
size_t remSize = PduHeaderReader::getWholePduSize() - currentIdx; size_t remSize = HeaderDeserializer::getWholePduSize() - currentIdx;
if (remSize < 1) { if (remSize < 1) {
return SerializeIF::STREAM_TOO_SHORT; return SerializeIF::STREAM_TOO_SHORT;
} }
@ -40,8 +41,8 @@ ReturnValue_t FileDataReader::parseData() {
return returnvalue::OK; return returnvalue::OK;
} }
SerializeIF::Endianness FileDataReader::getEndianness() const { return endianness; } SerializeIF::Endianness FileDataDeserializer::getEndianness() const { return endianness; }
void FileDataReader::setEndianness(SerializeIF::Endianness endianness_) { void FileDataDeserializer::setEndianness(SerializeIF::Endianness endianness) {
endianness = endianness_; this->endianness = endianness;
} }

View File

@ -3,14 +3,14 @@
#include "../definitions.h" #include "../definitions.h"
#include "FileDataInfo.h" #include "FileDataInfo.h"
#include "PduHeaderReader.h" #include "HeaderDeserializer.h"
class FileDataReader : public PduHeaderReader { class FileDataDeserializer : public HeaderDeserializer {
public: public:
FileDataReader(const uint8_t* pduBuf, size_t maxSize, FileDataInfo& info); FileDataDeserializer(const uint8_t* pduBuf, size_t maxSize, FileDataInfo& info);
ReturnValue_t parseData() override; ReturnValue_t parseData();
[[nodiscard]] SerializeIF::Endianness getEndianness() const; SerializeIF::Endianness getEndianness() const;
void setEndianness(SerializeIF::Endianness endianness = SerializeIF::Endianness::NETWORK); void setEndianness(SerializeIF::Endianness endianness = SerializeIF::Endianness::NETWORK);
private: private:

View File

@ -1,9 +1,9 @@
#include "FileDataInfo.h" #include "FileDataInfo.h"
#include <utility> FileDataInfo::FileDataInfo(cfdp::FileSize &offset, const uint8_t *fileData, size_t fileSize)
: offset(offset), fileData(fileData), fileSize(fileSize) {}
FileDataInfo::FileDataInfo(cfdp::Fss offset, const uint8_t *fileData, size_t fileSize) FileDataInfo::FileDataInfo(cfdp::FileSize &offset) : offset(offset) {}
: offset(std::move(offset)), fileData(fileData), fileSize(fileSize) {}
void FileDataInfo::setSegmentMetadataFlag(bool enable) { void FileDataInfo::setSegmentMetadataFlag(bool enable) {
if (enable) { if (enable) {
@ -57,21 +57,21 @@ ReturnValue_t FileDataInfo::addSegmentMetadataInfo(cfdp::RecordContinuationState
return returnvalue::OK; return returnvalue::OK;
} }
const uint8_t *FileDataInfo::getFileData(size_t *fileSize_) const { const uint8_t *FileDataInfo::getFileData(size_t *fileSize) const {
if (fileSize_ != nullptr) { if (fileSize != nullptr) {
*fileSize_ = this->fileSize; *fileSize = this->fileSize;
} }
return fileData; return fileData;
} }
const uint8_t *FileDataInfo::getSegmentMetadata(size_t *segmentMetadataLen_) { const uint8_t *FileDataInfo::getSegmentMetadata(size_t *segmentMetadataLen) {
if (segmentMetadataLen_ != nullptr) { if (segmentMetadataLen != nullptr) {
*segmentMetadataLen_ = this->segmentMetadataLen; *segmentMetadataLen = this->segmentMetadataLen;
} }
return segmentMetadata; return segmentMetadata;
} }
cfdp::Fss &FileDataInfo::getOffset() { return offset; } cfdp::FileSize &FileDataInfo::getOffset() { return offset; }
void FileDataInfo::setRecordContinuationState(cfdp::RecordContinuationState recContState) { void FileDataInfo::setRecordContinuationState(cfdp::RecordContinuationState recContState) {
this->recContState = recContState; this->recContState = recContState;

View File

@ -1,30 +1,30 @@
#ifndef FSFW_SRC_FSFW_CFDP_PDU_FILEDATAINFO_H_ #ifndef FSFW_SRC_FSFW_CFDP_PDU_FILEDATAINFO_H_
#define FSFW_SRC_FSFW_CFDP_PDU_FILEDATAINFO_H_ #define FSFW_SRC_FSFW_CFDP_PDU_FILEDATAINFO_H_
#include <fsfw/cfdp/Fss.h> #include <fsfw/cfdp/FileSize.h>
#include <fsfw/cfdp/definitions.h> #include <fsfw/cfdp/definitions.h>
class FileDataInfo { class FileDataInfo {
public: public:
FileDataInfo() = default; FileDataInfo(cfdp::FileSize& offset);
FileDataInfo(cfdp::Fss offset, const uint8_t* fileData, size_t fileSize); FileDataInfo(cfdp::FileSize& offset, const uint8_t* fileData, size_t fileSize);
[[nodiscard]] size_t getSerializedSize(bool largeFile = false) const; size_t getSerializedSize(bool largeFile = false) const;
cfdp::Fss& getOffset(); cfdp::FileSize& getOffset();
const uint8_t* getFileData(size_t* fileSize = nullptr) const; const uint8_t* getFileData(size_t* fileSize = nullptr) const;
void setFileData(const uint8_t* fileData, size_t fileSize); void setFileData(const uint8_t* fileData, size_t fileSize);
[[nodiscard]] cfdp::SegmentMetadataFlag getSegmentMetadataFlag() const; cfdp::SegmentMetadataFlag getSegmentMetadataFlag() const;
[[nodiscard]] cfdp::SegmentationControl getSegmentationControl() const; cfdp::SegmentationControl getSegmentationControl() const;
[[nodiscard]] cfdp::RecordContinuationState getRecordContinuationState() const; cfdp::RecordContinuationState getRecordContinuationState() const;
void setRecordContinuationState(cfdp::RecordContinuationState recContState); void setRecordContinuationState(cfdp::RecordContinuationState recContState);
void setSegmentationControl(cfdp::SegmentationControl segCtrl); void setSegmentationControl(cfdp::SegmentationControl segCtrl);
[[nodiscard]] size_t getSegmentMetadataLen() const; size_t getSegmentMetadataLen() const;
void setSegmentMetadataLen(size_t len); void setSegmentMetadataLen(size_t len);
void setSegmentMetadata(const uint8_t* ptr); void setSegmentMetadata(const uint8_t* ptr);
[[nodiscard]] bool hasSegmentMetadata() const; bool hasSegmentMetadata() const;
void setSegmentMetadataFlag(bool enable); void setSegmentMetadataFlag(bool enable);
ReturnValue_t addSegmentMetadataInfo(cfdp::RecordContinuationState recContState, ReturnValue_t addSegmentMetadataInfo(cfdp::RecordContinuationState recContState,
const uint8_t* segmentMetadata, size_t segmentMetadataLen); const uint8_t* segmentMetadata, size_t segmentMetadataLen);
@ -33,7 +33,7 @@ class FileDataInfo {
private: private:
cfdp::SegmentMetadataFlag segmentMetadataFlag = cfdp::SegmentMetadataFlag::NOT_PRESENT; cfdp::SegmentMetadataFlag segmentMetadataFlag = cfdp::SegmentMetadataFlag::NOT_PRESENT;
cfdp::SegmentationControl segCtrl = cfdp::SegmentationControl::NO_RECORD_BOUNDARIES_PRESERVATION; cfdp::SegmentationControl segCtrl = cfdp::SegmentationControl::NO_RECORD_BOUNDARIES_PRESERVATION;
cfdp::Fss offset; cfdp::FileSize& offset;
const uint8_t* fileData = nullptr; const uint8_t* fileData = nullptr;
size_t fileSize = 0; size_t fileSize = 0;
cfdp::RecordContinuationState recContState = cfdp::RecordContinuationState::NO_START_NO_END; cfdp::RecordContinuationState recContState = cfdp::RecordContinuationState::NO_START_NO_END;

View File

@ -1,31 +1,28 @@
#include "FileDataCreator.h" #include "FileDataSerializer.h"
#include <cstring> #include <cstring>
FileDataCreator::FileDataCreator(PduConfig& conf, FileDataInfo& info) FileDataSerializer::FileDataSerializer(PduConfig& conf, FileDataInfo& info)
: HeaderCreator(conf, cfdp::PduType::FILE_DATA, 0, info.getSegmentMetadataFlag()), info(info) { : HeaderSerializer(conf, cfdp::PduType::FILE_DATA, 0, info.getSegmentMetadataFlag()),
info(info) {
update(); update();
} }
void FileDataCreator::update() { void FileDataSerializer::update() {
this->setSegmentMetadataFlag(info.getSegmentMetadataFlag()); this->setSegmentMetadataFlag(info.getSegmentMetadataFlag());
this->setSegmentationControl(info.getSegmentationControl()); this->setSegmentationControl(info.getSegmentationControl());
setPduDataFieldLen(info.getSerializedSize(this->getLargeFileFlag())); setPduDataFieldLen(info.getSerializedSize(this->getLargeFileFlag()));
} }
ReturnValue_t FileDataCreator::serialize(uint8_t** buffer, size_t* size, size_t maxSize, ReturnValue_t FileDataSerializer::serialize(uint8_t** buffer, size_t* size, size_t maxSize,
Endianness streamEndianness) const { Endianness streamEndianness) const {
if (buffer == nullptr or size == nullptr) { ReturnValue_t result = HeaderSerializer::serialize(buffer, size, maxSize, streamEndianness);
return returnvalue::FAILED;
}
if (*size + getSerializedSize() > maxSize) {
return SerializeIF::BUFFER_TOO_SHORT;
}
ReturnValue_t result = HeaderCreator::serialize(buffer, size, maxSize, streamEndianness);
if (result != returnvalue::OK) { if (result != returnvalue::OK) {
return result; return result;
} }
if (*size + this->getSerializedSize() > maxSize) {
return SerializeIF::BUFFER_TOO_SHORT;
}
const uint8_t* readOnlyPtr = nullptr; const uint8_t* readOnlyPtr = nullptr;
if (this->hasSegmentMetadataFlag()) { if (this->hasSegmentMetadataFlag()) {
size_t segmentMetadataLen = info.getSegmentMetadataLen(); size_t segmentMetadataLen = info.getSegmentMetadataLen();
@ -37,7 +34,7 @@ ReturnValue_t FileDataCreator::serialize(uint8_t** buffer, size_t* size, size_t
*buffer += segmentMetadataLen; *buffer += segmentMetadataLen;
*size += segmentMetadataLen; *size += segmentMetadataLen;
} }
cfdp::Fss& offset = info.getOffset(); cfdp::FileSize& offset = info.getOffset();
result = offset.serialize(this->getLargeFileFlag(), buffer, size, maxSize, streamEndianness); result = offset.serialize(this->getLargeFileFlag(), buffer, size, maxSize, streamEndianness);
if (result != returnvalue::OK) { if (result != returnvalue::OK) {
return result; return result;
@ -53,6 +50,6 @@ ReturnValue_t FileDataCreator::serialize(uint8_t** buffer, size_t* size, size_t
return returnvalue::OK; return returnvalue::OK;
} }
size_t FileDataCreator::getSerializedSize() const { size_t FileDataSerializer::getSerializedSize() const {
return HeaderCreator::getSerializedSize() + info.getSerializedSize(this->getLargeFileFlag()); return HeaderSerializer::getSerializedSize() + info.getSerializedSize(this->getLargeFileFlag());
} }

View File

@ -0,0 +1,23 @@
#ifndef FSFW_SRC_FSFW_CFDP_PDU_FILEDATASERIALIZER_H_
#define FSFW_SRC_FSFW_CFDP_PDU_FILEDATASERIALIZER_H_
#include "../definitions.h"
#include "FileDataInfo.h"
#include "HeaderSerializer.h"
class FileDataSerializer : public HeaderSerializer {
public:
FileDataSerializer(PduConfig& conf, FileDataInfo& info);
void update();
ReturnValue_t serialize(uint8_t** buffer, size_t* size, size_t maxSize,
Endianness streamEndianness) const override;
size_t getSerializedSize() const override;
private:
FileDataInfo& info;
};
#endif /* FSFW_SRC_FSFW_CFDP_PDU_FILEDATADESERIALIZER_H_ */

View File

@ -1,39 +0,0 @@
#include "FileDirectiveCreator.h"
FileDirectiveCreator::FileDirectiveCreator(PduConfig &pduConf, cfdp::FileDirective directiveCode,
size_t directiveParamFieldLen)
: HeaderCreator(pduConf, cfdp::PduType::FILE_DIRECTIVE, directiveParamFieldLen + 1),
directiveCode(directiveCode) {}
size_t FileDirectiveCreator::getSerializedSize() const {
return HeaderCreator::getSerializedSize() + 1;
}
ReturnValue_t FileDirectiveCreator::serialize(uint8_t **buffer, size_t *size, size_t maxSize,
Endianness streamEndianness) const {
if (buffer == nullptr or size == nullptr) {
return returnvalue::FAILED;
}
if (FileDirectiveCreator::getWholePduSize() > maxSize) {
return BUFFER_TOO_SHORT;
}
ReturnValue_t result = HeaderCreator::serialize(buffer, size, maxSize, streamEndianness);
if (result != returnvalue::OK) {
return result;
}
if (*size >= maxSize) {
return BUFFER_TOO_SHORT;
}
**buffer = directiveCode;
*buffer += 1;
*size += 1;
return returnvalue::OK;
}
void FileDirectiveCreator::setDirectiveDataFieldLen(size_t len) {
// Set length of data field plus 1 byte for the directive octet
HeaderCreator::setPduDataFieldLen(len + 1);
}
cfdp::FileDirective FileDirectiveCreator::getDirectiveCode() const { return directiveCode; }

View File

@ -1,34 +0,0 @@
#ifndef FSFW_SRC_FSFW_CFDP_PDU_FILEDIRECTIVESERIALIZER_H_
#define FSFW_SRC_FSFW_CFDP_PDU_FILEDIRECTIVESERIALIZER_H_
#include "fsfw/cfdp/pdu/HeaderCreator.h"
class FileDirectiveCreator : public HeaderCreator {
public:
FileDirectiveCreator(PduConfig& pduConf, cfdp::FileDirective directiveCode,
size_t directiveParamFieldLen);
[[nodiscard]] cfdp::FileDirective getDirectiveCode() const;
/**
* This only returns the size of the PDU header + 1 for the directive code octet.
* Use FileDirectiveCreator::getWholePduSize to get the full packet length, assuming
* the length fields was set correctly
* @return
*/
[[nodiscard]] size_t getSerializedSize() const override;
[[nodiscard]] ReturnValue_t serialize(uint8_t* buffer, size_t& serLen, size_t maxSize) const {
return SerializeIF::serialize(buffer, serLen, maxSize, SerializeIF::Endianness::NETWORK);
}
ReturnValue_t serialize(uint8_t** buffer, size_t* size, size_t maxSize,
Endianness streamEndianness) const override;
void setDirectiveDataFieldLen(size_t len);
private:
cfdp::FileDirective directiveCode = cfdp::FileDirective::INVALID_DIRECTIVE;
};
#endif /* FSFW_SRC_FSFW_CFDP_PDU_FILEDIRECTIVESERIALIZER_H_ */

View File

@ -0,0 +1,49 @@
#include "FileDirectiveDeserializer.h"
FileDirectiveDeserializer::FileDirectiveDeserializer(const uint8_t *pduBuf, size_t maxSize)
: HeaderDeserializer(pduBuf, maxSize) {}
cfdp::FileDirectives FileDirectiveDeserializer::getFileDirective() const { return fileDirective; }
ReturnValue_t FileDirectiveDeserializer::parseData() {
ReturnValue_t result = HeaderDeserializer::parseData();
if (result != returnvalue::OK) {
return result;
}
if (this->getPduDataFieldLen() < 1) {
return cfdp::INVALID_PDU_DATAFIELD_LEN;
}
if (FileDirectiveDeserializer::getWholePduSize() > maxSize) {
return SerializeIF::STREAM_TOO_SHORT;
}
size_t currentIdx = HeaderDeserializer::getHeaderSize();
if (not checkFileDirective(rawPtr[currentIdx])) {
return cfdp::INVALID_DIRECTIVE_FIELDS;
}
setFileDirective(static_cast<cfdp::FileDirectives>(rawPtr[currentIdx]));
return returnvalue::OK;
}
size_t FileDirectiveDeserializer::getHeaderSize() const {
// return size of header plus the directive byte
return HeaderDeserializer::getHeaderSize() + 1;
}
bool FileDirectiveDeserializer::checkFileDirective(uint8_t rawByte) {
if (rawByte < cfdp::FileDirectives::EOF_DIRECTIVE or
(rawByte > cfdp::FileDirectives::PROMPT and rawByte != cfdp::FileDirectives::KEEP_ALIVE)) {
// Invalid directive field. TODO: Custom returnvalue
return false;
}
return true;
}
void FileDirectiveDeserializer::setFileDirective(cfdp::FileDirectives fileDirective) {
this->fileDirective = fileDirective;
}
void FileDirectiveDeserializer::setEndianness(SerializeIF::Endianness endianness) {
this->endianness = endianness;
}
SerializeIF::Endianness FileDirectiveDeserializer::getEndianness() const { return endianness; }

View File

@ -2,7 +2,7 @@
#define FSFW_SRC_FSFW_CFDP_PDU_FILEDIRECTIVEDESERIALIZER_H_ #define FSFW_SRC_FSFW_CFDP_PDU_FILEDIRECTIVEDESERIALIZER_H_
#include "../definitions.h" #include "../definitions.h"
#include "fsfw/cfdp/pdu/PduHeaderReader.h" #include "fsfw/cfdp/pdu/HeaderDeserializer.h"
/** /**
* @brief This class is used to deserialize a PDU file directive header from raw memory. * @brief This class is used to deserialize a PDU file directive header from raw memory.
@ -11,27 +11,28 @@
* This is a zero-copy implementation and #parseData needs to be called to ensure the data is * This is a zero-copy implementation and #parseData needs to be called to ensure the data is
* valid. * valid.
*/ */
class FileDirectiveReader : public PduHeaderReader { class FileDirectiveDeserializer : public HeaderDeserializer {
public: public:
FileDirectiveReader(const uint8_t* pduBuf, size_t maxSize); FileDirectiveDeserializer(const uint8_t* pduBuf, size_t maxSize);
/** /**
* This needs to be called before accessing the PDU fields to avoid segmentation faults. * This needs to be called before accessing the PDU fields to avoid segmentation faults.
* @return * @return
*/ */
ReturnValue_t parseData() override; virtual ReturnValue_t parseData();
[[nodiscard]] size_t getHeaderSize() const override; size_t getHeaderSize() const;
[[nodiscard]] cfdp::FileDirective getFileDirective() const; cfdp::FileDirectives getFileDirective() const;
void setEndianness(SerializeIF::Endianness endianness); void setEndianness(SerializeIF::Endianness endianness);
[[nodiscard]] SerializeIF::Endianness getEndianness() const; SerializeIF::Endianness getEndianness() const;
static bool checkFileDirective(uint8_t rawByte);
protected: protected:
bool checkFileDirective(uint8_t rawByte);
private: private:
void setFileDirective(cfdp::FileDirective fileDirective); void setFileDirective(cfdp::FileDirectives fileDirective);
cfdp::FileDirective fileDirective = cfdp::FileDirective::INVALID_DIRECTIVE; cfdp::FileDirectives fileDirective = cfdp::FileDirectives::INVALID_DIRECTIVE;
SerializeIF::Endianness endianness = SerializeIF::Endianness::NETWORK; SerializeIF::Endianness endianness = SerializeIF::Endianness::NETWORK;
}; };

View File

@ -1,49 +0,0 @@
#include "FileDirectiveReader.h"
FileDirectiveReader::FileDirectiveReader(const uint8_t *pduBuf, size_t maxSize)
: PduHeaderReader(pduBuf, maxSize) {}
cfdp::FileDirective FileDirectiveReader::getFileDirective() const { return fileDirective; }
ReturnValue_t FileDirectiveReader::parseData() {
ReturnValue_t result = PduHeaderReader::parseData();
if (result != returnvalue::OK) {
return result;
}
if (this->getPduDataFieldLen() < 1) {
return cfdp::INVALID_PDU_DATAFIELD_LEN;
}
if (FileDirectiveReader::getWholePduSize() > maxSize) {
return SerializeIF::STREAM_TOO_SHORT;
}
size_t currentIdx = PduHeaderReader::getHeaderSize();
if (not checkFileDirective(pointers.rawPtr[currentIdx])) {
return cfdp::INVALID_DIRECTIVE_FIELD;
}
setFileDirective(static_cast<cfdp::FileDirective>(pointers.rawPtr[currentIdx]));
return returnvalue::OK;
}
size_t FileDirectiveReader::getHeaderSize() const {
// return size of header plus the directive byte
return PduHeaderReader::getHeaderSize() + 1;
}
bool FileDirectiveReader::checkFileDirective(uint8_t rawByte) {
if (rawByte < cfdp::FileDirective::EOF_DIRECTIVE or
(rawByte > cfdp::FileDirective::PROMPT and rawByte != cfdp::FileDirective::KEEP_ALIVE)) {
// Invalid directive field
return false;
}
return true;
}
void FileDirectiveReader::setFileDirective(cfdp::FileDirective fileDirective_) {
fileDirective = fileDirective_;
}
void FileDirectiveReader::setEndianness(SerializeIF::Endianness endianness_) {
endianness = endianness_;
}
SerializeIF::Endianness FileDirectiveReader::getEndianness() const { return endianness; }

View File

@ -0,0 +1,38 @@
#include "FileDirectiveSerializer.h"
FileDirectiveSerializer::FileDirectiveSerializer(PduConfig &pduConf,
cfdp::FileDirectives directiveCode,
size_t directiveParamFieldLen)
: HeaderSerializer(pduConf, cfdp::PduType::FILE_DIRECTIVE, directiveParamFieldLen + 1),
directiveCode(directiveCode) {}
size_t FileDirectiveSerializer::getSerializedSize() const {
return HeaderSerializer::getSerializedSize() + 1;
}
ReturnValue_t FileDirectiveSerializer::serialize(uint8_t **buffer, size_t *size, size_t maxSize,
Endianness streamEndianness) const {
if (buffer == nullptr or size == nullptr) {
return returnvalue::FAILED;
}
if (FileDirectiveSerializer::getWholePduSize() > maxSize) {
return BUFFER_TOO_SHORT;
}
ReturnValue_t result = HeaderSerializer::serialize(buffer, size, maxSize, streamEndianness);
if (result != returnvalue::OK) {
return result;
}
if (*size >= maxSize) {
return BUFFER_TOO_SHORT;
}
**buffer = directiveCode;
*buffer += 1;
*size += 1;
return returnvalue::OK;
}
void FileDirectiveSerializer::setDirectiveDataFieldLen(size_t len) {
// Set length of data field plus 1 byte for the directive octet
HeaderSerializer::setPduDataFieldLen(len + 1);
}

View File

@ -0,0 +1,28 @@
#ifndef FSFW_SRC_FSFW_CFDP_PDU_FILEDIRECTIVESERIALIZER_H_
#define FSFW_SRC_FSFW_CFDP_PDU_FILEDIRECTIVESERIALIZER_H_
#include "fsfw/cfdp/pdu/HeaderSerializer.h"
class FileDirectiveSerializer : public HeaderSerializer {
public:
FileDirectiveSerializer(PduConfig& pduConf, cfdp::FileDirectives directiveCode,
size_t directiveParamFieldLen);
/**
* This only returns the size of the PDU header + 1 for the directive code octet.
* Use FileDirectiveSerializer::getWholePduSize to get the full packet length, assuming
* the length fields was set correctly
* @return
*/
size_t getSerializedSize() const override;
ReturnValue_t serialize(uint8_t** buffer, size_t* size, size_t maxSize,
Endianness streamEndianness) const override;
void setDirectiveDataFieldLen(size_t len);
private:
cfdp::FileDirectives directiveCode = cfdp::FileDirectives::INVALID_DIRECTIVE;
};
#endif /* FSFW_SRC_FSFW_CFDP_PDU_FILEDIRECTIVESERIALIZER_H_ */

View File

@ -2,8 +2,9 @@
FinishedInfo::FinishedInfo() {} FinishedInfo::FinishedInfo() {}
FinishedInfo::FinishedInfo(cfdp::ConditionCode conditionCode, cfdp::FileDeliveryCode deliveryCode, FinishedInfo::FinishedInfo(cfdp::ConditionCode conditionCode,
cfdp::FileDeliveryStatus fileStatus) cfdp::FinishedDeliveryCode deliveryCode,
cfdp::FinishedFileStatus fileStatus)
: conditionCode(conditionCode), deliveryCode(deliveryCode), fileStatus(fileStatus) {} : conditionCode(conditionCode), deliveryCode(deliveryCode), fileStatus(fileStatus) {}
size_t FinishedInfo::getSerializedSize() const { size_t FinishedInfo::getSerializedSize() const {
@ -82,13 +83,13 @@ void FinishedInfo::setConditionCode(cfdp::ConditionCode conditionCode) {
this->conditionCode = conditionCode; this->conditionCode = conditionCode;
} }
cfdp::FileDeliveryCode FinishedInfo::getDeliveryCode() const { return deliveryCode; } cfdp::FinishedDeliveryCode FinishedInfo::getDeliveryCode() const { return deliveryCode; }
void FinishedInfo::setDeliveryCode(cfdp::FileDeliveryCode deliveryCode) { void FinishedInfo::setDeliveryCode(cfdp::FinishedDeliveryCode deliveryCode) {
this->deliveryCode = deliveryCode; this->deliveryCode = deliveryCode;
} }
cfdp::FileDeliveryStatus FinishedInfo::getFileStatus() const { return fileStatus; } cfdp::FinishedFileStatus FinishedInfo::getFileStatus() const { return fileStatus; }
void FinishedInfo::setFilestoreResponsesArrayLen(size_t fsResponsesLen) { void FinishedInfo::setFilestoreResponsesArrayLen(size_t fsResponsesLen) {
this->fsResponsesLen = fsResponsesLen; this->fsResponsesLen = fsResponsesLen;
@ -96,6 +97,6 @@ void FinishedInfo::setFilestoreResponsesArrayLen(size_t fsResponsesLen) {
size_t FinishedInfo::getFsResponsesLen() const { return fsResponsesLen; } size_t FinishedInfo::getFsResponsesLen() const { return fsResponsesLen; }
void FinishedInfo::setFileStatus(cfdp::FileDeliveryStatus fileStatus) { void FinishedInfo::setFileStatus(cfdp::FinishedFileStatus fileStatus) {
this->fileStatus = fileStatus; this->fileStatus = fileStatus;
} }

View File

@ -8,13 +8,13 @@
class FinishedInfo { class FinishedInfo {
public: public:
FinishedInfo(); FinishedInfo();
FinishedInfo(cfdp::ConditionCode conditionCode, cfdp::FileDeliveryCode deliveryCode, FinishedInfo(cfdp::ConditionCode conditionCode, cfdp::FinishedDeliveryCode deliveryCode,
cfdp::FileDeliveryStatus fileStatus); cfdp::FinishedFileStatus fileStatus);
[[nodiscard]] size_t getSerializedSize() const; size_t getSerializedSize() const;
[[nodiscard]] bool hasFsResponses() const; bool hasFsResponses() const;
[[nodiscard]] bool canHoldFsResponses() const; bool canHoldFsResponses() const;
ReturnValue_t setFilestoreResponsesArray(FilestoreResponseTlv** fsResponses, ReturnValue_t setFilestoreResponsesArray(FilestoreResponseTlv** fsResponses,
size_t* fsResponsesLen, const size_t* maxFsResponseLen); size_t* fsResponsesLen, const size_t* maxFsResponseLen);
@ -22,20 +22,20 @@ class FinishedInfo {
ReturnValue_t getFilestoreResonses(FilestoreResponseTlv*** fsResponses, size_t* fsResponsesLen, ReturnValue_t getFilestoreResonses(FilestoreResponseTlv*** fsResponses, size_t* fsResponsesLen,
size_t* fsResponsesMaxLen); size_t* fsResponsesMaxLen);
[[nodiscard]] size_t getFsResponsesLen() const; size_t getFsResponsesLen() const;
void setFilestoreResponsesArrayLen(size_t fsResponsesLen); void setFilestoreResponsesArrayLen(size_t fsResponsesLen);
ReturnValue_t getFaultLocation(EntityIdTlv** entityId); ReturnValue_t getFaultLocation(EntityIdTlv** entityId);
[[nodiscard]] cfdp::ConditionCode getConditionCode() const; cfdp::ConditionCode getConditionCode() const;
void setConditionCode(cfdp::ConditionCode conditionCode); void setConditionCode(cfdp::ConditionCode conditionCode);
[[nodiscard]] cfdp::FileDeliveryCode getDeliveryCode() const; cfdp::FinishedDeliveryCode getDeliveryCode() const;
void setDeliveryCode(cfdp::FileDeliveryCode deliveryCode); void setDeliveryCode(cfdp::FinishedDeliveryCode deliveryCode);
[[nodiscard]] cfdp::FileDeliveryStatus getFileStatus() const; cfdp::FinishedFileStatus getFileStatus() const;
void setFileStatus(cfdp::FileDeliveryStatus fileStatus); void setFileStatus(cfdp::FinishedFileStatus fileStatus);
private: private:
cfdp::ConditionCode conditionCode = cfdp::ConditionCode::NO_CONDITION_FIELD; cfdp::ConditionCode conditionCode = cfdp::ConditionCode::NO_CONDITION_FIELD;
cfdp::FileDeliveryCode deliveryCode = cfdp::FileDeliveryCode::DATA_COMPLETE; cfdp::FinishedDeliveryCode deliveryCode = cfdp::FinishedDeliveryCode::DATA_COMPLETE;
cfdp::FileDeliveryStatus fileStatus = cfdp::FileDeliveryStatus::DISCARDED_DELIBERATELY; cfdp::FinishedFileStatus fileStatus = cfdp::FinishedFileStatus::DISCARDED_DELIBERATELY;
FilestoreResponseTlv** fsResponses = nullptr; FilestoreResponseTlv** fsResponses = nullptr;
size_t fsResponsesLen = 0; size_t fsResponsesLen = 0;
size_t fsResponsesMaxLen = 0; size_t fsResponsesMaxLen = 0;

View File

@ -1,24 +0,0 @@
#ifndef FSFW_CFDP_PDU_FINISHEDPDUSERIALIZER_H_
#define FSFW_CFDP_PDU_FINISHEDPDUSERIALIZER_H_
#include "FinishedInfo.h"
#include "fsfw/cfdp/pdu/FileDataCreator.h"
#include "fsfw/cfdp/pdu/FileDirectiveCreator.h"
class FinishPduCreator : public FileDirectiveCreator {
public:
FinishPduCreator(PduConfig& pduConf, FinishedInfo& finishInfo);
void updateDirectiveFieldLen();
[[nodiscard]] size_t getSerializedSize() const override;
ReturnValue_t serialize(uint8_t** buffer, size_t* size, size_t maxSize,
Endianness streamEndianness) const override;
using FileDirectiveCreator::serialize;
private:
FinishedInfo& finishInfo;
};
#endif /* FSFW_CFDP_PDU_FINISHEDPDUSERIALIZER_H_ */

View File

@ -1,24 +1,25 @@
#include "FinishedPduReader.h" #include "FinishedPduDeserializer.h"
FinishPduReader::FinishPduReader(const uint8_t* pduBuf, size_t maxSize, FinishedInfo& info) FinishPduDeserializer::FinishPduDeserializer(const uint8_t* pduBuf, size_t maxSize,
: FileDirectiveReader(pduBuf, maxSize), finishedInfo(info) {} FinishedInfo& info)
: FileDirectiveDeserializer(pduBuf, maxSize), finishedInfo(info) {}
ReturnValue_t FinishPduReader::parseData() { ReturnValue_t FinishPduDeserializer::parseData() {
ReturnValue_t result = FileDirectiveReader::parseData(); ReturnValue_t result = FileDirectiveDeserializer::parseData();
if (result != returnvalue::OK) { if (result != returnvalue::OK) {
return result; return result;
} }
size_t currentIdx = FileDirectiveReader::getHeaderSize(); size_t currentIdx = FileDirectiveDeserializer::getHeaderSize();
const uint8_t* buf = pointers.rawPtr + currentIdx; const uint8_t* buf = rawPtr + currentIdx;
size_t remSize = FileDirectiveReader::getWholePduSize() - currentIdx; size_t remSize = FileDirectiveDeserializer::getWholePduSize() - currentIdx;
if (remSize < 1) { if (remSize < 1) {
return SerializeIF::STREAM_TOO_SHORT; return SerializeIF::STREAM_TOO_SHORT;
} }
uint8_t firstByte = *buf; uint8_t firstByte = *buf;
auto condCode = static_cast<cfdp::ConditionCode>((firstByte >> 4) & 0x0f); cfdp::ConditionCode condCode = static_cast<cfdp::ConditionCode>((firstByte >> 4) & 0x0f);
finishedInfo.setConditionCode(condCode); finishedInfo.setConditionCode(condCode);
finishedInfo.setDeliveryCode(static_cast<cfdp::FileDeliveryCode>(firstByte >> 2 & 0b1)); finishedInfo.setDeliveryCode(static_cast<cfdp::FinishedDeliveryCode>(firstByte >> 2 & 0b1));
finishedInfo.setFileStatus(static_cast<cfdp::FileDeliveryStatus>(firstByte & 0b11)); finishedInfo.setFileStatus(static_cast<cfdp::FinishedFileStatus>(firstByte & 0b11));
buf += 1; buf += 1;
remSize -= 1; remSize -= 1;
currentIdx += 1; currentIdx += 1;
@ -28,9 +29,9 @@ ReturnValue_t FinishPduReader::parseData() {
return result; return result;
} }
FinishedInfo& FinishPduReader::getInfo() { return finishedInfo; } FinishedInfo& FinishPduDeserializer::getInfo() { return finishedInfo; }
ReturnValue_t FinishPduReader::parseTlvs(size_t remLen, size_t currentIdx, const uint8_t* buf, ReturnValue_t FinishPduDeserializer::parseTlvs(size_t remLen, size_t currentIdx, const uint8_t* buf,
cfdp::ConditionCode conditionCode) { cfdp::ConditionCode conditionCode) {
ReturnValue_t result = returnvalue::OK; ReturnValue_t result = returnvalue::OK;
size_t fsResponsesIdx = 0; size_t fsResponsesIdx = 0;
@ -38,7 +39,7 @@ ReturnValue_t FinishPduReader::parseTlvs(size_t remLen, size_t currentIdx, const
FilestoreResponseTlv** fsResponseArray = nullptr; FilestoreResponseTlv** fsResponseArray = nullptr;
size_t fsResponseMaxArrayLen = 0; size_t fsResponseMaxArrayLen = 0;
EntityIdTlv* faultLocation = nullptr; EntityIdTlv* faultLocation = nullptr;
cfdp::TlvType nextTlv = cfdp::TlvType::INVALID_TLV; cfdp::TlvTypes nextTlv = cfdp::TlvTypes::INVALID_TLV;
while (remLen > 0) { while (remLen > 0) {
// Simply forward parse the TLV type. Every TLV type except the last one must be a Filestore // Simply forward parse the TLV type. Every TLV type except the last one must be a Filestore
// Response TLV, and even the last one can be a Filestore Response TLV if the fault // Response TLV, and even the last one can be a Filestore Response TLV if the fault
@ -46,8 +47,8 @@ ReturnValue_t FinishPduReader::parseTlvs(size_t remLen, size_t currentIdx, const
if (currentIdx + 2 > maxSize) { if (currentIdx + 2 > maxSize) {
return SerializeIF::STREAM_TOO_SHORT; return SerializeIF::STREAM_TOO_SHORT;
} }
nextTlv = static_cast<cfdp::TlvType>(*buf); nextTlv = static_cast<cfdp::TlvTypes>(*buf);
if (nextTlv == cfdp::TlvType::FILESTORE_RESPONSE) { if (nextTlv == cfdp::TlvTypes::FILESTORE_RESPONSE) {
if (fsResponseArray == nullptr) { if (fsResponseArray == nullptr) {
if (not finishedInfo.canHoldFsResponses()) { if (not finishedInfo.canHoldFsResponses()) {
return cfdp::FINISHED_CANT_PARSE_FS_RESPONSES; return cfdp::FINISHED_CANT_PARSE_FS_RESPONSES;
@ -63,7 +64,7 @@ ReturnValue_t FinishPduReader::parseTlvs(size_t remLen, size_t currentIdx, const
return result; return result;
} }
fsResponsesIdx += 1; fsResponsesIdx += 1;
} else if (nextTlv == cfdp::TlvType::ENTITY_ID) { } else if (nextTlv == cfdp::TlvTypes::ENTITY_ID) {
// This needs to be the last TLV and it should not be here if the condition code // This needs to be the last TLV and it should not be here if the condition code
// is "No Error" or "Unsupported Checksum Type" // is "No Error" or "Unsupported Checksum Type"
if (conditionCode == cfdp::ConditionCode::NO_ERROR or if (conditionCode == cfdp::ConditionCode::NO_ERROR or

View File

@ -0,0 +1,22 @@
#ifndef FSFW_SRC_FSFW_CFDP_PDU_FINISHEDPDUDESERIALIZER_H_
#define FSFW_SRC_FSFW_CFDP_PDU_FINISHEDPDUDESERIALIZER_H_
#include "fsfw/cfdp/pdu/FileDirectiveDeserializer.h"
#include "fsfw/cfdp/pdu/FinishedInfo.h"
class FinishPduDeserializer : public FileDirectiveDeserializer {
public:
FinishPduDeserializer(const uint8_t* pduBuf, size_t maxSize, FinishedInfo& info);
ReturnValue_t parseData() override;
FinishedInfo& getInfo();
private:
FinishedInfo& finishedInfo;
ReturnValue_t parseTlvs(size_t remLen, size_t currentIdx, const uint8_t* buf,
cfdp::ConditionCode conditionCode);
};
#endif /* FSFW_SRC_FSFW_CFDP_PDU_FINISHEDPDUDESERIALIZER_H_ */

View File

@ -1,22 +0,0 @@
#ifndef FSFW_CFDP_PDU_FINISHEDPDUDESERIALIZER_H_
#define FSFW_CFDP_PDU_FINISHEDPDUDESERIALIZER_H_
#include "fsfw/cfdp/pdu/FileDirectiveReader.h"
#include "fsfw/cfdp/pdu/FinishedInfo.h"
class FinishPduReader : public FileDirectiveReader {
public:
FinishPduReader(const uint8_t* pduBuf, size_t maxSize, FinishedInfo& info);
ReturnValue_t parseData() override;
FinishedInfo& getInfo();
private:
FinishedInfo& finishedInfo;
ReturnValue_t parseTlvs(size_t remLen, size_t currentIdx, const uint8_t* buf,
cfdp::ConditionCode conditionCode);
};
#endif /* FSFW_CFDP_PDU_FINISHEDPDUDESERIALIZER_H_ */

View File

@ -1,23 +1,26 @@
#include "FinishedPduCreator.h" #include "FinishedPduSerializer.h"
FinishPduCreator::FinishPduCreator(PduConfig &conf, FinishedInfo &finishInfo) FinishPduSerializer::FinishPduSerializer(PduConfig &conf, FinishedInfo &finishInfo)
: FileDirectiveCreator(conf, cfdp::FileDirective::FINISH, 0), finishInfo(finishInfo) { : FileDirectiveSerializer(conf, cfdp::FileDirectives::FINISH, 0), finishInfo(finishInfo) {
updateDirectiveFieldLen(); updateDirectiveFieldLen();
} }
size_t FinishPduCreator::getSerializedSize() const { return FinishPduCreator::getWholePduSize(); } size_t FinishPduSerializer::getSerializedSize() const {
return FinishPduSerializer::getWholePduSize();
}
void FinishPduCreator::updateDirectiveFieldLen() { void FinishPduSerializer::updateDirectiveFieldLen() {
setDirectiveDataFieldLen(finishInfo.getSerializedSize()); setDirectiveDataFieldLen(finishInfo.getSerializedSize());
} }
ReturnValue_t FinishPduCreator::serialize(uint8_t **buffer, size_t *size, size_t maxSize, ReturnValue_t FinishPduSerializer::serialize(uint8_t **buffer, size_t *size, size_t maxSize,
Endianness streamEndianness) const { Endianness streamEndianness) const {
ReturnValue_t result = FileDirectiveCreator::serialize(buffer, size, maxSize, streamEndianness); ReturnValue_t result =
FileDirectiveSerializer::serialize(buffer, size, maxSize, streamEndianness);
if (result != returnvalue::OK) { if (result != returnvalue::OK) {
return result; return result;
} }
if (*size + 1 > maxSize) { if (*size + 1 >= maxSize) {
return SerializeIF::BUFFER_TOO_SHORT; return SerializeIF::BUFFER_TOO_SHORT;
} }
**buffer = finishInfo.getConditionCode() << 4 | finishInfo.getDeliveryCode() << 2 | **buffer = finishInfo.getConditionCode() << 4 | finishInfo.getDeliveryCode() << 2 |

View File

@ -0,0 +1,23 @@
#ifndef FSFW_SRC_FSFW_CFDP_PDU_FINISHEDPDUSERIALIZER_H_
#define FSFW_SRC_FSFW_CFDP_PDU_FINISHEDPDUSERIALIZER_H_
#include "FinishedInfo.h"
#include "fsfw/cfdp/pdu/FileDataSerializer.h"
#include "fsfw/cfdp/pdu/FileDirectiveSerializer.h"
class FinishPduSerializer : public FileDirectiveSerializer {
public:
FinishPduSerializer(PduConfig& pduConf, FinishedInfo& finishInfo);
void updateDirectiveFieldLen();
size_t getSerializedSize() const override;
ReturnValue_t serialize(uint8_t** buffer, size_t* size, size_t maxSize,
Endianness streamEndianness) const override;
private:
FinishedInfo& finishInfo;
};
#endif /* FSFW_SRC_FSFW_CFDP_PDU_FINISHEDPDUSERIALIZER_H_ */

View File

@ -1,111 +0,0 @@
#include "HeaderCreator.h"
HeaderCreator::HeaderCreator(PduConfig &pduConf, cfdp::PduType pduType, size_t initPduDataFieldLen,
cfdp::SegmentMetadataFlag segmentMetadataFlag,
cfdp::SegmentationControl segCtrl)
: pduType(pduType),
segmentMetadataFlag(segmentMetadataFlag),
segmentationCtrl(segCtrl),
pduDataFieldLen(initPduDataFieldLen),
pduConf(pduConf) {}
ReturnValue_t HeaderCreator::serialize(uint8_t **buffer, size_t *size, size_t maxSize,
Endianness streamEndianness) const {
if (buffer == nullptr or size == nullptr) {
return returnvalue::FAILED;
}
if (maxSize < this->getSerializedSize()) {
return BUFFER_TOO_SHORT;
}
**buffer = cfdp::VERSION_BITS | this->pduType << 4 | pduConf.direction << 3 | pduConf.mode << 2 |
pduConf.crcFlag << 1 | pduConf.largeFile;
*buffer += 1;
**buffer = (pduDataFieldLen & 0xff00) >> 8;
*buffer += 1;
**buffer = pduDataFieldLen & 0x00ff;
*buffer += 1;
**buffer = segmentationCtrl << 7 | ((pduConf.sourceId.getWidth() - 1) << 4) |
segmentMetadataFlag << 3 | (pduConf.seqNum.getWidth() - 1);
*buffer += 1;
*size += 4;
ReturnValue_t result = pduConf.sourceId.serialize(buffer, size, maxSize, streamEndianness);
if (result != returnvalue::OK) {
return result;
}
result = pduConf.seqNum.serialize(buffer, size, maxSize, streamEndianness);
if (result != returnvalue::OK) {
return result;
}
result = pduConf.destId.serialize(buffer, size, maxSize, streamEndianness);
if (result != returnvalue::OK) {
return result;
}
return returnvalue::OK;
}
size_t HeaderCreator::getSerializedSize() const {
return pduConf.seqNum.getWidth() + pduConf.sourceId.getWidth() * 2 + 4;
}
ReturnValue_t HeaderCreator::deSerialize(const uint8_t **buffer, size_t *size,
Endianness streamEndianness) {
// We could implement this, but I prefer dedicated classes
return returnvalue::FAILED;
}
size_t HeaderCreator::getWholePduSize() const {
// Return size of header plus the PDU data field length
return pduDataFieldLen + HeaderCreator::getSerializedSize();
}
size_t HeaderCreator::getPduDataFieldLen() const { return pduDataFieldLen; }
void HeaderCreator::setPduDataFieldLen(size_t pduDataFieldLen_) {
pduDataFieldLen = pduDataFieldLen_;
}
void HeaderCreator::setPduType(cfdp::PduType pduType_) { pduType = pduType_; }
void HeaderCreator::setSegmentMetadataFlag(cfdp::SegmentMetadataFlag segmentMetadataFlag_) {
segmentMetadataFlag = segmentMetadataFlag_;
}
cfdp::PduType HeaderCreator::getPduType() const { return pduType; }
cfdp::Direction HeaderCreator::getDirection() const { return pduConf.direction; }
cfdp::TransmissionMode HeaderCreator::getTransmissionMode() const { return pduConf.mode; }
bool HeaderCreator::getCrcFlag() const { return pduConf.crcFlag; }
bool HeaderCreator::getLargeFileFlag() const { return pduConf.largeFile; }
cfdp::SegmentationControl HeaderCreator::getSegmentationControl() const { return segmentationCtrl; }
cfdp::WidthInBytes HeaderCreator::getLenEntityIds() const { return pduConf.sourceId.getWidth(); }
cfdp::WidthInBytes HeaderCreator::getLenSeqNum() const { return pduConf.seqNum.getWidth(); }
cfdp::SegmentMetadataFlag HeaderCreator::getSegmentMetadataFlag() const {
return segmentMetadataFlag;
}
void HeaderCreator::getSourceId(cfdp::EntityId &sourceId) const { sourceId = pduConf.sourceId; }
void HeaderCreator::getDestId(cfdp::EntityId &destId) const { destId = pduConf.destId; }
void HeaderCreator::setSegmentationControl(cfdp::SegmentationControl segmentationControl) {
this->segmentationCtrl = segmentationControl;
}
void HeaderCreator::getTransactionSeqNum(cfdp::TransactionSeqNum &seqNum) const {
seqNum = pduConf.seqNum;
}
bool HeaderCreator::hasSegmentMetadataFlag() const {
if (this->segmentMetadataFlag == cfdp::SegmentMetadataFlag::PRESENT) {
return true;
}
return false;
}

View File

@ -0,0 +1,128 @@
#include "HeaderDeserializer.h"
#include <fsfw/serialize/SerializeAdapter.h>
#include <cstring>
HeaderDeserializer::HeaderDeserializer(const uint8_t *pduBuf, size_t maxSize)
: rawPtr(pduBuf), maxSize(maxSize) {}
ReturnValue_t HeaderDeserializer::parseData() {
if (maxSize < 7) {
return SerializeIF::STREAM_TOO_SHORT;
}
return setData(const_cast<uint8_t *>(rawPtr), maxSize);
}
ReturnValue_t HeaderDeserializer::setData(uint8_t *dataPtr, size_t maxSize, void *args) {
if (dataPtr == nullptr) {
// Allowed for now
this->fixedHeader = nullptr;
return returnvalue::OK;
}
this->fixedHeader = reinterpret_cast<PduHeaderFixedStruct *>(const_cast<uint8_t *>(dataPtr));
sourceIdRaw = static_cast<uint8_t *>(&fixedHeader->variableFieldsStart);
cfdp::WidthInBytes widthEntityIds = getLenEntityIds();
cfdp::WidthInBytes widthSeqNum = getLenSeqNum();
seqNumRaw = static_cast<uint8_t *>(sourceIdRaw) + static_cast<uint8_t>(widthEntityIds);
destIdRaw = static_cast<uint8_t *>(seqNumRaw) + static_cast<uint8_t>(widthSeqNum);
this->maxSize = maxSize;
return returnvalue::OK;
}
size_t HeaderDeserializer::getHeaderSize() const {
if (fixedHeader != nullptr) {
return getLenEntityIds() * 2 + getLenSeqNum() + 4;
}
return 0;
}
size_t HeaderDeserializer::getPduDataFieldLen() const {
uint16_t pduFiedlLen = (fixedHeader->pduDataFieldLenH << 8) | fixedHeader->pduDataFieldLenL;
return pduFiedlLen;
}
size_t HeaderDeserializer::getWholePduSize() const {
return getPduDataFieldLen() + getHeaderSize();
}
cfdp::PduType HeaderDeserializer::getPduType() const {
return static_cast<cfdp::PduType>((fixedHeader->firstByte >> 4) & 0x01);
}
cfdp::Direction HeaderDeserializer::getDirection() const {
return static_cast<cfdp::Direction>((fixedHeader->firstByte >> 3) & 0x01);
}
cfdp::TransmissionModes HeaderDeserializer::getTransmissionMode() const {
return static_cast<cfdp::TransmissionModes>((fixedHeader->firstByte >> 2) & 0x01);
}
bool HeaderDeserializer::getCrcFlag() const { return (fixedHeader->firstByte >> 1) & 0x01; }
bool HeaderDeserializer::getLargeFileFlag() const { return fixedHeader->firstByte & 0x01; }
cfdp::SegmentationControl HeaderDeserializer::getSegmentationControl() const {
return static_cast<cfdp::SegmentationControl>((fixedHeader->fourthByte >> 7) & 0x01);
}
cfdp::WidthInBytes HeaderDeserializer::getLenEntityIds() const {
return static_cast<cfdp::WidthInBytes>((fixedHeader->fourthByte >> 4) & 0x07);
}
cfdp::WidthInBytes HeaderDeserializer::getLenSeqNum() const {
return static_cast<cfdp::WidthInBytes>(fixedHeader->fourthByte & 0x07);
}
cfdp::SegmentMetadataFlag HeaderDeserializer::getSegmentMetadataFlag() const {
return static_cast<cfdp::SegmentMetadataFlag>((fixedHeader->fourthByte >> 3) & 0x01);
}
void HeaderDeserializer::getSourceId(cfdp::EntityId &sourceId) const {
assignVarLenField(dynamic_cast<cfdp::VarLenField *>(&sourceId), getLenEntityIds(),
this->sourceIdRaw);
}
void HeaderDeserializer::getDestId(cfdp::EntityId &destId) const {
assignVarLenField(dynamic_cast<cfdp::VarLenField *>(&destId), getLenEntityIds(), this->destIdRaw);
}
void HeaderDeserializer::getTransactionSeqNum(cfdp::TransactionSeqNum &seqNum) const {
assignVarLenField(dynamic_cast<cfdp::VarLenField *>(&seqNum), getLenSeqNum(), this->seqNumRaw);
}
void HeaderDeserializer::assignVarLenField(cfdp::VarLenField *field, cfdp::WidthInBytes width,
void *sourcePtr) const {
switch (width) {
case (cfdp::WidthInBytes::ONE_BYTE): {
uint8_t *fieldTyped = static_cast<uint8_t *>(sourcePtr);
field->setValue(width, *fieldTyped);
break;
}
case (cfdp::WidthInBytes::TWO_BYTES): {
uint16_t fieldTyped = 0;
size_t deserSize = 0;
SerializeAdapter::deSerialize(&fieldTyped, static_cast<uint8_t *>(sourcePtr), &deserSize,
SerializeIF::Endianness::NETWORK);
field->setValue(width, fieldTyped);
break;
}
case (cfdp::WidthInBytes::FOUR_BYTES): {
uint32_t fieldTyped = 0;
size_t deserSize = 0;
SerializeAdapter::deSerialize(&fieldTyped, static_cast<uint8_t *>(sourcePtr), &deserSize,
SerializeIF::Endianness::NETWORK);
field->setValue(width, fieldTyped);
break;
}
}
}
size_t HeaderDeserializer::getMaxSize() const { return maxSize; }
bool HeaderDeserializer::hasSegmentMetadataFlag() const {
if (this->getSegmentMetadataFlag() == cfdp::SegmentMetadataFlag::PRESENT) {
return true;
}
return false;
}

View File

@ -0,0 +1,90 @@
#ifndef FSFW_SRC_FSFW_CFDP_PDU_HEADERDESERIALIZER_H_
#define FSFW_SRC_FSFW_CFDP_PDU_HEADERDESERIALIZER_H_
#include <cstddef>
#include <cstdint>
#include "PduConfig.h"
#include "PduHeaderIF.h"
#include "fsfw/serialize/SerializeIF.h"
#include "fsfw/tmtcpacket/RedirectableDataPointerIF.h"
struct PduHeaderFixedStruct {
uint8_t firstByte;
uint8_t pduDataFieldLenH;
uint8_t pduDataFieldLenL;
uint8_t fourthByte;
uint8_t variableFieldsStart;
};
/**
* @brief This class is used to deserialize a PDU header from raw memory.
* @details
* This is a zero-copy implementation and #parseData needs to be called to ensure the data is
* valid.
*/
class HeaderDeserializer : public RedirectableDataPointerIF, public PduHeaderIF {
public:
/**
* Initialize a PDU header from raw data. This is a zero-copy implementation and #parseData
* needs to be called to ensure the data is valid
* @param pduBuf
* @param maxSize
*/
HeaderDeserializer(const uint8_t* pduBuf, size_t maxSize);
/**
* This needs to be called before accessing the PDU fields to avoid segmentation faults.
* @return
* - returnvalue::OK on parse success
* - returnvalue::FAILED Invalid raw data
* - SerializeIF::BUFFER_TOO_SHORT if buffer is shorter than expected
*/
virtual ReturnValue_t parseData();
size_t getHeaderSize() const;
size_t getPduDataFieldLen() const override;
size_t getWholePduSize() const override;
cfdp::PduType getPduType() const override;
cfdp::Direction getDirection() const override;
cfdp::TransmissionModes getTransmissionMode() const override;
bool getCrcFlag() const override;
bool getLargeFileFlag() const override;
cfdp::SegmentationControl getSegmentationControl() const override;
cfdp::WidthInBytes getLenEntityIds() const override;
cfdp::WidthInBytes getLenSeqNum() const override;
cfdp::SegmentMetadataFlag getSegmentMetadataFlag() const override;
bool hasSegmentMetadataFlag() const override;
void getSourceId(cfdp::EntityId& sourceId) const override;
void getDestId(cfdp::EntityId& destId) const override;
void getTransactionSeqNum(cfdp::TransactionSeqNum& seqNum) const override;
ReturnValue_t deserResult = returnvalue::OK;
/**
* Can also be used to reset the pointer to a nullptr, but the getter functions will not
* perform nullptr checks!
* @param dataPtr
* @param maxSize
* @param args
* @return
*/
ReturnValue_t setData(uint8_t* dataPtr, size_t maxSize, void* args = nullptr) override;
size_t getMaxSize() const;
protected:
PduHeaderFixedStruct* fixedHeader = nullptr;
const uint8_t* rawPtr = nullptr;
size_t maxSize = 0;
private:
void assignVarLenField(cfdp::VarLenField* field, cfdp::WidthInBytes width, void* sourcePtr) const;
void* sourceIdRaw = nullptr;
void* seqNumRaw = nullptr;
void* destIdRaw = nullptr;
};
#endif /* FSFW_SRC_FSFW_CFDP_PDU_HEADERDESERIALIZER_H_ */

View File

@ -1,168 +0,0 @@
#include <fsfw/serialize/SerializeAdapter.h>
#include <cstring>
#include "PduHeaderReader.h"
PduHeaderReader::PduHeaderReader(const uint8_t *pduBuf, size_t maxSize) {
setReadOnlyData(pduBuf, maxSize);
}
ReturnValue_t PduHeaderReader::parseData() {
if (pointers.rawPtr == nullptr) {
return returnvalue::FAILED;
}
if (maxSize < 7) {
return SerializeIF::STREAM_TOO_SHORT;
}
pointers.fixedHeader =
reinterpret_cast<PduHeaderFixedStruct *>(const_cast<uint8_t *>(pointers.rawPtr));
sourceIdRaw = static_cast<uint8_t *>(&pointers.fixedHeader->variableFieldsStart);
cfdp::WidthInBytes widthEntityIds = getLenEntityIds();
cfdp::WidthInBytes widthSeqNum = getLenSeqNum();
seqNumRaw = static_cast<uint8_t *>(sourceIdRaw) + static_cast<uint8_t>(widthEntityIds);
destIdRaw = static_cast<uint8_t *>(seqNumRaw) + static_cast<uint8_t>(widthSeqNum);
if (getWholePduSize() > PduHeaderReader::getHeaderSize()) {
pointers.dataFieldStart = reinterpret_cast<const uint8_t *>(destIdRaw) + widthEntityIds;
} else {
pointers.dataFieldStart = nullptr;
}
return returnvalue::OK;
}
ReturnValue_t PduHeaderReader::setData(uint8_t *dataPtr, size_t maxSize_, void *args) {
if (dataPtr == nullptr) {
return returnvalue::FAILED;
}
if (maxSize_ < 7) {
return SerializeIF::STREAM_TOO_SHORT;
}
pointers.rawPtr = dataPtr;
maxSize = maxSize_;
return returnvalue::OK;
}
size_t PduHeaderReader::getHeaderSize() const {
if (pointers.fixedHeader != nullptr) {
return getLenEntityIds() * 2 + getLenSeqNum() + 4;
}
return 0;
}
size_t PduHeaderReader::getPduDataFieldLen() const {
return (pointers.fixedHeader->pduDataFieldLenH << 8) | pointers.fixedHeader->pduDataFieldLenL;
}
size_t PduHeaderReader::getWholePduSize() const {
return getPduDataFieldLen() + PduHeaderReader::getHeaderSize();
}
cfdp::PduType PduHeaderReader::getPduType() const {
return static_cast<cfdp::PduType>((pointers.fixedHeader->firstByte >> 4) & 0x01);
}
cfdp::Direction PduHeaderReader::getDirection() const {
return static_cast<cfdp::Direction>((pointers.fixedHeader->firstByte >> 3) & 0x01);
}
cfdp::TransmissionMode PduHeaderReader::getTransmissionMode() const {
return static_cast<cfdp::TransmissionMode>((pointers.fixedHeader->firstByte >> 2) & 0x01);
}
bool PduHeaderReader::getCrcFlag() const { return (pointers.fixedHeader->firstByte >> 1) & 0x01; }
bool PduHeaderReader::getLargeFileFlag() const { return pointers.fixedHeader->firstByte & 0x01; }
cfdp::SegmentationControl PduHeaderReader::getSegmentationControl() const {
return static_cast<cfdp::SegmentationControl>((pointers.fixedHeader->fourthByte >> 7) & 0x01);
}
cfdp::WidthInBytes PduHeaderReader::getLenEntityIds() const {
return static_cast<cfdp::WidthInBytes>(((pointers.fixedHeader->fourthByte >> 4) & 0b111) + 1);
}
cfdp::WidthInBytes PduHeaderReader::getLenSeqNum() const {
return static_cast<cfdp::WidthInBytes>((pointers.fixedHeader->fourthByte & 0b111) + 1);
}
cfdp::SegmentMetadataFlag PduHeaderReader::getSegmentMetadataFlag() const {
return static_cast<cfdp::SegmentMetadataFlag>((pointers.fixedHeader->fourthByte >> 3) & 0x01);
}
void PduHeaderReader::getSourceId(cfdp::EntityId &sourceId) const {
assignVarLenField(dynamic_cast<cfdp::VarLenField *>(&sourceId), getLenEntityIds(),
this->sourceIdRaw);
}
void PduHeaderReader::getDestId(cfdp::EntityId &destId) const {
assignVarLenField(dynamic_cast<cfdp::VarLenField *>(&destId), getLenEntityIds(), this->destIdRaw);
}
void PduHeaderReader::getTransactionSeqNum(cfdp::TransactionSeqNum &seqNum) const {
assignVarLenField(dynamic_cast<cfdp::VarLenField *>(&seqNum), getLenSeqNum(), this->seqNumRaw);
}
void PduHeaderReader::assignVarLenField(cfdp::VarLenField *field, cfdp::WidthInBytes width,
void *sourcePtr) {
switch (width) {
case (cfdp::WidthInBytes::ONE_BYTE): {
auto *fieldTyped = static_cast<uint8_t *>(sourcePtr);
field->setValueAndWidth(width, *fieldTyped);
break;
}
case (cfdp::WidthInBytes::TWO_BYTES): {
uint16_t fieldTyped = 0;
size_t deserSize = 0;
SerializeAdapter::deSerialize(&fieldTyped, static_cast<uint8_t *>(sourcePtr), &deserSize,
SerializeIF::Endianness::NETWORK);
field->setValueAndWidth(width, fieldTyped);
break;
}
case (cfdp::WidthInBytes::FOUR_BYTES): {
uint32_t fieldTyped = 0;
size_t deserSize = 0;
SerializeAdapter::deSerialize(&fieldTyped, static_cast<uint8_t *>(sourcePtr), &deserSize,
SerializeIF::Endianness::NETWORK);
field->setValueAndWidth(width, fieldTyped);
break;
}
case (cfdp::WidthInBytes::EIGHT_BYTES): {
uint64_t fieldTyped = 0;
size_t deserSize = 0;
SerializeAdapter::deSerialize(&fieldTyped, static_cast<uint8_t *>(sourcePtr), &deserSize,
SerializeIF::Endianness::NETWORK);
field->setValueAndWidth(width, fieldTyped);
break;
}
}
}
size_t PduHeaderReader::getMaxSize() const { return maxSize; }
bool PduHeaderReader::hasSegmentMetadataFlag() const {
if (this->getSegmentMetadataFlag() == cfdp::SegmentMetadataFlag::PRESENT) {
return true;
}
return false;
}
ReturnValue_t PduHeaderReader::setReadOnlyData(const uint8_t *dataPtr, size_t maxSize_) {
return setData(const_cast<uint8_t *>(dataPtr), maxSize_, nullptr);
}
bool PduHeaderReader::isNull() const {
return pointers.rawPtr == nullptr or pointers.fixedHeader == nullptr;
}
PduHeaderReader::operator bool() const { return not isNull(); }
void PduHeaderReader::fillConfig(PduConfig &cfg) const {
cfg.largeFile = getLargeFileFlag();
cfg.crcFlag = getCrcFlag();
cfg.mode = getTransmissionMode();
cfg.direction = getDirection();
getTransactionSeqNum(cfg.seqNum);
getSourceId(cfg.sourceId);
getDestId(cfg.destId);
}
const uint8_t *PduHeaderReader::getPduDataField() const { return pointers.dataFieldStart; }

View File

@ -0,0 +1,117 @@
#include "HeaderSerializer.h"
#include "HeaderDeserializer.h"
HeaderSerializer::HeaderSerializer(PduConfig &pduConf, cfdp::PduType pduType,
size_t initPduDataFieldLen,
cfdp::SegmentMetadataFlag segmentMetadataFlag,
cfdp::SegmentationControl segCtrl)
: pduType(pduType),
segmentMetadataFlag(segmentMetadataFlag),
segmentationCtrl(segCtrl),
pduDataFieldLen(initPduDataFieldLen),
pduConf(pduConf) {}
ReturnValue_t HeaderSerializer::serialize(uint8_t **buffer, size_t *size, size_t maxSize,
Endianness streamEndianness) const {
if (buffer == nullptr or size == nullptr) {
return returnvalue::FAILED;
}
if (maxSize < this->getSerializedSize()) {
return BUFFER_TOO_SHORT;
}
**buffer = cfdp::VERSION_BITS | this->pduType << 4 | pduConf.direction << 3 | pduConf.mode << 2 |
pduConf.crcFlag << 1 | pduConf.largeFile;
*buffer += 1;
**buffer = (pduDataFieldLen & 0xff00) >> 8;
*buffer += 1;
**buffer = pduDataFieldLen & 0x00ff;
*buffer += 1;
**buffer = segmentationCtrl << 7 | pduConf.sourceId.getWidth() << 4 | segmentMetadataFlag << 3 |
pduConf.seqNum.getWidth();
*buffer += 1;
*size += 4;
ReturnValue_t result = pduConf.sourceId.serialize(buffer, size, maxSize, streamEndianness);
if (result != returnvalue::OK) {
return result;
}
result = pduConf.seqNum.serialize(buffer, size, maxSize, streamEndianness);
if (result != returnvalue::OK) {
return result;
}
result = pduConf.destId.serialize(buffer, size, maxSize, streamEndianness);
if (result != returnvalue::OK) {
return result;
}
return returnvalue::OK;
}
size_t HeaderSerializer::getSerializedSize() const {
size_t shit = pduConf.seqNum.getWidth() + pduConf.sourceId.getWidth() * 2 + 4;
return shit;
}
ReturnValue_t HeaderSerializer::deSerialize(const uint8_t **buffer, size_t *size,
Endianness streamEndianness) {
// We could implement this, but I prefer dedicated classes
return returnvalue::FAILED;
}
size_t HeaderSerializer::getWholePduSize() const {
// Return size of header plus the PDU data field length
return pduDataFieldLen + HeaderSerializer::getSerializedSize();
}
size_t HeaderSerializer::getPduDataFieldLen() const { return pduDataFieldLen; }
void HeaderSerializer::setPduDataFieldLen(size_t pduDataFieldLen) {
this->pduDataFieldLen = pduDataFieldLen;
}
void HeaderSerializer::setPduType(cfdp::PduType pduType) { this->pduType = pduType; }
void HeaderSerializer::setSegmentMetadataFlag(cfdp::SegmentMetadataFlag segmentMetadataFlag) {
this->segmentMetadataFlag = segmentMetadataFlag;
}
cfdp::PduType HeaderSerializer::getPduType() const { return pduType; }
cfdp::Direction HeaderSerializer::getDirection() const { return pduConf.direction; }
cfdp::TransmissionModes HeaderSerializer::getTransmissionMode() const { return pduConf.mode; }
bool HeaderSerializer::getCrcFlag() const { return pduConf.crcFlag; }
bool HeaderSerializer::getLargeFileFlag() const { return pduConf.largeFile; }
cfdp::SegmentationControl HeaderSerializer::getSegmentationControl() const {
return segmentationCtrl;
}
cfdp::WidthInBytes HeaderSerializer::getLenEntityIds() const { return pduConf.sourceId.getWidth(); }
cfdp::WidthInBytes HeaderSerializer::getLenSeqNum() const { return pduConf.seqNum.getWidth(); }
cfdp::SegmentMetadataFlag HeaderSerializer::getSegmentMetadataFlag() const {
return segmentMetadataFlag;
}
void HeaderSerializer::getSourceId(cfdp::EntityId &sourceId) const { sourceId = pduConf.sourceId; }
void HeaderSerializer::getDestId(cfdp::EntityId &destId) const { destId = pduConf.destId; }
void HeaderSerializer::setSegmentationControl(cfdp::SegmentationControl segmentationControl) {
this->segmentationCtrl = segmentationControl;
}
void HeaderSerializer::getTransactionSeqNum(cfdp::TransactionSeqNum &seqNum) const {
seqNum = pduConf.seqNum;
}
bool HeaderSerializer::hasSegmentMetadataFlag() const {
if (this->segmentMetadataFlag == cfdp::SegmentMetadataFlag::PRESENT) {
return true;
}
return false;
}

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