Compare commits

..

1 Commits

Author SHA1 Message Date
Jakob Meier
b0b75b85a9 Merge branch 'meier/sequenceCount' into meier/develop 2022-05-11 16:54:06 +02:00
1091 changed files with 16313 additions and 27017 deletions

8
.gitignore vendored
View File

@ -1,14 +1,6 @@
# PyCharm and CLion
.idea/*
!/.idea/runConfigurations
!/.idea/cmake.xml
!/.idea/codeStyles
# Eclipse
.cproject .cproject
.project .project
.settings .settings
.metadata .metadata
/build* /build*
/cmake-build*

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

@ -1,14 +0,0 @@
<component name="ProjectCodeStyleConfiguration">
<code_scheme name="Project" version="173">
<clangFormatSettings>
<option name="ENABLED" value="true" />
</clangFormatSettings>
<codeStyleSettings language="CMake">
<indentOptions>
<option name="INDENT_SIZE" value="2" />
<option name="CONTINUATION_INDENT_SIZE" value="0" />
<option name="TAB_SIZE" value="2" />
</indentOptions>
</codeStyleSettings>
</code_scheme>
</component>

View File

@ -1,5 +0,0 @@
<component name="ProjectCodeStyleConfiguration">
<state>
<option name="USE_PER_PROJECT_SETTINGS" value="true" />
</state>
</component>

View File

@ -8,267 +8,25 @@ and this project adheres to [Semantic Versioning](http://semver.org/).
# [unreleased] # [unreleased]
## Fixes # [v5.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
- add CFDP subsystem ID
https://egit.irs.uni-stuttgart.de/fsfw/fsfw/pulls/742
- `PusTmZcWriter` now exposes API to set message counter field.
- Relative timeshift in the PUS time service.
## Changed
- The PUS time service now dumps the time before setting a new time and after having set the
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
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`, - HAL Linux SPI: Set the Clock Default State when setting new SPI speed
service ID customizable now. `CServiceHealthCommanding` expects configuration struct and mode
`HealthServiceCfg` now PR: https://egit.irs.uni-stuttgart.de/fsfw/fsfw/pulls/573
PR: https://egit.irs.uni-stuttgart.de/fsfw/fsfw/pulls/725 - GPIO HAL: `Direction`, `GpioOperation` and `Levels` are enum classes now, which prevents
- `AcceptsTelemetryIF`: `getReportReceptionQueue` is const now name clashes with Windows defines.
PR: https://egit.irs.uni-stuttgart.de/fsfw/fsfw/pulls/712 PR: https://egit.irs.uni-stuttgart.de/fsfw/fsfw/pulls/572
- 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`
constants.
PR: https://egit.irs.uni-stuttgart.de/fsfw/fsfw/pulls/659
- Overhaul of the TMTC stack, including various changes and improvements
for other modules
PR: https://egit.irs.uni-stuttgart.de/fsfw/fsfw/pulls/655
which also includes a migration guide
- 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
## 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
- Renamed auto-formatting script to `auto-formatter.sh` and made it more robust.
If `cmake-format` is installed, it will also auto-format the `CMakeLists.txt` files now.
PR: https://egit.irs.uni-stuttgart.de/fsfw/fsfw/pulls/625
PR: https://egit.irs.uni-stuttgart.de/fsfw/fsfw/pulls/626
- Bump C++ required version to C++17. Every project which uses the FSFW and every modern
compiler supports it
PR: https://egit.irs.uni-stuttgart.de/fsfw/fsfw/pulls/622
- New CMake option `FSFW_HAL_LINUX_ADD_LIBGPIOD` to specifically exclude `gpiod` code. - New CMake option `FSFW_HAL_LINUX_ADD_LIBGPIOD` to specifically exclude `gpiod` code.
PR: https://egit.irs.uni-stuttgart.de/fsfw/fsfw/pulls/572 PR: https://egit.irs.uni-stuttgart.de/fsfw/fsfw/pulls/572
- HAL Devicehandlers: Periodic printout is run-time configurable now - HAL Devicehandlers: Periodic printout is run-time configurable now
- `oneShotAction` flag in the `TestTask` class is not static anymore - `oneShotAction` flag in the `TestTask` class is not static anymore
- `SimpleRingBuffer::writeData` now checks if the amount is larger than the total size of the - HAL Linux Uart: Baudrate and bits per word are enums now, avoiding misconfigurations
Buffer and rejects such writeData calls with `returnvalue::FAILED` PR: https://egit.irs.uni-stuttgart.de/fsfw/fsfw/pulls/585
PR: https://egit.irs.uni-stuttgart.de/fsfw/fsfw/pulls/586
- Major update for version handling, using `git describe` to fetch version information with git. - Major update for version handling, using `git describe` to fetch version information with git.
PR: https://egit.irs.uni-stuttgart.de/fsfw/fsfw/pulls/601 PR: https://egit.irs.uni-stuttgart.de/fsfw/fsfw/pulls/601
- Place `Version` class outside of `fsfw` namespace. It is generic
- Add helper functions provided by [`cmake-modules`](https://github.com/bilke/cmake-modules) - Add helper functions provided by [`cmake-modules`](https://github.com/bilke/cmake-modules)
manually now. Those should not change too often and only a small subset is needed manually now. Those should not change too often and only a small subset is needed
- Separate folder for easier update and for distinction - Separate folder for easier update and for distinction
@ -284,75 +42,13 @@ and this project adheres to [Semantic Versioning](http://semver.org/).
creation call. It allows passing context information and an arbitrary user argument into creation call. It allows passing context information and an arbitrary user argument into
the message queue. Also streamlined and simplified `MessageQueue` implementation for all OSALs the message queue. Also streamlined and simplified `MessageQueue` implementation for all OSALs
PR: https://egit.irs.uni-stuttgart.de/fsfw/fsfw/pulls/583 PR: https://egit.irs.uni-stuttgart.de/fsfw/fsfw/pulls/583
- Internal API change: Moved the `fsfw_hal` to the `src` folder and integration and internal - Clock:
tests part of `fsfw_tests` to `src`. Unittests are now in a dedicated folder called `unittests`
PR: https://egit.irs.uni-stuttgart.de/fsfw/fsfw/pulls/653
### Task Module Refactoring
PR: https://egit.irs.uni-stuttgart.de/fsfw/fsfw/pulls/636
**Refactoring general task code**
- There was a lot of duplicate/boilerplate code inside the individual task IF OSAL implementations.
Remove it by introducing base classes `PeriodicTaskBase` and `FixedTimeslotTaskBase`.
**Refactor PeriodicTaskIF**
- Convert `virtual ReturnValue_t addComponent(object_id_t object)` to
`virtual ReturnValue_t addComponent(object_id_t object, uint8_t opCode = 0)`, allowing to pass
the operation code passed to `performOperation`. Updated API taking
an `ExecutableObjectIF` accordingly
**Refactor FixedTimeslotTaskIF**
- Add additional `addSlot` function which takes an `ExecutableObjectIF` pointer and its Object ID
**Refactor FixedSequenceSlot**
- Introduce typedef `CustomCheckFunc` for `ReturnValue_t (*customCheckFunction)(const SlotList&)`.
- Convert `ReturnValue_t (*customCheckFunction)(const SlotList&)` to
`ReturnValue_t (*customCheckFunction)(const SlotList&, void*)`, allowing arbitrary user arguments
for the custom checker
**Linux Task Module**
- Use composition instead of inheritance for the `PeriodicPosixTask` and make the `PosixTask` a
member of the class
### HAL
- HAL Linux Uart: Baudrate and bits per word are enums now, avoiding misconfigurations
PR: https://egit.irs.uni-stuttgart.de/fsfw/fsfw/pulls/585
- HAL Linux SPI: Set the Clock Default State when setting new SPI speed
and mode
PR: https://egit.irs.uni-stuttgart.de/fsfw/fsfw/pulls/573
- GPIO HAL: `Direction`, `GpioOperation` and `Levels` are enum classes now, which prevents
name clashes with Windows defines.
PR: https://egit.irs.uni-stuttgart.de/fsfw/fsfw/pulls/572
- HAL Linux Uart: Baudrate and bits per word are enums now, avoiding misconfigurations
PR: https://egit.irs.uni-stuttgart.de/fsfw/fsfw/pulls/585
### Time
PR: https://egit.irs.uni-stuttgart.de/fsfw/fsfw/pulls/584 and
https://egit.irs.uni-stuttgart.de/fsfw/fsfw/pulls/593
- `timeval` to `TimeOfDay_t` - `timeval` to `TimeOfDay_t`
- Added Mutex for gmtime calls: (compare http://www.opengate.at/blog/2020/01/timeless/) - Added Mutex for gmtime calls: (compare http://www.opengate.at/blog/2020/01/timeless/)
- Moved the statics used by Clock in ClockCommon.cpp to this file - Moved the statics used by Clock in ClockCommon.cpp to this file
- Better check for leap seconds - Better check for leap seconds
- Added Unittests for Clock (only getter) - Added Unittests for Clock (only getter)
### Power
- `PowerSwitchIF`: Remove `const` specifier from `sendSwitchCommand` and `sendFuseOnCommand` and
also specify a `ReturnValue_t` return type
PR: https://egit.irs.uni-stuttgart.de/fsfw/fsfw/pulls/590
- Extend `PowerSwitcher` module to optionally check current state when calling `turnOn` or
`turnOff`. Tis can be helpful to avoid commanding switches which do not need commanding
PR: https://egit.irs.uni-stuttgart.de/fsfw/fsfw/pulls/590
## Removed ## Removed
- Removed the `HkSwitchHelper`. This module should not be needed anymore, now that the local - Removed the `HkSwitchHelper`. This module should not be needed anymore, now that the local
@ -361,52 +57,15 @@ https://egit.irs.uni-stuttgart.de/fsfw/fsfw/pulls/593
## Additions ## Additions
- New constructor for PoolEntry which allows to simply specify the length of the pool entry.
This is also the new default constructor for scalar value with 0 as an initial value
- Added options for CI/CD builds: `FSFW_CICD_BUILD`. This allows the source code to know
whether it is running in CI/CD
PR: https://egit.irs.uni-stuttgart.de/fsfw/fsfw/pulls/623
- Basic `clion` support: Update `.gitignore` and add some basic run configurations
PR: https://egit.irs.uni-stuttgart.de/fsfw/fsfw/pulls/625
- LTO support: Allow using LTO/IPO by setting `FSFW_ENABLE_LTO=1`. CMake is able to detect whether
the user compiler supports IPO/LPO. LTO is on by default now. Most modern compilers support it,
can make good use of it and it usually makes the code faster and/or smaller.
After some more research:
Enabling LTO will actually cause the compiler to only produce thin LTO by adding
`-flto -fno-fat-lto-objects` to the compiler options. I am not sure this is an ideal choice
because if an application linking against the FSFW does not use LTO, there can be compile
issues (e.g. observed when compiling the FSFW tests without LTO). This is a known issue as
can be seen in the multiple CMake issues for it:
- https://gitlab.kitware.com/cmake/cmake/-/issues/22913,
- https://gitlab.kitware.com/cmake/cmake/-/issues/16808,
- https://gitlab.kitware.com/cmake/cmake/-/issues/21696
Easiest solution for now: Keep this option OFF by default.
PR: https://egit.irs.uni-stuttgart.de/fsfw/fsfw/pulls/616
- Linux HAL: Add wiretapping option for I2C. Enabled with `FSFW_HAL_I2C_WIRETAPPING` defined to 1 - 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
- Added generic PUS TC Scheduler Service 11. It depends on the new added Emebeded Template Library
(ETL) dependency.
PR: https://egit.irs.uni-stuttgart.de/fsfw/fsfw/pulls/594
- Added ETL dependency and improved library dependency management - Added ETL dependency and improved library dependency management
PR: https://egit.irs.uni-stuttgart.de/fsfw/fsfw/pulls/592 PR: https://egit.irs.uni-stuttgart.de/fsfw/fsfw/pulls/592
- Add a `DummyPowerSwitcher` module which can be useful for test setups when no PCDU is available
PR: https://egit.irs.uni-stuttgart.de/fsfw/fsfw/pulls/590
- New typedef for switcher type
PR: https://egit.irs.uni-stuttgart.de/fsfw/fsfw/pulls/590
- `Subsystem`: New API to add table and sequence entries
## Fixed ## Fixed
- TCP TMTC Server: `MutexGuard` was not created properly in
`TcpTmTcServer::handleTmSending(socket_t connSocket, bool& tmSent)` call.
PR: https://egit.irs.uni-stuttgart.de/fsfw/fsfw/pulls/618
- Fix infinite recursion in `prepareHealthSetReply` of PUS Health Service 201.
Is not currently used right now but might be used in the future
PR: https://egit.irs.uni-stuttgart.de/fsfw/fsfw/pulls/617
- Move some CMake directives further up top so they are not ignored
PR: https://egit.irs.uni-stuttgart.de/fsfw/fsfw/pulls/621
- Small bugfix in STM32 HAL for SPI - Small bugfix in STM32 HAL for SPI
PR: https://egit.irs.uni-stuttgart.de/fsfw/fsfw/pulls/599 PR: https://egit.irs.uni-stuttgart.de/fsfw/fsfw/pulls/599
- HAL GPIO: Improved error checking in `LinuxLibgpioIF::configureGpios(...)`. If a GPIO - HAL GPIO: Improved error checking in `LinuxLibgpioIF::configureGpios(...)`. If a GPIO

View File

@ -1,21 +1,68 @@
cmake_minimum_required(VERSION 3.13) cmake_minimum_required(VERSION 3.13)
project(${LIB_FSFW_NAME})
set(MSG_PREFIX "fsfw |") set(FSFW_VERSION_IF_GIT_FAILS 4)
set(FSFW_SUBVERSION_IF_GIT_FAILS 0)
set(FSFW_REVISION_IF_GIT_FAILS 0)
# Add the cmake folder so the FindSphinx module is found # Add the cmake folder so the FindSphinx module is found
list(APPEND CMAKE_MODULE_PATH "${CMAKE_CURRENT_SOURCE_DIR}/cmake" ) list(APPEND CMAKE_MODULE_PATH "${CMAKE_CURRENT_SOURCE_DIR}/cmake" )
list(APPEND CMAKE_MODULE_PATH list(APPEND CMAKE_MODULE_PATH "${CMAKE_CURRENT_SOURCE_DIR}/cmake/cmake-modules")
"${CMAKE_CURRENT_SOURCE_DIR}/cmake/cmake-modules/bilke") set(MSG_PREFIX "fsfw |")
list(APPEND CMAKE_MODULE_PATH
"${CMAKE_CURRENT_SOURCE_DIR}/cmake/cmake-modules/rpavlik")
# ############################################################################## set(FSFW_ETL_LIB_MAJOR_VERSION 20 CACHE STRING
# Version file handling # "ETL library major version requirement"
# ############################################################################## )
set(FSFW_ETL_LIB_VERSION ${FSFW_ETL_LIB_MAJOR_VERSION}.27.3 CACHE STRING
"ETL library exact version requirement"
)
set(FSFW_ETL_LINK_TARGET etl::etl)
set(FSFW_VERSION_IF_GIT_FAILS 6) set(FSFW_CATCH2_LIB_MAJOR_VERSION 3 CACHE STRING
set(FSFW_SUBVERSION_IF_GIT_FAILS 0) "Catch2 library major version requirement"
set(FSFW_REVISION_IF_GIT_FAILS 0) )
set(FSFW_CATCH2_LIB_VERSION v${FSFW_CATCH2_LIB_MAJOR_VERSION}.0.0-preview5 CACHE STRING
"Catch2 library exact version requirement"
)
set(FSFW_ETL_LIB_NAME etl)
option(FSFW_GENERATE_SECTIONS
"Generate function and data sections. Required to remove unused code" ON
)
if(FSFW_GENERATE_SECTIONS)
option(FSFW_REMOVE_UNUSED_CODE "Remove unused code" ON)
endif()
option(FSFW_BUILD_UNITTESTS "Build unittest binary in addition to static library" OFF)
option(FSFW_BUILD_DOCS "Build documentation with Sphinx and Doxygen" OFF)
if(FSFW_BUILD_UNITTESTS)
option(FSFW_TESTS_GEN_COV "Generate coverage data for unittests" ON)
endif()
option(FSFW_WARNING_SHADOW_LOCAL_GCC "Enable -Wshadow=local warning in GCC" ON)
# Options to exclude parts of the FSFW from compilation.
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)
# Optional sources
option(FSFW_ADD_PUS "Compile with PUS sources" ON)
option(FSFW_ADD_MONITORING "Compile with monitoring components" ON)
option(FSFW_ADD_RMAP "Compile with RMAP" OFF)
option(FSFW_ADD_DATALINKLAYER "Compile with Data Link Layer" OFF)
option(FSFW_ADD_COORDINATES "Compile with coordinate components" OFF)
option(FSFW_ADD_TMSTORAGE "Compile with tm storage components" OFF)
# Contrib sources
option(FSFW_ADD_SGP4_PROPAGATOR "Add SGP4 propagator code" OFF)
set(LIB_FSFW_NAME fsfw)
set(FSFW_TEST_TGT fsfw-tests)
set(FSFW_DUMMY_TGT fsfw-dummy)
add_library(${LIB_FSFW_NAME})
set(FSFW_GIT_VER_HANDLING_OK FALSE) set(FSFW_GIT_VER_HANDLING_OK FALSE)
# Version handling # Version handling
@ -24,13 +71,11 @@ if(EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/.git)
include(FsfwHelpers) include(FsfwHelpers)
determine_version_with_git("--exclude" "docker_*") determine_version_with_git("--exclude" "docker_*")
if(GIT_INFO) if(GIT_INFO)
set(FSFW_GIT_INFO set(FSFW_GIT_INFO ${GIT_INFO} CACHE STRING "Version information retrieved with git describe")
${GIT_INFO}
CACHE STRING "Version information retrieved with git describe")
list(GET FSFW_GIT_INFO 1 FSFW_VERSION) list(GET FSFW_GIT_INFO 1 FSFW_VERSION)
list(GET FSFW_GIT_INFO 2 FSFW_SUBVERSION) list(GET FSFW_GIT_INFO 2 FSFW_SUBVERSION)
list(GET FSFW_GIT_INFO 3 FSFW_REVISION) list(GET FSFW_GIT_INFO 3 FSFW_REVISION)
list(GET FSFW_GIT_INFO 4 FSFW_VCS_INFO) list(GET FSFW_GIT_INFO 4 FSFW_VERSION_CST_GIT_SHA1)
if(NOT FSFW_VERSION) if(NOT FSFW_VERSION)
set(FSFW_VERSION ${FSFW_VERSION_IF_GIT_FAILS}) set(FSFW_VERSION ${FSFW_VERSION_IF_GIT_FAILS})
endif() endif()
@ -51,165 +96,57 @@ if(NOT FSFW_GIT_VER_HANDLING_OK)
set(FSFW_REVISION ${FSFW_REVISION_IF_GIT_FAILS}) set(FSFW_REVISION ${FSFW_REVISION_IF_GIT_FAILS})
endif() endif()
set(LIB_FSFW_NAME fsfw) if(FSFW_BUILD_UNITTESTS)
project(${LIB_FSFW_NAME} message(STATUS "${MSG_PREFIX} Building the FSFW unittests in addition to the static library")
VERSION ${FSFW_VERSION}.${FSFW_SUBVERSION}.${FSFW_REVISION})
if(NOT CMAKE_CXX_STANDARD)
set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED True)
elseif(${CMAKE_CXX_STANDARD} LESS 17)
message(
FATAL_ERROR
"${MSG_PREFIX} Compiling the FSFW requires a minimum of C++17 support")
endif()
set(FSFW_SOURCES_DIR "${CMAKE_SOURCE_DIR}/src/fsfw")
set(FSFW_ETL_LIB_NAME etl)
set(FSFW_ETL_LINK_TARGET etl::etl)
set(FSFW_ETL_LIB_MAJOR_VERSION
20
CACHE STRING "ETL library major version requirement")
set(FSFW_ETL_LIB_VERSION
${FSFW_ETL_LIB_MAJOR_VERSION}.35.14
CACHE STRING "ETL library exact version requirement")
set(FSFW_ETL_LINK_TARGET etl::etl)
set(FSFW_CATCH2_LIB_MAJOR_VERSION
3
CACHE STRING "Catch2 library major version requirement")
set(FSFW_CATCH2_LIB_VERSION
v${FSFW_CATCH2_LIB_MAJOR_VERSION}.1.0
CACHE STRING "Catch2 library exact version requirement")
# Keep this off by default for now. See PR:
# https://egit.irs.uni-stuttgart.de/fsfw/fsfw/pulls/616 for information which
# keeping this on by default is problematic
option(
FSFW_ENABLE_IPO
"Enable interprocedural optimization or link-time optimization if available"
OFF)
if(FSFW_ENABLE_IPO)
include(CheckIPOSupported)
check_ipo_supported(RESULT IPO_SUPPORTED OUTPUT IPO_ERROR)
if(NOT IPO_SUPPORTED)
message(STATUS "FSFW | IPO/LTO not supported: ${IPO_ERROR}")
endif()
endif()
option(FSFW_GENERATE_SECTIONS
"Generate function and data sections. Required to remove unused code" ON)
if(FSFW_GENERATE_SECTIONS)
option(FSFW_REMOVE_UNUSED_CODE "Remove unused code" ON)
endif()
option(FSFW_BUILD_TESTS
"Build unittest binary in addition to static library. Requires Catch2"
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)
if(FSFW_BUILD_TESTS)
option(FSFW_TESTS_GEN_COV "Generate coverage data for unittests" ON)
endif()
option(FSFW_WARNING_SHADOW_LOCAL_GCC "Enable -Wshadow=local warning in GCC" ON)
# Options to exclude parts of the FSFW from compilation.
option(FSFW_ADD_INTERNAL_TESTS "Add internal unit tests" ON)
option(FSFW_ADD_HAL "Add Hardware Abstraction Layer" ON)
if(UNIX)
option(FSFW_HAL_LINUX_ADD_PERIPHERAL_DRIVERS "Add Linux peripheral 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()
# Optional sources
option(FSFW_ADD_PUS "Compile with PUS sources" ON)
option(FSFW_ADD_MONITORING "Compile with monitoring components" ON)
option(FSFW_ADD_RMAP "Compile with RMAP" OFF)
option(FSFW_ADD_DATALINKLAYER "Compile with Data Link Layer" OFF)
option(FSFW_ADD_COORDINATES "Compile with coordinate components" OFF)
option(FSFW_ADD_TMSTORAGE "Compile with tm storage components" OFF)
# Contrib sources
option(FSFW_ADD_SGP4_PROPAGATOR "Add SGP4 propagator code" OFF)
set(FSFW_TEST_TGT fsfw-tests)
set(FSFW_DUMMY_TGT fsfw-dummy)
add_library(${LIB_FSFW_NAME})
if(IPO_SUPPORTED AND FSFW_ENABLE_IPO)
set_property(TARGET ${LIB_FSFW_NAME} PROPERTY INTERPROCEDURAL_OPTIMIZATION
TRUE)
endif()
if(FSFW_BUILD_TESTS)
message(
STATUS
"${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} CONFIG QUIET)
# 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 "${MSG_PREFIX} Catch2 installation not found. Downloading Catch2 library with FetchContent")
STATUS
"${MSG_PREFIX} Catch2 installation not found. Downloading Catch2 library with FetchContent."
)
include(FetchContent) include(FetchContent)
FetchContent_Declare( FetchContent_Declare(
Catch2 Catch2
GIT_REPOSITORY https://github.com/catchorg/Catch2.git GIT_REPOSITORY https://github.com/catchorg/Catch2.git
GIT_TAG ${FSFW_CATCH2_LIB_VERSION}) GIT_TAG ${FSFW_CATCH2_LIB_VERSION}
)
list(APPEND FSFW_FETCH_CONTENT_TARGETS Catch2) list(APPEND FSFW_FETCH_CONTENT_TARGETS Catch2)
endif() endif()
set(FSFW_CONFIG_PATH unittests/testcfg) set(FSFW_CONFIG_PATH tests/src/fsfw_tests/unit/testcfg)
configure_file(unittests/testcfg/FSFWConfig.h.in FSFWConfig.h) configure_file(tests/src/fsfw_tests/unit/testcfg/FSFWConfig.h.in FSFWConfig.h)
configure_file(unittests/testcfg/TestsConfig.h.in tests/TestsConfig.h) configure_file(tests/src/fsfw_tests/unit/testcfg/TestsConfig.h.in tests/TestsConfig.h)
project(${FSFW_TEST_TGT} CXX C) project(${FSFW_TEST_TGT} CXX C)
add_executable(${FSFW_TEST_TGT}) add_executable(${FSFW_TEST_TGT})
if(IPO_SUPPORTED AND FSFW_ENABLE_IPO)
set_property(TARGET ${FSFW_TEST_TGT} PROPERTY INTERPROCEDURAL_OPTIMIZATION
TRUE)
endif()
if(FSFW_TESTS_GEN_COV) if(FSFW_TESTS_GEN_COV)
message(STATUS "${MSG_PREFIX} Generating coverage data for the library") message(STATUS "${MSG_PREFIX} Generating coverage data for the library")
message(STATUS "${MSG_PREFIX} Targets linking against ${LIB_FSFW_NAME} " message(STATUS "${MSG_PREFIX} Targets linking against ${LIB_FSFW_NAME} "
"will be compiled with coverage data as well") "will be compiled with coverage data as well"
)
set(CMAKE_BUILD_TYPE "Debug") set(CMAKE_BUILD_TYPE "Debug")
include(CodeCoverage) include(CodeCoverage)
endif() endif()
endif() endif()
message( message(STATUS "Finding and/or providing etl library with version ${FSFW_ETL_LIB_MAJOR_VERSION}")
STATUS
"${MSG_PREFIX} Finding and/or providing etl library with version ${FSFW_ETL_LIB_MAJOR_VERSION}"
)
# 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 "No ETL installation was found with find_package. Installing and providing "
"${MSG_PREFIX} ETL installation not found. Downloading ETL with FetchContent." "etl with FindPackage"
) )
include(FetchContent) include(FetchContent)
FetchContent_Declare( FetchContent_Declare(
${FSFW_ETL_LIB_NAME} ${FSFW_ETL_LIB_NAME}
GIT_REPOSITORY https://github.com/ETLCPP/etl GIT_REPOSITORY https://github.com/ETLCPP/etl
GIT_TAG ${FSFW_ETL_LIB_VERSION}) GIT_TAG ${FSFW_ETL_LIB_VERSION}
)
list(APPEND FSFW_FETCH_CONTENT_TARGETS ${FSFW_ETL_LIB_NAME}) list(APPEND FSFW_FETCH_CONTENT_TARGETS ${FSFW_ETL_LIB_NAME})
endif() endif()
@ -222,8 +159,8 @@ if(FSFW_FETCH_CONTENT_TARGETS)
add_library(${FSFW_ETL_LINK_TARGET} ALIAS ${FSFW_ETL_LIB_NAME}) add_library(${FSFW_ETL_LINK_TARGET} ALIAS ${FSFW_ETL_LIB_NAME})
endif() endif()
if(TARGET Catch2) if(TARGET Catch2)
# Fixes regression -preview4, to be confirmed in later releases Related # Fixes regression -preview4, to be confirmed in later releases
# GitHub issue: https://github.com/catchorg/Catch2/issues/2417 # Related GitHub issue: https://github.com/catchorg/Catch2/issues/2417
set_target_properties(Catch2 PROPERTIES DEBUG_POSTFIX "") set_target_properties(Catch2 PROPERTIES DEBUG_POSTFIX "")
endif() endif()
endif() endif()
@ -233,30 +170,40 @@ set(FSFW_CORE_INC_PATH "inc")
set_property(CACHE FSFW_OSAL PROPERTY STRINGS host linux rtems freertos) set_property(CACHE FSFW_OSAL PROPERTY STRINGS host linux rtems freertos)
# For configure files # For configure files
target_include_directories(${LIB_FSFW_NAME} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}) target_include_directories(${LIB_FSFW_NAME} PRIVATE
target_include_directories(${LIB_FSFW_NAME} ${CMAKE_CURRENT_BINARY_DIR}
INTERFACE ${CMAKE_CURRENT_BINARY_DIR}) )
target_include_directories(${LIB_FSFW_NAME} INTERFACE
${CMAKE_CURRENT_BINARY_DIR}
)
if(NOT CMAKE_CXX_STANDARD)
set(CMAKE_CXX_STANDARD 11)
set(CMAKE_CXX_STANDARD_REQUIRED True)
elseif(${CMAKE_CXX_STANDARD} LESS 11)
message(FATAL_ERROR "${MSG_PREFIX} Compiling the FSFW requires a minimum of C++11 support")
endif()
# Backwards comptability # Backwards comptability
if(OS_FSFW AND NOT FSFW_OSAL) if(OS_FSFW AND NOT FSFW_OSAL)
message( message(WARNING "${MSG_PREFIX} Please pass the FSFW OSAL as FSFW_OSAL instead of OS_FSFW")
WARNING
"${MSG_PREFIX} Please pass the FSFW OSAL as FSFW_OSAL instead of OS_FSFW")
set(FSFW_OSAL OS_FSFW) set(FSFW_OSAL OS_FSFW)
endif() endif()
if(NOT FSFW_OSAL) if(NOT FSFW_OSAL)
message(STATUS "No OS for FSFW via FSFW_OSAL set. Assuming host OS") message(STATUS "${MSG_PREFIX} No OS for FSFW via FSFW_OSAL set. Assuming host OS")
# Assume host OS and autodetermine from OS_FSFW # Assume host OS and autodetermine from OS_FSFW
if(UNIX) if(UNIX)
set(FSFW_OSAL set(FSFW_OSAL "linux"
"linux" CACHE STRING
CACHE STRING "OS abstraction layer used in the FSFW") "OS abstraction layer used in the FSFW"
)
elseif(WIN32) elseif(WIN32)
set(FSFW_OSAL set(FSFW_OSAL "host"
"host" CACHE STRING "OS abstraction layer used in the FSFW"
CACHE STRING "OS abstraction layer used in the FSFW") )
endif() endif()
endif() endif()
set(FSFW_OSAL_DEFINITION FSFW_OSAL_HOST) set(FSFW_OSAL_DEFINITION FSFW_OSAL_HOST)
@ -270,13 +217,14 @@ elseif(FSFW_OSAL MATCHES linux)
elseif(FSFW_OSAL MATCHES freertos) elseif(FSFW_OSAL MATCHES freertos)
set(FSFW_OS_NAME "FreeRTOS") set(FSFW_OS_NAME "FreeRTOS")
set(FSFW_OSAL_FREERTOS ON) set(FSFW_OSAL_FREERTOS ON)
target_link_libraries(${LIB_FSFW_NAME} PRIVATE ${LIB_OS_NAME}) target_link_libraries(${LIB_FSFW_NAME} PRIVATE
${LIB_OS_NAME}
)
elseif(FSFW_OSAL STREQUAL rtems) elseif(FSFW_OSAL STREQUAL rtems)
set(FSFW_OS_NAME "RTEMS") set(FSFW_OS_NAME "RTEMS")
set(FSFW_OSAL_RTEMS ON) set(FSFW_OSAL_RTEMS ON)
else() else()
message( message(WARNING
WARNING
"${MSG_PREFIX} Invalid operating system for FSFW specified! Setting to host.." "${MSG_PREFIX} Invalid operating system for FSFW specified! Setting to host.."
) )
set(FSFW_OS_NAME "Host") set(FSFW_OS_NAME "Host")
@ -286,114 +234,113 @@ endif()
configure_file(src/fsfw/FSFW.h.in fsfw/FSFW.h) configure_file(src/fsfw/FSFW.h.in fsfw/FSFW.h)
configure_file(src/fsfw/FSFWVersion.h.in fsfw/FSFWVersion.h) configure_file(src/fsfw/FSFWVersion.h.in fsfw/FSFWVersion.h)
message( message(STATUS "${MSG_PREFIX} Compiling FSFW for the ${FSFW_OS_NAME} operating system")
STATUS "${MSG_PREFIX} Compiling FSFW for the ${FSFW_OS_NAME} operating system"
)
add_subdirectory(src) add_subdirectory(src)
add_subdirectory(contrib) add_subdirectory(tests)
if(FSFW_BUILD_TESTS) if(FSFW_ADD_HAL)
add_subdirectory(unittests) add_subdirectory(hal)
endif() endif()
add_subdirectory(contrib)
if(FSFW_BUILD_DOCS) if(FSFW_BUILD_DOCS)
add_subdirectory(docs) add_subdirectory(docs)
endif() endif()
if(FSFW_BUILD_TESTS) if(FSFW_BUILD_UNITTESTS)
if(FSFW_TESTS_GEN_COV) if(FSFW_TESTS_GEN_COV)
if(CMAKE_COMPILER_IS_GNUCXX) if(CMAKE_COMPILER_IS_GNUCXX)
include(CodeCoverage) include(CodeCoverage)
# Remove quotes. # Remove quotes.
separate_arguments(COVERAGE_COMPILER_FLAGS NATIVE_COMMAND separate_arguments(COVERAGE_COMPILER_FLAGS
"${COVERAGE_COMPILER_FLAGS}") NATIVE_COMMAND "${COVERAGE_COMPILER_FLAGS}"
)
# Add compile options manually, we don't want coverage for Catch2 # Add compile options manually, we don't want coverage for Catch2
target_compile_options(${FSFW_TEST_TGT} target_compile_options(${FSFW_TEST_TGT} PRIVATE
PRIVATE "${COVERAGE_COMPILER_FLAGS}") "${COVERAGE_COMPILER_FLAGS}"
target_compile_options(${LIB_FSFW_NAME} )
PRIVATE "${COVERAGE_COMPILER_FLAGS}") target_compile_options(${LIB_FSFW_NAME} PRIVATE
"${COVERAGE_COMPILER_FLAGS}"
)
# Exclude directories here # Exclude directories here
if(WIN32) if(WIN32)
set(GCOVR_ADDITIONAL_ARGS "--exclude-throw-branches" set(GCOVR_ADDITIONAL_ARGS
"--exclude-unreachable-branches") "--exclude-throw-branches"
set(COVERAGE_EXCLUDES "/c/msys64/mingw64/*" "*/fsfw_hal/*") "--exclude-unreachable-branches"
)
set(COVERAGE_EXCLUDES
"/c/msys64/mingw64/*" "*/fsfw_hal/*"
)
elseif(UNIX) elseif(UNIX)
set(COVERAGE_EXCLUDES set(COVERAGE_EXCLUDES
"/usr/include/*" "/usr/include/*" "/usr/bin/*" "Catch2/*"
"/usr/bin/*" "/usr/local/include/*" "*/fsfw_tests/*"
"Catch2/*" "*/catch2-src/*" "*/fsfw_hal/*"
"/usr/local/include/*" )
"*/fsfw_tests/*"
"*/catch2-src/*"
"*/fsfw_hal/*"
"unittests/*")
endif() endif()
target_link_options(${FSFW_TEST_TGT} PRIVATE -fprofile-arcs target_link_options(${FSFW_TEST_TGT} PRIVATE
-ftest-coverage) -fprofile-arcs
target_link_options(${LIB_FSFW_NAME} PRIVATE -fprofile-arcs -ftest-coverage
-ftest-coverage) )
# Need to specify this as an interface, otherwise there will the compile target_link_options(${LIB_FSFW_NAME} PRIVATE
# issues -fprofile-arcs
target_link_options(${LIB_FSFW_NAME} INTERFACE -fprofile-arcs -ftest-coverage
-ftest-coverage) )
# Need to specify this as an interface, otherwise there will the compile issues
target_link_options(${LIB_FSFW_NAME} INTERFACE
-fprofile-arcs
-ftest-coverage
)
if(WIN32) if(WIN32)
setup_target_for_coverage_gcovr_html( setup_target_for_coverage_gcovr_html(
NAME ${FSFW_TEST_TGT}_coverage EXECUTABLE ${FSFW_TEST_TGT} NAME ${FSFW_TEST_TGT}_coverage
DEPENDENCIES ${FSFW_TEST_TGT}) EXECUTABLE ${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
${FSFW_TEST_TGT}_coverage EXECUTABLE ${FSFW_TEST_TGT}
EXECUTABLE DEPENDENCIES ${FSFW_TEST_TGT}
${FSFW_TEST_TGT} )
DEPENDENCIES
${FSFW_TEST_TGT}
GENHTML_ARGS
--html-epilog
${CMAKE_SOURCE_DIR}/unittests/lcov_epilog.html)
endif() endif()
endif() endif()
endif() endif()
target_link_libraries(${FSFW_TEST_TGT} PRIVATE Catch2::Catch2 target_link_libraries(${FSFW_TEST_TGT} PRIVATE Catch2::Catch2 ${LIB_FSFW_NAME})
${LIB_FSFW_NAME})
endif() endif()
# The project CMakeLists file has to set the FSFW_CONFIG_PATH and add it. If # The project CMakeLists file has to set the FSFW_CONFIG_PATH and add it.
# this is not given, we include the default configuration and emit a warning. # If this is not given, we include the default configuration and emit a warning.
if(NOT FSFW_CONFIG_PATH) if(NOT FSFW_CONFIG_PATH)
set(DEF_CONF_PATH misc/defaultcfg/fsfwconfig) set(DEF_CONF_PATH misc/defaultcfg/fsfwconfig)
if(NOT FSFW_BUILD_DOCS) if(NOT FSFW_BUILD_DOCS)
message( message(WARNING "${MSG_PREFIX} Flight Software Framework configuration path not set")
WARNING message(WARNING "${MSG_PREFIX} Setting default configuration from ${DEF_CONF_PATH} ..")
"${MSG_PREFIX} Flight Software Framework configuration path FSFW_CONFIG_PATH not set"
)
message(
WARNING
"${MSG_PREFIX} Setting default configuration from ${DEF_CONF_PATH} ..")
endif() endif()
add_subdirectory(${DEF_CONF_PATH}) add_subdirectory(${DEF_CONF_PATH})
set(FSFW_CONFIG_PATH ${DEF_CONF_PATH}) set(FSFW_CONFIG_PATH ${DEF_CONF_PATH})
endif() endif()
# FSFW might be part of a possibly complicated folder structure, so we extract # FSFW might be part of a possibly complicated folder structure, so we
# the absolute path of the fsfwconfig folder. # extract the absolute path of the fsfwconfig folder.
if(IS_ABSOLUTE ${FSFW_CONFIG_PATH}) if(IS_ABSOLUTE ${FSFW_CONFIG_PATH})
set(FSFW_CONFIG_PATH_ABSOLUTE ${FSFW_CONFIG_PATH}) set(FSFW_CONFIG_PATH_ABSOLUTE ${FSFW_CONFIG_PATH})
else() else()
get_filename_component(FSFW_CONFIG_PATH_ABSOLUTE ${FSFW_CONFIG_PATH} REALPATH get_filename_component(FSFW_CONFIG_PATH_ABSOLUTE
BASE_DIR ${CMAKE_SOURCE_DIR}) ${FSFW_CONFIG_PATH} REALPATH BASE_DIR ${CMAKE_SOURCE_DIR}
)
endif() endif()
foreach(INCLUDE_PATH ${FSFW_ADDITIONAL_INC_PATHS}) foreach(INCLUDE_PATH ${FSFW_ADDITIONAL_INC_PATHS})
if(IS_ABSOLUTE ${INCLUDE_PATH}) if(IS_ABSOLUTE ${INCLUDE_PATH})
set(CURR_ABS_INC_PATH "${INCLUDE_PATH}") set(CURR_ABS_INC_PATH "${INCLUDE_PATH}")
else() else()
get_filename_component(CURR_ABS_INC_PATH ${INCLUDE_PATH} REALPATH BASE_DIR get_filename_component(CURR_ABS_INC_PATH
${CMAKE_SOURCE_DIR}) ${INCLUDE_PATH} REALPATH BASE_DIR ${CMAKE_SOURCE_DIR})
endif() endif()
if(CMAKE_VERBOSE) if(CMAKE_VERBOSE)
@ -426,19 +373,23 @@ if(CMAKE_CXX_COMPILER_ID STREQUAL "GNU")
-Wcast-qual # Warn if the constness is cast away -Wcast-qual # Warn if the constness is cast away
-Wstringop-overflow=4 -Wstringop-overflow=4
# -Wstack-protector # Emits a few false positives for low level access # -Wstack-protector # Emits a few false positives for low level access
# -Wconversion # Creates many false positives -Warith-conversion # Use # -Wconversion # Creates many false positives
# with Wconversion to find more implicit conversions -fanalyzer # Should # -Warith-conversion # Use with Wconversion to find more implicit conversions
# be used to look through problems # -fanalyzer # Should be used to look through problems
) )
endif() endif()
if(FSFW_GENERATE_SECTIONS) if(FSFW_GENERATE_SECTIONS)
target_compile_options(${LIB_FSFW_NAME} PRIVATE "-ffunction-sections" target_compile_options(${LIB_FSFW_NAME} PRIVATE
"-fdata-sections") "-ffunction-sections"
"-fdata-sections"
)
endif() endif()
if(FSFW_REMOVE_UNUSED_CODE) if(FSFW_REMOVE_UNUSED_CODE)
target_link_options(${LIB_FSFW_NAME} PRIVATE "Wl,--gc-sections") target_link_options(${LIB_FSFW_NAME} PRIVATE
"Wl,--gc-sections"
)
endif() endif()
if(FSFW_WARNING_SHADOW_LOCAL_GCC) if(FSFW_WARNING_SHADOW_LOCAL_GCC)
@ -452,31 +403,42 @@ if(CMAKE_CXX_COMPILER_ID STREQUAL "MSVC")
endif() endif()
# Required include paths to compile the FSFW # Required include paths to compile the FSFW
target_include_directories( target_include_directories(${LIB_FSFW_NAME} INTERFACE
${LIB_FSFW_NAME} INTERFACE ${CMAKE_SOURCE_DIR} ${FSFW_CONFIG_PATH_ABSOLUTE} ${CMAKE_SOURCE_DIR}
${FSFW_CORE_INC_PATH} ${FSFW_ADD_INC_PATHS_ABS}) ${FSFW_CONFIG_PATH_ABSOLUTE}
${FSFW_CORE_INC_PATH}
${FSFW_ADD_INC_PATHS_ABS}
)
# Includes path required to compile FSFW itself as well We assume that the # Includes path required to compile FSFW itself as well
# fsfwconfig folder uses include relative to the project root here! # We assume that the fsfwconfig folder uses include relative to the project
target_include_directories( # root here!
${LIB_FSFW_NAME} PRIVATE ${CMAKE_SOURCE_DIR} ${FSFW_CONFIG_PATH_ABSOLUTE} target_include_directories(${LIB_FSFW_NAME} PRIVATE
${FSFW_CORE_INC_PATH} ${FSFW_ADD_INC_PATHS_ABS}) ${CMAKE_SOURCE_DIR}
${FSFW_CONFIG_PATH_ABSOLUTE}
${FSFW_CORE_INC_PATH}
${FSFW_ADD_INC_PATHS_ABS}
)
target_compile_options(${LIB_FSFW_NAME} PRIVATE ${FSFW_WARNING_FLAGS} target_compile_options(${LIB_FSFW_NAME} PRIVATE
${COMPILER_FLAGS}) ${FSFW_WARNING_FLAGS}
${COMPILER_FLAGS}
)
target_link_libraries(${LIB_FSFW_NAME} PRIVATE ${FSFW_ADDITIONAL_LINK_LIBS}) target_link_libraries(${LIB_FSFW_NAME} PRIVATE
target_link_libraries(${LIB_FSFW_NAME} PUBLIC ${FSFW_ETL_LINK_TARGET}) ${FSFW_ETL_LINK_TARGET}
${FSFW_ADDITIONAL_LINK_LIBS}
)
string( string(CONCAT POST_BUILD_COMMENT
CONCAT
POST_BUILD_COMMENT
"######################################################################\n" "######################################################################\n"
"Built FSFW v${FSFW_VERSION}.${FSFW_SUBVERSION}.${FSFW_REVISION}, " "Built FSFW v${FSFW_VERSION}.${FSFW_SUBVERSION}.${FSFW_REVISION}, "
"Target OSAL: ${FSFW_OS_NAME}\n" "Target OSAL: ${FSFW_OS_NAME}\n"
"######################################################################\n") "######################################################################\n"
)
add_custom_command( add_custom_command(
TARGET ${LIB_FSFW_NAME} TARGET ${LIB_FSFW_NAME}
POST_BUILD POST_BUILD
COMMENT ${POST_BUILD_COMMENT}) COMMENT ${POST_BUILD_COMMENT}
)

View File

View File

@ -99,7 +99,7 @@ add and link against the FSFW library in general.
4. Link against the FSFW library 4. Link against the FSFW library
```sh ```cmake
target_link_libraries(${YourProjectName} PRIVATE fsfw) target_link_libraries(${YourProjectName} PRIVATE fsfw)
``` ```
@ -131,15 +131,15 @@ default. This can be disabled by setting the `FSFW_TESTS_COV_GEN` option to `OFF
You can use the following commands inside the `fsfw` folder to set up the build system You can use the following commands inside the `fsfw` folder to set up the build system
```sh ```sh
mkdir build-tests && cd build-tests mkdir build-Unittest && cd build-Unittest
cmake -DFSFW_BUILD_TESTS=ON -DFSFW_OSAL=host -DCMAKE_BUILD_TYPE=Debug .. cmake -DFSFW_BUILD_UNITTESTS=ON -DFSFW_OSAL=host -DCMAKE_BUILD_TYPE=Debug ..
``` ```
You can also use `-DFSFW_OSAL=linux` on Linux systems. You can also use `-DFSFW_OSAL=linux` on Linux systems.
Coverage data in HTML format can be generated using the `CodeCoverage` Coverage data in HTML format can be generated using the `CodeCoverage`
[CMake module](https://github.com/bilke/cmake-modules/tree/master). [CMake module](https://github.com/bilke/cmake-modules/tree/master).
To build the unittests, run them and then generate the coverage data in this format, To build the unittests, run them and then generare the coverage data in this format,
the following command can be used inside the build directory after the build system was set up the following command can be used inside the build directory after the build system was set up
```sh ```sh
@ -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
@ -188,10 +188,7 @@ and open the documentation conveniently. Try `helper.py -h for more information.
The formatting is done by the `clang-format` tool. The configuration is contained within the The formatting is done by the `clang-format` tool. The configuration is contained within the
`.clang-format` file in the repository root. As long as `clang-format` is installed, you `.clang-format` file in the repository root. As long as `clang-format` is installed, you
can run the `auto-format.sh` helper script to format all source files consistently. Furthermore cmake-format is required to format CMake files which can be installed with: can run the `apply-clang-format.sh` helper script to format all source files consistently.
````sh
sudo pip install cmakelang
````
## Index ## Index

View File

@ -5,25 +5,10 @@ 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
RUN git clone https://github.com/ETLCPP/etl.git && \
cd etl && \
git checkout 20.28.0 && \
cmake -B 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

100
automation/Jenkinsfile vendored
View File

@ -1,127 +1,43 @@
pipeline { pipeline {
environment { environment {
BUILDDIR_HOST = 'cmake-build-tests-host' BUILDDIR = 'build-tests'
BUILDDIR_LINUX = 'cmake-build-tests-linux'
DOCDDIR = 'cmake-build-documentation'
} }
agent { agent {
docker { docker { image 'fsfw-ci:d2'}
image 'fsfw-ci:d6'
args '--network host --sysctl fs.mqueue.msg_max=100'
} }
}
stages {
stage('Host') {
stages { 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_UNITTESTS=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) { dir(BUILDDIR) {
sh 'valgrind --leak-check=full --error-exitcode=1 ./fsfw-tests' 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) {
sshagent(credentials: ['documentation-buildfix']) {
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)

View File

@ -0,0 +1,141 @@
# - Returns a version string from Git
#
# These functions force a re-configure on each git commit so that you can
# trust the values of the variables in your build system.
#
# get_git_head_revision(<refspecvar> <hashvar> [<additional arguments to git describe> ...])
#
# Returns the refspec and sha hash of the current head revision
#
# git_describe(<var> [<additional arguments to git describe> ...])
#
# Returns the results of git describe on the source tree, and adjusting
# the output so that it tests false if an error occurs.
#
# git_get_exact_tag(<var> [<additional arguments to git describe> ...])
#
# Returns the results of git describe --exact-match on the source tree,
# and adjusting the output so that it tests false if there was no exact
# matching tag.
#
# Requires CMake 2.6 or newer (uses the 'function' command)
#
# Original Author:
# 2009-2010 Ryan Pavlik <rpavlik@iastate.edu> <abiryan@ryand.net>
# http://academic.cleardefinition.com
# Iowa State University HCI Graduate Program/VRAC
#
# Copyright Iowa State University 2009-2010.
# Distributed under the Boost Software License, Version 1.0.
# (See accompanying file LICENSE_1_0.txt or copy at
# http://www.boost.org/LICENSE_1_0.txt)
if(__get_git_revision_description)
return()
endif()
set(__get_git_revision_description YES)
# We must run the following at "include" time, not at function call time,
# to find the path to this module rather than the path to a calling list file
get_filename_component(_gitdescmoddir ${CMAKE_CURRENT_LIST_FILE} PATH)
function(get_git_head_revision _refspecvar _hashvar)
set(GIT_PARENT_DIR "${CMAKE_CURRENT_SOURCE_DIR}")
set(GIT_DIR "${GIT_PARENT_DIR}/.git")
while(NOT EXISTS "${GIT_DIR}") # .git dir not found, search parent directories
set(GIT_PREVIOUS_PARENT "${GIT_PARENT_DIR}")
get_filename_component(GIT_PARENT_DIR ${GIT_PARENT_DIR} PATH)
if(GIT_PARENT_DIR STREQUAL GIT_PREVIOUS_PARENT)
# We have reached the root directory, we are not in git
set(${_refspecvar} "GITDIR-NOTFOUND" PARENT_SCOPE)
set(${_hashvar} "GITDIR-NOTFOUND" PARENT_SCOPE)
return()
endif()
set(GIT_DIR "${GIT_PARENT_DIR}/.git")
endwhile()
# check if this is a submodule
if(NOT IS_DIRECTORY ${GIT_DIR})
file(READ ${GIT_DIR} submodule)
string(REGEX REPLACE "gitdir: (.*)\n$" "\\1" GIT_DIR_RELATIVE ${submodule})
get_filename_component(SUBMODULE_DIR ${GIT_DIR} PATH)
if (IS_ABSOLUTE ${GIT_DIR_RELATIVE})
set(GIT_DIR ${GIT_DIR_RELATIVE})
else()
get_filename_component(GIT_DIR ${SUBMODULE_DIR}/${GIT_DIR_RELATIVE} ABSOLUTE)
endif()
endif()
set(GIT_DATA "${CMAKE_CURRENT_BINARY_DIR}/CMakeFiles/git-data")
if(NOT EXISTS "${GIT_DATA}")
file(MAKE_DIRECTORY "${GIT_DATA}")
endif()
if(NOT EXISTS "${GIT_DIR}/HEAD")
return()
endif()
set(HEAD_FILE "${GIT_DATA}/HEAD")
configure_file("${GIT_DIR}/HEAD" "${HEAD_FILE}" COPYONLY)
configure_file("${_gitdescmoddir}/GetGitRevisionDescription.cmake.in"
"${GIT_DATA}/grabRef.cmake"
@ONLY)
include("${GIT_DATA}/grabRef.cmake")
set(${_refspecvar} "${HEAD_REF}" PARENT_SCOPE)
set(${_hashvar} "${HEAD_HASH}" PARENT_SCOPE)
endfunction()
function(git_describe _var)
if(NOT GIT_FOUND)
find_package(Git QUIET)
endif()
get_git_head_revision(refspec hash)
if(NOT GIT_FOUND)
set(${_var} "GIT-NOTFOUND" PARENT_SCOPE)
return()
endif()
if(NOT hash)
set(${_var} "HEAD-HASH-NOTFOUND" PARENT_SCOPE)
return()
endif()
# TODO sanitize
#if((${ARGN}" MATCHES "&&") OR
# (ARGN MATCHES "||") OR
# (ARGN MATCHES "\\;"))
# message("Please report the following error to the project!")
# message(FATAL_ERROR "Looks like someone's doing something nefarious with git_describe! Passed arguments ${ARGN}")
#endif()
#message(STATUS "Arguments to execute_process: ${ARGN}")
execute_process(COMMAND
${GIT_EXECUTABLE}
describe
${hash}
${ARGN}
WORKING_DIRECTORY
"${CMAKE_SOURCE_DIR}"
RESULT_VARIABLE
res
OUTPUT_VARIABLE
out
ERROR_QUIET
OUTPUT_STRIP_TRAILING_WHITESPACE)
if(NOT res EQUAL 0)
set(out "${out}-${res}-NOTFOUND")
endif()
set(${_var} "${out}" PARENT_SCOPE)
endfunction()
function(git_get_exact_tag _var)
git_describe(out --exact-match ${ARGN})
set(${_var} "${out}" PARENT_SCOPE)
endfunction()
function(git_get_tag _var)
git_describe(out --tags ${ARGN})
set(${_var} "${out}" PARENT_SCOPE)
endfunction()

View File

@ -8,12 +8,10 @@
# http://academic.cleardefinition.com # http://academic.cleardefinition.com
# Iowa State University HCI Graduate Program/VRAC # Iowa State University HCI Graduate Program/VRAC
# #
# Copyright 2009-2012, Iowa State University # Copyright Iowa State University 2009-2010.
# Copyright 2011-2015, Contributors
# Distributed under the Boost Software License, Version 1.0. # Distributed under the Boost Software License, Version 1.0.
# (See accompanying file LICENSE_1_0.txt or copy at # (See accompanying file LICENSE_1_0.txt or copy at
# http://www.boost.org/LICENSE_1_0.txt) # http://www.boost.org/LICENSE_1_0.txt)
# SPDX-License-Identifier: BSL-1.0
set(HEAD_HASH) set(HEAD_HASH)
@ -25,12 +23,9 @@ if(HEAD_CONTENTS MATCHES "ref")
string(REPLACE "ref: " "" HEAD_REF "${HEAD_CONTENTS}") string(REPLACE "ref: " "" HEAD_REF "${HEAD_CONTENTS}")
if(EXISTS "@GIT_DIR@/${HEAD_REF}") if(EXISTS "@GIT_DIR@/${HEAD_REF}")
configure_file("@GIT_DIR@/${HEAD_REF}" "@GIT_DATA@/head-ref" COPYONLY) configure_file("@GIT_DIR@/${HEAD_REF}" "@GIT_DATA@/head-ref" COPYONLY)
else() elseif(EXISTS "@GIT_DIR@/logs/${HEAD_REF}")
configure_file("@GIT_DIR@/packed-refs" "@GIT_DATA@/packed-refs" COPYONLY) configure_file("@GIT_DIR@/logs/${HEAD_REF}" "@GIT_DATA@/head-ref" COPYONLY)
file(READ "@GIT_DATA@/packed-refs" PACKED_REFS) set(HEAD_HASH "${HEAD_REF}")
if(${PACKED_REFS} MATCHES "([0-9a-z]*) ${HEAD_REF}")
set(HEAD_HASH "${CMAKE_MATCH_1}")
endif()
endif() endif()
else() else()
# detached HEAD # detached HEAD

View File

@ -1,7 +1,5 @@
The files in the `bilke` folder were manually copy and pasted from the The files in these folder were manually copy and pasted from the
[cmake-modules repository](https://github.com/bilke/cmake-modules). It was decided to do [cmake-modules repository](https://github.com/bilke/cmake-modules). It was decided to do
this because only a small subset of its provided functions are needed. this because only a small subset of its provided functions are needed.
The files in the `rpavlik` folder were manually copy and pasted from the The license file in included here as well.
[cmake-modules repository](https://github.com/rpavlik/cmake-modules). It was decided to do
this because only a small subset of its provided functions are needed.

View File

@ -1,284 +0,0 @@
# - Returns a version string from Git
#
# These functions force a re-configure on each git commit so that you can
# trust the values of the variables in your build system.
#
# get_git_head_revision(<refspecvar> <hashvar> [ALLOW_LOOKING_ABOVE_CMAKE_SOURCE_DIR])
#
# Returns the refspec and sha hash of the current head revision
#
# git_describe(<var> [<additional arguments to git describe> ...])
#
# Returns the results of git describe on the source tree, and adjusting
# the output so that it tests false if an error occurs.
#
# git_describe_working_tree(<var> [<additional arguments to git describe> ...])
#
# Returns the results of git describe on the working tree (--dirty option),
# and adjusting the output so that it tests false if an error occurs.
#
# git_get_exact_tag(<var> [<additional arguments to git describe> ...])
#
# Returns the results of git describe --exact-match on the source tree,
# and adjusting the output so that it tests false if there was no exact
# matching tag.
#
# git_local_changes(<var>)
#
# Returns either "CLEAN" or "DIRTY" with respect to uncommitted changes.
# Uses the return code of "git diff-index --quiet HEAD --".
# Does not regard untracked files.
#
# Requires CMake 2.6 or newer (uses the 'function' command)
#
# Original Author:
# 2009-2020 Ryan Pavlik <ryan.pavlik@gmail.com> <abiryan@ryand.net>
# http://academic.cleardefinition.com
#
# Copyright 2009-2013, Iowa State University.
# Copyright 2013-2020, Ryan Pavlik
# Copyright 2013-2020, Contributors
# SPDX-License-Identifier: BSL-1.0
# Distributed under the Boost Software License, Version 1.0.
# (See accompanying file LICENSE_1_0.txt or copy at
# http://www.boost.org/LICENSE_1_0.txt)
if(__get_git_revision_description)
return()
endif()
set(__get_git_revision_description YES)
# We must run the following at "include" time, not at function call time,
# to find the path to this module rather than the path to a calling list file
get_filename_component(_gitdescmoddir ${CMAKE_CURRENT_LIST_FILE} PATH)
# Function _git_find_closest_git_dir finds the next closest .git directory
# that is part of any directory in the path defined by _start_dir.
# The result is returned in the parent scope variable whose name is passed
# as variable _git_dir_var. If no .git directory can be found, the
# function returns an empty string via _git_dir_var.
#
# Example: Given a path C:/bla/foo/bar and assuming C:/bla/.git exists and
# neither foo nor bar contain a file/directory .git. This wil return
# C:/bla/.git
#
function(_git_find_closest_git_dir _start_dir _git_dir_var)
set(cur_dir "${_start_dir}")
set(git_dir "${_start_dir}/.git")
while(NOT EXISTS "${git_dir}")
# .git dir not found, search parent directories
set(git_previous_parent "${cur_dir}")
get_filename_component(cur_dir "${cur_dir}" DIRECTORY)
if(cur_dir STREQUAL git_previous_parent)
# We have reached the root directory, we are not in git
set(${_git_dir_var}
""
PARENT_SCOPE)
return()
endif()
set(git_dir "${cur_dir}/.git")
endwhile()
set(${_git_dir_var}
"${git_dir}"
PARENT_SCOPE)
endfunction()
function(get_git_head_revision _refspecvar _hashvar)
_git_find_closest_git_dir("${CMAKE_CURRENT_SOURCE_DIR}" GIT_DIR)
if("${ARGN}" STREQUAL "ALLOW_LOOKING_ABOVE_CMAKE_SOURCE_DIR")
set(ALLOW_LOOKING_ABOVE_CMAKE_SOURCE_DIR TRUE)
else()
set(ALLOW_LOOKING_ABOVE_CMAKE_SOURCE_DIR FALSE)
endif()
if(NOT "${GIT_DIR}" STREQUAL "")
file(RELATIVE_PATH _relative_to_source_dir "${CMAKE_SOURCE_DIR}"
"${GIT_DIR}")
if("${_relative_to_source_dir}" MATCHES "[.][.]" AND NOT ALLOW_LOOKING_ABOVE_CMAKE_SOURCE_DIR)
# We've gone above the CMake root dir.
set(GIT_DIR "")
endif()
endif()
if("${GIT_DIR}" STREQUAL "")
set(${_refspecvar}
"GITDIR-NOTFOUND"
PARENT_SCOPE)
set(${_hashvar}
"GITDIR-NOTFOUND"
PARENT_SCOPE)
return()
endif()
# Check if the current source dir is a git submodule or a worktree.
# In both cases .git is a file instead of a directory.
#
if(NOT IS_DIRECTORY ${GIT_DIR})
# The following git command will return a non empty string that
# points to the super project working tree if the current
# source dir is inside a git submodule.
# Otherwise the command will return an empty string.
#
execute_process(
COMMAND "${GIT_EXECUTABLE}" rev-parse
--show-superproject-working-tree
WORKING_DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}"
OUTPUT_VARIABLE out
ERROR_QUIET OUTPUT_STRIP_TRAILING_WHITESPACE)
if(NOT "${out}" STREQUAL "")
# If out is empty, GIT_DIR/CMAKE_CURRENT_SOURCE_DIR is in a submodule
file(READ ${GIT_DIR} submodule)
string(REGEX REPLACE "gitdir: (.*)$" "\\1" GIT_DIR_RELATIVE
${submodule})
string(STRIP ${GIT_DIR_RELATIVE} GIT_DIR_RELATIVE)
get_filename_component(SUBMODULE_DIR ${GIT_DIR} PATH)
get_filename_component(GIT_DIR ${SUBMODULE_DIR}/${GIT_DIR_RELATIVE}
ABSOLUTE)
set(HEAD_SOURCE_FILE "${GIT_DIR}/HEAD")
else()
# GIT_DIR/CMAKE_CURRENT_SOURCE_DIR is in a worktree
file(READ ${GIT_DIR} worktree_ref)
# The .git directory contains a path to the worktree information directory
# inside the parent git repo of the worktree.
#
string(REGEX REPLACE "gitdir: (.*)$" "\\1" git_worktree_dir
${worktree_ref})
string(STRIP ${git_worktree_dir} git_worktree_dir)
_git_find_closest_git_dir("${git_worktree_dir}" GIT_DIR)
set(HEAD_SOURCE_FILE "${git_worktree_dir}/HEAD")
endif()
else()
set(HEAD_SOURCE_FILE "${GIT_DIR}/HEAD")
endif()
set(GIT_DATA "${CMAKE_CURRENT_BINARY_DIR}/CMakeFiles/git-data")
if(NOT EXISTS "${GIT_DATA}")
file(MAKE_DIRECTORY "${GIT_DATA}")
endif()
if(NOT EXISTS "${HEAD_SOURCE_FILE}")
return()
endif()
set(HEAD_FILE "${GIT_DATA}/HEAD")
configure_file("${HEAD_SOURCE_FILE}" "${HEAD_FILE}" COPYONLY)
configure_file("${_gitdescmoddir}/GetGitRevisionDescription.cmake.in"
"${GIT_DATA}/grabRef.cmake" @ONLY)
include("${GIT_DATA}/grabRef.cmake")
set(${_refspecvar}
"${HEAD_REF}"
PARENT_SCOPE)
set(${_hashvar}
"${HEAD_HASH}"
PARENT_SCOPE)
endfunction()
function(git_describe _var)
if(NOT GIT_FOUND)
find_package(Git QUIET)
endif()
get_git_head_revision(refspec hash)
if(NOT GIT_FOUND)
set(${_var}
"GIT-NOTFOUND"
PARENT_SCOPE)
return()
endif()
if(NOT hash)
set(${_var}
"HEAD-HASH-NOTFOUND"
PARENT_SCOPE)
return()
endif()
# TODO sanitize
#if((${ARGN}" MATCHES "&&") OR
# (ARGN MATCHES "||") OR
# (ARGN MATCHES "\\;"))
# message("Please report the following error to the project!")
# message(FATAL_ERROR "Looks like someone's doing something nefarious with git_describe! Passed arguments ${ARGN}")
#endif()
#message(STATUS "Arguments to execute_process: ${ARGN}")
execute_process(
COMMAND "${GIT_EXECUTABLE}" describe --tags --always ${hash} ${ARGN}
WORKING_DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}"
RESULT_VARIABLE res
OUTPUT_VARIABLE out
ERROR_QUIET OUTPUT_STRIP_TRAILING_WHITESPACE)
if(NOT res EQUAL 0)
set(out "${out}-${res}-NOTFOUND")
endif()
set(${_var}
"${out}"
PARENT_SCOPE)
endfunction()
function(git_describe_working_tree _var)
if(NOT GIT_FOUND)
find_package(Git QUIET)
endif()
if(NOT GIT_FOUND)
set(${_var}
"GIT-NOTFOUND"
PARENT_SCOPE)
return()
endif()
execute_process(
COMMAND "${GIT_EXECUTABLE}" describe --dirty ${ARGN}
WORKING_DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}"
RESULT_VARIABLE res
OUTPUT_VARIABLE out
ERROR_QUIET OUTPUT_STRIP_TRAILING_WHITESPACE)
if(NOT res EQUAL 0)
set(out "${out}-${res}-NOTFOUND")
endif()
set(${_var}
"${out}"
PARENT_SCOPE)
endfunction()
function(git_get_exact_tag _var)
git_describe(out --exact-match ${ARGN})
set(${_var}
"${out}"
PARENT_SCOPE)
endfunction()
function(git_local_changes _var)
if(NOT GIT_FOUND)
find_package(Git QUIET)
endif()
get_git_head_revision(refspec hash)
if(NOT GIT_FOUND)
set(${_var}
"GIT-NOTFOUND"
PARENT_SCOPE)
return()
endif()
if(NOT hash)
set(${_var}
"HEAD-HASH-NOTFOUND"
PARENT_SCOPE)
return()
endif()
execute_process(
COMMAND "${GIT_EXECUTABLE}" diff-index --quiet HEAD --
WORKING_DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}"
RESULT_VARIABLE res
OUTPUT_VARIABLE out
ERROR_QUIET OUTPUT_STRIP_TRAILING_WHITESPACE)
if(res EQUAL 0)
set(${_var}
"CLEAN"
PARENT_SCOPE)
else()
set(${_var}
"DIRTY"
PARENT_SCOPE)
endif()
endfunction()

View File

@ -1,26 +0,0 @@
Copyright (c) <year> <owner>. All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its contributors
may be used to endorse or promote products derived from this software without
specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

View File

@ -1,23 +0,0 @@
Boost Software License - Version 1.0 - August 17th, 2003
Permission is hereby granted, free of charge, to any person or organization
obtaining a copy of the software and accompanying documentation covered by
this license (the "Software") to use, reproduce, display, distribute, execute,
and transmit the Software, and to prepare derivative works of the Software,
and to permit third-parties to whom the Software is furnished to do so, all
subject to the following:
The copyright notices in the Software and this entire statement, including
the above license grant, this restriction and the following disclaimer, must
be included in all copies of the Software, in whole or in part, and all derivative
works of the Software, unless such copies or derivative works are solely in
the form of machine-executable object code generated by a source language
processor.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE
COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE FOR ANY DAMAGES
OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

View File

@ -1,23 +0,0 @@
Boost Software License - Version 1.0 - August 17th, 2003
Permission is hereby granted, free of charge, to any person or organization
obtaining a copy of the software and accompanying documentation covered by
this license (the "Software") to use, reproduce, display, distribute,
execute, and transmit the Software, and to prepare derivative works of the
Software, and to permit third-parties to whom the Software is furnished to
do so, all subject to the following:
The copyright notices in the Software and this entire statement, including
the above license grant, this restriction and the following disclaimer,
must be included in all copies of the Software, in whole or in part, and
all derivative works of the Software, unless such copies or derivative
works are solely in the form of machine-executable object code generated by
a source language processor.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.

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 `HasReturnvaluesIF::makeReturnCode`
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 HasReturnvaluesIF::RETURN_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() == HasReturnvaluesIF::RETURN_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

@ -3,7 +3,7 @@
Returnvalue API Returnvalue API
================== ==================
.. doxygenfile:: returnvalue.h .. doxygenfile:: HasReturnvaluesIF.h
.. _fwclassids: .. _fwclassids:

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 ---------------------------------------------------
@ -35,12 +35,12 @@ 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

@ -75,11 +75,11 @@ and the respective source file with sensible default return values:
void TestDeviceHandler::doShutDown() {} void TestDeviceHandler::doShutDown() {}
ReturnValue_t TestDeviceHandler::buildNormalDeviceCommand(DeviceCommandId_t* id) { ReturnValue_t TestDeviceHandler::buildNormalDeviceCommand(DeviceCommandId_t* id) {
return returnvalue::OK; return HasReturnvaluesIF::RETURN_OK;
} }
ReturnValue_t TestDeviceHandler::buildTransitionDeviceCommand(DeviceCommandId_t* id) { ReturnValue_t TestDeviceHandler::buildTransitionDeviceCommand(DeviceCommandId_t* id) {
return returnvalue::OK; return HasReturnvaluesIF::RETURN_OK;
} }
void TestDeviceHandler::fillCommandAndReplyMap() {} void TestDeviceHandler::fillCommandAndReplyMap() {}
@ -87,17 +87,17 @@ and the respective source file with sensible default return values:
ReturnValue_t TestDeviceHandler::buildCommandFromCommand(DeviceCommandId_t deviceCommand, ReturnValue_t TestDeviceHandler::buildCommandFromCommand(DeviceCommandId_t deviceCommand,
const uint8_t* commandData, const uint8_t* commandData,
size_t commandDataLen) { size_t commandDataLen) {
return returnvalue::OK; return HasReturnvaluesIF::RETURN_OK;
} }
ReturnValue_t TestDeviceHandler::scanForReply(const uint8_t* start, size_t remainingSize, ReturnValue_t TestDeviceHandler::scanForReply(const uint8_t* start, size_t remainingSize,
DeviceCommandId_t* foundId, size_t* foundLen) { DeviceCommandId_t* foundId, size_t* foundLen) {
return returnvalue::OK; return HasReturnvaluesIF::RETURN_OK;
} }
ReturnValue_t TestDeviceHandler::interpretDeviceReply(DeviceCommandId_t id, ReturnValue_t TestDeviceHandler::interpretDeviceReply(DeviceCommandId_t id,
const uint8_t* packet) { const uint8_t* packet) {
return returnvalue::OK; return HasReturnvaluesIF::RETURN_OK;
} }
uint32_t TestDeviceHandler::getTransitionDelayMs(Mode_t modeFrom, Mode_t modeTo) { uint32_t TestDeviceHandler::getTransitionDelayMs(Mode_t modeFrom, Mode_t modeTo) {
@ -106,5 +106,5 @@ and the respective source file with sensible default return values:
ReturnValue_t TestDeviceHandler::initializeLocalDataPool(localpool::DataPool& localDataPoolMap, ReturnValue_t TestDeviceHandler::initializeLocalDataPool(localpool::DataPool& localDataPoolMap,
LocalDataPoolManager& poolManager) { LocalDataPoolManager& poolManager) {
return returnvalue::OK; return HasReturnvaluesIF::RETURN_OK;
} }

View File

@ -106,7 +106,7 @@ You can use the following commands inside the ``fsfw`` folder to set up the buil
.. code-block:: console .. code-block:: console
mkdir build-tests && cd build-tests mkdir build-tests && cd build-tests
cmake -DFSFW_BUILD_TESTS=ON -DFSFW_OSAL=host .. cmake -DFSFW_BUILD_UNITTESTS=ON -DFSFW_OSAL=host ..
You can also use ``-DFSFW_OSAL=linux`` on Linux systems. You can also use ``-DFSFW_OSAL=linux`` on Linux systems.

View File

@ -7,19 +7,18 @@ 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
----------------- -----------------
Functions should return a defined :cpp:type:`ReturnValue_t` to signal to the caller that something has Functions should return a defined :cpp:type:`ReturnValue_t` to signal to the caller that something has
gone wrong. Returnvalues must be unique. For this the function :cpp:func:`returnvalue::makeCode` gone wrong. Returnvalues must be unique. For this the function :cpp:func:`HasReturnvaluesIF::makeReturnCode`
or the :ref:`macro MAKE_RETURN_CODE <retvalapi>` can be used. The ``CLASS_ID`` is a unique ID for that type of object. or the :ref:`macro MAKE_RETURN_CODE <retvalapi>` can be used. The ``CLASS_ID`` is a unique ID for that type of object.
See the :ref:`FSFW Class IDs file <fwclassids>`. The user can add custom ``CLASS_ID``\s via the See the :ref:`FSFW Class IDs file <fwclassids>`. The user can add custom ``CLASS_ID``\s via the
``fsfwconfig`` folder. ``fsfwconfig`` folder.

View File

@ -150,7 +150,7 @@ with a housekeeping service command.
new PoolEntry<uint8_t>({0})); new PoolEntry<uint8_t>({0}));
poolManager.subscribeForPeriodicPacket(gyroData.getSid(), false, 4.0, false); poolManager.subscribeForPeriodicPacket(gyroData.getSid(), false, 4.0, false);
return returnvalue::OK; return HasReturnvaluesIF::RETURN_OK;
} }
Now, if we receive some sensor data and converted them into the right format, Now, if we receive some sensor data and converted them into the right format,
@ -160,7 +160,7 @@ in any case:
.. code-block:: cpp .. code-block:: cpp
PoolReadGuard readHelper(&gyroData); PoolReadGuard readHelper(&gyroData);
if(readHelper.getReadResult() == returnvalue::OK) { if(readHelper.getReadResult() == HasReturnvaluesIF::RETURN_OK) {
if(not gyroData.isValid()) { if(not gyroData.isValid()) {
gyroData.setValidity(true, true); gyroData.setValidity(true, true);
} }

48
hal/CMakeLists.txt Normal file
View File

@ -0,0 +1,48 @@
cmake_minimum_required(VERSION 3.13)
# Can also be changed by upper CMakeLists.txt file
find_library(LIB_FSFW_NAME fsfw REQUIRED)
option(FSFW_HAL_ADD_LINUX "Add the Linux HAL to the sources. Requires gpiod library" OFF)
# On by default for now because I did not have an issue including and compiling those files
# and libraries on a Desktop Linux system and the primary target of the FSFW is still embedded
# Linux. The only exception from this is the gpiod library which requires a dedicated installation,
# but CMake is able to determine whether this library is installed with find_library.
option(FSFW_HAL_LINUX_ADD_PERIPHERAL_DRIVERS "Add peripheral drivers for embedded Linux" ON)
option(FSFW_HAL_LINUX_ADD_LIBGPIOD "Target implements libgpiod" ON)
option(FSFW_HAL_ADD_RASPBERRY_PI "Add Raspberry Pi specific code to the sources" OFF)
option(FSFW_HAL_ADD_STM32H7 "Add the STM32H7 HAL to the sources" OFF)
option(FSFW_HAL_WARNING_SHADOW_LOCAL_GCC "Enable -Wshadow=local warning in GCC" ON)
set(LINUX_HAL_PATH_NAME linux)
set(STM32H7_PATH_NAME stm32h7)
add_subdirectory(src)
foreach(INCLUDE_PATH ${FSFW_HAL_ADDITIONAL_INC_PATHS})
if(IS_ABSOLUTE ${INCLUDE_PATH})
set(CURR_ABS_INC_PATH "${INCLUDE_PATH}")
else()
get_filename_component(CURR_ABS_INC_PATH
${INCLUDE_PATH} REALPATH BASE_DIR ${CMAKE_SOURCE_DIR})
endif()
if(CMAKE_VERBOSE)
message(STATUS "FSFW include path: ${CURR_ABS_INC_PATH}")
endif()
list(APPEND FSFW_HAL_ADD_INC_PATHS_ABS ${CURR_ABS_INC_PATH})
endforeach()
target_include_directories(${LIB_FSFW_NAME} PRIVATE
${FSFW_HAL_ADD_INC_PATHS_ABS}
)
target_compile_definitions(${LIB_FSFW_NAME} PRIVATE
${FSFW_HAL_DEFINES}
)
target_link_libraries(${LIB_FSFW_NAME} PRIVATE
${FSFW_HAL_LINK_LIBS}
)

9
hal/src/CMakeLists.txt Normal file
View File

@ -0,0 +1,9 @@
target_include_directories(${LIB_FSFW_NAME} PRIVATE
${CMAKE_CURRENT_SOURCE_DIR}
)
target_include_directories(${LIB_FSFW_NAME} INTERFACE
${CMAKE_CURRENT_SOURCE_DIR}
)
add_subdirectory(fsfw_hal)

View File

@ -1,6 +1,5 @@
add_subdirectory(devicehandlers) add_subdirectory(devicehandlers)
add_subdirectory(common) add_subdirectory(common)
add_subdirectory(host)
if(UNIX) if(UNIX)
add_subdirectory(linux) add_subdirectory(linux)

View File

@ -0,0 +1 @@
add_subdirectory(gpio)

View File

@ -0,0 +1,3 @@
target_sources(${LIB_FSFW_NAME} PRIVATE
GpioCookie.cpp
)

View File

@ -11,7 +11,7 @@ ReturnValue_t GpioCookie::addGpio(gpioId_t gpioId, GpioBase* gpioConfig) {
#else #else
sif::printWarning("GpioCookie::addGpio: gpioConfig is nullpointer\n"); sif::printWarning("GpioCookie::addGpio: gpioConfig is nullpointer\n");
#endif #endif
return returnvalue::FAILED; return HasReturnvaluesIF::RETURN_FAILED;
} }
auto gpioMapIter = gpioMap.find(gpioId); auto gpioMapIter = gpioMap.find(gpioId);
if (gpioMapIter == gpioMap.end()) { if (gpioMapIter == gpioMap.end()) {
@ -25,9 +25,9 @@ ReturnValue_t GpioCookie::addGpio(gpioId_t gpioId, GpioBase* gpioConfig) {
sif::printWarning("GpioCookie::addGpio: Failed to add GPIO %d to GPIO map\n", gpioId); sif::printWarning("GpioCookie::addGpio: Failed to add GPIO %d to GPIO map\n", gpioId);
#endif #endif
#endif #endif
return returnvalue::FAILED; return HasReturnvaluesIF::RETURN_FAILED;
} }
return returnvalue::OK; return HasReturnvaluesIF::RETURN_OK;
} }
#if FSFW_VERBOSE_LEVEL >= 1 #if FSFW_VERBOSE_LEVEL >= 1
#if FSFW_CPP_OSTREAM_ENABLED == 1 #if FSFW_CPP_OSTREAM_ENABLED == 1
@ -36,7 +36,7 @@ ReturnValue_t GpioCookie::addGpio(gpioId_t gpioId, GpioBase* gpioConfig) {
sif::printWarning("GpioCookie::addGpio: GPIO already exists in GPIO map\n"); sif::printWarning("GpioCookie::addGpio: GPIO already exists in GPIO map\n");
#endif #endif
#endif #endif
return returnvalue::FAILED; return HasReturnvaluesIF::RETURN_FAILED;
} }
GpioMap GpioCookie::getGpioMap() const { return gpioMap; } GpioMap GpioCookie::getGpioMap() const { return gpioMap; }

View File

@ -2,7 +2,7 @@
#define COMMON_GPIO_GPIOCOOKIE_H_ #define COMMON_GPIO_GPIOCOOKIE_H_
#include <fsfw/devicehandlers/CookieIF.h> #include <fsfw/devicehandlers/CookieIF.h>
#include <fsfw/returnvalues/returnvalue.h> #include <fsfw/returnvalues/HasReturnvaluesIF.h>
#include "GpioIF.h" #include "GpioIF.h"
#include "gpioDefinitions.h" #include "gpioDefinitions.h"

View File

@ -2,7 +2,7 @@
#define COMMON_GPIO_GPIOIF_H_ #define COMMON_GPIO_GPIOIF_H_
#include <fsfw/devicehandlers/CookieIF.h> #include <fsfw/devicehandlers/CookieIF.h>
#include <fsfw/returnvalues/returnvalue.h> #include <fsfw/returnvalues/HasReturnvaluesIF.h>
#include "gpioDefinitions.h" #include "gpioDefinitions.h"
@ -13,7 +13,7 @@ class GpioCookie;
* over GPIOs. * over GPIOs.
* @author J. Meier * @author J. Meier
*/ */
class GpioIF { class GpioIF : public HasReturnvaluesIF {
public: public:
virtual ~GpioIF(){}; virtual ~GpioIF(){};
@ -29,7 +29,7 @@ class GpioIF {
* functionality to pull a certain GPIO to high logic level. * functionality to pull a certain GPIO to high logic level.
* *
* @param gpioId A unique number which specifies the GPIO to drive. * @param gpioId A unique number which specifies the GPIO to drive.
* @return Returns returnvalue::OK for success. This should never return returnvalue::FAILED. * @return Returns RETURN_OK for success. This should never return RETURN_FAILED.
*/ */
virtual ReturnValue_t pullHigh(gpioId_t gpioId) = 0; virtual ReturnValue_t pullHigh(gpioId_t gpioId) = 0;

View File

@ -5,14 +5,6 @@
#include <string> #include <string>
#include <unordered_map> #include <unordered_map>
#ifdef PLATFORM_WIN
// Defined in Windows header for whatever reason, and leads to nameclash issues with
// class enums which have entries of the same name.
#undef IN
#undef OUT
#undef CALLBACK
#endif
using gpioId_t = uint16_t; using gpioId_t = uint16_t;
namespace gpio { namespace gpio {

View File

@ -0,0 +1,12 @@
#ifndef FSFW_HAL_COMMON_SPI_SPICOMMON_H_
#define FSFW_HAL_COMMON_SPI_SPICOMMON_H_
#include <cstdint>
namespace spi {
enum SpiModes : uint8_t { MODE_0, MODE_1, MODE_2, MODE_3 };
}
#endif /* FSFW_HAL_COMMON_SPI_SPICOMMON_H_ */

View File

@ -0,0 +1,5 @@
target_sources(${LIB_FSFW_NAME} PRIVATE
GyroL3GD20Handler.cpp
MgmRM3100Handler.cpp
MgmLIS3MDLHandler.cpp
)

View File

@ -46,17 +46,17 @@ ReturnValue_t GyroHandlerL3GD20H::buildTransitionDeviceCommand(DeviceCommandId_t
return NOTHING_TO_SEND; return NOTHING_TO_SEND;
} }
case (InternalState::CONFIGURE): { case (InternalState::CONFIGURE): {
*id = l3gd20h::CONFIGURE_CTRL_REGS; *id = L3GD20H::CONFIGURE_CTRL_REGS;
uint8_t command[5]; uint8_t command[5];
command[0] = l3gd20h::CTRL_REG_1_VAL; command[0] = L3GD20H::CTRL_REG_1_VAL;
command[1] = l3gd20h::CTRL_REG_2_VAL; command[1] = L3GD20H::CTRL_REG_2_VAL;
command[2] = l3gd20h::CTRL_REG_3_VAL; command[2] = L3GD20H::CTRL_REG_3_VAL;
command[3] = l3gd20h::CTRL_REG_4_VAL; command[3] = L3GD20H::CTRL_REG_4_VAL;
command[4] = l3gd20h::CTRL_REG_5_VAL; command[4] = L3GD20H::CTRL_REG_5_VAL;
return buildCommandFromCommand(*id, command, 5); return buildCommandFromCommand(*id, command, 5);
} }
case (InternalState::CHECK_REGS): { case (InternalState::CHECK_REGS): {
*id = l3gd20h::READ_REGS; *id = L3GD20H::READ_REGS;
return buildCommandFromCommand(*id, nullptr, 0); return buildCommandFromCommand(*id, nullptr, 0);
} }
default: default:
@ -70,13 +70,13 @@ ReturnValue_t GyroHandlerL3GD20H::buildTransitionDeviceCommand(DeviceCommandId_t
"GyroL3GD20Handler::buildTransitionDeviceCommand: " "GyroL3GD20Handler::buildTransitionDeviceCommand: "
"Unknown internal state!\n"); "Unknown internal state!\n");
#endif #endif
return returnvalue::OK; return HasReturnvaluesIF::RETURN_OK;
} }
return returnvalue::OK; return HasReturnvaluesIF::RETURN_OK;
} }
ReturnValue_t GyroHandlerL3GD20H::buildNormalDeviceCommand(DeviceCommandId_t *id) { ReturnValue_t GyroHandlerL3GD20H::buildNormalDeviceCommand(DeviceCommandId_t *id) {
*id = l3gd20h::READ_REGS; *id = L3GD20H::READ_REGS;
return buildCommandFromCommand(*id, nullptr, 0); return buildCommandFromCommand(*id, nullptr, 0);
} }
@ -84,15 +84,15 @@ ReturnValue_t GyroHandlerL3GD20H::buildCommandFromCommand(DeviceCommandId_t devi
const uint8_t *commandData, const uint8_t *commandData,
size_t commandDataLen) { size_t commandDataLen) {
switch (deviceCommand) { switch (deviceCommand) {
case (l3gd20h::READ_REGS): { case (L3GD20H::READ_REGS): {
commandBuffer[0] = l3gd20h::READ_START | l3gd20h::AUTO_INCREMENT_MASK | l3gd20h::READ_MASK; commandBuffer[0] = L3GD20H::READ_START | L3GD20H::AUTO_INCREMENT_MASK | L3GD20H::READ_MASK;
std::memset(commandBuffer + 1, 0, l3gd20h::READ_LEN); std::memset(commandBuffer + 1, 0, L3GD20H::READ_LEN);
rawPacket = commandBuffer; rawPacket = commandBuffer;
rawPacketLen = l3gd20h::READ_LEN + 1; rawPacketLen = L3GD20H::READ_LEN + 1;
break; break;
} }
case (l3gd20h::CONFIGURE_CTRL_REGS): { case (L3GD20H::CONFIGURE_CTRL_REGS): {
commandBuffer[0] = l3gd20h::CTRL_REG_1 | l3gd20h::AUTO_INCREMENT_MASK; commandBuffer[0] = L3GD20H::CTRL_REG_1 | L3GD20H::AUTO_INCREMENT_MASK;
if (commandData == nullptr or commandDataLen != 5) { if (commandData == nullptr or commandDataLen != 5) {
return DeviceHandlerIF::INVALID_COMMAND_PARAMETER; return DeviceHandlerIF::INVALID_COMMAND_PARAMETER;
} }
@ -103,15 +103,15 @@ ReturnValue_t GyroHandlerL3GD20H::buildCommandFromCommand(DeviceCommandId_t devi
ctrlReg4Value = commandData[3]; ctrlReg4Value = commandData[3];
ctrlReg5Value = commandData[4]; ctrlReg5Value = commandData[4];
bool fsH = ctrlReg4Value & l3gd20h::SET_FS_1; bool fsH = ctrlReg4Value & L3GD20H::SET_FS_1;
bool fsL = ctrlReg4Value & l3gd20h::SET_FS_0; bool fsL = ctrlReg4Value & L3GD20H::SET_FS_0;
if (not fsH and not fsL) { if (not fsH and not fsL) {
sensitivity = l3gd20h::SENSITIVITY_00; sensitivity = L3GD20H::SENSITIVITY_00;
} else if (not fsH and fsL) { } else if (not fsH and fsL) {
sensitivity = l3gd20h::SENSITIVITY_01; sensitivity = L3GD20H::SENSITIVITY_01;
} else { } else {
sensitivity = l3gd20h::SENSITIVITY_11; sensitivity = L3GD20H::SENSITIVITY_11;
} }
commandBuffer[1] = ctrlReg1Value; commandBuffer[1] = ctrlReg1Value;
@ -124,8 +124,8 @@ ReturnValue_t GyroHandlerL3GD20H::buildCommandFromCommand(DeviceCommandId_t devi
rawPacketLen = 6; rawPacketLen = 6;
break; break;
} }
case (l3gd20h::READ_CTRL_REGS): { case (L3GD20H::READ_CTRL_REGS): {
commandBuffer[0] = l3gd20h::READ_START | l3gd20h::AUTO_INCREMENT_MASK | l3gd20h::READ_MASK; commandBuffer[0] = L3GD20H::READ_START | L3GD20H::AUTO_INCREMENT_MASK | L3GD20H::READ_MASK;
std::memset(commandBuffer + 1, 0, 5); std::memset(commandBuffer + 1, 0, 5);
rawPacket = commandBuffer; rawPacket = commandBuffer;
@ -135,7 +135,7 @@ ReturnValue_t GyroHandlerL3GD20H::buildCommandFromCommand(DeviceCommandId_t devi
default: default:
return DeviceHandlerIF::COMMAND_NOT_IMPLEMENTED; return DeviceHandlerIF::COMMAND_NOT_IMPLEMENTED;
} }
return returnvalue::OK; return HasReturnvaluesIF::RETURN_OK;
} }
ReturnValue_t GyroHandlerL3GD20H::scanForReply(const uint8_t *start, size_t len, ReturnValue_t GyroHandlerL3GD20H::scanForReply(const uint8_t *start, size_t len,
@ -144,18 +144,18 @@ ReturnValue_t GyroHandlerL3GD20H::scanForReply(const uint8_t *start, size_t len,
*foundId = this->getPendingCommand(); *foundId = this->getPendingCommand();
*foundLen = this->rawPacketLen; *foundLen = this->rawPacketLen;
return returnvalue::OK; return HasReturnvaluesIF::RETURN_OK;
} }
ReturnValue_t GyroHandlerL3GD20H::interpretDeviceReply(DeviceCommandId_t id, ReturnValue_t GyroHandlerL3GD20H::interpretDeviceReply(DeviceCommandId_t id,
const uint8_t *packet) { const uint8_t *packet) {
ReturnValue_t result = returnvalue::OK; ReturnValue_t result = HasReturnvaluesIF::RETURN_OK;
switch (id) { switch (id) {
case (l3gd20h::CONFIGURE_CTRL_REGS): { case (L3GD20H::CONFIGURE_CTRL_REGS): {
commandExecuted = true; commandExecuted = true;
break; break;
} }
case (l3gd20h::READ_CTRL_REGS): { case (L3GD20H::READ_CTRL_REGS): {
if (packet[1] == ctrlReg1Value and packet[2] == ctrlReg2Value and if (packet[1] == ctrlReg1Value and packet[2] == ctrlReg2Value and
packet[3] == ctrlReg3Value and packet[4] == ctrlReg4Value and packet[3] == ctrlReg3Value and packet[4] == ctrlReg4Value and
packet[5] == ctrlReg5Value) { packet[5] == ctrlReg5Value) {
@ -167,7 +167,7 @@ ReturnValue_t GyroHandlerL3GD20H::interpretDeviceReply(DeviceCommandId_t id,
} }
break; break;
} }
case (l3gd20h::READ_REGS): { case (L3GD20H::READ_REGS): {
if (packet[1] != ctrlReg1Value and packet[2] != ctrlReg2Value and if (packet[1] != ctrlReg1Value and packet[2] != ctrlReg2Value and
packet[3] != ctrlReg3Value and packet[4] != ctrlReg4Value and packet[3] != ctrlReg3Value and packet[4] != ctrlReg4Value and
packet[5] != ctrlReg5Value) { packet[5] != ctrlReg5Value) {
@ -178,16 +178,16 @@ ReturnValue_t GyroHandlerL3GD20H::interpretDeviceReply(DeviceCommandId_t id,
} }
} }
statusReg = packet[l3gd20h::STATUS_IDX]; statusReg = packet[L3GD20H::STATUS_IDX];
int16_t angVelocXRaw = packet[l3gd20h::OUT_X_H] << 8 | packet[l3gd20h::OUT_X_L]; int16_t angVelocXRaw = packet[L3GD20H::OUT_X_H] << 8 | packet[L3GD20H::OUT_X_L];
int16_t angVelocYRaw = packet[l3gd20h::OUT_Y_H] << 8 | packet[l3gd20h::OUT_Y_L]; int16_t angVelocYRaw = packet[L3GD20H::OUT_Y_H] << 8 | packet[L3GD20H::OUT_Y_L];
int16_t angVelocZRaw = packet[l3gd20h::OUT_Z_H] << 8 | packet[l3gd20h::OUT_Z_L]; int16_t angVelocZRaw = packet[L3GD20H::OUT_Z_H] << 8 | packet[L3GD20H::OUT_Z_L];
float angVelocX = angVelocXRaw * sensitivity; float angVelocX = angVelocXRaw * sensitivity;
float angVelocY = angVelocYRaw * sensitivity; float angVelocY = angVelocYRaw * sensitivity;
float angVelocZ = angVelocZRaw * sensitivity; float angVelocZ = angVelocZRaw * sensitivity;
int8_t temperaturOffset = (-1) * packet[l3gd20h::TEMPERATURE_IDX]; int8_t temperaturOffset = (-1) * packet[L3GD20H::TEMPERATURE_IDX];
float temperature = 25.0 + temperaturOffset; float temperature = 25.0 + temperaturOffset;
if (periodicPrintout) { if (periodicPrintout) {
if (debugDivider.checkAndIncrement()) { if (debugDivider.checkAndIncrement()) {
@ -207,7 +207,7 @@ ReturnValue_t GyroHandlerL3GD20H::interpretDeviceReply(DeviceCommandId_t id,
} }
PoolReadGuard readSet(&dataset); PoolReadGuard readSet(&dataset);
if (readSet.getReadResult() == returnvalue::OK) { if (readSet.getReadResult() == HasReturnvaluesIF::RETURN_OK) {
if (std::abs(angVelocX) < this->absLimitX) { if (std::abs(angVelocX) < this->absLimitX) {
dataset.angVelocX = angVelocX; dataset.angVelocX = angVelocX;
dataset.angVelocX.setValid(true); dataset.angVelocX.setValid(true);
@ -248,19 +248,17 @@ void GyroHandlerL3GD20H::setToGoToNormalMode(bool enable) { this->goNormalModeIm
ReturnValue_t GyroHandlerL3GD20H::initializeLocalDataPool(localpool::DataPool &localDataPoolMap, ReturnValue_t GyroHandlerL3GD20H::initializeLocalDataPool(localpool::DataPool &localDataPoolMap,
LocalDataPoolManager &poolManager) { LocalDataPoolManager &poolManager) {
localDataPoolMap.emplace(l3gd20h::ANG_VELOC_X, new PoolEntry<float>({0.0})); localDataPoolMap.emplace(L3GD20H::ANG_VELOC_X, new PoolEntry<float>({0.0}));
localDataPoolMap.emplace(l3gd20h::ANG_VELOC_Y, new PoolEntry<float>({0.0})); localDataPoolMap.emplace(L3GD20H::ANG_VELOC_Y, new PoolEntry<float>({0.0}));
localDataPoolMap.emplace(l3gd20h::ANG_VELOC_Z, new PoolEntry<float>({0.0})); localDataPoolMap.emplace(L3GD20H::ANG_VELOC_Z, new PoolEntry<float>({0.0}));
localDataPoolMap.emplace(l3gd20h::TEMPERATURE, new PoolEntry<float>({0.0})); localDataPoolMap.emplace(L3GD20H::TEMPERATURE, new PoolEntry<float>({0.0}));
poolManager.subscribeForRegularPeriodicPacket( return HasReturnvaluesIF::RETURN_OK;
subdp::RegularHkPeriodicParams(dataset.getSid(), false, 10.0));
return returnvalue::OK;
} }
void GyroHandlerL3GD20H::fillCommandAndReplyMap() { void GyroHandlerL3GD20H::fillCommandAndReplyMap() {
insertInCommandAndReplyMap(l3gd20h::READ_REGS, 1, &dataset); insertInCommandAndReplyMap(L3GD20H::READ_REGS, 1, &dataset);
insertInCommandAndReplyMap(l3gd20h::CONFIGURE_CTRL_REGS, 1); insertInCommandAndReplyMap(L3GD20H::CONFIGURE_CTRL_REGS, 1);
insertInCommandAndReplyMap(l3gd20h::READ_CTRL_REGS, 1); insertInCommandAndReplyMap(L3GD20H::READ_CTRL_REGS, 1);
} }
void GyroHandlerL3GD20H::modeChanged() { internalState = InternalState::NONE; } void GyroHandlerL3GD20H::modeChanged() { internalState = InternalState::NONE; }

View File

@ -3,7 +3,8 @@
#include <fsfw/devicehandlers/DeviceHandlerBase.h> #include <fsfw/devicehandlers/DeviceHandlerBase.h>
#include <fsfw/globalfunctions/PeriodicOperationDivider.h> #include <fsfw/globalfunctions/PeriodicOperationDivider.h>
#include <fsfw_hal/devicehandlers/devicedefinitions/gyroL3gHelpers.h>
#include "devicedefinitions/GyroL3GD20Definitions.h"
/** /**
* @brief Device Handler for the L3GD20H gyroscope sensor * @brief Device Handler for the L3GD20H gyroscope sensor
@ -58,9 +59,9 @@ class GyroHandlerL3GD20H : public DeviceHandlerBase {
uint32_t transitionDelayMs = 0; uint32_t transitionDelayMs = 0;
GyroPrimaryDataset dataset; GyroPrimaryDataset dataset;
float absLimitX = l3gd20h::RANGE_DPS_00; float absLimitX = L3GD20H::RANGE_DPS_00;
float absLimitY = l3gd20h::RANGE_DPS_00; float absLimitY = L3GD20H::RANGE_DPS_00;
float absLimitZ = l3gd20h::RANGE_DPS_00; float absLimitZ = L3GD20H::RANGE_DPS_00;
enum class InternalState { NONE, CONFIGURE, CHECK_REGS, NORMAL }; enum class InternalState { NONE, CONFIGURE, CHECK_REGS, NORMAL };
InternalState internalState = InternalState::NONE; InternalState internalState = InternalState::NONE;
@ -69,16 +70,16 @@ class GyroHandlerL3GD20H : public DeviceHandlerBase {
uint8_t statusReg = 0; uint8_t statusReg = 0;
bool goNormalModeImmediately = false; bool goNormalModeImmediately = false;
uint8_t ctrlReg1Value = l3gd20h::CTRL_REG_1_VAL; uint8_t ctrlReg1Value = L3GD20H::CTRL_REG_1_VAL;
uint8_t ctrlReg2Value = l3gd20h::CTRL_REG_2_VAL; uint8_t ctrlReg2Value = L3GD20H::CTRL_REG_2_VAL;
uint8_t ctrlReg3Value = l3gd20h::CTRL_REG_3_VAL; uint8_t ctrlReg3Value = L3GD20H::CTRL_REG_3_VAL;
uint8_t ctrlReg4Value = l3gd20h::CTRL_REG_4_VAL; uint8_t ctrlReg4Value = L3GD20H::CTRL_REG_4_VAL;
uint8_t ctrlReg5Value = l3gd20h::CTRL_REG_5_VAL; uint8_t ctrlReg5Value = L3GD20H::CTRL_REG_5_VAL;
uint8_t commandBuffer[l3gd20h::READ_LEN + 1]; uint8_t commandBuffer[L3GD20H::READ_LEN + 1];
// Set default value // Set default value
float sensitivity = l3gd20h::SENSITIVITY_00; float sensitivity = L3GD20H::SENSITIVITY_00;
bool periodicPrintout = false; bool periodicPrintout = false;
PeriodicOperationDivider debugDivider = PeriodicOperationDivider(3); PeriodicOperationDivider debugDivider = PeriodicOperationDivider(3);

View File

@ -10,11 +10,11 @@ MgmLIS3MDLHandler::MgmLIS3MDLHandler(object_id_t objectId, object_id_t deviceCom
dataset(this), dataset(this),
transitionDelay(transitionDelay) { transitionDelay(transitionDelay) {
// Set to default values right away // Set to default values right away
registers[0] = mgmLis3::CTRL_REG1_DEFAULT; registers[0] = MGMLIS3MDL::CTRL_REG1_DEFAULT;
registers[1] = mgmLis3::CTRL_REG2_DEFAULT; registers[1] = MGMLIS3MDL::CTRL_REG2_DEFAULT;
registers[2] = mgmLis3::CTRL_REG3_DEFAULT; registers[2] = MGMLIS3MDL::CTRL_REG3_DEFAULT;
registers[3] = mgmLis3::CTRL_REG4_DEFAULT; registers[3] = MGMLIS3MDL::CTRL_REG4_DEFAULT;
registers[4] = mgmLis3::CTRL_REG5_DEFAULT; registers[4] = MGMLIS3MDL::CTRL_REG5_DEFAULT;
} }
MgmLIS3MDLHandler::~MgmLIS3MDLHandler() {} MgmLIS3MDLHandler::~MgmLIS3MDLHandler() {}
@ -63,15 +63,15 @@ ReturnValue_t MgmLIS3MDLHandler::buildTransitionDeviceCommand(DeviceCommandId_t
return DeviceHandlerBase::NOTHING_TO_SEND; return DeviceHandlerBase::NOTHING_TO_SEND;
} }
case (InternalState::STATE_FIRST_CONTACT): { case (InternalState::STATE_FIRST_CONTACT): {
*id = mgmLis3::IDENTIFY_DEVICE; *id = MGMLIS3MDL::IDENTIFY_DEVICE;
break; break;
} }
case (InternalState::STATE_SETUP): { case (InternalState::STATE_SETUP): {
*id = mgmLis3::SETUP_MGM; *id = MGMLIS3MDL::SETUP_MGM;
break; break;
} }
case (InternalState::STATE_CHECK_REGISTERS): { case (InternalState::STATE_CHECK_REGISTERS): {
*id = mgmLis3::READ_CONFIG_AND_DATA; *id = MGMLIS3MDL::READ_CONFIG_AND_DATA;
break; break;
} }
default: { default: {
@ -82,18 +82,34 @@ ReturnValue_t MgmLIS3MDLHandler::buildTransitionDeviceCommand(DeviceCommandId_t
#else #else
sif::printWarning("GyroHandler::buildTransitionDeviceCommand: Unknown internal state!\n"); sif::printWarning("GyroHandler::buildTransitionDeviceCommand: Unknown internal state!\n");
#endif /* FSFW_CPP_OSTREAM_ENABLED == 1 */ #endif /* FSFW_CPP_OSTREAM_ENABLED == 1 */
return returnvalue::OK; return HasReturnvaluesIF::RETURN_OK;
} }
} }
return buildCommandFromCommand(*id, NULL, 0); return buildCommandFromCommand(*id, NULL, 0);
} }
uint8_t MgmLIS3MDLHandler::readCommand(uint8_t command, bool continuousCom) {
command |= (1 << MGMLIS3MDL::RW_BIT);
if (continuousCom == true) {
command |= (1 << MGMLIS3MDL::MS_BIT);
}
return command;
}
uint8_t MgmLIS3MDLHandler::writeCommand(uint8_t command, bool continuousCom) {
command &= ~(1 << MGMLIS3MDL::RW_BIT);
if (continuousCom == true) {
command |= (1 << MGMLIS3MDL::MS_BIT);
}
return command;
}
void MgmLIS3MDLHandler::setupMgm() { void MgmLIS3MDLHandler::setupMgm() {
registers[0] = mgmLis3::CTRL_REG1_DEFAULT; registers[0] = MGMLIS3MDL::CTRL_REG1_DEFAULT;
registers[1] = mgmLis3::CTRL_REG2_DEFAULT; registers[1] = MGMLIS3MDL::CTRL_REG2_DEFAULT;
registers[2] = mgmLis3::CTRL_REG3_DEFAULT; registers[2] = MGMLIS3MDL::CTRL_REG3_DEFAULT;
registers[3] = mgmLis3::CTRL_REG4_DEFAULT; registers[3] = MGMLIS3MDL::CTRL_REG4_DEFAULT;
registers[4] = mgmLis3::CTRL_REG5_DEFAULT; registers[4] = MGMLIS3MDL::CTRL_REG5_DEFAULT;
prepareCtrlRegisterWrite(); prepareCtrlRegisterWrite();
} }
@ -101,11 +117,11 @@ void MgmLIS3MDLHandler::setupMgm() {
ReturnValue_t MgmLIS3MDLHandler::buildNormalDeviceCommand(DeviceCommandId_t *id) { ReturnValue_t MgmLIS3MDLHandler::buildNormalDeviceCommand(DeviceCommandId_t *id) {
// Data/config register will be read in an alternating manner. // Data/config register will be read in an alternating manner.
if (communicationStep == CommunicationStep::DATA) { if (communicationStep == CommunicationStep::DATA) {
*id = mgmLis3::READ_CONFIG_AND_DATA; *id = MGMLIS3MDL::READ_CONFIG_AND_DATA;
communicationStep = CommunicationStep::TEMPERATURE; communicationStep = CommunicationStep::TEMPERATURE;
return buildCommandFromCommand(*id, NULL, 0); return buildCommandFromCommand(*id, NULL, 0);
} else { } else {
*id = mgmLis3::READ_TEMPERATURE; *id = MGMLIS3MDL::READ_TEMPERATURE;
communicationStep = CommunicationStep::DATA; communicationStep = CommunicationStep::DATA;
return buildCommandFromCommand(*id, NULL, 0); return buildCommandFromCommand(*id, NULL, 0);
} }
@ -115,58 +131,58 @@ ReturnValue_t MgmLIS3MDLHandler::buildCommandFromCommand(DeviceCommandId_t devic
const uint8_t *commandData, const uint8_t *commandData,
size_t commandDataLen) { size_t commandDataLen) {
switch (deviceCommand) { switch (deviceCommand) {
case (mgmLis3::READ_CONFIG_AND_DATA): { case (MGMLIS3MDL::READ_CONFIG_AND_DATA): {
std::memset(commandBuffer, 0, sizeof(commandBuffer)); std::memset(commandBuffer, 0, sizeof(commandBuffer));
commandBuffer[0] = mgmLis3::readCommand(mgmLis3::CTRL_REG1, true); commandBuffer[0] = readCommand(MGMLIS3MDL::CTRL_REG1, true);
rawPacket = commandBuffer; rawPacket = commandBuffer;
rawPacketLen = mgmLis3::NR_OF_DATA_AND_CFG_REGISTERS + 1; rawPacketLen = MGMLIS3MDL::NR_OF_DATA_AND_CFG_REGISTERS + 1;
return returnvalue::OK; return RETURN_OK;
} }
case (mgmLis3::READ_TEMPERATURE): { case (MGMLIS3MDL::READ_TEMPERATURE): {
std::memset(commandBuffer, 0, 3); std::memset(commandBuffer, 0, 3);
commandBuffer[0] = mgmLis3::readCommand(mgmLis3::TEMP_LOWBYTE, true); commandBuffer[0] = readCommand(MGMLIS3MDL::TEMP_LOWBYTE, true);
rawPacket = commandBuffer; rawPacket = commandBuffer;
rawPacketLen = 3; rawPacketLen = 3;
return returnvalue::OK; return RETURN_OK;
} }
case (mgmLis3::IDENTIFY_DEVICE): { case (MGMLIS3MDL::IDENTIFY_DEVICE): {
return identifyDevice(); return identifyDevice();
} }
case (mgmLis3::TEMP_SENSOR_ENABLE): { case (MGMLIS3MDL::TEMP_SENSOR_ENABLE): {
return enableTemperatureSensor(commandData, commandDataLen); return enableTemperatureSensor(commandData, commandDataLen);
} }
case (mgmLis3::SETUP_MGM): { case (MGMLIS3MDL::SETUP_MGM): {
setupMgm(); setupMgm();
return returnvalue::OK; return HasReturnvaluesIF::RETURN_OK;
} }
case (mgmLis3::ACCURACY_OP_MODE_SET): { case (MGMLIS3MDL::ACCURACY_OP_MODE_SET): {
return setOperatingMode(commandData, commandDataLen); return setOperatingMode(commandData, commandDataLen);
} }
default: default:
return DeviceHandlerIF::COMMAND_NOT_IMPLEMENTED; return DeviceHandlerIF::COMMAND_NOT_IMPLEMENTED;
} }
return returnvalue::FAILED; return HasReturnvaluesIF::RETURN_FAILED;
} }
ReturnValue_t MgmLIS3MDLHandler::identifyDevice() { ReturnValue_t MgmLIS3MDLHandler::identifyDevice() {
uint32_t size = 2; uint32_t size = 2;
commandBuffer[0] = mgmLis3::readCommand(mgmLis3::IDENTIFY_DEVICE_REG_ADDR); commandBuffer[0] = readCommand(MGMLIS3MDL::IDENTIFY_DEVICE_REG_ADDR);
commandBuffer[1] = 0x00; commandBuffer[1] = 0x00;
rawPacket = commandBuffer; rawPacket = commandBuffer;
rawPacketLen = size; rawPacketLen = size;
return returnvalue::OK; return RETURN_OK;
} }
ReturnValue_t MgmLIS3MDLHandler::scanForReply(const uint8_t *start, size_t len, ReturnValue_t MgmLIS3MDLHandler::scanForReply(const uint8_t *start, size_t len,
DeviceCommandId_t *foundId, size_t *foundLen) { DeviceCommandId_t *foundId, size_t *foundLen) {
*foundLen = len; *foundLen = len;
if (len == mgmLis3::NR_OF_DATA_AND_CFG_REGISTERS + 1) { if (len == MGMLIS3MDL::NR_OF_DATA_AND_CFG_REGISTERS + 1) {
*foundLen = len; *foundLen = len;
*foundId = mgmLis3::READ_CONFIG_AND_DATA; *foundId = MGMLIS3MDL::READ_CONFIG_AND_DATA;
// Check validity by checking config registers // Check validity by checking config registers
if (start[1] != registers[0] or start[2] != registers[1] or start[3] != registers[2] or if (start[1] != registers[0] or start[2] != registers[1] or start[3] != registers[2] or
start[4] != registers[3] or start[5] != registers[4]) { start[4] != registers[3] or start[5] != registers[4]) {
@ -179,21 +195,21 @@ ReturnValue_t MgmLIS3MDLHandler::scanForReply(const uint8_t *start, size_t len,
#endif #endif
return DeviceHandlerIF::INVALID_DATA; return DeviceHandlerIF::INVALID_DATA;
} }
if (getMode() == _MODE_START_UP) { if (mode == _MODE_START_UP) {
commandExecuted = true; commandExecuted = true;
} }
} else if (len == mgmLis3::TEMPERATURE_REPLY_LEN) { } else if (len == MGMLIS3MDL::TEMPERATURE_REPLY_LEN) {
*foundLen = len; *foundLen = len;
*foundId = mgmLis3::READ_TEMPERATURE; *foundId = MGMLIS3MDL::READ_TEMPERATURE;
} else if (len == mgmLis3::SETUP_REPLY_LEN) { } else if (len == MGMLIS3MDL::SETUP_REPLY_LEN) {
*foundLen = len; *foundLen = len;
*foundId = mgmLis3::SETUP_MGM; *foundId = MGMLIS3MDL::SETUP_MGM;
} else if (len == SINGLE_COMMAND_ANSWER_LEN) { } else if (len == SINGLE_COMMAND_ANSWER_LEN) {
*foundLen = len; *foundLen = len;
*foundId = getPendingCommand(); *foundId = getPendingCommand();
if (*foundId == mgmLis3::IDENTIFY_DEVICE) { if (*foundId == MGMLIS3MDL::IDENTIFY_DEVICE) {
if (start[1] != mgmLis3::DEVICE_ID) { if (start[1] != MGMLIS3MDL::DEVICE_ID) {
#if FSFW_VERBOSE_LEVEL >= 1 #if FSFW_VERBOSE_LEVEL >= 1
#if FSFW_CPP_OSTREAM_ENABLED == 1 #if FSFW_CPP_OSTREAM_ENABLED == 1
sif::warning << "MGMHandlerLIS3MDL::scanForReply: " sif::warning << "MGMHandlerLIS3MDL::scanForReply: "
@ -208,7 +224,7 @@ ReturnValue_t MgmLIS3MDLHandler::scanForReply(const uint8_t *start, size_t len,
return DeviceHandlerIF::INVALID_DATA; return DeviceHandlerIF::INVALID_DATA;
} }
if (getMode() == _MODE_START_UP) { if (mode == _MODE_START_UP) {
commandExecuted = true; commandExecuted = true;
} }
} }
@ -218,38 +234,37 @@ ReturnValue_t MgmLIS3MDLHandler::scanForReply(const uint8_t *start, size_t len,
/* Data with SPI Interface always has this answer */ /* Data with SPI Interface always has this answer */
if (start[0] == 0b11111111) { if (start[0] == 0b11111111) {
return returnvalue::OK; return RETURN_OK;
} else { } else {
return DeviceHandlerIF::INVALID_DATA; return DeviceHandlerIF::INVALID_DATA;
} }
} }
ReturnValue_t MgmLIS3MDLHandler::interpretDeviceReply(DeviceCommandId_t id, const uint8_t *packet) { ReturnValue_t MgmLIS3MDLHandler::interpretDeviceReply(DeviceCommandId_t id, const uint8_t *packet) {
switch (id) { switch (id) {
case mgmLis3::IDENTIFY_DEVICE: { case MGMLIS3MDL::IDENTIFY_DEVICE: {
break; break;
} }
case mgmLis3::SETUP_MGM: { case MGMLIS3MDL::SETUP_MGM: {
break; break;
} }
case mgmLis3::READ_CONFIG_AND_DATA: { case MGMLIS3MDL::READ_CONFIG_AND_DATA: {
using namespace mgmLis3;
// TODO: Store configuration in new local datasets. // TODO: Store configuration in new local datasets.
float sensitivityFactor = getSensitivityFactor(getSensitivity(registers[2])); float sensitivityFactor = getSensitivityFactor(getSensitivity(registers[2]));
int16_t mgmMeasurementRawX = int16_t mgmMeasurementRawX =
packet[mgmLis3::X_HIGHBYTE_IDX] << 8 | packet[mgmLis3::X_LOWBYTE_IDX]; packet[MGMLIS3MDL::X_HIGHBYTE_IDX] << 8 | packet[MGMLIS3MDL::X_LOWBYTE_IDX];
int16_t mgmMeasurementRawY = int16_t mgmMeasurementRawY =
packet[mgmLis3::Y_HIGHBYTE_IDX] << 8 | packet[mgmLis3::Y_LOWBYTE_IDX]; packet[MGMLIS3MDL::Y_HIGHBYTE_IDX] << 8 | packet[MGMLIS3MDL::Y_LOWBYTE_IDX];
int16_t mgmMeasurementRawZ = int16_t mgmMeasurementRawZ =
packet[mgmLis3::Z_HIGHBYTE_IDX] << 8 | packet[mgmLis3::Z_LOWBYTE_IDX]; packet[MGMLIS3MDL::Z_HIGHBYTE_IDX] << 8 | packet[MGMLIS3MDL::Z_LOWBYTE_IDX];
// Target value in microtesla // Target value in microtesla
float mgmX = static_cast<float>(mgmMeasurementRawX) * sensitivityFactor * float mgmX = static_cast<float>(mgmMeasurementRawX) * sensitivityFactor *
mgmLis3::GAUSS_TO_MICROTESLA_FACTOR; MGMLIS3MDL::GAUSS_TO_MICROTESLA_FACTOR;
float mgmY = static_cast<float>(mgmMeasurementRawY) * sensitivityFactor * float mgmY = static_cast<float>(mgmMeasurementRawY) * sensitivityFactor *
mgmLis3::GAUSS_TO_MICROTESLA_FACTOR; MGMLIS3MDL::GAUSS_TO_MICROTESLA_FACTOR;
float mgmZ = static_cast<float>(mgmMeasurementRawZ) * sensitivityFactor * float mgmZ = static_cast<float>(mgmMeasurementRawZ) * sensitivityFactor *
mgmLis3::GAUSS_TO_MICROTESLA_FACTOR; MGMLIS3MDL::GAUSS_TO_MICROTESLA_FACTOR;
if (periodicPrintout) { if (periodicPrintout) {
if (debugDivider.checkAndIncrement()) { if (debugDivider.checkAndIncrement()) {
@ -270,28 +285,32 @@ ReturnValue_t MgmLIS3MDLHandler::interpretDeviceReply(DeviceCommandId_t id, cons
} }
PoolReadGuard readHelper(&dataset); PoolReadGuard readHelper(&dataset);
if (readHelper.getReadResult() == returnvalue::OK) { if (readHelper.getReadResult() == HasReturnvaluesIF::RETURN_OK) {
if (std::abs(mgmX) > absLimitX or std::abs(mgmY) > absLimitY or
std::abs(mgmZ) > absLimitZ) {
dataset.fieldStrengths.setValid(false);
}
if (std::abs(mgmX) < absLimitX) { if (std::abs(mgmX) < absLimitX) {
dataset.fieldStrengths[0] = mgmX; dataset.fieldStrengthX = mgmX;
dataset.fieldStrengthX.setValid(true);
} else {
dataset.fieldStrengthX.setValid(false);
} }
if (std::abs(mgmY) < absLimitY) { if (std::abs(mgmY) < absLimitY) {
dataset.fieldStrengths[1] = mgmY; dataset.fieldStrengthY = mgmY;
dataset.fieldStrengthY.setValid(true);
} else {
dataset.fieldStrengthY.setValid(false);
} }
if (std::abs(mgmZ) < absLimitZ) { if (std::abs(mgmZ) < absLimitZ) {
dataset.fieldStrengths[2] = mgmZ; dataset.fieldStrengthZ = mgmZ;
dataset.fieldStrengthZ.setValid(true);
} else {
dataset.fieldStrengthZ.setValid(false);
} }
dataset.fieldStrengths.setValid(true);
} }
break; break;
} }
case mgmLis3::READ_TEMPERATURE: { case MGMLIS3MDL::READ_TEMPERATURE: {
int16_t tempValueRaw = packet[2] << 8 | packet[1]; int16_t tempValueRaw = packet[2] << 8 | packet[1];
float tempValue = 25.0 + ((static_cast<float>(tempValueRaw)) / 8.0); float tempValue = 25.0 + ((static_cast<float>(tempValueRaw)) / 8.0);
if (periodicPrintout) { if (periodicPrintout) {
@ -305,7 +324,7 @@ ReturnValue_t MgmLIS3MDLHandler::interpretDeviceReply(DeviceCommandId_t id, cons
} }
ReturnValue_t result = dataset.read(); ReturnValue_t result = dataset.read();
if (result == returnvalue::OK) { if (result == HasReturnvaluesIF::RETURN_OK) {
dataset.temperature = tempValue; dataset.temperature = tempValue;
dataset.commit(); dataset.commit();
} }
@ -316,7 +335,42 @@ ReturnValue_t MgmLIS3MDLHandler::interpretDeviceReply(DeviceCommandId_t id, cons
return DeviceHandlerIF::UNKNOWN_DEVICE_REPLY; return DeviceHandlerIF::UNKNOWN_DEVICE_REPLY;
} }
} }
return returnvalue::OK; return RETURN_OK;
}
MGMLIS3MDL::Sensitivies MgmLIS3MDLHandler::getSensitivity(uint8_t ctrlRegister2) {
bool fs0Set = ctrlRegister2 & (1 << MGMLIS3MDL::FSO); // Checks if FS0 bit is set
bool fs1Set = ctrlRegister2 & (1 << MGMLIS3MDL::FS1); // Checks if FS1 bit is set
if (fs0Set && fs1Set)
return MGMLIS3MDL::Sensitivies::GAUSS_16;
else if (!fs0Set && fs1Set)
return MGMLIS3MDL::Sensitivies::GAUSS_12;
else if (fs0Set && !fs1Set)
return MGMLIS3MDL::Sensitivies::GAUSS_8;
else
return MGMLIS3MDL::Sensitivies::GAUSS_4;
}
float MgmLIS3MDLHandler::getSensitivityFactor(MGMLIS3MDL::Sensitivies sens) {
switch (sens) {
case (MGMLIS3MDL::GAUSS_4): {
return MGMLIS3MDL::FIELD_LSB_PER_GAUSS_4_SENS;
}
case (MGMLIS3MDL::GAUSS_8): {
return MGMLIS3MDL::FIELD_LSB_PER_GAUSS_8_SENS;
}
case (MGMLIS3MDL::GAUSS_12): {
return MGMLIS3MDL::FIELD_LSB_PER_GAUSS_12_SENS;
}
case (MGMLIS3MDL::GAUSS_16): {
return MGMLIS3MDL::FIELD_LSB_PER_GAUSS_16_SENS;
}
default: {
// Should never happen
return MGMLIS3MDL::FIELD_LSB_PER_GAUSS_4_SENS;
}
}
} }
ReturnValue_t MgmLIS3MDLHandler::enableTemperatureSensor(const uint8_t *commandData, ReturnValue_t MgmLIS3MDLHandler::enableTemperatureSensor(const uint8_t *commandData,
@ -326,16 +380,16 @@ ReturnValue_t MgmLIS3MDLHandler::enableTemperatureSensor(const uint8_t *commandD
} }
triggerEvent(CHANGE_OF_SETUP_PARAMETER); triggerEvent(CHANGE_OF_SETUP_PARAMETER);
uint32_t size = 2; uint32_t size = 2;
commandBuffer[0] = mgmLis3::writeCommand(mgmLis3::CTRL_REG1); commandBuffer[0] = writeCommand(MGMLIS3MDL::CTRL_REG1);
if (commandDataLen > 1) { if (commandDataLen > 1) {
return INVALID_NUMBER_OR_LENGTH_OF_PARAMETERS; return INVALID_NUMBER_OR_LENGTH_OF_PARAMETERS;
} }
switch (commandData[0]) { switch (commandData[0]) {
case (mgmLis3::ON): { case (MGMLIS3MDL::ON): {
commandBuffer[1] = registers[0] | (1 << 7); commandBuffer[1] = registers[0] | (1 << 7);
break; break;
} }
case (mgmLis3::OFF): { case (MGMLIS3MDL::OFF): {
commandBuffer[1] = registers[0] & ~(1 << 7); commandBuffer[1] = registers[0] & ~(1 << 7);
break; break;
} }
@ -347,7 +401,7 @@ ReturnValue_t MgmLIS3MDLHandler::enableTemperatureSensor(const uint8_t *commandD
rawPacket = commandBuffer; rawPacket = commandBuffer;
rawPacketLen = size; rawPacketLen = size;
return returnvalue::OK; return RETURN_OK;
} }
ReturnValue_t MgmLIS3MDLHandler::setOperatingMode(const uint8_t *commandData, ReturnValue_t MgmLIS3MDLHandler::setOperatingMode(const uint8_t *commandData,
@ -358,23 +412,23 @@ ReturnValue_t MgmLIS3MDLHandler::setOperatingMode(const uint8_t *commandData,
} }
switch (commandData[0]) { switch (commandData[0]) {
case mgmLis3::LOW: case MGMLIS3MDL::LOW:
registers[0] = (registers[0] & (~(1 << mgmLis3::OM1))) & (~(1 << mgmLis3::OM0)); registers[0] = (registers[0] & (~(1 << MGMLIS3MDL::OM1))) & (~(1 << MGMLIS3MDL::OM0));
registers[3] = (registers[3] & (~(1 << mgmLis3::OMZ1))) & (~(1 << mgmLis3::OMZ0)); registers[3] = (registers[3] & (~(1 << MGMLIS3MDL::OMZ1))) & (~(1 << MGMLIS3MDL::OMZ0));
break; break;
case mgmLis3::MEDIUM: case MGMLIS3MDL::MEDIUM:
registers[0] = (registers[0] & (~(1 << mgmLis3::OM1))) | (1 << mgmLis3::OM0); registers[0] = (registers[0] & (~(1 << MGMLIS3MDL::OM1))) | (1 << MGMLIS3MDL::OM0);
registers[3] = (registers[3] & (~(1 << mgmLis3::OMZ1))) | (1 << mgmLis3::OMZ0); registers[3] = (registers[3] & (~(1 << MGMLIS3MDL::OMZ1))) | (1 << MGMLIS3MDL::OMZ0);
break; break;
case mgmLis3::HIGH: case MGMLIS3MDL::HIGH:
registers[0] = (registers[0] | (1 << mgmLis3::OM1)) & (~(1 << mgmLis3::OM0)); registers[0] = (registers[0] | (1 << MGMLIS3MDL::OM1)) & (~(1 << MGMLIS3MDL::OM0));
registers[3] = (registers[3] | (1 << mgmLis3::OMZ1)) & (~(1 << mgmLis3::OMZ0)); registers[3] = (registers[3] | (1 << MGMLIS3MDL::OMZ1)) & (~(1 << MGMLIS3MDL::OMZ0));
break; break;
case mgmLis3::ULTRA: case MGMLIS3MDL::ULTRA:
registers[0] = (registers[0] | (1 << mgmLis3::OM1)) | (1 << mgmLis3::OM0); registers[0] = (registers[0] | (1 << MGMLIS3MDL::OM1)) | (1 << MGMLIS3MDL::OM0);
registers[3] = (registers[3] | (1 << mgmLis3::OMZ1)) | (1 << mgmLis3::OMZ0); registers[3] = (registers[3] | (1 << MGMLIS3MDL::OMZ1)) | (1 << MGMLIS3MDL::OMZ0);
break; break;
default: default:
break; break;
@ -384,27 +438,27 @@ ReturnValue_t MgmLIS3MDLHandler::setOperatingMode(const uint8_t *commandData,
} }
void MgmLIS3MDLHandler::fillCommandAndReplyMap() { void MgmLIS3MDLHandler::fillCommandAndReplyMap() {
insertInCommandAndReplyMap(mgmLis3::READ_CONFIG_AND_DATA, 1, &dataset); insertInCommandAndReplyMap(MGMLIS3MDL::READ_CONFIG_AND_DATA, 1, &dataset);
insertInCommandAndReplyMap(mgmLis3::READ_TEMPERATURE, 1); insertInCommandAndReplyMap(MGMLIS3MDL::READ_TEMPERATURE, 1);
insertInCommandAndReplyMap(mgmLis3::SETUP_MGM, 1); insertInCommandAndReplyMap(MGMLIS3MDL::SETUP_MGM, 1);
insertInCommandAndReplyMap(mgmLis3::IDENTIFY_DEVICE, 1); insertInCommandAndReplyMap(MGMLIS3MDL::IDENTIFY_DEVICE, 1);
insertInCommandAndReplyMap(mgmLis3::TEMP_SENSOR_ENABLE, 1); insertInCommandAndReplyMap(MGMLIS3MDL::TEMP_SENSOR_ENABLE, 1);
insertInCommandAndReplyMap(mgmLis3::ACCURACY_OP_MODE_SET, 1); insertInCommandAndReplyMap(MGMLIS3MDL::ACCURACY_OP_MODE_SET, 1);
} }
void MgmLIS3MDLHandler::setToGoToNormalMode(bool enable) { this->goToNormalMode = enable; } void MgmLIS3MDLHandler::setToGoToNormalMode(bool enable) { this->goToNormalMode = enable; }
ReturnValue_t MgmLIS3MDLHandler::prepareCtrlRegisterWrite() { ReturnValue_t MgmLIS3MDLHandler::prepareCtrlRegisterWrite() {
commandBuffer[0] = mgmLis3::writeCommand(mgmLis3::CTRL_REG1, true); commandBuffer[0] = writeCommand(MGMLIS3MDL::CTRL_REG1, true);
for (size_t i = 0; i < mgmLis3::NR_OF_CTRL_REGISTERS; i++) { for (size_t i = 0; i < MGMLIS3MDL::NR_OF_CTRL_REGISTERS; i++) {
commandBuffer[i + 1] = registers[i]; commandBuffer[i + 1] = registers[i];
} }
rawPacket = commandBuffer; rawPacket = commandBuffer;
rawPacketLen = mgmLis3::NR_OF_CTRL_REGISTERS + 1; rawPacketLen = MGMLIS3MDL::NR_OF_CTRL_REGISTERS + 1;
// We dont have to check if this is working because we just did i // We dont have to check if this is working because we just did i
return returnvalue::OK; return RETURN_OK;
} }
void MgmLIS3MDLHandler::doTransition(Mode_t modeFrom, Submode_t subModeFrom) { void MgmLIS3MDLHandler::doTransition(Mode_t modeFrom, Submode_t subModeFrom) {
@ -417,10 +471,11 @@ void MgmLIS3MDLHandler::modeChanged(void) { internalState = InternalState::STATE
ReturnValue_t MgmLIS3MDLHandler::initializeLocalDataPool(localpool::DataPool &localDataPoolMap, ReturnValue_t MgmLIS3MDLHandler::initializeLocalDataPool(localpool::DataPool &localDataPoolMap,
LocalDataPoolManager &poolManager) { LocalDataPoolManager &poolManager) {
localDataPoolMap.emplace(mgmLis3::FIELD_STRENGTHS, &mgmXYZ); localDataPoolMap.emplace(MGMLIS3MDL::FIELD_STRENGTH_X, new PoolEntry<float>({0.0}));
localDataPoolMap.emplace(mgmLis3::TEMPERATURE_CELCIUS, &temperature); localDataPoolMap.emplace(MGMLIS3MDL::FIELD_STRENGTH_Y, new PoolEntry<float>({0.0}));
poolManager.subscribeForRegularPeriodicPacket({dataset.getSid(), false, 10.0}); localDataPoolMap.emplace(MGMLIS3MDL::FIELD_STRENGTH_Z, new PoolEntry<float>({0.0}));
return returnvalue::OK; localDataPoolMap.emplace(MGMLIS3MDL::TEMPERATURE_CELCIUS, new PoolEntry<float>({0.0}));
return HasReturnvaluesIF::RETURN_OK;
} }
void MgmLIS3MDLHandler::setAbsoluteLimits(float xLimit, float yLimit, float zLimit) { void MgmLIS3MDLHandler::setAbsoluteLimits(float xLimit, float yLimit, float zLimit) {

View File

@ -1,8 +1,8 @@
#ifndef MISSION_DEVICES_MGMLIS3MDLHANDLER_H_ #ifndef MISSION_DEVICES_MGMLIS3MDLHANDLER_H_
#define MISSION_DEVICES_MGMLIS3MDLHANDLER_H_ #define MISSION_DEVICES_MGMLIS3MDLHANDLER_H_
#include <fsfw_hal/devicehandlers/devicedefinitions/mgmLis3Helpers.h> #include "devicedefinitions/MgmLIS3HandlerDefs.h"
#include "events/subsystemIdRanges.h"
#include "fsfw/devicehandlers/DeviceHandlerBase.h" #include "fsfw/devicehandlers/DeviceHandlerBase.h"
#include "fsfw/globalfunctions/PeriodicOperationDivider.h" #include "fsfw/globalfunctions/PeriodicOperationDivider.h"
@ -67,7 +67,7 @@ class MgmLIS3MDLHandler : public DeviceHandlerBase {
LocalDataPoolManager &poolManager) override; LocalDataPoolManager &poolManager) override;
private: private:
mgmLis3::MgmPrimaryDataset dataset; MGMLIS3MDL::MgmPrimaryDataset dataset;
// Length a single command SPI answer // Length a single command SPI answer
static const uint8_t SINGLE_COMMAND_ANSWER_LEN = 2; static const uint8_t SINGLE_COMMAND_ANSWER_LEN = 2;
@ -75,7 +75,7 @@ class MgmLIS3MDLHandler : public DeviceHandlerBase {
// Single SPI command has 2 bytes, first for adress, second for content // Single SPI command has 2 bytes, first for adress, second for content
size_t singleComandSize = 2; size_t singleComandSize = 2;
// Has the size for all adresses of the lis3mdl + the continous write bit // Has the size for all adresses of the lis3mdl + the continous write bit
uint8_t commandBuffer[mgmLis3::NR_OF_DATA_AND_CFG_REGISTERS + 1]; uint8_t commandBuffer[MGMLIS3MDL::NR_OF_DATA_AND_CFG_REGISTERS + 1];
float absLimitX = 100; float absLimitX = 100;
float absLimitY = 100; float absLimitY = 100;
@ -86,7 +86,7 @@ class MgmLIS3MDLHandler : public DeviceHandlerBase {
* registers when we want to change something. * registers when we want to change something.
* --> everytime we change set a register we have to save it * --> everytime we change set a register we have to save it
*/ */
uint8_t registers[mgmLis3::NR_OF_CTRL_REGISTERS]; uint8_t registers[MGMLIS3MDL::NR_OF_CTRL_REGISTERS];
uint8_t statusRegister = 0; uint8_t statusRegister = 0;
bool goToNormalMode = false; bool goToNormalMode = false;
@ -103,11 +103,38 @@ class MgmLIS3MDLHandler : public DeviceHandlerBase {
CommunicationStep communicationStep = CommunicationStep::DATA; CommunicationStep communicationStep = CommunicationStep::DATA;
bool commandExecuted = false; bool commandExecuted = false;
PoolEntry<float> mgmXYZ = PoolEntry<float>(3);
PoolEntry<float> temperature = PoolEntry<float>();
/*------------------------------------------------------------------------*/ /*------------------------------------------------------------------------*/
/* Device specific commands and variables */ /* Device specific commands and variables */
/*------------------------------------------------------------------------*/ /*------------------------------------------------------------------------*/
/**
* Sets the read bit for the command
* @param single command to set the read-bit at
* @param boolean to select a continuous read bit, default = false
*/
uint8_t readCommand(uint8_t command, bool continuousCom = false);
/**
* Sets the write bit for the command
* @param single command to set the write-bit at
* @param boolean to select a continuous write bit, default = false
*/
uint8_t writeCommand(uint8_t command, bool continuousCom = false);
/**
* This Method gets the full scale for the measurement range
* e.g.: +- 4 gauss. See p.25 datasheet.
* @return The ReturnValue does not contain the sign of the value
*/
MGMLIS3MDL::Sensitivies getSensitivity(uint8_t ctrlReg2);
/**
* The 16 bit value needs to be multiplied with a sensitivity factor
* which depends on the sensitivity configuration
*
* @param sens Configured sensitivity of the LIS3 device
* @return Multiplication factor to get the sensor value from raw data.
*/
float getSensitivityFactor(MGMLIS3MDL::Sensitivies sens);
/** /**
* This Command detects the device ID * This Command detects the device ID

View File

@ -4,7 +4,7 @@
#include "fsfw/devicehandlers/DeviceHandlerMessage.h" #include "fsfw/devicehandlers/DeviceHandlerMessage.h"
#include "fsfw/globalfunctions/bitutility.h" #include "fsfw/globalfunctions/bitutility.h"
#include "fsfw/objectmanager/SystemObjectIF.h" #include "fsfw/objectmanager/SystemObjectIF.h"
#include "fsfw/returnvalues/returnvalue.h" #include "fsfw/returnvalues/HasReturnvaluesIF.h"
MgmRM3100Handler::MgmRM3100Handler(object_id_t objectId, object_id_t deviceCommunication, MgmRM3100Handler::MgmRM3100Handler(object_id_t objectId, object_id_t deviceCommunication,
CookieIF *comCookie, uint32_t transitionDelay) CookieIF *comCookie, uint32_t transitionDelay)
@ -63,21 +63,21 @@ ReturnValue_t MgmRM3100Handler::buildTransitionDeviceCommand(DeviceCommandId_t *
return NOTHING_TO_SEND; return NOTHING_TO_SEND;
} }
case (InternalState::CONFIGURE_CMM): { case (InternalState::CONFIGURE_CMM): {
*id = mgmRm3100::CONFIGURE_CMM; *id = RM3100::CONFIGURE_CMM;
break; break;
} }
case (InternalState::READ_CMM): { case (InternalState::READ_CMM): {
*id = mgmRm3100::READ_CMM; *id = RM3100::READ_CMM;
break; break;
} }
case (InternalState::STATE_CONFIGURE_TMRC): { case (InternalState::STATE_CONFIGURE_TMRC): {
commandBuffer[0] = mgmRm3100::TMRC_DEFAULT_VALUE; commandBuffer[0] = RM3100::TMRC_DEFAULT_VALUE;
commandLen = 1; commandLen = 1;
*id = mgmRm3100::CONFIGURE_TMRC; *id = RM3100::CONFIGURE_TMRC;
break; break;
} }
case (InternalState::STATE_READ_TMRC): { case (InternalState::STATE_READ_TMRC): {
*id = mgmRm3100::READ_TMRC; *id = RM3100::READ_TMRC;
break; break;
} }
default: default:
@ -93,7 +93,7 @@ ReturnValue_t MgmRM3100Handler::buildTransitionDeviceCommand(DeviceCommandId_t *
"Unknown internal state\n"); "Unknown internal state\n");
#endif #endif
#endif #endif
return returnvalue::OK; return HasReturnvaluesIF::RETURN_OK;
} }
return buildCommandFromCommand(*id, commandBuffer, commandLen); return buildCommandFromCommand(*id, commandBuffer, commandLen);
@ -103,42 +103,42 @@ ReturnValue_t MgmRM3100Handler::buildCommandFromCommand(DeviceCommandId_t device
const uint8_t *commandData, const uint8_t *commandData,
size_t commandDataLen) { size_t commandDataLen) {
switch (deviceCommand) { switch (deviceCommand) {
case (mgmRm3100::CONFIGURE_CMM): { case (RM3100::CONFIGURE_CMM): {
commandBuffer[0] = mgmRm3100::CMM_REGISTER; commandBuffer[0] = RM3100::CMM_REGISTER;
commandBuffer[1] = mgmRm3100::CMM_VALUE; commandBuffer[1] = RM3100::CMM_VALUE;
rawPacket = commandBuffer; rawPacket = commandBuffer;
rawPacketLen = 2; rawPacketLen = 2;
break; break;
} }
case (mgmRm3100::READ_CMM): { case (RM3100::READ_CMM): {
commandBuffer[0] = mgmRm3100::CMM_REGISTER | mgmRm3100::READ_MASK; commandBuffer[0] = RM3100::CMM_REGISTER | RM3100::READ_MASK;
commandBuffer[1] = 0; commandBuffer[1] = 0;
rawPacket = commandBuffer; rawPacket = commandBuffer;
rawPacketLen = 2; rawPacketLen = 2;
break; break;
} }
case (mgmRm3100::CONFIGURE_TMRC): { case (RM3100::CONFIGURE_TMRC): {
return handleTmrcConfigCommand(deviceCommand, commandData, commandDataLen); return handleTmrcConfigCommand(deviceCommand, commandData, commandDataLen);
} }
case (mgmRm3100::READ_TMRC): { case (RM3100::READ_TMRC): {
commandBuffer[0] = mgmRm3100::TMRC_REGISTER | mgmRm3100::READ_MASK; commandBuffer[0] = RM3100::TMRC_REGISTER | RM3100::READ_MASK;
commandBuffer[1] = 0; commandBuffer[1] = 0;
rawPacket = commandBuffer; rawPacket = commandBuffer;
rawPacketLen = 2; rawPacketLen = 2;
break; break;
} }
case (mgmRm3100::CONFIGURE_CYCLE_COUNT): { case (RM3100::CONFIGURE_CYCLE_COUNT): {
return handleCycleCountConfigCommand(deviceCommand, commandData, commandDataLen); return handleCycleCountConfigCommand(deviceCommand, commandData, commandDataLen);
} }
case (mgmRm3100::READ_CYCLE_COUNT): { case (RM3100::READ_CYCLE_COUNT): {
commandBuffer[0] = mgmRm3100::CYCLE_COUNT_START_REGISTER | mgmRm3100::READ_MASK; commandBuffer[0] = RM3100::CYCLE_COUNT_START_REGISTER | RM3100::READ_MASK;
std::memset(commandBuffer + 1, 0, 6); std::memset(commandBuffer + 1, 0, 6);
rawPacket = commandBuffer; rawPacket = commandBuffer;
rawPacketLen = 7; rawPacketLen = 7;
break; break;
} }
case (mgmRm3100::READ_DATA): { case (RM3100::READ_DATA): {
commandBuffer[0] = mgmRm3100::MEASUREMENT_REG_START | mgmRm3100::READ_MASK; commandBuffer[0] = RM3100::MEASUREMENT_REG_START | RM3100::READ_MASK;
std::memset(commandBuffer + 1, 0, 9); std::memset(commandBuffer + 1, 0, 9);
rawPacketLen = 10; rawPacketLen = 10;
break; break;
@ -146,11 +146,11 @@ ReturnValue_t MgmRM3100Handler::buildCommandFromCommand(DeviceCommandId_t device
default: default:
return DeviceHandlerIF::COMMAND_NOT_IMPLEMENTED; return DeviceHandlerIF::COMMAND_NOT_IMPLEMENTED;
} }
return returnvalue::OK; return RETURN_OK;
} }
ReturnValue_t MgmRM3100Handler::buildNormalDeviceCommand(DeviceCommandId_t *id) { ReturnValue_t MgmRM3100Handler::buildNormalDeviceCommand(DeviceCommandId_t *id) {
*id = mgmRm3100::READ_DATA; *id = RM3100::READ_DATA;
return buildCommandFromCommand(*id, nullptr, 0); return buildCommandFromCommand(*id, nullptr, 0);
} }
@ -159,22 +159,22 @@ ReturnValue_t MgmRM3100Handler::scanForReply(const uint8_t *start, size_t len,
// For SPI, ID will always be the one of the last sent command // For SPI, ID will always be the one of the last sent command
*foundId = this->getPendingCommand(); *foundId = this->getPendingCommand();
*foundLen = len; *foundLen = len;
return returnvalue::OK; return HasReturnvaluesIF::RETURN_OK;
} }
ReturnValue_t MgmRM3100Handler::interpretDeviceReply(DeviceCommandId_t id, const uint8_t *packet) { ReturnValue_t MgmRM3100Handler::interpretDeviceReply(DeviceCommandId_t id, const uint8_t *packet) {
ReturnValue_t result = returnvalue::OK; ReturnValue_t result = HasReturnvaluesIF::RETURN_OK;
switch (id) { switch (id) {
case (mgmRm3100::CONFIGURE_CMM): case (RM3100::CONFIGURE_CMM):
case (mgmRm3100::CONFIGURE_CYCLE_COUNT): case (RM3100::CONFIGURE_CYCLE_COUNT):
case (mgmRm3100::CONFIGURE_TMRC): { case (RM3100::CONFIGURE_TMRC): {
// We can only check whether write was successful with read operation // We can only check whether write was successful with read operation
if (getMode() == _MODE_START_UP) { if (mode == _MODE_START_UP) {
commandExecuted = true; commandExecuted = true;
} }
break; break;
} }
case (mgmRm3100::READ_CMM): { case (RM3100::READ_CMM): {
uint8_t cmmValue = packet[1]; uint8_t cmmValue = packet[1];
// We clear the seventh bit in any case // We clear the seventh bit in any case
// because this one is zero sometimes for some reason // because this one is zero sometimes for some reason
@ -188,11 +188,11 @@ ReturnValue_t MgmRM3100Handler::interpretDeviceReply(DeviceCommandId_t id, const
} }
break; break;
} }
case (mgmRm3100::READ_TMRC): { case (RM3100::READ_TMRC): {
if (packet[1] == tmrcRegValue) { if (packet[1] == tmrcRegValue) {
commandExecuted = true; commandExecuted = true;
// Reading TMRC was commanded. Trigger event to inform ground // Reading TMRC was commanded. Trigger event to inform ground
if (getMode() != _MODE_START_UP) { if (mode != _MODE_START_UP) {
triggerEvent(tmrcSet, tmrcRegValue, 0); triggerEvent(tmrcSet, tmrcRegValue, 0);
} }
} else { } else {
@ -202,7 +202,7 @@ ReturnValue_t MgmRM3100Handler::interpretDeviceReply(DeviceCommandId_t id, const
} }
break; break;
} }
case (mgmRm3100::READ_CYCLE_COUNT): { case (RM3100::READ_CYCLE_COUNT): {
uint16_t cycleCountX = packet[1] << 8 | packet[2]; uint16_t cycleCountX = packet[1] << 8 | packet[2];
uint16_t cycleCountY = packet[3] << 8 | packet[4]; uint16_t cycleCountY = packet[3] << 8 | packet[4];
uint16_t cycleCountZ = packet[5] << 8 | packet[6]; uint16_t cycleCountZ = packet[5] << 8 | packet[6];
@ -211,13 +211,13 @@ ReturnValue_t MgmRM3100Handler::interpretDeviceReply(DeviceCommandId_t id, const
return DeviceHandlerIF::DEVICE_REPLY_INVALID; return DeviceHandlerIF::DEVICE_REPLY_INVALID;
} }
// Reading TMRC was commanded. Trigger event to inform ground // Reading TMRC was commanded. Trigger event to inform ground
if (getMode() != _MODE_START_UP) { if (mode != _MODE_START_UP) {
uint32_t eventParam1 = (cycleCountX << 16) | cycleCountY; uint32_t eventParam1 = (cycleCountX << 16) | cycleCountY;
triggerEvent(cycleCountersSet, eventParam1, cycleCountZ); triggerEvent(cycleCountersSet, eventParam1, cycleCountZ);
} }
break; break;
} }
case (mgmRm3100::READ_DATA): { case (RM3100::READ_DATA): {
result = handleDataReadout(packet); result = handleDataReadout(packet);
break; break;
} }
@ -244,21 +244,21 @@ ReturnValue_t MgmRM3100Handler::handleCycleCountConfigCommand(DeviceCommandId_t
return DeviceHandlerIF::INVALID_COMMAND_PARAMETER; return DeviceHandlerIF::INVALID_COMMAND_PARAMETER;
} }
commandBuffer[0] = mgmRm3100::CYCLE_COUNT_VALUE; commandBuffer[0] = RM3100::CYCLE_COUNT_VALUE;
std::memcpy(commandBuffer + 1, &cycleCountRegValueX, 2); std::memcpy(commandBuffer + 1, &cycleCountRegValueX, 2);
std::memcpy(commandBuffer + 3, &cycleCountRegValueY, 2); std::memcpy(commandBuffer + 3, &cycleCountRegValueY, 2);
std::memcpy(commandBuffer + 5, &cycleCountRegValueZ, 2); std::memcpy(commandBuffer + 5, &cycleCountRegValueZ, 2);
rawPacketLen = 7; rawPacketLen = 7;
rawPacket = commandBuffer; rawPacket = commandBuffer;
return returnvalue::OK; return HasReturnvaluesIF::RETURN_OK;
} }
ReturnValue_t MgmRM3100Handler::handleCycleCommand(bool oneCycleValue, const uint8_t *commandData, ReturnValue_t MgmRM3100Handler::handleCycleCommand(bool oneCycleValue, const uint8_t *commandData,
size_t commandDataLen) { size_t commandDataLen) {
mgmRm3100::CycleCountCommand command(oneCycleValue); RM3100::CycleCountCommand command(oneCycleValue);
ReturnValue_t result = ReturnValue_t result =
command.deSerialize(&commandData, &commandDataLen, SerializeIF::Endianness::BIG); command.deSerialize(&commandData, &commandDataLen, SerializeIF::Endianness::BIG);
if (result != returnvalue::OK) { if (result != HasReturnvaluesIF::RETURN_OK) {
return result; return result;
} }
@ -274,7 +274,7 @@ ReturnValue_t MgmRM3100Handler::handleCycleCommand(bool oneCycleValue, const uin
cycleCountRegValueX = command.cycleCountX; cycleCountRegValueX = command.cycleCountX;
cycleCountRegValueY = command.cycleCountY; cycleCountRegValueY = command.cycleCountY;
cycleCountRegValueZ = command.cycleCountZ; cycleCountRegValueZ = command.cycleCountZ;
return returnvalue::OK; return HasReturnvaluesIF::RETURN_OK;
} }
ReturnValue_t MgmRM3100Handler::handleTmrcConfigCommand(DeviceCommandId_t deviceCommand, ReturnValue_t MgmRM3100Handler::handleTmrcConfigCommand(DeviceCommandId_t deviceCommand,
@ -284,34 +284,35 @@ ReturnValue_t MgmRM3100Handler::handleTmrcConfigCommand(DeviceCommandId_t device
return DeviceHandlerIF::INVALID_COMMAND_PARAMETER; return DeviceHandlerIF::INVALID_COMMAND_PARAMETER;
} }
commandBuffer[0] = mgmRm3100::TMRC_REGISTER; commandBuffer[0] = RM3100::TMRC_REGISTER;
commandBuffer[1] = commandData[0]; commandBuffer[1] = commandData[0];
tmrcRegValue = commandData[0]; tmrcRegValue = commandData[0];
rawPacketLen = 2; rawPacketLen = 2;
rawPacket = commandBuffer; rawPacket = commandBuffer;
return returnvalue::OK; return HasReturnvaluesIF::RETURN_OK;
} }
void MgmRM3100Handler::fillCommandAndReplyMap() { void MgmRM3100Handler::fillCommandAndReplyMap() {
insertInCommandAndReplyMap(mgmRm3100::CONFIGURE_CMM, 3); insertInCommandAndReplyMap(RM3100::CONFIGURE_CMM, 3);
insertInCommandAndReplyMap(mgmRm3100::READ_CMM, 3); insertInCommandAndReplyMap(RM3100::READ_CMM, 3);
insertInCommandAndReplyMap(mgmRm3100::CONFIGURE_TMRC, 3); insertInCommandAndReplyMap(RM3100::CONFIGURE_TMRC, 3);
insertInCommandAndReplyMap(mgmRm3100::READ_TMRC, 3); insertInCommandAndReplyMap(RM3100::READ_TMRC, 3);
insertInCommandAndReplyMap(mgmRm3100::CONFIGURE_CYCLE_COUNT, 3); insertInCommandAndReplyMap(RM3100::CONFIGURE_CYCLE_COUNT, 3);
insertInCommandAndReplyMap(mgmRm3100::READ_CYCLE_COUNT, 3); insertInCommandAndReplyMap(RM3100::READ_CYCLE_COUNT, 3);
insertInCommandAndReplyMap(mgmRm3100::READ_DATA, 3, &primaryDataset); insertInCommandAndReplyMap(RM3100::READ_DATA, 3, &primaryDataset);
} }
void MgmRM3100Handler::modeChanged() { internalState = InternalState::NONE; } void MgmRM3100Handler::modeChanged(void) { internalState = InternalState::NONE; }
ReturnValue_t MgmRM3100Handler::initializeLocalDataPool(localpool::DataPool &localDataPoolMap, ReturnValue_t MgmRM3100Handler::initializeLocalDataPool(localpool::DataPool &localDataPoolMap,
LocalDataPoolManager &poolManager) { LocalDataPoolManager &poolManager) {
localDataPoolMap.emplace(mgmRm3100::FIELD_STRENGTHS, &mgmXYZ); localDataPoolMap.emplace(RM3100::FIELD_STRENGTH_X, new PoolEntry<float>({0.0}));
poolManager.subscribeForRegularPeriodicPacket({primaryDataset.getSid(), false, 10.0}); localDataPoolMap.emplace(RM3100::FIELD_STRENGTH_Y, new PoolEntry<float>({0.0}));
return returnvalue::OK; localDataPoolMap.emplace(RM3100::FIELD_STRENGTH_Z, new PoolEntry<float>({0.0}));
return HasReturnvaluesIF::RETURN_OK;
} }
uint32_t MgmRM3100Handler::getTransitionDelayMs(Mode_t from, Mode_t to) { uint32_t MgmRM3100Handler::getTransitionDelayMs(Mode_t from, Mode_t to) {
@ -325,12 +326,12 @@ ReturnValue_t MgmRM3100Handler::handleDataReadout(const uint8_t *packet) {
// trickery here to calculate the raw values first // trickery here to calculate the raw values first
int32_t fieldStrengthRawX = ((packet[1] << 24) | (packet[2] << 16) | (packet[3] << 8)) >> 8; int32_t fieldStrengthRawX = ((packet[1] << 24) | (packet[2] << 16) | (packet[3] << 8)) >> 8;
int32_t fieldStrengthRawY = ((packet[4] << 24) | (packet[5] << 16) | (packet[6] << 8)) >> 8; int32_t fieldStrengthRawY = ((packet[4] << 24) | (packet[5] << 16) | (packet[6] << 8)) >> 8;
int32_t fieldStrengthRawZ = ((packet[7] << 24) | (packet[8] << 16) | (packet[9] << 8)) >> 8; int32_t fieldStrengthRawZ = ((packet[7] << 24) | (packet[8] << 16) | (packet[3] << 8)) >> 8;
// Now scale to physical value in microtesla // Now scale to physical value in microtesla
float fieldStrengthX = fieldStrengthRawX * scaleFactorX; float fieldStrengthX = fieldStrengthRawX * scaleFactorX;
float fieldStrengthY = fieldStrengthRawY * scaleFactorY; float fieldStrengthY = fieldStrengthRawY * scaleFactorX;
float fieldStrengthZ = fieldStrengthRawZ * scaleFactorZ; float fieldStrengthZ = fieldStrengthRawZ * scaleFactorX;
if (periodicPrintout) { if (periodicPrintout) {
if (debugDivider.checkAndIncrement()) { if (debugDivider.checkAndIncrement()) {
@ -352,13 +353,13 @@ ReturnValue_t MgmRM3100Handler::handleDataReadout(const uint8_t *packet) {
// TODO: Sanity check on values? // TODO: Sanity check on values?
PoolReadGuard readGuard(&primaryDataset); PoolReadGuard readGuard(&primaryDataset);
if (readGuard.getReadResult() == returnvalue::OK) { if (readGuard.getReadResult() == HasReturnvaluesIF::RETURN_OK) {
primaryDataset.fieldStrengths[0] = fieldStrengthX; primaryDataset.fieldStrengthX = fieldStrengthX;
primaryDataset.fieldStrengths[1] = fieldStrengthY; primaryDataset.fieldStrengthY = fieldStrengthY;
primaryDataset.fieldStrengths[2] = fieldStrengthZ; primaryDataset.fieldStrengthZ = fieldStrengthZ;
primaryDataset.setValidity(true, true); primaryDataset.setValidity(true, true);
} }
return returnvalue::OK; return RETURN_OK;
} }
void MgmRM3100Handler::enablePeriodicPrintouts(bool enable, uint8_t divider) { void MgmRM3100Handler::enablePeriodicPrintouts(bool enable, uint8_t divider) {

View File

@ -1,8 +1,7 @@
#ifndef MISSION_DEVICES_MGMRM3100HANDLER_H_ #ifndef MISSION_DEVICES_MGMRM3100HANDLER_H_
#define MISSION_DEVICES_MGMRM3100HANDLER_H_ #define MISSION_DEVICES_MGMRM3100HANDLER_H_
#include <fsfw_hal/devicehandlers/devicedefinitions/mgmRm3100Helpers.h> #include "devicedefinitions/MgmRM3100HandlerDefs.h"
#include "fsfw/devicehandlers/DeviceHandlerBase.h" #include "fsfw/devicehandlers/DeviceHandlerBase.h"
#include "fsfw/globalfunctions/PeriodicOperationDivider.h" #include "fsfw/globalfunctions/PeriodicOperationDivider.h"
@ -70,23 +69,22 @@ class MgmRM3100Handler : public DeviceHandlerBase {
}; };
InternalState internalState = InternalState::NONE; InternalState internalState = InternalState::NONE;
bool commandExecuted = false; bool commandExecuted = false;
mgmRm3100::Rm3100PrimaryDataset primaryDataset; RM3100::Rm3100PrimaryDataset primaryDataset;
uint8_t commandBuffer[10]; uint8_t commandBuffer[10];
uint8_t commandBufferLen = 0; uint8_t commandBufferLen = 0;
uint8_t cmmRegValue = mgmRm3100::CMM_VALUE; uint8_t cmmRegValue = RM3100::CMM_VALUE;
uint8_t tmrcRegValue = mgmRm3100::TMRC_DEFAULT_VALUE; uint8_t tmrcRegValue = RM3100::TMRC_DEFAULT_VALUE;
uint16_t cycleCountRegValueX = mgmRm3100::CYCLE_COUNT_VALUE; uint16_t cycleCountRegValueX = RM3100::CYCLE_COUNT_VALUE;
uint16_t cycleCountRegValueY = mgmRm3100::CYCLE_COUNT_VALUE; uint16_t cycleCountRegValueY = RM3100::CYCLE_COUNT_VALUE;
uint16_t cycleCountRegValueZ = mgmRm3100::CYCLE_COUNT_VALUE; uint16_t cycleCountRegValueZ = RM3100::CYCLE_COUNT_VALUE;
float scaleFactorX = 1.0 / mgmRm3100::DEFAULT_GAIN; float scaleFactorX = 1.0 / RM3100::DEFAULT_GAIN;
float scaleFactorY = 1.0 / mgmRm3100::DEFAULT_GAIN; float scaleFactorY = 1.0 / RM3100::DEFAULT_GAIN;
float scaleFactorZ = 1.0 / mgmRm3100::DEFAULT_GAIN; float scaleFactorZ = 1.0 / RM3100::DEFAULT_GAIN;
bool goToNormalModeAtStartup = false; bool goToNormalModeAtStartup = false;
uint32_t transitionDelay; uint32_t transitionDelay;
PoolEntry<float> mgmXYZ = PoolEntry<float>(3);
ReturnValue_t handleCycleCountConfigCommand(DeviceCommandId_t deviceCommand, ReturnValue_t handleCycleCountConfigCommand(DeviceCommandId_t deviceCommand,
const uint8_t *commandData, size_t commandDataLen); const uint8_t *commandData, size_t commandDataLen);

View File

@ -6,9 +6,7 @@
#include <cstdint> #include <cstdint>
namespace l3gd20h { namespace L3GD20H {
float ctrlReg4ToSensitivity(uint8_t reg);
/* Actual size is 15 but we round up a bit */ /* Actual size is 15 but we round up a bit */
static constexpr size_t MAX_BUFFER_SIZE = 16; static constexpr size_t MAX_BUFFER_SIZE = 16;
@ -73,10 +71,8 @@ static constexpr uint8_t CTRL_REG_4_VAL = SET_BLE;
/* Register 5 */ /* Register 5 */
static constexpr uint8_t SET_REBOOT_MEM = 1 << 7; static constexpr uint8_t SET_REBOOT_MEM = 1 << 7;
static constexpr uint8_t SET_FIFO_ENB = 1 << 6; static constexpr uint8_t SET_FIFO_ENB = 1 << 6;
static constexpr uint8_t SET_OUT_SEL_1 = 1 << 1;
static constexpr uint8_t SET_OUT_SEL_0 = 1 << 0;
static constexpr uint8_t CTRL_REG_5_VAL = SET_OUT_SEL_1 | SET_OUT_SEL_0; static constexpr uint8_t CTRL_REG_5_VAL = 0b00000000;
/* Possible range values in degrees per second (DPS). */ /* Possible range values in degrees per second (DPS). */
static constexpr uint16_t RANGE_DPS_00 = 245; static constexpr uint16_t RANGE_DPS_00 = 245;
@ -107,33 +103,31 @@ static constexpr DeviceCommandId_t READ_REGS = 0;
static constexpr DeviceCommandId_t CONFIGURE_CTRL_REGS = 1; static constexpr DeviceCommandId_t CONFIGURE_CTRL_REGS = 1;
static constexpr DeviceCommandId_t READ_CTRL_REGS = 2; static constexpr DeviceCommandId_t READ_CTRL_REGS = 2;
static constexpr DeviceCommandId_t REQUEST = 0x70;
static constexpr DeviceCommandId_t REPLY = 0x77;
static constexpr uint32_t GYRO_DATASET_ID = READ_REGS; static constexpr uint32_t GYRO_DATASET_ID = READ_REGS;
enum GyroPoolIds : lp_id_t { ANG_VELOC_X, ANG_VELOC_Y, ANG_VELOC_Z, TEMPERATURE }; enum GyroPoolIds : lp_id_t { ANG_VELOC_X, ANG_VELOC_Y, ANG_VELOC_Z, TEMPERATURE };
} // namespace l3gd20h } // namespace L3GD20H
class GyroPrimaryDataset : public StaticLocalDataSet<5> { class GyroPrimaryDataset : public StaticLocalDataSet<5> {
public: public:
/** Constructor for data users like controllers */ /** Constructor for data users like controllers */
GyroPrimaryDataset(object_id_t mgmId) GyroPrimaryDataset(object_id_t mgmId)
: StaticLocalDataSet(sid_t(mgmId, l3gd20h::GYRO_DATASET_ID)) { : StaticLocalDataSet(sid_t(mgmId, L3GD20H::GYRO_DATASET_ID)) {
setAllVariablesReadOnly(); setAllVariablesReadOnly();
} }
/** Constructor for the data creator */
GyroPrimaryDataset(HasLocalDataPoolIF* hkOwner)
: StaticLocalDataSet(hkOwner, l3gd20h::GYRO_DATASET_ID) {}
/* Angular velocities in degrees per second (DPS) */ /* Angular velocities in degrees per second (DPS) */
lp_var_t<float> angVelocX = lp_var_t<float>(sid.objectId, l3gd20h::ANG_VELOC_X, this); lp_var_t<float> angVelocX = lp_var_t<float>(sid.objectId, L3GD20H::ANG_VELOC_X, this);
lp_var_t<float> angVelocY = lp_var_t<float>(sid.objectId, l3gd20h::ANG_VELOC_Y, this); lp_var_t<float> angVelocY = lp_var_t<float>(sid.objectId, L3GD20H::ANG_VELOC_Y, this);
lp_var_t<float> angVelocZ = lp_var_t<float>(sid.objectId, l3gd20h::ANG_VELOC_Z, this); lp_var_t<float> angVelocZ = lp_var_t<float>(sid.objectId, L3GD20H::ANG_VELOC_Z, this);
lp_var_t<float> temperature = lp_var_t<float>(sid.objectId, l3gd20h::TEMPERATURE, this); lp_var_t<float> temperature = lp_var_t<float>(sid.objectId, L3GD20H::TEMPERATURE, this);
private: private:
friend class GyroHandlerL3GD20H;
/** Constructor for the data creator */
GyroPrimaryDataset(HasLocalDataPoolIF* hkOwner)
: StaticLocalDataSet(hkOwner, L3GD20H::GYRO_DATASET_ID) {}
}; };
#endif /* MISSION_DEVICES_DEVICEDEFINITIONS_GYROL3GD20DEFINITIONS_H_ */ #endif /* MISSION_DEVICES_DEVICEDEFINITIONS_GYROL3GD20DEFINITIONS_H_ */

View File

@ -7,43 +7,13 @@
#include <cstdint> #include <cstdint>
namespace mgmLis3 { namespace MGMLIS3MDL {
enum Set { ON, OFF }; enum Set { ON, OFF };
enum OpMode { LOW, MEDIUM, HIGH, ULTRA }; enum OpMode { LOW, MEDIUM, HIGH, ULTRA };
enum Sensitivies : uint8_t { GAUSS_4 = 4, GAUSS_8 = 8, GAUSS_12 = 12, GAUSS_16 = 16 }; enum Sensitivies : uint8_t { GAUSS_4 = 4, GAUSS_8 = 8, GAUSS_12 = 12, GAUSS_16 = 16 };
/**
* Sets the read bit for the command
* @param single command to set the read-bit at
* @param boolean to select a continuous read bit, default = false
*/
uint8_t readCommand(uint8_t command, bool continuousCom = false);
/**
* Sets the write bit for the command
* @param single command to set the write-bit at
* @param boolean to select a continuous write bit, default = false
*/
uint8_t writeCommand(uint8_t command, bool continuousCom = false);
/**
* This Method gets the full scale for the measurement range
* e.g.: +- 4 gauss. See p.25 datasheet.
* @return The ReturnValue does not contain the sign of the value
*/
mgmLis3::Sensitivies getSensitivity(uint8_t ctrlReg2);
/**
* The 16 bit value needs to be multiplied with a sensitivity factor
* which depends on the sensitivity configuration
*
* @param sens Configured sensitivity of the LIS3 device
* @return Multiplication factor to get the sensor value from raw data.
*/
float getSensitivityFactor(mgmLis3::Sensitivies sens);
/* Actually 15, we just round up a bit */ /* Actually 15, we just round up a bit */
static constexpr size_t MAX_BUFFER_SIZE = 16; static constexpr size_t MAX_BUFFER_SIZE = 16;
@ -169,7 +139,12 @@ static const uint8_t CTRL_REG5_DEFAULT = 0;
static const uint32_t MGM_DATA_SET_ID = READ_CONFIG_AND_DATA; static const uint32_t MGM_DATA_SET_ID = READ_CONFIG_AND_DATA;
enum MgmPoolIds : lp_id_t { FIELD_STRENGTHS, TEMPERATURE_CELCIUS }; enum MgmPoolIds : lp_id_t {
FIELD_STRENGTH_X,
FIELD_STRENGTH_Y,
FIELD_STRENGTH_Z,
TEMPERATURE_CELCIUS
};
class MgmPrimaryDataset : public StaticLocalDataSet<4> { class MgmPrimaryDataset : public StaticLocalDataSet<4> {
public: public:
@ -177,13 +152,12 @@ class MgmPrimaryDataset : public StaticLocalDataSet<4> {
MgmPrimaryDataset(object_id_t mgmId) : StaticLocalDataSet(sid_t(mgmId, MGM_DATA_SET_ID)) {} MgmPrimaryDataset(object_id_t mgmId) : StaticLocalDataSet(sid_t(mgmId, MGM_DATA_SET_ID)) {}
/** lp_var_t<float> fieldStrengthX = lp_var_t<float>(sid.objectId, FIELD_STRENGTH_X, this);
* Field strenghts in uT lp_var_t<float> fieldStrengthY = lp_var_t<float>(sid.objectId, FIELD_STRENGTH_Y, this);
*/ lp_var_t<float> fieldStrengthZ = lp_var_t<float>(sid.objectId, FIELD_STRENGTH_Z, this);
lp_vec_t<float, 3> fieldStrengths = lp_vec_t<float, 3>(sid.objectId, FIELD_STRENGTHS, this);
lp_var_t<float> temperature = lp_var_t<float>(sid.objectId, TEMPERATURE_CELCIUS, this); lp_var_t<float> temperature = lp_var_t<float>(sid.objectId, TEMPERATURE_CELCIUS, this);
}; };
} // namespace mgmLis3 } // namespace MGMLIS3MDL
#endif /* MISSION_DEVICES_DEVICEDEFINITIONS_MGMLIS3HANDLERDEFS_H_ */ #endif /* MISSION_DEVICES_DEVICEDEFINITIONS_MGMLIS3HANDLERDEFS_H_ */

View File

@ -8,7 +8,7 @@
#include <cstdint> #include <cstdint>
namespace mgmRm3100 { namespace RM3100 {
/* Actually 10, we round up a little bit */ /* Actually 10, we round up a little bit */
static constexpr size_t MAX_BUFFER_SIZE = 12; static constexpr size_t MAX_BUFFER_SIZE = 12;
@ -101,7 +101,11 @@ class CycleCountCommand : public SerialLinkedListAdapter<SerializeIF> {
static constexpr uint32_t MGM_DATASET_ID = READ_DATA; static constexpr uint32_t MGM_DATASET_ID = READ_DATA;
enum MgmPoolIds : lp_id_t { FIELD_STRENGTHS }; enum MgmPoolIds : lp_id_t {
FIELD_STRENGTH_X,
FIELD_STRENGTH_Y,
FIELD_STRENGTH_Z,
};
class Rm3100PrimaryDataset : public StaticLocalDataSet<3> { class Rm3100PrimaryDataset : public StaticLocalDataSet<3> {
public: public:
@ -109,12 +113,12 @@ class Rm3100PrimaryDataset : public StaticLocalDataSet<3> {
Rm3100PrimaryDataset(object_id_t mgmId) : StaticLocalDataSet(sid_t(mgmId, MGM_DATASET_ID)) {} Rm3100PrimaryDataset(object_id_t mgmId) : StaticLocalDataSet(sid_t(mgmId, MGM_DATASET_ID)) {}
/** // Field strengths in micro Tesla.
* Field strenghts in uT lp_var_t<float> fieldStrengthX = lp_var_t<float>(sid.objectId, FIELD_STRENGTH_X, this);
*/ lp_var_t<float> fieldStrengthY = lp_var_t<float>(sid.objectId, FIELD_STRENGTH_Y, this);
lp_vec_t<float, 3> fieldStrengths = lp_vec_t<float, 3>(sid.objectId, FIELD_STRENGTHS, this); lp_var_t<float> fieldStrengthZ = lp_var_t<float>(sid.objectId, FIELD_STRENGTH_Z, this);
}; };
} // namespace mgmRm3100 } // namespace RM3100
#endif /* MISSION_DEVICES_DEVICEDEFINITIONS_MGMHANDLERRM3100DEFINITIONS_H_ */ #endif /* MISSION_DEVICES_DEVICEDEFINITIONS_MGMHANDLERRM3100DEFINITIONS_H_ */

View File

@ -0,0 +1 @@

View File

@ -0,0 +1,25 @@
if(FSFW_HAL_ADD_RASPBERRY_PI)
add_subdirectory(rpi)
endif()
target_sources(${LIB_FSFW_NAME} PRIVATE
UnixFileGuard.cpp
CommandExecutor.cpp
utility.cpp
)
if(FSFW_HAL_LINUX_ADD_PERIPHERAL_DRIVERS)
if(FSFW_HAL_LINUX_ADD_LIBGPIOD)
add_subdirectory(gpio)
endif()
add_subdirectory(uart)
# Adding those does not really make sense on Apple systems which
# are generally host systems. It won't even compile as the headers
# are missing
if(NOT APPLE)
add_subdirectory(i2c)
add_subdirectory(spi)
endif()
endif()
add_subdirectory(uio)

View File

@ -17,13 +17,13 @@ ReturnValue_t CommandExecutor::load(std::string command, bool blocking, bool pri
return COMMAND_PENDING; return COMMAND_PENDING;
} }
currentCmd = std::move(command); currentCmd = command;
this->blocking = blocking; this->blocking = blocking;
this->printOutput = printOutput; this->printOutput = printOutput;
if (state == States::IDLE) { if (state == States::IDLE) {
state = States::COMMAND_LOADED; state = States::COMMAND_LOADED;
} }
return returnvalue::OK; return HasReturnvaluesIF::RETURN_OK;
} }
ReturnValue_t CommandExecutor::execute() { ReturnValue_t CommandExecutor::execute() {
@ -32,12 +32,10 @@ ReturnValue_t CommandExecutor::execute() {
} else if (state == States::PENDING) { } else if (state == States::PENDING) {
return COMMAND_PENDING; return COMMAND_PENDING;
} }
// Reset data in read vector
std::memset(readVec.data(), 0, readVec.size());
currentCmdFile = popen(currentCmd.c_str(), "r"); currentCmdFile = popen(currentCmd.c_str(), "r");
if (currentCmdFile == nullptr) { if (currentCmdFile == nullptr) {
lastError = errno; lastError = errno;
return returnvalue::FAILED; return HasReturnvaluesIF::RETURN_FAILED;
} }
if (blocking) { if (blocking) {
ReturnValue_t result = executeBlocking(); ReturnValue_t result = executeBlocking();
@ -48,7 +46,7 @@ ReturnValue_t CommandExecutor::execute() {
waiter.fd = currentFd; waiter.fd = currentFd;
} }
state = States::PENDING; state = States::PENDING;
return returnvalue::OK; return HasReturnvaluesIF::RETURN_OK;
} }
ReturnValue_t CommandExecutor::close() { ReturnValue_t CommandExecutor::close() {
@ -58,7 +56,7 @@ ReturnValue_t CommandExecutor::close() {
pclose(currentCmdFile); pclose(currentCmdFile);
} }
} }
return returnvalue::OK; return HasReturnvaluesIF::RETURN_OK;
} }
void CommandExecutor::printLastError(std::string funcName) const { void CommandExecutor::printLastError(std::string funcName) const {
@ -81,7 +79,7 @@ void CommandExecutor::setRingBuffer(SimpleRingBuffer* ringBuffer,
ReturnValue_t CommandExecutor::check(bool& replyReceived) { ReturnValue_t CommandExecutor::check(bool& replyReceived) {
if (blocking) { if (blocking) {
return returnvalue::OK; return HasReturnvaluesIF::RETURN_OK;
} }
switch (state) { switch (state) {
case (States::IDLE): case (States::IDLE):
@ -96,7 +94,7 @@ ReturnValue_t CommandExecutor::check(bool& replyReceived) {
int result = poll(&waiter, 1, 0); int result = poll(&waiter, 1, 0);
switch (result) { switch (result) {
case (0): { case (0): {
return returnvalue::OK; return HasReturnvaluesIF::RETURN_OK;
break; break;
} }
case (1): { case (1): {
@ -153,7 +151,7 @@ ReturnValue_t CommandExecutor::check(bool& replyReceived) {
ReturnValue_t retval = EXECUTION_FINISHED; ReturnValue_t retval = EXECUTION_FINISHED;
if (result != 0) { if (result != 0) {
lastError = result; lastError = result;
retval = returnvalue::FAILED; retval = HasReturnvaluesIF::RETURN_FAILED;
} }
state = States::IDLE; state = States::IDLE;
currentCmdFile = nullptr; currentCmdFile = nullptr;
@ -163,7 +161,7 @@ ReturnValue_t CommandExecutor::check(bool& replyReceived) {
break; break;
} }
} }
return returnvalue::OK; return HasReturnvaluesIF::RETURN_OK;
} }
void CommandExecutor::reset() { void CommandExecutor::reset() {
@ -203,9 +201,7 @@ ReturnValue_t CommandExecutor::executeBlocking() {
int result = pclose(currentCmdFile); int result = pclose(currentCmdFile);
if (result != 0) { if (result != 0) {
lastError = result; lastError = result;
return returnvalue::FAILED; return HasReturnvaluesIF::RETURN_FAILED;
} }
return returnvalue::OK; return HasReturnvaluesIF::RETURN_OK;
} }
const std::vector<char>& CommandExecutor::getReadVector() const { return readVec; }

View File

@ -7,7 +7,7 @@
#include <vector> #include <vector>
#include "fsfw/returnvalues/FwClassIds.h" #include "fsfw/returnvalues/FwClassIds.h"
#include "fsfw/returnvalues/returnvalue.h" #include "fsfw/returnvalues/HasReturnvaluesIF.h"
class SimpleRingBuffer; class SimpleRingBuffer;
template <typename T> template <typename T>
@ -31,25 +31,27 @@ class CommandExecutor {
static constexpr uint8_t CLASS_ID = CLASS_ID::LINUX_OSAL; static constexpr uint8_t CLASS_ID = CLASS_ID::LINUX_OSAL;
//! [EXPORT] : [COMMENT] Execution of the current command has finished //! [EXPORT] : [COMMENT] Execution of the current command has finished
static constexpr ReturnValue_t EXECUTION_FINISHED = returnvalue::makeCode(CLASS_ID, 0); static constexpr ReturnValue_t EXECUTION_FINISHED =
HasReturnvaluesIF::makeReturnCode(CLASS_ID, 0);
//! [EXPORT] : [COMMENT] Command is pending. This will also be returned if the user tries //! [EXPORT] : [COMMENT] Command is pending. This will also be returned if the user tries
//! to load another command but a command is still pending //! to load another command but a command is still pending
static constexpr ReturnValue_t COMMAND_PENDING = returnvalue::makeCode(CLASS_ID, 1); static constexpr ReturnValue_t COMMAND_PENDING = HasReturnvaluesIF::makeReturnCode(CLASS_ID, 1);
//! [EXPORT] : [COMMENT] Some bytes have been read from the executing process //! [EXPORT] : [COMMENT] Some bytes have been read from the executing process
static constexpr ReturnValue_t BYTES_READ = returnvalue::makeCode(CLASS_ID, 2); static constexpr ReturnValue_t BYTES_READ = HasReturnvaluesIF::makeReturnCode(CLASS_ID, 2);
//! [EXPORT] : [COMMENT] Command execution failed //! [EXPORT] : [COMMENT] Command execution failed
static constexpr ReturnValue_t COMMAND_ERROR = returnvalue::makeCode(CLASS_ID, 3); static constexpr ReturnValue_t COMMAND_ERROR = HasReturnvaluesIF::makeReturnCode(CLASS_ID, 3);
//! [EXPORT] : [COMMENT] //! [EXPORT] : [COMMENT]
static constexpr ReturnValue_t NO_COMMAND_LOADED_OR_PENDING = returnvalue::makeCode(CLASS_ID, 4); static constexpr ReturnValue_t NO_COMMAND_LOADED_OR_PENDING =
static constexpr ReturnValue_t PCLOSE_CALL_ERROR = returnvalue::makeCode(CLASS_ID, 6); HasReturnvaluesIF::makeReturnCode(CLASS_ID, 4);
static constexpr ReturnValue_t PCLOSE_CALL_ERROR = HasReturnvaluesIF::makeReturnCode(CLASS_ID, 6);
/** /**
* Constructor. Is initialized with maximum size of internal buffer to read data from the * Constructor. Is initialized with maximum size of internal buffer to read data from the
* executed process. * executed process.
* @param maxSize * @param maxSize
*/ */
explicit CommandExecutor(size_t maxSize); CommandExecutor(const size_t maxSize);
/** /**
* Load a new command which should be executed * Load a new command which should be executed
@ -62,11 +64,11 @@ class CommandExecutor {
/** /**
* Execute the loaded command. * Execute the loaded command.
* @return * @return
* - In blocking mode, it will return returnvalue::FAILED if * - In blocking mode, it will return RETURN_FAILED if
* the result of the system call was not 0. The error value can be accessed using * the result of the system call was not 0. The error value can be accessed using
* getLastError * getLastError
* - In non-blocking mode, this call will start * - In non-blocking mode, this call will start
* the execution and then return returnvalue::OK * the execution and then return RETURN_OK
*/ */
ReturnValue_t execute(); ReturnValue_t execute();
/** /**
@ -75,8 +77,8 @@ class CommandExecutor {
* @return * @return
* - BYTES_READ if bytes have been read from the executing process. It is recommended to call * - BYTES_READ if bytes have been read from the executing process. It is recommended to call
* check again after this * check again after this
* - returnvalue::OK execution is pending, but no bytes have been read from the executing process * - RETURN_OK execution is pending, but no bytes have been read from the executing process
* - returnvalue::FAILED if execution has failed, error value can be accessed using getLastError * - RETURN_FAILED if execution has failed, error value can be accessed using getLastError
* - EXECUTION_FINISHED if the process was executed successfully * - EXECUTION_FINISHED if the process was executed successfully
* - NO_COMMAND_LOADED_OR_PENDING self-explanatory * - NO_COMMAND_LOADED_OR_PENDING self-explanatory
* - COMMAND_ERROR internal poll error * - COMMAND_ERROR internal poll error
@ -85,7 +87,7 @@ class CommandExecutor {
/** /**
* Abort the current command. Should normally not be necessary, check can be used to find * Abort the current command. Should normally not be necessary, check can be used to find
* out whether command execution was successful * out whether command execution was successful
* @return returnvalue::OK * @return RETURN_OK
*/ */
ReturnValue_t close(); ReturnValue_t close();
@ -107,8 +109,6 @@ class CommandExecutor {
*/ */
void reset(); void reset();
const std::vector<char>& getReadVector() const;
private: private:
std::string currentCmd; std::string currentCmd;
bool blocking = true; bool blocking = true;

View File

@ -6,11 +6,14 @@
#include "fsfw/FSFW.h" #include "fsfw/FSFW.h"
#include "fsfw/serviceinterface.h" #include "fsfw/serviceinterface.h"
UnixFileGuard::UnixFileGuard(const std::string& device, int& fileDescriptor, int flags, UnixFileGuard::UnixFileGuard(std::string device, int* fileDescriptor, int flags,
std::string diagnosticPrefix) std::string diagnosticPrefix)
: fdRef(fileDescriptor) { : fileDescriptor(fileDescriptor) {
fileDescriptor = open(device.c_str(), flags); if (fileDescriptor == nullptr) {
if (fileDescriptor < 0) { return;
}
*fileDescriptor = open(device.c_str(), flags);
if (*fileDescriptor < 0) {
#if FSFW_VERBOSE_LEVEL >= 1 #if FSFW_VERBOSE_LEVEL >= 1
#if FSFW_CPP_OSTREAM_ENABLED == 1 #if FSFW_CPP_OSTREAM_ENABLED == 1
sif::warning << diagnosticPrefix << ": Opening device failed with error code " << errno << ": " sif::warning << diagnosticPrefix << ": Opening device failed with error code " << errno << ": "
@ -24,6 +27,10 @@ UnixFileGuard::UnixFileGuard(const std::string& device, int& fileDescriptor, int
} }
} }
UnixFileGuard::~UnixFileGuard() { close(fdRef); } UnixFileGuard::~UnixFileGuard() {
if (fileDescriptor != nullptr) {
close(*fileDescriptor);
}
}
ReturnValue_t UnixFileGuard::getOpenResult() const { return openStatus; } ReturnValue_t UnixFileGuard::getOpenResult() const { return openStatus; }

View File

@ -2,7 +2,7 @@
#define LINUX_UTILITY_UNIXFILEGUARD_H_ #define LINUX_UTILITY_UNIXFILEGUARD_H_
#include <fcntl.h> #include <fcntl.h>
#include <fsfw/returnvalues/returnvalue.h> #include <fsfw/returnvalues/HasReturnvaluesIF.h>
#include <unistd.h> #include <unistd.h>
#include <string> #include <string>
@ -15,15 +15,7 @@ class UnixFileGuard {
static constexpr ReturnValue_t OPEN_FILE_FAILED = 1; static constexpr ReturnValue_t OPEN_FILE_FAILED = 1;
/** UnixFileGuard(std::string device, int* fileDescriptor, int flags,
* Open a device and assign the given file descriptor variable
* @param device [in] Device name.
* @param fileDescriptor [in/out] Will be assigned by file guard and re-used to
* close the guard.
* @param flags
* @param diagnosticPrefix
*/
UnixFileGuard(const std::string& device, int& fileDescriptor, int flags,
std::string diagnosticPrefix = ""); std::string diagnosticPrefix = "");
virtual ~UnixFileGuard(); virtual ~UnixFileGuard();
@ -31,8 +23,8 @@ class UnixFileGuard {
ReturnValue_t getOpenResult() const; ReturnValue_t getOpenResult() const;
private: private:
int& fdRef; int* fileDescriptor = nullptr;
ReturnValue_t openStatus = returnvalue::OK; ReturnValue_t openStatus = HasReturnvaluesIF::RETURN_OK;
}; };
#endif /* LINUX_UTILITY_UNIXFILEGUARD_H_ */ #endif /* LINUX_UTILITY_UNIXFILEGUARD_H_ */

View File

@ -0,0 +1,16 @@
# This abstraction layer requires the gpiod library. You can install this library
# with "sudo apt-get install -y libgpiod-dev". If you are cross-compiling, you need
# to install the package before syncing the sysroot to your host computer.
find_library(LIB_GPIO gpiod)
if(${LIB_GPIO} MATCHES LIB_GPIO-NOTFOUND)
message(STATUS "gpiod library not found, not linking against it")
else()
target_sources(${LIB_FSFW_NAME} PRIVATE
LinuxLibgpioIF.cpp
)
target_link_libraries(${LIB_FSFW_NAME} PRIVATE
${LIB_GPIO}
)
endif()

View File

@ -20,33 +20,31 @@ LinuxLibgpioIF::~LinuxLibgpioIF() {
ReturnValue_t LinuxLibgpioIF::addGpios(GpioCookie* gpioCookie) { ReturnValue_t LinuxLibgpioIF::addGpios(GpioCookie* gpioCookie) {
ReturnValue_t result; ReturnValue_t result;
if (gpioCookie == nullptr) { if (gpioCookie == nullptr) {
#if FSFW_CPP_OSTREAM_ENABLED == 1
sif::error << "LinuxLibgpioIF::addGpios: Invalid cookie" << std::endl; sif::error << "LinuxLibgpioIF::addGpios: Invalid cookie" << std::endl;
#endif return RETURN_FAILED;
return returnvalue::FAILED;
} }
GpioMap mapToAdd = gpioCookie->getGpioMap(); GpioMap mapToAdd = gpioCookie->getGpioMap();
/* Check whether this ID already exists in the map and remove duplicates */ /* Check whether this ID already exists in the map and remove duplicates */
result = checkForConflicts(mapToAdd); result = checkForConflicts(mapToAdd);
if (result != returnvalue::OK) { if (result != RETURN_OK) {
return result; return result;
} }
result = configureGpios(mapToAdd); result = configureGpios(mapToAdd);
if (result != returnvalue::OK) { if (result != RETURN_OK) {
return returnvalue::FAILED; return RETURN_FAILED;
} }
/* Register new GPIOs in gpioMap */ /* Register new GPIOs in gpioMap */
gpioMap.insert(mapToAdd.begin(), mapToAdd.end()); gpioMap.insert(mapToAdd.begin(), mapToAdd.end());
return returnvalue::OK; return RETURN_OK;
} }
ReturnValue_t LinuxLibgpioIF::configureGpios(GpioMap& mapToAdd) { ReturnValue_t LinuxLibgpioIF::configureGpios(GpioMap& mapToAdd) {
ReturnValue_t result = returnvalue::OK; ReturnValue_t result = RETURN_OK;
for (auto& gpioConfig : mapToAdd) { for (auto& gpioConfig : mapToAdd) {
auto& gpioType = gpioConfig.second->gpioType; auto& gpioType = gpioConfig.second->gpioType;
switch (gpioType) { switch (gpioType) {
@ -86,7 +84,7 @@ ReturnValue_t LinuxLibgpioIF::configureGpios(GpioMap& mapToAdd) {
gpioCallback->initValue, gpioCallback->callbackArgs); gpioCallback->initValue, gpioCallback->callbackArgs);
} }
} }
if (result != returnvalue::OK) { if (result != RETURN_OK) {
return GPIO_INIT_FAILED; return GPIO_INIT_FAILED;
} }
} }
@ -98,11 +96,9 @@ ReturnValue_t LinuxLibgpioIF::configureGpioByLabel(gpioId_t gpioId,
std::string& label = gpioByLabel.label; std::string& label = gpioByLabel.label;
struct gpiod_chip* chip = gpiod_chip_open_by_label(label.c_str()); struct gpiod_chip* chip = gpiod_chip_open_by_label(label.c_str());
if (chip == nullptr) { if (chip == nullptr) {
#if FSFW_CPP_OSTREAM_ENABLED == 1
sif::warning << "LinuxLibgpioIF::configureGpioByLabel: Failed to open gpio from gpio " sif::warning << "LinuxLibgpioIF::configureGpioByLabel: Failed to open gpio from gpio "
<< "group with label " << label << ". Gpio ID: " << gpioId << std::endl; << "group with label " << label << ". Gpio ID: " << gpioId << std::endl;
#endif return RETURN_FAILED;
return returnvalue::FAILED;
} }
std::string failOutput = "label: " + label; std::string failOutput = "label: " + label;
return configureRegularGpio(gpioId, chip, gpioByLabel, failOutput); return configureRegularGpio(gpioId, chip, gpioByLabel, failOutput);
@ -112,11 +108,9 @@ ReturnValue_t LinuxLibgpioIF::configureGpioByChip(gpioId_t gpioId, GpiodRegularB
std::string& chipname = gpioByChip.chipname; std::string& chipname = gpioByChip.chipname;
struct gpiod_chip* chip = gpiod_chip_open_by_name(chipname.c_str()); struct gpiod_chip* chip = gpiod_chip_open_by_name(chipname.c_str());
if (chip == nullptr) { if (chip == nullptr) {
#if FSFW_CPP_OSTREAM_ENABLED == 1
sif::warning << "LinuxLibgpioIF::configureGpioByChip: Failed to open chip " << chipname sif::warning << "LinuxLibgpioIF::configureGpioByChip: Failed to open chip " << chipname
<< ". Gpio ID: " << gpioId << std::endl; << ". Gpio ID: " << gpioId << std::endl;
#endif return RETURN_FAILED;
return returnvalue::FAILED;
} }
std::string failOutput = "chipname: " + chipname; std::string failOutput = "chipname: " + chipname;
return configureRegularGpio(gpioId, chip, gpioByChip, failOutput); return configureRegularGpio(gpioId, chip, gpioByChip, failOutput);
@ -132,18 +126,16 @@ ReturnValue_t LinuxLibgpioIF::configureGpioByLineName(gpioId_t gpioId,
gpiod_ctxless_find_line(lineName.c_str(), chipname, MAX_CHIPNAME_LENGTH, &lineOffset); gpiod_ctxless_find_line(lineName.c_str(), chipname, MAX_CHIPNAME_LENGTH, &lineOffset);
if (result != LINE_FOUND) { if (result != LINE_FOUND) {
parseFindeLineResult(result, lineName); parseFindeLineResult(result, lineName);
return returnvalue::FAILED; return RETURN_FAILED;
} }
gpioByLineName.lineNum = static_cast<int>(lineOffset); gpioByLineName.lineNum = static_cast<int>(lineOffset);
struct gpiod_chip* chip = gpiod_chip_open_by_name(chipname); struct gpiod_chip* chip = gpiod_chip_open_by_name(chipname);
if (chip == nullptr) { if (chip == nullptr) {
#if FSFW_CPP_OSTREAM_ENABLED == 1
sif::warning << "LinuxLibgpioIF::configureGpioByLineName: Failed to open chip " << chipname sif::warning << "LinuxLibgpioIF::configureGpioByLineName: Failed to open chip " << chipname
<< ". <Gpio ID: " << gpioId << std::endl; << ". <Gpio ID: " << gpioId << std::endl;
#endif return RETURN_FAILED;
return returnvalue::FAILED;
} }
std::string failOutput = "line name: " + lineName; std::string failOutput = "line name: " + lineName;
return configureRegularGpio(gpioId, chip, gpioByLineName, failOutput); return configureRegularGpio(gpioId, chip, gpioByLineName, failOutput);
@ -161,14 +153,12 @@ ReturnValue_t LinuxLibgpioIF::configureRegularGpio(gpioId_t gpioId, struct gpiod
lineNum = regularGpio.lineNum; lineNum = regularGpio.lineNum;
lineHandle = gpiod_chip_get_line(chip, lineNum); lineHandle = gpiod_chip_get_line(chip, lineNum);
if (!lineHandle) { if (!lineHandle) {
#if FSFW_CPP_OSTREAM_ENABLED == 1
sif::warning << "LinuxLibgpioIF::configureRegularGpio: Failed to open line " << std::endl; sif::warning << "LinuxLibgpioIF::configureRegularGpio: Failed to open line " << std::endl;
sif::warning << "GPIO ID: " << gpioId << ", line number: " << lineNum << ", " << failOutput sif::warning << "GPIO ID: " << gpioId << ", line number: " << lineNum << ", " << failOutput
<< std::endl; << std::endl;
sif::warning << "Check if Linux GPIO configuration has changed. " << std::endl; sif::warning << "Check if Linux GPIO configuration has changed. " << std::endl;
#endif
gpiod_chip_close(chip); gpiod_chip_close(chip);
return returnvalue::FAILED; return RETURN_FAILED;
} }
direction = regularGpio.direction; direction = regularGpio.direction;
@ -185,9 +175,7 @@ ReturnValue_t LinuxLibgpioIF::configureRegularGpio(gpioId_t gpioId, struct gpiod
break; break;
} }
default: { default: {
#if FSFW_CPP_OSTREAM_ENABLED == 1
sif::error << "LinuxLibgpioIF::configureGpios: Invalid direction specified" << std::endl; sif::error << "LinuxLibgpioIF::configureGpios: Invalid direction specified" << std::endl;
#endif
return GPIO_INVALID_INSTANCE; return GPIO_INVALID_INSTANCE;
} }
@ -202,7 +190,7 @@ ReturnValue_t LinuxLibgpioIF::configureRegularGpio(gpioId_t gpioId, struct gpiod
lineNum, gpioId); lineNum, gpioId);
#endif #endif
gpiod_line_release(lineHandle); gpiod_line_release(lineHandle);
return returnvalue::FAILED; return RETURN_FAILED;
} }
} }
/** /**
@ -210,15 +198,13 @@ ReturnValue_t LinuxLibgpioIF::configureRegularGpio(gpioId_t gpioId, struct gpiod
* read states of GPIOs. * read states of GPIOs.
*/ */
regularGpio.lineHandle = lineHandle; regularGpio.lineHandle = lineHandle;
return returnvalue::OK; return RETURN_OK;
} }
ReturnValue_t LinuxLibgpioIF::pullHigh(gpioId_t gpioId) { ReturnValue_t LinuxLibgpioIF::pullHigh(gpioId_t gpioId) {
auto gpioMapIter = gpioMap.find(gpioId); gpioMapIter = gpioMap.find(gpioId);
if (gpioMapIter == gpioMap.end()) { if (gpioMapIter == gpioMap.end()) {
#if FSFW_CPP_OSTREAM_ENABLED == 1
sif::warning << "LinuxLibgpioIF::pullHigh: Unknown GPIO ID " << gpioId << std::endl; sif::warning << "LinuxLibgpioIF::pullHigh: Unknown GPIO ID " << gpioId << std::endl;
#endif
return UNKNOWN_GPIO_ID; return UNKNOWN_GPIO_ID;
} }
@ -238,13 +224,13 @@ ReturnValue_t LinuxLibgpioIF::pullHigh(gpioId_t gpioId) {
} }
gpioCallback->callback(gpioMapIter->first, gpio::GpioOperation::WRITE, gpio::Levels::HIGH, gpioCallback->callback(gpioMapIter->first, gpio::GpioOperation::WRITE, gpio::Levels::HIGH,
gpioCallback->callbackArgs); gpioCallback->callbackArgs);
return returnvalue::OK; return RETURN_OK;
} }
return GPIO_TYPE_FAILURE; return GPIO_TYPE_FAILURE;
} }
ReturnValue_t LinuxLibgpioIF::pullLow(gpioId_t gpioId) { ReturnValue_t LinuxLibgpioIF::pullLow(gpioId_t gpioId) {
auto gpioMapIter = gpioMap.find(gpioId); gpioMapIter = gpioMap.find(gpioId);
if (gpioMapIter == gpioMap.end()) { if (gpioMapIter == gpioMap.end()) {
#if FSFW_CPP_OSTREAM_ENABLED == 1 #if FSFW_CPP_OSTREAM_ENABLED == 1
sif::warning << "LinuxLibgpioIF::pullLow: Unknown GPIO ID " << gpioId << std::endl; sif::warning << "LinuxLibgpioIF::pullLow: Unknown GPIO ID " << gpioId << std::endl;
@ -270,7 +256,7 @@ ReturnValue_t LinuxLibgpioIF::pullLow(gpioId_t gpioId) {
} }
gpioCallback->callback(gpioMapIter->first, gpio::GpioOperation::WRITE, gpio::Levels::LOW, gpioCallback->callback(gpioMapIter->first, gpio::GpioOperation::WRITE, gpio::Levels::LOW,
gpioCallback->callbackArgs); gpioCallback->callbackArgs);
return returnvalue::OK; return RETURN_OK;
} }
return GPIO_TYPE_FAILURE; return GPIO_TYPE_FAILURE;
} }
@ -291,11 +277,11 @@ ReturnValue_t LinuxLibgpioIF::driveGpio(gpioId_t gpioId, GpiodRegularBase& regul
return DRIVE_GPIO_FAILURE; return DRIVE_GPIO_FAILURE;
} }
return returnvalue::OK; return RETURN_OK;
} }
ReturnValue_t LinuxLibgpioIF::readGpio(gpioId_t gpioId, gpio::Levels& gpioState) { ReturnValue_t LinuxLibgpioIF::readGpio(gpioId_t gpioId, gpio::Levels& gpioState) {
auto gpioMapIter = gpioMap.find(gpioId); gpioMapIter = gpioMap.find(gpioId);
if (gpioMapIter == gpioMap.end()) { if (gpioMapIter == gpioMap.end()) {
#if FSFW_CPP_OSTREAM_ENABLED == 1 #if FSFW_CPP_OSTREAM_ENABLED == 1
sif::warning << "LinuxLibgpioIF::readGpio: Unknown GPIOD ID " << gpioId << std::endl; sif::warning << "LinuxLibgpioIF::readGpio: Unknown GPIOD ID " << gpioId << std::endl;
@ -324,14 +310,14 @@ ReturnValue_t LinuxLibgpioIF::readGpio(gpioId_t gpioId, gpio::Levels& gpioState)
} }
gpioCallback->callback(gpioMapIter->first, gpio::GpioOperation::READ, gpio::Levels::NONE, gpioCallback->callback(gpioMapIter->first, gpio::GpioOperation::READ, gpio::Levels::NONE,
gpioCallback->callbackArgs); gpioCallback->callbackArgs);
return returnvalue::OK; return RETURN_OK;
} }
return returnvalue::OK; return RETURN_OK;
} }
ReturnValue_t LinuxLibgpioIF::checkForConflicts(GpioMap& mapToAdd) { ReturnValue_t LinuxLibgpioIF::checkForConflicts(GpioMap& mapToAdd) {
ReturnValue_t status = returnvalue::OK; ReturnValue_t status = HasReturnvaluesIF::RETURN_OK;
ReturnValue_t result = returnvalue::OK; ReturnValue_t result = HasReturnvaluesIF::RETURN_OK;
for (auto& gpioConfig : mapToAdd) { for (auto& gpioConfig : mapToAdd) {
switch (gpioConfig.second->gpioType) { switch (gpioConfig.second->gpioType) {
case (gpio::GpioTypes::GPIO_REGULAR_BY_CHIP): case (gpio::GpioTypes::GPIO_REGULAR_BY_CHIP):
@ -343,7 +329,7 @@ ReturnValue_t LinuxLibgpioIF::checkForConflicts(GpioMap& mapToAdd) {
} }
// Check for conflicts and remove duplicates if necessary // Check for conflicts and remove duplicates if necessary
result = checkForConflictsById(gpioConfig.first, gpioConfig.second->gpioType, mapToAdd); result = checkForConflictsById(gpioConfig.first, gpioConfig.second->gpioType, mapToAdd);
if (result != returnvalue::OK) { if (result != HasReturnvaluesIF::RETURN_OK) {
status = result; status = result;
} }
break; break;
@ -355,7 +341,7 @@ ReturnValue_t LinuxLibgpioIF::checkForConflicts(GpioMap& mapToAdd) {
} }
// Check for conflicts and remove duplicates if necessary // Check for conflicts and remove duplicates if necessary
result = checkForConflictsById(gpioConfig.first, gpioConfig.second->gpioType, mapToAdd); result = checkForConflictsById(gpioConfig.first, gpioConfig.second->gpioType, mapToAdd);
if (result != returnvalue::OK) { if (result != HasReturnvaluesIF::RETURN_OK) {
status = result; status = result;
} }
break; break;
@ -377,7 +363,7 @@ ReturnValue_t LinuxLibgpioIF::checkForConflictsById(gpioId_t gpioIdToCheck,
gpio::GpioTypes expectedType, gpio::GpioTypes expectedType,
GpioMap& mapToAdd) { GpioMap& mapToAdd) {
// Cross check with private map // Cross check with private map
auto gpioMapIter = gpioMap.find(gpioIdToCheck); gpioMapIter = gpioMap.find(gpioIdToCheck);
if (gpioMapIter != gpioMap.end()) { if (gpioMapIter != gpioMap.end()) {
auto& gpioType = gpioMapIter->second->gpioType; auto& gpioType = gpioMapIter->second->gpioType;
bool eraseDuplicateDifferentType = false; bool eraseDuplicateDifferentType = false;
@ -429,7 +415,7 @@ ReturnValue_t LinuxLibgpioIF::checkForConflictsById(gpioId_t gpioIdToCheck,
mapToAdd.erase(gpioIdToCheck); mapToAdd.erase(gpioIdToCheck);
return GPIO_DUPLICATE_DETECTED; return GPIO_DUPLICATE_DETECTED;
} }
return returnvalue::OK; return HasReturnvaluesIF::RETURN_OK;
} }
void LinuxLibgpioIF::parseFindeLineResult(int result, std::string& lineName) { void LinuxLibgpioIF::parseFindeLineResult(int result, std::string& lineName) {

View File

@ -19,15 +19,21 @@ class LinuxLibgpioIF : public GpioIF, public SystemObject {
public: public:
static const uint8_t gpioRetvalId = CLASS_ID::HAL_GPIO; static const uint8_t gpioRetvalId = CLASS_ID::HAL_GPIO;
static constexpr ReturnValue_t UNKNOWN_GPIO_ID = returnvalue::makeCode(gpioRetvalId, 1); static constexpr ReturnValue_t UNKNOWN_GPIO_ID =
static constexpr ReturnValue_t DRIVE_GPIO_FAILURE = returnvalue::makeCode(gpioRetvalId, 2); HasReturnvaluesIF::makeReturnCode(gpioRetvalId, 1);
static constexpr ReturnValue_t GPIO_TYPE_FAILURE = returnvalue::makeCode(gpioRetvalId, 3); static constexpr ReturnValue_t DRIVE_GPIO_FAILURE =
static constexpr ReturnValue_t GPIO_INVALID_INSTANCE = returnvalue::makeCode(gpioRetvalId, 4); HasReturnvaluesIF::makeReturnCode(gpioRetvalId, 2);
static constexpr ReturnValue_t GPIO_DUPLICATE_DETECTED = returnvalue::makeCode(gpioRetvalId, 5); static constexpr ReturnValue_t GPIO_TYPE_FAILURE =
static constexpr ReturnValue_t GPIO_INIT_FAILED = returnvalue::makeCode(gpioRetvalId, 6); HasReturnvaluesIF::makeReturnCode(gpioRetvalId, 3);
static constexpr ReturnValue_t GPIO_INVALID_INSTANCE =
HasReturnvaluesIF::makeReturnCode(gpioRetvalId, 4);
static constexpr ReturnValue_t GPIO_DUPLICATE_DETECTED =
HasReturnvaluesIF::makeReturnCode(gpioRetvalId, 5);
static constexpr ReturnValue_t GPIO_INIT_FAILED =
HasReturnvaluesIF::makeReturnCode(gpioRetvalId, 6);
// Will be returned if getting the line value failed. Error type will be set to errno in this case // Will be returned if getting the line value failed. Error type will be set to errno in this case
static constexpr ReturnValue_t GPIO_GET_VALUE_FAILED = returnvalue::makeCode(gpioRetvalId, 7); static constexpr ReturnValue_t GPIO_GET_VALUE_FAILED =
HasReturnvaluesIF::makeReturnCode(gpioRetvalId, 7);
LinuxLibgpioIF(object_id_t objectId); LinuxLibgpioIF(object_id_t objectId);
virtual ~LinuxLibgpioIF(); virtual ~LinuxLibgpioIF();
@ -44,6 +50,7 @@ class LinuxLibgpioIF : public GpioIF, public SystemObject {
// Holds the information and configuration of all used GPIOs // Holds the information and configuration of all used GPIOs
GpioUnorderedMap gpioMap; GpioUnorderedMap gpioMap;
GpioUnorderedMapIter gpioMapIter;
/** /**
* @brief This functions drives line of a GPIO specified by the GPIO ID. * @brief This functions drives line of a GPIO specified by the GPIO ID.
@ -66,7 +73,7 @@ class LinuxLibgpioIF : public GpioIF, public SystemObject {
* *
* @param mapToAdd The GPIOs which shall be added to the gpioMap. * @param mapToAdd The GPIOs which shall be added to the gpioMap.
* *
* @return returnvalue::OK if successful, otherwise returnvalue::FAILED * @return RETURN_OK if successful, otherwise RETURN_FAILED
*/ */
ReturnValue_t checkForConflicts(GpioMap& mapToAdd); ReturnValue_t checkForConflicts(GpioMap& mapToAdd);

View File

@ -0,0 +1,8 @@
target_sources(${LIB_FSFW_NAME} PUBLIC
I2cComIF.cpp
I2cCookie.cpp
)

View File

@ -41,7 +41,7 @@ ReturnValue_t I2cComIF::initializeInterface(CookieIF* cookie) {
i2cAddress = i2cCookie->getAddress(); i2cAddress = i2cCookie->getAddress();
auto i2cDeviceMapIter = i2cDeviceMap.find(i2cAddress); i2cDeviceMapIter = i2cDeviceMap.find(i2cAddress);
if (i2cDeviceMapIter == i2cDeviceMap.end()) { if (i2cDeviceMapIter == i2cDeviceMap.end()) {
size_t maxReplyLen = i2cCookie->getMaxReplyLen(); size_t maxReplyLen = i2cCookie->getMaxReplyLen();
I2cInstance i2cInstance = {std::vector<uint8_t>(maxReplyLen), 0}; I2cInstance i2cInstance = {std::vector<uint8_t>(maxReplyLen), 0};
@ -52,31 +52,32 @@ ReturnValue_t I2cComIF::initializeInterface(CookieIF* cookie) {
<< i2cAddress << "to I2C device " << i2cAddress << "to I2C device "
<< "map" << std::endl; << "map" << std::endl;
#endif #endif
return returnvalue::FAILED; return HasReturnvaluesIF::RETURN_FAILED;
} }
return returnvalue::OK; return HasReturnvaluesIF::RETURN_OK;
} }
#if FSFW_CPP_OSTREAM_ENABLED == 1 #if FSFW_CPP_OSTREAM_ENABLED == 1
sif::error << "I2cComIF::initializeInterface: Device with address " << i2cAddress sif::error << "I2cComIF::initializeInterface: Device with address " << i2cAddress
<< "already in use" << std::endl; << "already in use" << std::endl;
#endif #endif
return returnvalue::FAILED; return HasReturnvaluesIF::RETURN_FAILED;
} }
ReturnValue_t I2cComIF::sendMessage(CookieIF* cookie, const uint8_t* sendData, size_t sendLen) { ReturnValue_t I2cComIF::sendMessage(CookieIF* cookie, const uint8_t* sendData, size_t sendLen) {
ReturnValue_t result; ReturnValue_t result;
int fd = 0; int fd;
std::string deviceFile;
if (sendData == nullptr) { if (sendData == nullptr) {
#if FSFW_CPP_OSTREAM_ENABLED == 1 #if FSFW_CPP_OSTREAM_ENABLED == 1
sif::error << "I2cComIF::sendMessage: Send Data is nullptr" << std::endl; sif::error << "I2cComIF::sendMessage: Send Data is nullptr" << std::endl;
#endif #endif
return returnvalue::FAILED; return HasReturnvaluesIF::RETURN_FAILED;
} }
if (sendLen == 0) { if (sendLen == 0) {
return returnvalue::OK; return HasReturnvaluesIF::RETURN_OK;
} }
I2cCookie* i2cCookie = dynamic_cast<I2cCookie*>(cookie); I2cCookie* i2cCookie = dynamic_cast<I2cCookie*>(cookie);
@ -88,53 +89,50 @@ ReturnValue_t I2cComIF::sendMessage(CookieIF* cookie, const uint8_t* sendData, s
} }
address_t i2cAddress = i2cCookie->getAddress(); address_t i2cAddress = i2cCookie->getAddress();
auto i2cDeviceMapIter = i2cDeviceMap.find(i2cAddress); i2cDeviceMapIter = i2cDeviceMap.find(i2cAddress);
if (i2cDeviceMapIter == i2cDeviceMap.end()) { if (i2cDeviceMapIter == i2cDeviceMap.end()) {
#if FSFW_CPP_OSTREAM_ENABLED == 1 #if FSFW_CPP_OSTREAM_ENABLED == 1
sif::error << "I2cComIF::sendMessage: i2cAddress of Cookie not " sif::error << "I2cComIF::sendMessage: i2cAddress of Cookie not "
<< "registered in i2cDeviceMap" << std::endl; << "registered in i2cDeviceMap" << std::endl;
#endif #endif
return returnvalue::FAILED; return HasReturnvaluesIF::RETURN_FAILED;
} }
const auto& deviceFile = i2cCookie->getDeviceFile(); deviceFile = i2cCookie->getDeviceFile();
UnixFileGuard fileHelper(deviceFile, fd, O_RDWR, "I2cComIF::sendMessage"); UnixFileGuard fileHelper(deviceFile, &fd, O_RDWR, "I2cComIF::sendMessage");
if (fileHelper.getOpenResult() != returnvalue::OK) { if (fileHelper.getOpenResult() != HasReturnvaluesIF::RETURN_OK) {
return fileHelper.getOpenResult(); return fileHelper.getOpenResult();
} }
result = openI2cSlave(deviceFile, i2cAddress, fd); result = openDevice(deviceFile, i2cAddress, &fd);
if (result != returnvalue::OK) { if (result != HasReturnvaluesIF::RETURN_OK) {
return result; return result;
} }
if (write(fd, sendData, sendLen) != static_cast<int>(sendLen)) { if (write(fd, sendData, sendLen) != static_cast<int>(sendLen)) {
i2cCookie->errorCounter++;
if (i2cCookie->errorCounter < 3) {
#if FSFW_CPP_OSTREAM_ENABLED == 1 #if FSFW_CPP_OSTREAM_ENABLED == 1
sif::error << "I2cComIF::sendMessage: Failed to send data to I2C " sif::error << "I2cComIF::sendMessage: Failed to send data to I2C "
"device from " "device with error code "
<< deviceFile << " with error code " << errno << errno << ". Error description: " << strerror(errno) << std::endl;
<< ". Error description: " << strerror(errno) << std::endl;
#endif #endif
return HasReturnvaluesIF::RETURN_FAILED;
} }
return returnvalue::FAILED;
}
i2cCookie->errorCounter = 0;
#if FSFW_HAL_I2C_WIRETAPPING == 1 #if FSFW_HAL_I2C_WIRETAPPING == 1
sif::info << "Sent I2C data to bus " << deviceFile << ":" << std::endl; sif::info << "Sent I2C data to bus " << deviceFile << ":" << std::endl;
arrayprinter::print(sendData, sendLen); arrayprinter::print(sendData, sendLen);
#endif #endif
return returnvalue::OK; return HasReturnvaluesIF::RETURN_OK;
} }
ReturnValue_t I2cComIF::getSendSuccess(CookieIF* cookie) { return returnvalue::OK; } ReturnValue_t I2cComIF::getSendSuccess(CookieIF* cookie) { return HasReturnvaluesIF::RETURN_OK; }
ReturnValue_t I2cComIF::requestReceiveMessage(CookieIF* cookie, size_t requestLen) { ReturnValue_t I2cComIF::requestReceiveMessage(CookieIF* cookie, size_t requestLen) {
ReturnValue_t result; ReturnValue_t result;
int fd = 0; int fd;
std::string deviceFile;
if (requestLen == 0) { if (requestLen == 0) {
return returnvalue::OK; return HasReturnvaluesIF::RETURN_OK;
} }
I2cCookie* i2cCookie = dynamic_cast<I2cCookie*>(cookie); I2cCookie* i2cCookie = dynamic_cast<I2cCookie*>(cookie);
@ -142,27 +140,29 @@ ReturnValue_t I2cComIF::requestReceiveMessage(CookieIF* cookie, size_t requestLe
#if FSFW_CPP_OSTREAM_ENABLED == 1 #if FSFW_CPP_OSTREAM_ENABLED == 1
sif::error << "I2cComIF::requestReceiveMessage: Invalid I2C Cookie!" << std::endl; sif::error << "I2cComIF::requestReceiveMessage: Invalid I2C Cookie!" << std::endl;
#endif #endif
i2cDeviceMapIter->second.replyLen = 0;
return NULLPOINTER; return NULLPOINTER;
} }
address_t i2cAddress = i2cCookie->getAddress(); address_t i2cAddress = i2cCookie->getAddress();
auto i2cDeviceMapIter = i2cDeviceMap.find(i2cAddress); i2cDeviceMapIter = i2cDeviceMap.find(i2cAddress);
if (i2cDeviceMapIter == i2cDeviceMap.end()) { if (i2cDeviceMapIter == i2cDeviceMap.end()) {
#if FSFW_CPP_OSTREAM_ENABLED == 1 #if FSFW_CPP_OSTREAM_ENABLED == 1
sif::error << "I2cComIF::requestReceiveMessage: i2cAddress of Cookie not " sif::error << "I2cComIF::requestReceiveMessage: i2cAddress of Cookie not "
<< "registered in i2cDeviceMap" << std::endl; << "registered in i2cDeviceMap" << std::endl;
#endif #endif
return returnvalue::FAILED;
}
i2cDeviceMapIter->second.replyLen = 0; i2cDeviceMapIter->second.replyLen = 0;
return HasReturnvaluesIF::RETURN_FAILED;
}
auto& deviceFile = i2cCookie->getDeviceFile(); deviceFile = i2cCookie->getDeviceFile();
UnixFileGuard fileHelper(deviceFile, fd, O_RDWR, "I2cComIF::requestReceiveMessage"); UnixFileGuard fileHelper(deviceFile, &fd, O_RDWR, "I2cComIF::requestReceiveMessage");
if (fileHelper.getOpenResult() != returnvalue::OK) { if (fileHelper.getOpenResult() != HasReturnvaluesIF::RETURN_OK) {
return fileHelper.getOpenResult(); return fileHelper.getOpenResult();
} }
result = openI2cSlave(deviceFile, i2cAddress, fd); result = openDevice(deviceFile, i2cAddress, &fd);
if (result != returnvalue::OK) { if (result != HasReturnvaluesIF::RETURN_OK) {
i2cDeviceMapIter->second.replyLen = 0;
return result; return result;
} }
@ -183,7 +183,8 @@ ReturnValue_t I2cComIF::requestReceiveMessage(CookieIF* cookie, size_t requestLe
#else #else
#endif #endif
#endif #endif
return returnvalue::FAILED; i2cDeviceMapIter->second.replyLen = 0;
return HasReturnvaluesIF::RETURN_FAILED;
} }
#if FSFW_HAL_I2C_WIRETAPPING == 1 #if FSFW_HAL_I2C_WIRETAPPING == 1
@ -192,7 +193,7 @@ ReturnValue_t I2cComIF::requestReceiveMessage(CookieIF* cookie, size_t requestLe
#endif #endif
i2cDeviceMapIter->second.replyLen = requestLen; i2cDeviceMapIter->second.replyLen = requestLen;
return returnvalue::OK; return HasReturnvaluesIF::RETURN_OK;
} }
ReturnValue_t I2cComIF::readReceivedMessage(CookieIF* cookie, uint8_t** buffer, size_t* size) { ReturnValue_t I2cComIF::readReceivedMessage(CookieIF* cookie, uint8_t** buffer, size_t* size) {
@ -205,23 +206,23 @@ ReturnValue_t I2cComIF::readReceivedMessage(CookieIF* cookie, uint8_t** buffer,
} }
address_t i2cAddress = i2cCookie->getAddress(); address_t i2cAddress = i2cCookie->getAddress();
auto i2cDeviceMapIter = i2cDeviceMap.find(i2cAddress); i2cDeviceMapIter = i2cDeviceMap.find(i2cAddress);
if (i2cDeviceMapIter == i2cDeviceMap.end()) { if (i2cDeviceMapIter == i2cDeviceMap.end()) {
#if FSFW_CPP_OSTREAM_ENABLED == 1 #if FSFW_CPP_OSTREAM_ENABLED == 1
sif::error << "I2cComIF::readReceivedMessage: i2cAddress of Cookie not " sif::error << "I2cComIF::readReceivedMessage: i2cAddress of Cookie not "
<< "found in i2cDeviceMap" << std::endl; << "found in i2cDeviceMap" << std::endl;
#endif #endif
return returnvalue::FAILED; return HasReturnvaluesIF::RETURN_FAILED;
} }
*buffer = i2cDeviceMapIter->second.replyBuffer.data(); *buffer = i2cDeviceMapIter->second.replyBuffer.data();
*size = i2cDeviceMapIter->second.replyLen; *size = i2cDeviceMapIter->second.replyLen;
i2cDeviceMapIter->second.replyLen = 0;
return returnvalue::OK; return HasReturnvaluesIF::RETURN_OK;
} }
ReturnValue_t I2cComIF::openI2cSlave(const std::string& deviceFile, address_t i2cAddress, ReturnValue_t I2cComIF::openDevice(std::string deviceFile, address_t i2cAddress,
int& fileDescriptor) { int* fileDescriptor) {
if (ioctl(fileDescriptor, I2C_SLAVE, i2cAddress) < 0) { if (ioctl(*fileDescriptor, I2C_SLAVE, i2cAddress) < 0) {
#if FSFW_VERBOSE_LEVEL >= 1 #if FSFW_VERBOSE_LEVEL >= 1
#if FSFW_CPP_OSTREAM_ENABLED == 1 #if FSFW_CPP_OSTREAM_ENABLED == 1
sif::warning << "I2cComIF: Specifying target device failed with error code " << errno << "." sif::warning << "I2cComIF: Specifying target device failed with error code " << errno << "."
@ -232,7 +233,7 @@ ReturnValue_t I2cComIF::openI2cSlave(const std::string& deviceFile, address_t i2
sif::printWarning("Error description: %s\n", strerror(errno)); sif::printWarning("Error description: %s\n", strerror(errno));
#endif /* FSFW_CPP_OSTREAM_ENABLED == 1 */ #endif /* FSFW_CPP_OSTREAM_ENABLED == 1 */
#endif /* FSFW_VERBOSE_LEVEL >= 1 */ #endif /* FSFW_VERBOSE_LEVEL >= 1 */
return returnvalue::FAILED; return HasReturnvaluesIF::RETURN_FAILED;
} }
return returnvalue::OK; return HasReturnvaluesIF::RETURN_OK;
} }

View File

@ -36,10 +36,12 @@ class I2cComIF : public DeviceCommunicationIF, public SystemObject {
}; };
using I2cDeviceMap = std::unordered_map<address_t, I2cInstance>; using I2cDeviceMap = std::unordered_map<address_t, I2cInstance>;
using I2cDeviceMapIter = I2cDeviceMap::iterator;
/* In this map all i2c devices will be registered with their address and /* In this map all i2c devices will be registered with their address and
* the appropriate file descriptor will be stored */ * the appropriate file descriptor will be stored */
I2cDeviceMap i2cDeviceMap; I2cDeviceMap i2cDeviceMap;
I2cDeviceMapIter i2cDeviceMapIter;
/** /**
* @brief This function opens an I2C device and binds the opened file * @brief This function opens an I2C device and binds the opened file
@ -47,10 +49,9 @@ class I2cComIF : public DeviceCommunicationIF, public SystemObject {
* @param deviceFile The name of the device file. E.g. i2c-0 * @param deviceFile The name of the device file. E.g. i2c-0
* @param i2cAddress The address of the i2c slave device. * @param i2cAddress The address of the i2c slave device.
* @param fileDescriptor Pointer to device descriptor. * @param fileDescriptor Pointer to device descriptor.
* @return returnvalue::OK if successful, otherwise returnvalue::FAILED. * @return RETURN_OK if successful, otherwise RETURN_FAILED.
*/ */
ReturnValue_t openI2cSlave(const std::string &deviceFile, address_t i2cAddress, ReturnValue_t openDevice(std::string deviceFile, address_t i2cAddress, int *fileDescriptor);
int &fileDescriptor);
}; };
#endif /* LINUX_I2C_I2COMIF_H_ */ #endif /* LINUX_I2C_I2COMIF_H_ */

View File

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

View File

@ -25,9 +25,7 @@ class I2cCookie : public CookieIF {
address_t getAddress() const; address_t getAddress() const;
size_t getMaxReplyLen() const; size_t getMaxReplyLen() const;
const std::string& getDeviceFile() const; std::string getDeviceFile() const;
uint8_t errorCounter = 0;
private: private:
address_t i2cAddress = 0; address_t i2cAddress = 0;

View File

@ -0,0 +1,3 @@
target_sources(${LIB_FSFW_NAME} PRIVATE
GpioRPi.cpp
)

View File

@ -9,7 +9,7 @@ ReturnValue_t gpio::createRpiGpioConfig(GpioCookie* cookie, gpioId_t gpioId, int
std::string consumer, gpio::Direction direction, std::string consumer, gpio::Direction direction,
gpio::Levels initValue) { gpio::Levels initValue) {
if (cookie == nullptr) { if (cookie == nullptr) {
return returnvalue::FAILED; return HasReturnvaluesIF::RETURN_FAILED;
} }
auto config = new GpiodRegularByChip(); auto config = new GpiodRegularByChip();
@ -30,9 +30,9 @@ ReturnValue_t gpio::createRpiGpioConfig(GpioCookie* cookie, gpioId_t gpioId, int
sif::printError("createRpiGpioConfig: BCM pin %d invalid!\n", bcmPin); sif::printError("createRpiGpioConfig: BCM pin %d invalid!\n", bcmPin);
#endif /* FSFW_CPP_OSTREAM_ENABLED == 1 */ #endif /* FSFW_CPP_OSTREAM_ENABLED == 1 */
#endif /* FSFW_VERBOSE_LEVEL >= 1 */ #endif /* FSFW_VERBOSE_LEVEL >= 1 */
return returnvalue::FAILED; return HasReturnvaluesIF::RETURN_FAILED;
} }
config->lineNum = bcmPin; config->lineNum = bcmPin;
cookie->addGpio(gpioId, config); cookie->addGpio(gpioId, config);
return returnvalue::OK; return HasReturnvaluesIF::RETURN_OK;
} }

View File

@ -1,7 +1,7 @@
#ifndef BSP_RPI_GPIO_GPIORPI_H_ #ifndef BSP_RPI_GPIO_GPIORPI_H_
#define BSP_RPI_GPIO_GPIORPI_H_ #define BSP_RPI_GPIO_GPIORPI_H_
#include <fsfw/returnvalues/returnvalue.h> #include <fsfw/returnvalues/HasReturnvaluesIF.h>
#include "../../common/gpio/gpioDefinitions.h" #include "../../common/gpio/gpioDefinitions.h"

View File

@ -0,0 +1,8 @@
target_sources(${LIB_FSFW_NAME} PUBLIC
SpiComIF.cpp
SpiCookie.cpp
)

View File

@ -15,9 +15,19 @@
#include "fsfw_hal/linux/spi/SpiCookie.h" #include "fsfw_hal/linux/spi/SpiCookie.h"
#include "fsfw_hal/linux/utility.h" #include "fsfw_hal/linux/utility.h"
SpiComIF::SpiComIF(object_id_t objectId, std::string devname, GpioIF& gpioComIF) SpiComIF::SpiComIF(object_id_t objectId, GpioIF* gpioComIF)
: SystemObject(objectId), gpioComIF(gpioComIF), dev(std::move(devname)) { : SystemObject(objectId), gpioComIF(gpioComIF) {
csMutex = MutexFactory::instance()->createMutex(); if (gpioComIF == nullptr) {
#if FSFW_VERBOSE_LEVEL >= 1
#if FSFW_CPP_OSTREAM_ENABLED == 1
sif::error << "SpiComIF::SpiComIF: GPIO communication interface invalid!" << std::endl;
#else
sif::printError("SpiComIF::SpiComIF: GPIO communication interface invalid!\n");
#endif /* FSFW_CPP_OSTREAM_ENABLED == 1 */
#endif /* FSFW_VERBOSE_LEVEL >= 1 */
}
spiMutex = MutexFactory::instance()->createMutex();
} }
ReturnValue_t SpiComIF::initializeInterface(CookieIF* cookie) { ReturnValue_t SpiComIF::initializeInterface(CookieIF* cookie) {
@ -46,7 +56,7 @@ ReturnValue_t SpiComIF::initializeInterface(CookieIF* cookie) {
static_cast<unsigned long>(spiAddress)); static_cast<unsigned long>(spiAddress));
#endif /* FSFW_CPP_OSTREAM_ENABLED == 1 */ #endif /* FSFW_CPP_OSTREAM_ENABLED == 1 */
#endif /* FSFW_VERBOSE_LEVEL >= 1 */ #endif /* FSFW_VERBOSE_LEVEL >= 1 */
return returnvalue::FAILED; return HasReturnvaluesIF::RETURN_FAILED;
} }
/* Now we emplaced the read buffer in the map, we still need to assign that location /* Now we emplaced the read buffer in the map, we still need to assign that location
to the SPI driver transfer struct */ to the SPI driver transfer struct */
@ -59,13 +69,13 @@ ReturnValue_t SpiComIF::initializeInterface(CookieIF* cookie) {
sif::printError("SpiComIF::initializeInterface: SPI address already exists!\n"); sif::printError("SpiComIF::initializeInterface: SPI address already exists!\n");
#endif /* FSFW_CPP_OSTREAM_ENABLED == 1 */ #endif /* FSFW_CPP_OSTREAM_ENABLED == 1 */
#endif /* FSFW_VERBOSE_LEVEL >= 1 */ #endif /* FSFW_VERBOSE_LEVEL >= 1 */
return returnvalue::FAILED; return HasReturnvaluesIF::RETURN_FAILED;
} }
/* Pull CS high in any case to be sure that device is inactive */ /* Pull CS high in any case to be sure that device is inactive */
gpioId_t gpioId = spiCookie->getChipSelectPin(); gpioId_t gpioId = spiCookie->getChipSelectPin();
if (gpioId != gpio::NO_GPIO) { if (gpioId != gpio::NO_GPIO) {
gpioComIF.pullHigh(gpioId); gpioComIF->pullHigh(gpioId);
} }
uint32_t spiSpeed = 0; uint32_t spiSpeed = 0;
@ -75,8 +85,9 @@ ReturnValue_t SpiComIF::initializeInterface(CookieIF* cookie) {
spiCookie->getSpiParameters(spiMode, spiSpeed, &params); spiCookie->getSpiParameters(spiMode, spiSpeed, &params);
int fileDescriptor = 0; int fileDescriptor = 0;
UnixFileGuard fileHelper(dev, fileDescriptor, O_RDWR, "SpiComIF::initializeInterface"); UnixFileGuard fileHelper(spiCookie->getSpiDevice(), &fileDescriptor, O_RDWR,
if (fileHelper.getOpenResult() != returnvalue::OK) { "SpiComIF::initializeInterface");
if (fileHelper.getOpenResult() != HasReturnvaluesIF::RETURN_OK) {
return fileHelper.getOpenResult(); return fileHelper.getOpenResult();
} }
@ -118,12 +129,12 @@ ReturnValue_t SpiComIF::initializeInterface(CookieIF* cookie) {
"Could not write bits per word!"); "Could not write bits per word!");
} }
} }
return returnvalue::OK; return HasReturnvaluesIF::RETURN_OK;
} }
ReturnValue_t SpiComIF::sendMessage(CookieIF* cookie, const uint8_t* sendData, size_t sendLen) { ReturnValue_t SpiComIF::sendMessage(CookieIF* cookie, const uint8_t* sendData, size_t sendLen) {
SpiCookie* spiCookie = dynamic_cast<SpiCookie*>(cookie); SpiCookie* spiCookie = dynamic_cast<SpiCookie*>(cookie);
ReturnValue_t result = returnvalue::OK; ReturnValue_t result = HasReturnvaluesIF::RETURN_OK;
if (spiCookie == nullptr) { if (spiCookie == nullptr) {
return NULLPOINTER; return NULLPOINTER;
@ -167,49 +178,40 @@ ReturnValue_t SpiComIF::performRegularSendOperation(SpiCookie* spiCookie, const
spiCookie->assignReadBuffer(iter->second.replyBuffer.data()); spiCookie->assignReadBuffer(iter->second.replyBuffer.data());
} }
ReturnValue_t result = returnvalue::OK; ReturnValue_t result = HasReturnvaluesIF::RETURN_OK;
int retval = 0; int retval = 0;
/* Prepare transfer */ /* Prepare transfer */
int fileDescriptor = 0; int fileDescriptor = 0;
UnixFileGuard fileHelper(dev, fileDescriptor, O_RDWR, "SpiComIF::sendMessage"); std::string device = spiCookie->getSpiDevice();
if (fileHelper.getOpenResult() != returnvalue::OK) { UnixFileGuard fileHelper(device, &fileDescriptor, O_RDWR, "SpiComIF::sendMessage");
return spi::OPENING_FILE_FAILED; if (fileHelper.getOpenResult() != HasReturnvaluesIF::RETURN_OK) {
return OPENING_FILE_FAILED;
} }
spi::SpiModes spiMode = spi::SpiModes::MODE_0; spi::SpiModes spiMode = spi::SpiModes::MODE_0;
uint32_t spiSpeed = 0; uint32_t spiSpeed = 0;
spiCookie->getSpiParameters(spiMode, spiSpeed, nullptr); spiCookie->getSpiParameters(spiMode, spiSpeed, nullptr);
setSpiSpeedAndMode(fileDescriptor, spiMode, spiSpeed); setSpiSpeedAndMode(fileDescriptor, spiMode, spiSpeed);
spiCookie->assignWriteBuffer(sendData);
spiCookie->setTransferSize(sendLen);
bool fullDuplex = spiCookie->isFullDuplex(); bool fullDuplex = spiCookie->isFullDuplex();
gpioId_t gpioId = spiCookie->getChipSelectPin(); gpioId_t gpioId = spiCookie->getChipSelectPin();
bool csLockManual = spiCookie->getCsLockManual();
spiCookie->setTransferSize(0);
MutexIF::TimeoutType csType; /* Pull SPI CS low. For now, no support for active high given */
dur_millis_t csTimeout = 0; if (gpioId != gpio::NO_GPIO) {
// Pull SPI CS low. For now, no support for active high given result = spiMutex->lockMutex(timeoutType, timeoutMs);
if (gpioId != gpio::NO_GPIO and not csLockManual) { if (result != RETURN_OK) {
spiCookie->getMutexParams(csType, csTimeout);
result = csMutex->lockMutex(csType, csTimeout);
if (result != returnvalue::OK) {
#if FSFW_VERBOSE_LEVEL >= 1 #if FSFW_VERBOSE_LEVEL >= 1
#if FSFW_CPP_OSTREAM_ENABLED == 1 #if FSFW_CPP_OSTREAM_ENABLED == 1
if (result == MutexIF::MUTEX_TIMEOUT) { sif::error << "SpiComIF::sendMessage: Failed to lock mutex" << std::endl;
sif::error << "SpiComIF::sendMessage: Lock timeout" << std::endl;
} else {
sif::error << "SpiComIF::sendMessage: Failed to lock mutex with code "
<< "0x" << std::hex << std::setfill('0') << std::setw(4) << result << std::dec
<< std::endl;
}
#else #else
sif::printError("SpiComIF::sendMessage: Failed to lock mutex with code %d\n", result); sif::printError("SpiComIF::sendMessage: Failed to lock mutex\n");
#endif #endif
#endif #endif
return result; return result;
} }
updateLinePolarity(fileDescriptor); ReturnValue_t result = gpioComIF->pullLow(gpioId);
result = gpioComIF.pullLow(gpioId); if (result != HasReturnvaluesIF::RETURN_OK) {
if (result != returnvalue::OK) {
#if FSFW_VERBOSE_LEVEL >= 1 #if FSFW_VERBOSE_LEVEL >= 1
#if FSFW_CPP_OSTREAM_ENABLED == 1 #if FSFW_CPP_OSTREAM_ENABLED == 1
sif::warning << "SpiComIF::sendMessage: Pulling low CS pin failed" << std::endl; sif::warning << "SpiComIF::sendMessage: Pulling low CS pin failed" << std::endl;
@ -217,24 +219,17 @@ ReturnValue_t SpiComIF::performRegularSendOperation(SpiCookie* spiCookie, const
sif::printWarning("SpiComIF::sendMessage: Pulling low CS pin failed"); sif::printWarning("SpiComIF::sendMessage: Pulling low CS pin failed");
#endif #endif
#endif #endif
csMutex->unlockMutex();
return result; return result;
} }
} else {
updateLinePolarity(fileDescriptor);
} }
spiCookie->assignWriteBuffer(sendData);
spiCookie->setTransferSize(sendLen);
/* Execute transfer */ /* Execute transfer */
if (fullDuplex) { if (fullDuplex) {
/* Initiate a full duplex SPI transfer. */ /* Initiate a full duplex SPI transfer. */
retval = ioctl(fileDescriptor, SPI_IOC_MESSAGE(1), spiCookie->getTransferStructHandle()); retval = ioctl(fileDescriptor, SPI_IOC_MESSAGE(1), spiCookie->getTransferStructHandle());
if (retval < 0) { if (retval < 0) {
spiCookie->setTransferSize(0);
utility::handleIoctlError("SpiComIF::sendMessage: ioctl error."); utility::handleIoctlError("SpiComIF::sendMessage: ioctl error.");
result = spi::FULL_DUPLEX_TRANSFER_FAILED; result = FULL_DUPLEX_TRANSFER_FAILED;
} }
#if FSFW_HAL_SPI_WIRETAPPING == 1 #if FSFW_HAL_SPI_WIRETAPPING == 1
performSpiWiretapping(spiCookie); performSpiWiretapping(spiCookie);
@ -242,7 +237,6 @@ ReturnValue_t SpiComIF::performRegularSendOperation(SpiCookie* spiCookie, const
} else { } else {
/* We write with a blocking half-duplex transfer here */ /* We write with a blocking half-duplex transfer here */
if (write(fileDescriptor, sendData, sendLen) != static_cast<ssize_t>(sendLen)) { if (write(fileDescriptor, sendData, sendLen) != static_cast<ssize_t>(sendLen)) {
spiCookie->setTransferSize(0);
#if FSFW_VERBOSE_LEVEL >= 1 #if FSFW_VERBOSE_LEVEL >= 1
#if FSFW_CPP_OSTREAM_ENABLED == 1 #if FSFW_CPP_OSTREAM_ENABLED == 1
sif::warning << "SpiComIF::sendMessage: Half-Duplex write operation failed!" << std::endl; sif::warning << "SpiComIF::sendMessage: Half-Duplex write operation failed!" << std::endl;
@ -250,14 +244,14 @@ ReturnValue_t SpiComIF::performRegularSendOperation(SpiCookie* spiCookie, const
sif::printWarning("SpiComIF::sendMessage: Half-Duplex write operation failed!\n"); sif::printWarning("SpiComIF::sendMessage: Half-Duplex write operation failed!\n");
#endif /* FSFW_CPP_OSTREAM_ENABLED == 1 */ #endif /* FSFW_CPP_OSTREAM_ENABLED == 1 */
#endif /* FSFW_VERBOSE_LEVEL >= 1 */ #endif /* FSFW_VERBOSE_LEVEL >= 1 */
result = spi::HALF_DUPLEX_TRANSFER_FAILED; result = HALF_DUPLEX_TRANSFER_FAILED;
} }
} }
if (gpioId != gpio::NO_GPIO and not csLockManual) { if (gpioId != gpio::NO_GPIO) {
gpioComIF.pullHigh(gpioId); gpioComIF->pullHigh(gpioId);
result = csMutex->unlockMutex(); result = spiMutex->unlockMutex();
if (result != returnvalue::OK) { if (result != RETURN_OK) {
#if FSFW_CPP_OSTREAM_ENABLED == 1 #if FSFW_CPP_OSTREAM_ENABLED == 1
sif::error << "SpiComIF::sendMessage: Failed to unlock mutex" << std::endl; sif::error << "SpiComIF::sendMessage: Failed to unlock mutex" << std::endl;
#endif #endif
@ -267,7 +261,7 @@ ReturnValue_t SpiComIF::performRegularSendOperation(SpiCookie* spiCookie, const
return result; return result;
} }
ReturnValue_t SpiComIF::getSendSuccess(CookieIF* cookie) { return returnvalue::OK; } ReturnValue_t SpiComIF::getSendSuccess(CookieIF* cookie) { return HasReturnvaluesIF::RETURN_OK; }
ReturnValue_t SpiComIF::requestReceiveMessage(CookieIF* cookie, size_t requestLen) { ReturnValue_t SpiComIF::requestReceiveMessage(CookieIF* cookie, size_t requestLen) {
SpiCookie* spiCookie = dynamic_cast<SpiCookie*>(cookie); SpiCookie* spiCookie = dynamic_cast<SpiCookie*>(cookie);
@ -276,47 +270,38 @@ ReturnValue_t SpiComIF::requestReceiveMessage(CookieIF* cookie, size_t requestLe
} }
if (spiCookie->isFullDuplex()) { if (spiCookie->isFullDuplex()) {
return returnvalue::OK; return HasReturnvaluesIF::RETURN_OK;
} }
return performHalfDuplexReception(spiCookie); return performHalfDuplexReception(spiCookie);
} }
ReturnValue_t SpiComIF::performHalfDuplexReception(SpiCookie* spiCookie) { ReturnValue_t SpiComIF::performHalfDuplexReception(SpiCookie* spiCookie) {
ReturnValue_t result = returnvalue::OK; ReturnValue_t result = HasReturnvaluesIF::RETURN_OK;
std::string device = spiCookie->getSpiDevice();
int fileDescriptor = 0; int fileDescriptor = 0;
UnixFileGuard fileHelper(dev, fileDescriptor, O_RDWR, "SpiComIF::requestReceiveMessage"); UnixFileGuard fileHelper(device, &fileDescriptor, O_RDWR, "SpiComIF::requestReceiveMessage");
if (fileHelper.getOpenResult() != returnvalue::OK) { if (fileHelper.getOpenResult() != HasReturnvaluesIF::RETURN_OK) {
return spi::OPENING_FILE_FAILED; return OPENING_FILE_FAILED;
} }
uint8_t* rxBuf = nullptr; uint8_t* rxBuf = nullptr;
size_t readSize = spiCookie->getCurrentTransferSize(); size_t readSize = spiCookie->getCurrentTransferSize();
result = getReadBuffer(spiCookie->getSpiAddress(), &rxBuf); result = getReadBuffer(spiCookie->getSpiAddress(), &rxBuf);
if (result != returnvalue::OK) { if (result != HasReturnvaluesIF::RETURN_OK) {
return result; return result;
} }
bool csLockManual = spiCookie->getCsLockManual();
gpioId_t gpioId = spiCookie->getChipSelectPin(); gpioId_t gpioId = spiCookie->getChipSelectPin();
MutexIF::TimeoutType csType; if (gpioId != gpio::NO_GPIO) {
dur_millis_t csTimeout = 0; result = spiMutex->lockMutex(timeoutType, timeoutMs);
if (gpioId != gpio::NO_GPIO and not csLockManual) { if (result != RETURN_OK) {
spiCookie->getMutexParams(csType, csTimeout);
result = csMutex->lockMutex(csType, csTimeout);
if (result != returnvalue::OK) {
#if FSFW_VERBOSE_LEVEL >= 1
#if FSFW_CPP_OSTREAM_ENABLED == 1 #if FSFW_CPP_OSTREAM_ENABLED == 1
sif::error << "SpiComIF::sendMessage: Failed to lock mutex with code " sif::error << "SpiComIF::getSendSuccess: Failed to lock mutex" << std::endl;
<< "0x" << std::hex << std::setfill('0') << std::setw(4) << result << std::dec
<< std::endl;
#else
sif::printError("SpiComIF::sendMessage: Failed to lock mutex with code %d\n", result);
#endif
#endif #endif
return result; return result;
} }
gpioComIF.pullLow(gpioId); gpioComIF->pullLow(gpioId);
} }
if (read(fileDescriptor, rxBuf, readSize) != static_cast<ssize_t>(readSize)) { if (read(fileDescriptor, rxBuf, readSize) != static_cast<ssize_t>(readSize)) {
@ -327,13 +312,13 @@ ReturnValue_t SpiComIF::performHalfDuplexReception(SpiCookie* spiCookie) {
sif::printWarning("SpiComIF::sendMessage: Half-Duplex read operation failed!\n"); sif::printWarning("SpiComIF::sendMessage: Half-Duplex read operation failed!\n");
#endif /* FSFW_CPP_OSTREAM_ENABLED == 1 */ #endif /* FSFW_CPP_OSTREAM_ENABLED == 1 */
#endif /* FSFW_VERBOSE_LEVEL >= 1 */ #endif /* FSFW_VERBOSE_LEVEL >= 1 */
result = spi::HALF_DUPLEX_TRANSFER_FAILED; result = HALF_DUPLEX_TRANSFER_FAILED;
} }
if (gpioId != gpio::NO_GPIO and not csLockManual) { if (gpioId != gpio::NO_GPIO) {
gpioComIF.pullHigh(gpioId); gpioComIF->pullHigh(gpioId);
result = csMutex->unlockMutex(); result = spiMutex->unlockMutex();
if (result != returnvalue::OK) { if (result != RETURN_OK) {
#if FSFW_CPP_OSTREAM_ENABLED == 1 #if FSFW_CPP_OSTREAM_ENABLED == 1
sif::error << "SpiComIF::getSendSuccess: Failed to unlock mutex" << std::endl; sif::error << "SpiComIF::getSendSuccess: Failed to unlock mutex" << std::endl;
#endif #endif
@ -347,21 +332,29 @@ ReturnValue_t SpiComIF::performHalfDuplexReception(SpiCookie* spiCookie) {
ReturnValue_t SpiComIF::readReceivedMessage(CookieIF* cookie, uint8_t** buffer, size_t* size) { ReturnValue_t SpiComIF::readReceivedMessage(CookieIF* cookie, uint8_t** buffer, size_t* size) {
SpiCookie* spiCookie = dynamic_cast<SpiCookie*>(cookie); SpiCookie* spiCookie = dynamic_cast<SpiCookie*>(cookie);
if (spiCookie == nullptr) { if (spiCookie == nullptr) {
return returnvalue::FAILED; return HasReturnvaluesIF::RETURN_FAILED;
} }
uint8_t* rxBuf = nullptr; uint8_t* rxBuf = nullptr;
ReturnValue_t result = getReadBuffer(spiCookie->getSpiAddress(), &rxBuf); ReturnValue_t result = getReadBuffer(spiCookie->getSpiAddress(), &rxBuf);
if (result != returnvalue::OK) { if (result != HasReturnvaluesIF::RETURN_OK) {
return result; return result;
} }
*buffer = rxBuf; *buffer = rxBuf;
*size = spiCookie->getCurrentTransferSize(); *size = spiCookie->getCurrentTransferSize();
spiCookie->setTransferSize(0); spiCookie->setTransferSize(0);
return returnvalue::OK; return HasReturnvaluesIF::RETURN_OK;
} }
MutexIF* SpiComIF::getCsMutex() { return csMutex; } MutexIF* SpiComIF::getMutex(MutexIF::TimeoutType* timeoutType, uint32_t* timeoutMs) {
if (timeoutType != nullptr) {
*timeoutType = this->timeoutType;
}
if (timeoutMs != nullptr) {
*timeoutMs = this->timeoutMs;
}
return spiMutex;
}
void SpiComIF::performSpiWiretapping(SpiCookie* spiCookie) { void SpiComIF::performSpiWiretapping(SpiCookie* spiCookie) {
if (spiCookie == nullptr) { if (spiCookie == nullptr) {
@ -384,19 +377,19 @@ void SpiComIF::performSpiWiretapping(SpiCookie* spiCookie) {
ReturnValue_t SpiComIF::getReadBuffer(address_t spiAddress, uint8_t** buffer) { ReturnValue_t SpiComIF::getReadBuffer(address_t spiAddress, uint8_t** buffer) {
if (buffer == nullptr) { if (buffer == nullptr) {
return returnvalue::FAILED; return HasReturnvaluesIF::RETURN_FAILED;
} }
auto iter = spiDeviceMap.find(spiAddress); auto iter = spiDeviceMap.find(spiAddress);
if (iter == spiDeviceMap.end()) { if (iter == spiDeviceMap.end()) {
return returnvalue::FAILED; return HasReturnvaluesIF::RETURN_FAILED;
} }
*buffer = iter->second.replyBuffer.data(); *buffer = iter->second.replyBuffer.data();
return returnvalue::OK; return HasReturnvaluesIF::RETURN_OK;
} }
GpioIF& SpiComIF::getGpioInterface() { return gpioComIF; } GpioIF* SpiComIF::getGpioInterface() { return gpioComIF; }
void SpiComIF::setSpiSpeedAndMode(int spiFd, spi::SpiModes mode, uint32_t speed) { void SpiComIF::setSpiSpeedAndMode(int spiFd, spi::SpiModes mode, uint32_t speed) {
int retval = ioctl(spiFd, SPI_IOC_WR_MODE, reinterpret_cast<uint8_t*>(&mode)); int retval = ioctl(spiFd, SPI_IOC_WR_MODE, reinterpret_cast<uint8_t*>(&mode));
@ -408,27 +401,11 @@ void SpiComIF::setSpiSpeedAndMode(int spiFd, spi::SpiModes mode, uint32_t speed)
if (retval != 0) { if (retval != 0) {
utility::handleIoctlError("SpiComIF::setSpiSpeedAndMode: Setting SPI speed failed"); utility::handleIoctlError("SpiComIF::setSpiSpeedAndMode: Setting SPI speed failed");
} }
} // This updates the SPI clock default polarity. Only setting the mode does not update
// the line state, which can be an issue on mode switches because the clock line will
void SpiComIF::getSpiSpeedAndMode(int spiFd, spi::SpiModes& mode, uint32_t& speed) const { // switch the state after the chip select is pulled low
uint8_t tmpMode = 0;
int retval = ioctl(spiFd, SPI_IOC_RD_MODE, &tmpMode);
if (retval != 0) {
utility::handleIoctlError("SpiComIF::getSpiSpeedAndMode: Reading SPI mode failed");
}
mode = static_cast<spi::SpiModes>(tmpMode);
retval = ioctl(spiFd, SPI_IOC_RD_MAX_SPEED_HZ, &speed);
if (retval != 0) {
utility::handleIoctlError("SpiComIF::getSpiSpeedAndMode: Getting SPI speed failed");
}
}
const std::string& SpiComIF::getSpiDev() const { return dev; }
void SpiComIF::updateLinePolarity(int spiFd) {
clockUpdateTransfer.len = 0; clockUpdateTransfer.len = 0;
int retval = ioctl(spiFd, SPI_IOC_MESSAGE(1), &clockUpdateTransfer); retval = ioctl(spiFd, SPI_IOC_MESSAGE(1), &clockUpdateTransfer);
if (retval != 0) { if (retval != 0) {
utility::handleIoctlError("SpiComIF::setSpiSpeedAndMode: Updating SPI default clock failed"); utility::handleIoctlError("SpiComIF::setSpiSpeedAndMode: Updating SPI default clock failed");
} }

View File

@ -22,7 +22,17 @@ class SpiCookie;
*/ */
class SpiComIF : public DeviceCommunicationIF, public SystemObject { class SpiComIF : public DeviceCommunicationIF, public SystemObject {
public: public:
SpiComIF(object_id_t objectId, std::string devname, GpioIF& gpioComIF); static constexpr uint8_t spiRetvalId = CLASS_ID::HAL_SPI;
static constexpr ReturnValue_t OPENING_FILE_FAILED =
HasReturnvaluesIF::makeReturnCode(spiRetvalId, 0);
/* Full duplex (ioctl) transfer failure */
static constexpr ReturnValue_t FULL_DUPLEX_TRANSFER_FAILED =
HasReturnvaluesIF::makeReturnCode(spiRetvalId, 1);
/* Half duplex (read/write) transfer failure */
static constexpr ReturnValue_t HALF_DUPLEX_TRANSFER_FAILED =
HasReturnvaluesIF::makeReturnCode(spiRetvalId, 2);
SpiComIF(object_id_t objectId, GpioIF* gpioComIF);
ReturnValue_t initializeInterface(CookieIF* cookie) override; ReturnValue_t initializeInterface(CookieIF* cookie) override;
ReturnValue_t sendMessage(CookieIF* cookie, const uint8_t* sendData, size_t sendLen) override; ReturnValue_t sendMessage(CookieIF* cookie, const uint8_t* sendData, size_t sendLen) override;
@ -34,8 +44,7 @@ class SpiComIF : public DeviceCommunicationIF, public SystemObject {
* @brief This function returns the mutex which can be used to protect the spi bus when * @brief This function returns the mutex which can be used to protect the spi bus when
* the chip select must be driven from outside of the com if. * the chip select must be driven from outside of the com if.
*/ */
MutexIF* getCsMutex(); MutexIF* getMutex(MutexIF::TimeoutType* timeoutType = nullptr, uint32_t* timeoutMs = nullptr);
void setMutexParams(MutexIF::TimeoutType timeoutType, uint32_t timeoutMs);
/** /**
* Perform a regular send operation using Linux iotcl. This is public so it can be used * Perform a regular send operation using Linux iotcl. This is public so it can be used
@ -48,22 +57,8 @@ class SpiComIF : public DeviceCommunicationIF, public SystemObject {
ReturnValue_t performRegularSendOperation(SpiCookie* spiCookie, const uint8_t* sendData, ReturnValue_t performRegularSendOperation(SpiCookie* spiCookie, const uint8_t* sendData,
size_t sendLen); size_t sendLen);
GpioIF& getGpioInterface(); GpioIF* getGpioInterface();
void setSpiSpeedAndMode(int spiFd, spi::SpiModes mode, uint32_t speed); void setSpiSpeedAndMode(int spiFd, spi::SpiModes mode, uint32_t speed);
void getSpiSpeedAndMode(int spiFd, spi::SpiModes& mode, uint32_t& speed) const;
/**
* This updates the SPI clock default polarity. Only setting the mode does not update
* the line state, which can be an issue on mode switches because the clock line will
* switch the state after the chip select is pulled low.
*
* It is recommended to call this function after #setSpiSpeedAndMode and after locking the
* CS mutex if the SPI bus has multiple SPI devices with different speed and SPI modes attached.
* @param spiFd
*/
void updateLinePolarity(int spiFd);
const std::string& getSpiDev() const;
void performSpiWiretapping(SpiCookie* spiCookie); void performSpiWiretapping(SpiCookie* spiCookie);
ReturnValue_t getReadBuffer(address_t spiAddress, uint8_t** buffer); ReturnValue_t getReadBuffer(address_t spiAddress, uint8_t** buffer);
@ -74,13 +69,11 @@ class SpiComIF : public DeviceCommunicationIF, public SystemObject {
std::vector<uint8_t> replyBuffer; std::vector<uint8_t> replyBuffer;
}; };
GpioIF& gpioComIF; GpioIF* gpioComIF = nullptr;
std::string dev = "";
/** MutexIF* spiMutex = nullptr;
* Protects the chip select operations. Lock when GPIO is pulled low, unlock after it was MutexIF::TimeoutType timeoutType = MutexIF::TimeoutType::WAITING;
* pulled high uint32_t timeoutMs = 20;
*/
MutexIF* csMutex = nullptr;
spi_ioc_transfer clockUpdateTransfer = {}; spi_ioc_transfer clockUpdateTransfer = {};
using SpiDeviceMap = std::unordered_map<address_t, SpiInstance>; using SpiDeviceMap = std::unordered_map<address_t, SpiInstance>;

View File

@ -1,25 +1,26 @@
#include "SpiCookie.h" #include "SpiCookie.h"
SpiCookie::SpiCookie(address_t spiAddress, gpioId_t chipSelect, const size_t maxSize, SpiCookie::SpiCookie(address_t spiAddress, gpioId_t chipSelect, std::string spiDev,
const size_t maxSize, spi::SpiModes spiMode, uint32_t spiSpeed)
: SpiCookie(spi::SpiComIfModes::REGULAR, spiAddress, chipSelect, spiDev, maxSize, spiMode,
spiSpeed, nullptr, nullptr) {}
SpiCookie::SpiCookie(address_t spiAddress, std::string spiDev, const size_t maxSize,
spi::SpiModes spiMode, uint32_t spiSpeed) spi::SpiModes spiMode, uint32_t spiSpeed)
: SpiCookie(spi::SpiComIfModes::REGULAR, spiAddress, chipSelect, maxSize, spiMode, spiSpeed, : SpiCookie(spiAddress, gpio::NO_GPIO, spiDev, maxSize, spiMode, spiSpeed) {}
nullptr, nullptr) {}
SpiCookie::SpiCookie(address_t spiAddress, const size_t maxSize, spi::SpiModes spiMode, SpiCookie::SpiCookie(address_t spiAddress, gpioId_t chipSelect, std::string spiDev,
uint32_t spiSpeed)
: SpiCookie(spiAddress, gpio::NO_GPIO, maxSize, spiMode, spiSpeed) {}
SpiCookie::SpiCookie(address_t spiAddress, gpioId_t chipSelect, const size_t maxSize,
spi::SpiModes spiMode, uint32_t spiSpeed,
spi::send_callback_function_t callback, void* args)
: SpiCookie(spi::SpiComIfModes::CALLBACK, spiAddress, chipSelect, maxSize, spiMode, spiSpeed,
callback, args) {}
SpiCookie::SpiCookie(spi::SpiComIfModes comIfMode, address_t spiAddress, gpioId_t chipSelect,
const size_t maxSize, spi::SpiModes spiMode, uint32_t spiSpeed, const size_t maxSize, spi::SpiModes spiMode, uint32_t spiSpeed,
spi::send_callback_function_t callback, void* args) spi::send_callback_function_t callback, void* args)
: SpiCookie(spi::SpiComIfModes::CALLBACK, spiAddress, chipSelect, spiDev, maxSize, spiMode,
spiSpeed, callback, args) {}
SpiCookie::SpiCookie(spi::SpiComIfModes comIfMode, address_t spiAddress, gpioId_t chipSelect,
std::string spiDev, const size_t maxSize, spi::SpiModes spiMode,
uint32_t spiSpeed, spi::send_callback_function_t callback, void* args)
: spiAddress(spiAddress), : spiAddress(spiAddress),
chipSelectPin(chipSelect), chipSelectPin(chipSelect),
spiDevice(spiDev),
comIfMode(comIfMode), comIfMode(comIfMode),
maxSize(maxSize), maxSize(maxSize),
spiMode(spiMode), spiMode(spiMode),
@ -49,6 +50,8 @@ size_t SpiCookie::getMaxBufferSize() const { return maxSize; }
address_t SpiCookie::getSpiAddress() const { return spiAddress; } address_t SpiCookie::getSpiAddress() const { return spiAddress; }
std::string SpiCookie::getSpiDevice() const { return spiDevice; }
void SpiCookie::setThreeWireSpi(bool enable) { uncommonParameters.threeWireSpi = enable; } void SpiCookie::setThreeWireSpi(bool enable) { uncommonParameters.threeWireSpi = enable; }
void SpiCookie::setLsbFirst(bool enable) { uncommonParameters.lsbFirst = enable; } void SpiCookie::setLsbFirst(bool enable) { uncommonParameters.lsbFirst = enable; }
@ -104,17 +107,3 @@ void SpiCookie::getCallback(spi::send_callback_function_t* callback, void** args
*callback = this->sendCallback; *callback = this->sendCallback;
*args = this->callbackArgs; *args = this->callbackArgs;
} }
void SpiCookie::setCsLockManual(bool enable) { manualCsLock = enable; }
bool SpiCookie::getCsLockManual() const { return manualCsLock; }
void SpiCookie::getMutexParams(MutexIF::TimeoutType& csTimeoutType, dur_millis_t& csTimeout) const {
csTimeoutType = this->csTimeoutType;
csTimeout = this->csTimeout;
}
void SpiCookie::setMutexParams(MutexIF::TimeoutType csTimeoutType, dur_millis_t csTimeout) {
this->csTimeoutType = csTimeoutType;
this->csTimeout = csTimeout;
}

View File

@ -2,8 +2,6 @@
#define LINUX_SPI_SPICOOKIE_H_ #define LINUX_SPI_SPICOOKIE_H_
#include <fsfw/devicehandlers/CookieIF.h> #include <fsfw/devicehandlers/CookieIF.h>
#include <fsfw/ipc/MutexIF.h>
#include <fsfw/timemanager/clockDefinitions.h>
#include <linux/spi/spidev.h> #include <linux/spi/spidev.h>
#include "../../common/gpio/gpioDefinitions.h" #include "../../common/gpio/gpioDefinitions.h"
@ -22,8 +20,6 @@
*/ */
class SpiCookie : public CookieIF { class SpiCookie : public CookieIF {
public: public:
static constexpr dur_millis_t DEFAULT_MUTEX_TIMEOUT = 20;
/** /**
* Each SPI device will have a corresponding cookie. The cookie is used by the communication * Each SPI device will have a corresponding cookie. The cookie is used by the communication
* interface and contains device specific information like the largest expected size to be * interface and contains device specific information like the largest expected size to be
@ -33,22 +29,23 @@ class SpiCookie : public CookieIF {
* @param spiDev * @param spiDev
* @param maxSize * @param maxSize
*/ */
SpiCookie(address_t spiAddress, gpioId_t chipSelect, const size_t maxSize, spi::SpiModes spiMode, SpiCookie(address_t spiAddress, gpioId_t chipSelect, std::string spiDev, const size_t maxSize,
uint32_t spiSpeed); spi::SpiModes spiMode, uint32_t spiSpeed);
/** /**
* Like constructor above, but without a dedicated GPIO CS. Can be used for hardware * Like constructor above, but without a dedicated GPIO CS. Can be used for hardware
* slave select or if CS logic is performed with decoders. * slave select or if CS logic is performed with decoders.
*/ */
SpiCookie(address_t spiAddress, const size_t maxReplySize, spi::SpiModes spiMode, SpiCookie(address_t spiAddress, std::string spiDev, const size_t maxReplySize,
uint32_t spiSpeed); spi::SpiModes spiMode, uint32_t spiSpeed);
/** /**
* Use the callback mode of the SPI communication interface. The user can pass the callback * Use the callback mode of the SPI communication interface. The user can pass the callback
* function here or by using the setter function #setCallbackMode * function here or by using the setter function #setCallbackMode
*/ */
SpiCookie(address_t spiAddress, gpioId_t chipSelect, const size_t maxSize, spi::SpiModes spiMode, SpiCookie(address_t spiAddress, gpioId_t chipSelect, std::string spiDev, const size_t maxSize,
uint32_t spiSpeed, spi::send_callback_function_t callback, void* args); spi::SpiModes spiMode, uint32_t spiSpeed, spi::send_callback_function_t callback,
void* args);
/** /**
* Get the callback function * Get the callback function
@ -58,6 +55,7 @@ class SpiCookie : public CookieIF {
void getCallback(spi::send_callback_function_t* callback, void** args); void getCallback(spi::send_callback_function_t* callback, void** args);
address_t getSpiAddress() const; address_t getSpiAddress() const;
std::string getSpiDevice() const;
gpioId_t getChipSelectPin() const; gpioId_t getChipSelectPin() const;
size_t getMaxBufferSize() const; size_t getMaxBufferSize() const;
@ -141,42 +139,9 @@ class SpiCookie : public CookieIF {
*/ */
void activateCsDeselect(bool deselectCs, uint16_t delayUsecs); void activateCsDeselect(bool deselectCs, uint16_t delayUsecs);
void getMutexParams(MutexIF::TimeoutType& csTimeoutType, dur_millis_t& csTimeout) const;
void setMutexParams(MutexIF::TimeoutType csTimeoutType, dur_millis_t csTimeout);
void setCsLockManual(bool enable);
bool getCsLockManual() const;
spi_ioc_transfer* getTransferStructHandle(); spi_ioc_transfer* getTransferStructHandle();
private: private:
address_t spiAddress;
gpioId_t chipSelectPin;
spi::SpiComIfModes comIfMode;
// Required for regular mode
const size_t maxSize;
spi::SpiModes spiMode;
/**
* If this is set to true, the SPI ComIF will not perform any mutex locking for the
* CS mechanism. The user is responsible to locking and unlocking the mutex for the
* whole duration of the transfers.
*/
bool manualCsLock = false;
uint32_t spiSpeed;
bool halfDuplex = false;
MutexIF::TimeoutType csTimeoutType = MutexIF::TimeoutType::WAITING;
dur_millis_t csTimeout = DEFAULT_MUTEX_TIMEOUT;
// Required for callback mode
spi::send_callback_function_t sendCallback = nullptr;
void* callbackArgs = nullptr;
struct spi_ioc_transfer spiTransferStruct = {};
UncommonParameters uncommonParameters;
/** /**
* Internal constructor which initializes every field * Internal constructor which initializes every field
* @param spiAddress * @param spiAddress
@ -189,8 +154,27 @@ class SpiCookie : public CookieIF {
* @param args * @param args
*/ */
SpiCookie(spi::SpiComIfModes comIfMode, address_t spiAddress, gpioId_t chipSelect, SpiCookie(spi::SpiComIfModes comIfMode, address_t spiAddress, gpioId_t chipSelect,
const size_t maxSize, spi::SpiModes spiMode, uint32_t spiSpeed, std::string spiDev, const size_t maxSize, spi::SpiModes spiMode, uint32_t spiSpeed,
spi::send_callback_function_t callback, void* args); spi::send_callback_function_t callback, void* args);
address_t spiAddress;
gpioId_t chipSelectPin;
std::string spiDevice;
spi::SpiComIfModes comIfMode;
// Required for regular mode
const size_t maxSize;
spi::SpiModes spiMode;
uint32_t spiSpeed;
bool halfDuplex = false;
// Required for callback mode
spi::send_callback_function_t sendCallback = nullptr;
void* callbackArgs = nullptr;
struct spi_ioc_transfer spiTransferStruct = {};
UncommonParameters uncommonParameters;
}; };
#endif /* LINUX_SPI_SPICOOKIE_H_ */ #endif /* LINUX_SPI_SPICOOKIE_H_ */

View File

@ -7,7 +7,7 @@
#include "../../common/gpio/gpioDefinitions.h" #include "../../common/gpio/gpioDefinitions.h"
#include "../../common/spi/spiCommon.h" #include "../../common/spi/spiCommon.h"
#include "fsfw/returnvalues/returnvalue.h" #include "fsfw/returnvalues/HasReturnvaluesIF.h"
class SpiCookie; class SpiCookie;
class SpiComIF; class SpiComIF;

View File

@ -0,0 +1,4 @@
target_sources(${LIB_FSFW_NAME} PUBLIC
UartComIF.cpp
UartCookie.cpp
)

View File

@ -1,4 +1,4 @@
#include "SerialComIF.h" #include "UartComIF.h"
#include <errno.h> #include <errno.h>
#include <fcntl.h> #include <fcntl.h>
@ -11,18 +11,19 @@
#include "fsfw/serviceinterface.h" #include "fsfw/serviceinterface.h"
#include "fsfw_hal/linux/utility.h" #include "fsfw_hal/linux/utility.h"
SerialComIF::SerialComIF(object_id_t objectId) : SystemObject(objectId) {} UartComIF::UartComIF(object_id_t objectId) : SystemObject(objectId) {}
SerialComIF::~SerialComIF() {} UartComIF::~UartComIF() {}
ReturnValue_t SerialComIF::initializeInterface(CookieIF* cookie) { ReturnValue_t UartComIF::initializeInterface(CookieIF* cookie) {
std::string deviceFile; std::string deviceFile;
UartDeviceMapIter uartDeviceMapIter;
if (cookie == nullptr) { if (cookie == nullptr) {
return NULLPOINTER; return NULLPOINTER;
} }
SerialCookie* uartCookie = dynamic_cast<SerialCookie*>(cookie); UartCookie* uartCookie = dynamic_cast<UartCookie*>(cookie);
if (uartCookie == nullptr) { if (uartCookie == nullptr) {
#if FSFW_CPP_OSTREAM_ENABLED == 1 #if FSFW_CPP_OSTREAM_ENABLED == 1
sif::error << "UartComIF::initializeInterface: Invalid UART Cookie!" << std::endl; sif::error << "UartComIF::initializeInterface: Invalid UART Cookie!" << std::endl;
@ -32,11 +33,11 @@ ReturnValue_t SerialComIF::initializeInterface(CookieIF* cookie) {
deviceFile = uartCookie->getDeviceFile(); deviceFile = uartCookie->getDeviceFile();
auto uartDeviceMapIter = uartDeviceMap.find(deviceFile); uartDeviceMapIter = uartDeviceMap.find(deviceFile);
if (uartDeviceMapIter == uartDeviceMap.end()) { if (uartDeviceMapIter == uartDeviceMap.end()) {
int fileDescriptor = configureUartPort(uartCookie); int fileDescriptor = configureUartPort(uartCookie);
if (fileDescriptor < 0) { if (fileDescriptor < 0) {
return returnvalue::FAILED; return RETURN_FAILED;
} }
size_t maxReplyLen = uartCookie->getMaxReplyLen(); size_t maxReplyLen = uartCookie->getMaxReplyLen();
UartElements uartElements = {fileDescriptor, std::vector<uint8_t>(maxReplyLen), 0}; UartElements uartElements = {fileDescriptor, std::vector<uint8_t>(maxReplyLen), 0};
@ -46,20 +47,20 @@ ReturnValue_t SerialComIF::initializeInterface(CookieIF* cookie) {
sif::warning << "UartComIF::initializeInterface: Failed to insert device " << deviceFile sif::warning << "UartComIF::initializeInterface: Failed to insert device " << deviceFile
<< "to UART device map" << std::endl; << "to UART device map" << std::endl;
#endif #endif
return returnvalue::FAILED; return RETURN_FAILED;
} }
} else { } else {
#if FSFW_CPP_OSTREAM_ENABLED == 1 #if FSFW_CPP_OSTREAM_ENABLED == 1
sif::warning << "UartComIF::initializeInterface: UART device " << deviceFile sif::warning << "UartComIF::initializeInterface: UART device " << deviceFile
<< " already in use" << std::endl; << " already in use" << std::endl;
#endif #endif
return returnvalue::FAILED; return RETURN_FAILED;
} }
return returnvalue::OK; return RETURN_OK;
} }
int SerialComIF::configureUartPort(SerialCookie* uartCookie) { int UartComIF::configureUartPort(UartCookie* uartCookie) {
struct termios options = {}; struct termios options = {};
std::string deviceFile = uartCookie->getDeviceFile(); std::string deviceFile = uartCookie->getDeviceFile();
@ -88,11 +89,11 @@ int SerialComIF::configureUartPort(SerialCookie* uartCookie) {
return fd; return fd;
} }
serial::setParity(options, uartCookie->getParity()); setParityOptions(&options, uartCookie);
setStopBitOptions(&options, uartCookie); setStopBitOptions(&options, uartCookie);
setDatasizeOptions(&options, uartCookie); setDatasizeOptions(&options, uartCookie);
setFixedOptions(&options); setFixedOptions(&options);
serial::setMode(options, uartCookie->getUartMode()); setUartMode(&options, *uartCookie);
if (uartCookie->getInputShouldBeFlushed()) { if (uartCookie->getInputShouldBeFlushed()) {
tcflush(fd, TCIFLUSH); tcflush(fd, TCIFLUSH);
} }
@ -101,7 +102,7 @@ int SerialComIF::configureUartPort(SerialCookie* uartCookie) {
options.c_cc[VTIME] = 0; options.c_cc[VTIME] = 0;
options.c_cc[VMIN] = 0; options.c_cc[VMIN] = 0;
serial::setBaudrate(options, uartCookie->getBaudrate()); configureBaudrate(&options, uartCookie);
/* Save option settings */ /* Save option settings */
if (tcsetattr(fd, TCSANOW, &options) != 0) { if (tcsetattr(fd, TCSANOW, &options) != 0) {
@ -114,7 +115,24 @@ int SerialComIF::configureUartPort(SerialCookie* uartCookie) {
return fd; return fd;
} }
void SerialComIF::setStopBitOptions(struct termios* options, SerialCookie* uartCookie) { void UartComIF::setParityOptions(struct termios* options, UartCookie* uartCookie) {
/* Clear parity bit */
options->c_cflag &= ~PARENB;
switch (uartCookie->getParity()) {
case Parity::EVEN:
options->c_cflag |= PARENB;
options->c_cflag &= ~PARODD;
break;
case Parity::ODD:
options->c_cflag |= PARENB;
options->c_cflag |= PARODD;
break;
default:
break;
}
}
void UartComIF::setStopBitOptions(struct termios* options, UartCookie* uartCookie) {
/* Clear stop field. Sets stop bit to one bit */ /* Clear stop field. Sets stop bit to one bit */
options->c_cflag &= ~CSTOPB; options->c_cflag &= ~CSTOPB;
switch (uartCookie->getStopBits()) { switch (uartCookie->getStopBits()) {
@ -126,7 +144,7 @@ void SerialComIF::setStopBitOptions(struct termios* options, SerialCookie* uartC
} }
} }
void SerialComIF::setDatasizeOptions(struct termios* options, SerialCookie* uartCookie) { void UartComIF::setDatasizeOptions(struct termios* options, UartCookie* uartCookie) {
/* Clear size bits */ /* Clear size bits */
options->c_cflag &= ~CSIZE; options->c_cflag &= ~CSIZE;
switch (uartCookie->getBitsPerWord()) { switch (uartCookie->getBitsPerWord()) {
@ -150,7 +168,7 @@ void SerialComIF::setDatasizeOptions(struct termios* options, SerialCookie* uart
} }
} }
void SerialComIF::setFixedOptions(struct termios* options) { void UartComIF::setFixedOptions(struct termios* options) {
/* Disable RTS/CTS hardware flow control */ /* Disable RTS/CTS hardware flow control */
options->c_cflag &= ~CRTSCTS; options->c_cflag &= ~CRTSCTS;
/* Turn on READ & ignore ctrl lines (CLOCAL = 1) */ /* Turn on READ & ignore ctrl lines (CLOCAL = 1) */
@ -173,22 +191,155 @@ void SerialComIF::setFixedOptions(struct termios* options) {
options->c_oflag &= ~ONLCR; options->c_oflag &= ~ONLCR;
} }
ReturnValue_t SerialComIF::sendMessage(CookieIF* cookie, const uint8_t* sendData, size_t sendLen) { void UartComIF::configureBaudrate(struct termios* options, UartCookie* uartCookie) {
switch (uartCookie->getBaudrate()) {
case UartBaudRate::RATE_50:
cfsetispeed(options, B50);
cfsetospeed(options, B50);
break;
case UartBaudRate::RATE_75:
cfsetispeed(options, B75);
cfsetospeed(options, B75);
break;
case UartBaudRate::RATE_110:
cfsetispeed(options, B110);
cfsetospeed(options, B110);
break;
case UartBaudRate::RATE_134:
cfsetispeed(options, B134);
cfsetospeed(options, B134);
break;
case UartBaudRate::RATE_150:
cfsetispeed(options, B150);
cfsetospeed(options, B150);
break;
case UartBaudRate::RATE_200:
cfsetispeed(options, B200);
cfsetospeed(options, B200);
break;
case UartBaudRate::RATE_300:
cfsetispeed(options, B300);
cfsetospeed(options, B300);
break;
case UartBaudRate::RATE_600:
cfsetispeed(options, B600);
cfsetospeed(options, B600);
break;
case UartBaudRate::RATE_1200:
cfsetispeed(options, B1200);
cfsetospeed(options, B1200);
break;
case UartBaudRate::RATE_1800:
cfsetispeed(options, B1800);
cfsetospeed(options, B1800);
break;
case UartBaudRate::RATE_2400:
cfsetispeed(options, B2400);
cfsetospeed(options, B2400);
break;
case UartBaudRate::RATE_4800:
cfsetispeed(options, B4800);
cfsetospeed(options, B4800);
break;
case UartBaudRate::RATE_9600:
cfsetispeed(options, B9600);
cfsetospeed(options, B9600);
break;
case UartBaudRate::RATE_19200:
cfsetispeed(options, B19200);
cfsetospeed(options, B19200);
break;
case UartBaudRate::RATE_38400:
cfsetispeed(options, B38400);
cfsetospeed(options, B38400);
break;
case UartBaudRate::RATE_57600:
cfsetispeed(options, B57600);
cfsetospeed(options, B57600);
break;
case UartBaudRate::RATE_115200:
cfsetispeed(options, B115200);
cfsetospeed(options, B115200);
break;
case UartBaudRate::RATE_230400:
cfsetispeed(options, B230400);
cfsetospeed(options, B230400);
break;
#ifndef __APPLE__
case UartBaudRate::RATE_460800:
cfsetispeed(options, B460800);
cfsetospeed(options, B460800);
break;
case UartBaudRate::RATE_500000:
cfsetispeed(options, B500000);
cfsetospeed(options, B500000);
break;
case UartBaudRate::RATE_576000:
cfsetispeed(options, B576000);
cfsetospeed(options, B576000);
break;
case UartBaudRate::RATE_921600:
cfsetispeed(options, B921600);
cfsetospeed(options, B921600);
break;
case UartBaudRate::RATE_1000000:
cfsetispeed(options, B1000000);
cfsetospeed(options, B1000000);
break;
case UartBaudRate::RATE_1152000:
cfsetispeed(options, B1152000);
cfsetospeed(options, B1152000);
break;
case UartBaudRate::RATE_1500000:
cfsetispeed(options, B1500000);
cfsetospeed(options, B1500000);
break;
case UartBaudRate::RATE_2000000:
cfsetispeed(options, B2000000);
cfsetospeed(options, B2000000);
break;
case UartBaudRate::RATE_2500000:
cfsetispeed(options, B2500000);
cfsetospeed(options, B2500000);
break;
case UartBaudRate::RATE_3000000:
cfsetispeed(options, B3000000);
cfsetospeed(options, B3000000);
break;
case UartBaudRate::RATE_3500000:
cfsetispeed(options, B3500000);
cfsetospeed(options, B3500000);
break;
case UartBaudRate::RATE_4000000:
cfsetispeed(options, B4000000);
cfsetospeed(options, B4000000);
break;
#endif // ! __APPLE__
default:
#if FSFW_CPP_OSTREAM_ENABLED == 1
sif::warning << "UartComIF::configureBaudrate: Baudrate not supported" << std::endl;
#endif
break;
}
}
ReturnValue_t UartComIF::sendMessage(CookieIF* cookie, const uint8_t* sendData, size_t sendLen) {
int fd = 0; int fd = 0;
std::string deviceFile; std::string deviceFile;
UartDeviceMapIter uartDeviceMapIter;
if (sendLen == 0) { if (sendLen == 0) {
return returnvalue::OK; return RETURN_OK;
} }
if (sendData == nullptr) { if (sendData == nullptr) {
#if FSFW_CPP_OSTREAM_ENABLED == 1 #if FSFW_CPP_OSTREAM_ENABLED == 1
sif::warning << "UartComIF::sendMessage: Send data is nullptr" << std::endl; sif::warning << "UartComIF::sendMessage: Send data is nullptr" << std::endl;
#endif #endif
return returnvalue::FAILED; return RETURN_FAILED;
} }
SerialCookie* uartCookie = dynamic_cast<SerialCookie*>(cookie); UartCookie* uartCookie = dynamic_cast<UartCookie*>(cookie);
if (uartCookie == nullptr) { if (uartCookie == nullptr) {
#if FSFW_CPP_OSTREAM_ENABLED == 1 #if FSFW_CPP_OSTREAM_ENABLED == 1
sif::warning << "UartComIF::sendMessasge: Invalid UART Cookie!" << std::endl; sif::warning << "UartComIF::sendMessasge: Invalid UART Cookie!" << std::endl;
@ -197,13 +348,13 @@ ReturnValue_t SerialComIF::sendMessage(CookieIF* cookie, const uint8_t* sendData
} }
deviceFile = uartCookie->getDeviceFile(); deviceFile = uartCookie->getDeviceFile();
auto uartDeviceMapIter = uartDeviceMap.find(deviceFile); uartDeviceMapIter = uartDeviceMap.find(deviceFile);
if (uartDeviceMapIter == uartDeviceMap.end()) { if (uartDeviceMapIter == uartDeviceMap.end()) {
#if FSFW_CPP_OSTREAM_ENABLED == 1 #if FSFW_CPP_OSTREAM_ENABLED == 1
sif::debug << "UartComIF::sendMessage: Device file " << deviceFile << "not in UART map" sif::debug << "UartComIF::sendMessage: Device file " << deviceFile << "not in UART map"
<< std::endl; << std::endl;
#endif #endif
return returnvalue::FAILED; return RETURN_FAILED;
} }
fd = uartDeviceMapIter->second.fileDescriptor; fd = uartDeviceMapIter->second.fileDescriptor;
@ -213,18 +364,19 @@ ReturnValue_t SerialComIF::sendMessage(CookieIF* cookie, const uint8_t* sendData
sif::error << "UartComIF::sendMessage: Failed to send data with error code " << errno sif::error << "UartComIF::sendMessage: Failed to send data with error code " << errno
<< ": Error description: " << strerror(errno) << std::endl; << ": Error description: " << strerror(errno) << std::endl;
#endif #endif
return returnvalue::FAILED; return RETURN_FAILED;
} }
return returnvalue::OK; return RETURN_OK;
} }
ReturnValue_t SerialComIF::getSendSuccess(CookieIF* cookie) { return returnvalue::OK; } ReturnValue_t UartComIF::getSendSuccess(CookieIF* cookie) { return RETURN_OK; }
ReturnValue_t SerialComIF::requestReceiveMessage(CookieIF* cookie, size_t requestLen) { ReturnValue_t UartComIF::requestReceiveMessage(CookieIF* cookie, size_t requestLen) {
std::string deviceFile; std::string deviceFile;
UartDeviceMapIter uartDeviceMapIter;
SerialCookie* uartCookie = dynamic_cast<SerialCookie*>(cookie); UartCookie* uartCookie = dynamic_cast<UartCookie*>(cookie);
if (uartCookie == nullptr) { if (uartCookie == nullptr) {
#if FSFW_CPP_OSTREAM_ENABLED == 1 #if FSFW_CPP_OSTREAM_ENABLED == 1
sif::debug << "UartComIF::requestReceiveMessage: Invalid Uart Cookie!" << std::endl; sif::debug << "UartComIF::requestReceiveMessage: Invalid Uart Cookie!" << std::endl;
@ -234,10 +386,10 @@ ReturnValue_t SerialComIF::requestReceiveMessage(CookieIF* cookie, size_t reques
UartModes uartMode = uartCookie->getUartMode(); UartModes uartMode = uartCookie->getUartMode();
deviceFile = uartCookie->getDeviceFile(); deviceFile = uartCookie->getDeviceFile();
auto uartDeviceMapIter = uartDeviceMap.find(deviceFile); uartDeviceMapIter = uartDeviceMap.find(deviceFile);
if (uartMode == UartModes::NON_CANONICAL and requestLen == 0) { if (uartMode == UartModes::NON_CANONICAL and requestLen == 0) {
return returnvalue::OK; return RETURN_OK;
} }
if (uartDeviceMapIter == uartDeviceMap.end()) { if (uartDeviceMapIter == uartDeviceMap.end()) {
@ -245,7 +397,7 @@ ReturnValue_t SerialComIF::requestReceiveMessage(CookieIF* cookie, size_t reques
sif::debug << "UartComIF::requestReceiveMessage: Device file " << deviceFile sif::debug << "UartComIF::requestReceiveMessage: Device file " << deviceFile
<< " not in uart map" << std::endl; << " not in uart map" << std::endl;
#endif #endif
return returnvalue::FAILED; return RETURN_FAILED;
} }
if (uartMode == UartModes::CANONICAL) { if (uartMode == UartModes::CANONICAL) {
@ -253,13 +405,13 @@ ReturnValue_t SerialComIF::requestReceiveMessage(CookieIF* cookie, size_t reques
} else if (uartMode == UartModes::NON_CANONICAL) { } else if (uartMode == UartModes::NON_CANONICAL) {
return handleNoncanonicalRead(*uartCookie, uartDeviceMapIter, requestLen); return handleNoncanonicalRead(*uartCookie, uartDeviceMapIter, requestLen);
} else { } else {
return returnvalue::FAILED; return HasReturnvaluesIF::RETURN_FAILED;
} }
} }
ReturnValue_t SerialComIF::handleCanonicalRead(SerialCookie& uartCookie, ReturnValue_t UartComIF::handleCanonicalRead(UartCookie& uartCookie, UartDeviceMapIter& iter,
UartDeviceMap::iterator& iter, size_t requestLen) { size_t requestLen) {
ReturnValue_t result = returnvalue::OK; ReturnValue_t result = HasReturnvaluesIF::RETURN_OK;
uint8_t maxReadCycles = uartCookie.getReadCycles(); uint8_t maxReadCycles = uartCookie.getReadCycles();
uint8_t currentReadCycles = 0; uint8_t currentReadCycles = 0;
int bytesRead = 0; int bytesRead = 0;
@ -302,7 +454,7 @@ ReturnValue_t SerialComIF::handleCanonicalRead(SerialCookie& uartCookie,
strerror(errno)); strerror(errno));
#endif #endif
#endif #endif
return returnvalue::FAILED; return RETURN_FAILED;
} }
} else if (bytesRead > 0) { } else if (bytesRead > 0) {
@ -315,8 +467,7 @@ ReturnValue_t SerialComIF::handleCanonicalRead(SerialCookie& uartCookie,
return result; return result;
} }
ReturnValue_t SerialComIF::handleNoncanonicalRead(SerialCookie& uartCookie, ReturnValue_t UartComIF::handleNoncanonicalRead(UartCookie& uartCookie, UartDeviceMapIter& iter,
UartDeviceMap::iterator& iter,
size_t requestLen) { size_t requestLen) {
int fd = iter->second.fileDescriptor; int fd = iter->second.fileDescriptor;
auto bufferPtr = iter->second.replyBuffer.data(); auto bufferPtr = iter->second.replyBuffer.data();
@ -336,24 +487,25 @@ ReturnValue_t SerialComIF::handleNoncanonicalRead(SerialCookie& uartCookie,
} }
int bytesRead = read(fd, bufferPtr, requestLen); int bytesRead = read(fd, bufferPtr, requestLen);
if (bytesRead < 0) { if (bytesRead < 0) {
return returnvalue::FAILED; return RETURN_FAILED;
} else if (bytesRead != static_cast<int>(requestLen)) { } else if (bytesRead != static_cast<int>(requestLen)) {
if (uartCookie.isReplySizeFixed()) { if (uartCookie.isReplySizeFixed()) {
#if FSFW_CPP_OSTREAM_ENABLED == 1 #if FSFW_CPP_OSTREAM_ENABLED == 1
sif::warning << "UartComIF::requestReceiveMessage: Only read " << bytesRead << " of " sif::warning << "UartComIF::requestReceiveMessage: Only read " << bytesRead << " of "
<< requestLen << " bytes" << std::endl; << requestLen << " bytes" << std::endl;
#endif #endif
return returnvalue::FAILED; return RETURN_FAILED;
} }
} }
iter->second.replyLen = bytesRead; iter->second.replyLen = bytesRead;
return returnvalue::OK; return HasReturnvaluesIF::RETURN_OK;
} }
ReturnValue_t SerialComIF::readReceivedMessage(CookieIF* cookie, uint8_t** buffer, size_t* size) { ReturnValue_t UartComIF::readReceivedMessage(CookieIF* cookie, uint8_t** buffer, size_t* size) {
std::string deviceFile; std::string deviceFile;
UartDeviceMapIter uartDeviceMapIter;
SerialCookie* uartCookie = dynamic_cast<SerialCookie*>(cookie); UartCookie* uartCookie = dynamic_cast<UartCookie*>(cookie);
if (uartCookie == nullptr) { if (uartCookie == nullptr) {
#if FSFW_CPP_OSTREAM_ENABLED == 1 #if FSFW_CPP_OSTREAM_ENABLED == 1
sif::debug << "UartComIF::readReceivedMessage: Invalid uart cookie!" << std::endl; sif::debug << "UartComIF::readReceivedMessage: Invalid uart cookie!" << std::endl;
@ -362,13 +514,13 @@ ReturnValue_t SerialComIF::readReceivedMessage(CookieIF* cookie, uint8_t** buffe
} }
deviceFile = uartCookie->getDeviceFile(); deviceFile = uartCookie->getDeviceFile();
auto uartDeviceMapIter = uartDeviceMap.find(deviceFile); uartDeviceMapIter = uartDeviceMap.find(deviceFile);
if (uartDeviceMapIter == uartDeviceMap.end()) { if (uartDeviceMapIter == uartDeviceMap.end()) {
#if FSFW_CPP_OSTREAM_ENABLED == 1 #if FSFW_CPP_OSTREAM_ENABLED == 1
sif::debug << "UartComIF::readReceivedMessage: Device file " << deviceFile << " not in uart map" sif::debug << "UartComIF::readReceivedMessage: Device file " << deviceFile << " not in uart map"
<< std::endl; << std::endl;
#endif #endif
return returnvalue::FAILED; return RETURN_FAILED;
} }
*buffer = uartDeviceMapIter->second.replyBuffer.data(); *buffer = uartDeviceMapIter->second.replyBuffer.data();
@ -377,12 +529,13 @@ ReturnValue_t SerialComIF::readReceivedMessage(CookieIF* cookie, uint8_t** buffe
/* Length is reset to 0 to prevent reading the same data twice */ /* Length is reset to 0 to prevent reading the same data twice */
uartDeviceMapIter->second.replyLen = 0; uartDeviceMapIter->second.replyLen = 0;
return returnvalue::OK; return RETURN_OK;
} }
ReturnValue_t SerialComIF::flushUartRxBuffer(CookieIF* cookie) { ReturnValue_t UartComIF::flushUartRxBuffer(CookieIF* cookie) {
std::string deviceFile; std::string deviceFile;
SerialCookie* uartCookie = dynamic_cast<SerialCookie*>(cookie); UartDeviceMapIter uartDeviceMapIter;
UartCookie* uartCookie = dynamic_cast<UartCookie*>(cookie);
if (uartCookie == nullptr) { if (uartCookie == nullptr) {
#if FSFW_CPP_OSTREAM_ENABLED == 1 #if FSFW_CPP_OSTREAM_ENABLED == 1
sif::warning << "UartComIF::flushUartRxBuffer: Invalid uart cookie!" << std::endl; sif::warning << "UartComIF::flushUartRxBuffer: Invalid uart cookie!" << std::endl;
@ -390,18 +543,19 @@ ReturnValue_t SerialComIF::flushUartRxBuffer(CookieIF* cookie) {
return NULLPOINTER; return NULLPOINTER;
} }
deviceFile = uartCookie->getDeviceFile(); deviceFile = uartCookie->getDeviceFile();
auto uartDeviceMapIter = uartDeviceMap.find(deviceFile); uartDeviceMapIter = uartDeviceMap.find(deviceFile);
if (uartDeviceMapIter != uartDeviceMap.end()) { if (uartDeviceMapIter != uartDeviceMap.end()) {
int fd = uartDeviceMapIter->second.fileDescriptor; int fd = uartDeviceMapIter->second.fileDescriptor;
tcflush(fd, TCIFLUSH); tcflush(fd, TCIFLUSH);
return returnvalue::OK; return RETURN_OK;
} }
return returnvalue::FAILED; return RETURN_FAILED;
} }
ReturnValue_t SerialComIF::flushUartTxBuffer(CookieIF* cookie) { ReturnValue_t UartComIF::flushUartTxBuffer(CookieIF* cookie) {
std::string deviceFile; std::string deviceFile;
SerialCookie* uartCookie = dynamic_cast<SerialCookie*>(cookie); UartDeviceMapIter uartDeviceMapIter;
UartCookie* uartCookie = dynamic_cast<UartCookie*>(cookie);
if (uartCookie == nullptr) { if (uartCookie == nullptr) {
#if FSFW_CPP_OSTREAM_ENABLED == 1 #if FSFW_CPP_OSTREAM_ENABLED == 1
sif::warning << "UartComIF::flushUartTxBuffer: Invalid uart cookie!" << std::endl; sif::warning << "UartComIF::flushUartTxBuffer: Invalid uart cookie!" << std::endl;
@ -409,18 +563,19 @@ ReturnValue_t SerialComIF::flushUartTxBuffer(CookieIF* cookie) {
return NULLPOINTER; return NULLPOINTER;
} }
deviceFile = uartCookie->getDeviceFile(); deviceFile = uartCookie->getDeviceFile();
auto uartDeviceMapIter = uartDeviceMap.find(deviceFile); uartDeviceMapIter = uartDeviceMap.find(deviceFile);
if (uartDeviceMapIter != uartDeviceMap.end()) { if (uartDeviceMapIter != uartDeviceMap.end()) {
int fd = uartDeviceMapIter->second.fileDescriptor; int fd = uartDeviceMapIter->second.fileDescriptor;
tcflush(fd, TCOFLUSH); tcflush(fd, TCOFLUSH);
return returnvalue::OK; return RETURN_OK;
} }
return returnvalue::FAILED; return RETURN_FAILED;
} }
ReturnValue_t SerialComIF::flushUartTxAndRxBuf(CookieIF* cookie) { ReturnValue_t UartComIF::flushUartTxAndRxBuf(CookieIF* cookie) {
std::string deviceFile; std::string deviceFile;
SerialCookie* uartCookie = dynamic_cast<SerialCookie*>(cookie); UartDeviceMapIter uartDeviceMapIter;
UartCookie* uartCookie = dynamic_cast<UartCookie*>(cookie);
if (uartCookie == nullptr) { if (uartCookie == nullptr) {
#if FSFW_CPP_OSTREAM_ENABLED == 1 #if FSFW_CPP_OSTREAM_ENABLED == 1
sif::warning << "UartComIF::flushUartTxAndRxBuf: Invalid uart cookie!" << std::endl; sif::warning << "UartComIF::flushUartTxAndRxBuf: Invalid uart cookie!" << std::endl;
@ -428,11 +583,21 @@ ReturnValue_t SerialComIF::flushUartTxAndRxBuf(CookieIF* cookie) {
return NULLPOINTER; return NULLPOINTER;
} }
deviceFile = uartCookie->getDeviceFile(); deviceFile = uartCookie->getDeviceFile();
auto uartDeviceMapIter = uartDeviceMap.find(deviceFile); uartDeviceMapIter = uartDeviceMap.find(deviceFile);
if (uartDeviceMapIter != uartDeviceMap.end()) { if (uartDeviceMapIter != uartDeviceMap.end()) {
int fd = uartDeviceMapIter->second.fileDescriptor; int fd = uartDeviceMapIter->second.fileDescriptor;
tcflush(fd, TCIOFLUSH); tcflush(fd, TCIOFLUSH);
return returnvalue::OK; return RETURN_OK;
}
return RETURN_FAILED;
}
void UartComIF::setUartMode(struct termios* options, UartCookie& uartCookie) {
UartModes uartMode = uartCookie.getUartMode();
if (uartMode == UartModes::NON_CANONICAL) {
/* Disable canonical mode */
options->c_lflag &= ~ICANON;
} else if (uartMode == UartModes::CANONICAL) {
options->c_lflag |= ICANON;
} }
return returnvalue::FAILED;
} }

View File

@ -3,12 +3,12 @@
#include <fsfw/devicehandlers/DeviceCommunicationIF.h> #include <fsfw/devicehandlers/DeviceCommunicationIF.h>
#include <fsfw/objectmanager/SystemObject.h> #include <fsfw/objectmanager/SystemObject.h>
#include <fsfw_hal/linux/serial/SerialCookie.h>
#include <fsfw_hal/linux/serial/helper.h>
#include <unordered_map> #include <unordered_map>
#include <vector> #include <vector>
#include "UartCookie.h"
/** /**
* @brief This is the communication interface to access serial ports on linux based operating * @brief This is the communication interface to access serial ports on linux based operating
* systems. * systems.
@ -18,17 +18,20 @@
* *
* @author J. Meier * @author J. Meier
*/ */
class SerialComIF : public DeviceCommunicationIF, public SystemObject { class UartComIF : public DeviceCommunicationIF, public SystemObject {
public: public:
static constexpr uint8_t uartRetvalId = CLASS_ID::HAL_UART; static constexpr uint8_t uartRetvalId = CLASS_ID::HAL_UART;
static constexpr ReturnValue_t UART_READ_FAILURE = returnvalue::makeCode(uartRetvalId, 1); static constexpr ReturnValue_t UART_READ_FAILURE =
static constexpr ReturnValue_t UART_READ_SIZE_MISSMATCH = returnvalue::makeCode(uartRetvalId, 2); HasReturnvaluesIF::makeReturnCode(uartRetvalId, 1);
static constexpr ReturnValue_t UART_RX_BUFFER_TOO_SMALL = returnvalue::makeCode(uartRetvalId, 3); static constexpr ReturnValue_t UART_READ_SIZE_MISSMATCH =
HasReturnvaluesIF::makeReturnCode(uartRetvalId, 2);
static constexpr ReturnValue_t UART_RX_BUFFER_TOO_SMALL =
HasReturnvaluesIF::makeReturnCode(uartRetvalId, 3);
SerialComIF(object_id_t objectId); UartComIF(object_id_t objectId);
virtual ~SerialComIF(); virtual ~UartComIF();
ReturnValue_t initializeInterface(CookieIF* cookie) override; ReturnValue_t initializeInterface(CookieIF* cookie) override;
ReturnValue_t sendMessage(CookieIF* cookie, const uint8_t* sendData, size_t sendLen) override; ReturnValue_t sendMessage(CookieIF* cookie, const uint8_t* sendData, size_t sendLen) override;
@ -62,6 +65,7 @@ class SerialComIF : public DeviceCommunicationIF, public SystemObject {
}; };
using UartDeviceMap = std::unordered_map<UartDeviceFile_t, UartElements>; using UartDeviceMap = std::unordered_map<UartDeviceFile_t, UartElements>;
using UartDeviceMapIter = UartDeviceMap::iterator;
/** /**
* The uart devie map stores informations of initialized uart ports. * The uart devie map stores informations of initialized uart ports.
@ -75,9 +79,20 @@ class SerialComIF : public DeviceCommunicationIF, public SystemObject {
* uart device file, baudrate, parity, stopbits etc. * uart device file, baudrate, parity, stopbits etc.
* @return The file descriptor of the configured uart. * @return The file descriptor of the configured uart.
*/ */
int configureUartPort(SerialCookie* uartCookie); int configureUartPort(UartCookie* uartCookie);
void setStopBitOptions(struct termios* options, SerialCookie* uartCookie); /**
* @brief This function adds the parity settings to the termios options struct.
*
* @param options Pointer to termios options struct which will be modified to enable or disable
* parity checking.
* @param uartCookie Pointer to uart cookie containing the information about the desired
* parity settings.
*
*/
void setParityOptions(struct termios* options, UartCookie* uartCookie);
void setStopBitOptions(struct termios* options, UartCookie* uartCookie);
/** /**
* @brief This function sets options which are not configurable by the uartCookie. * @brief This function sets options which are not configurable by the uartCookie.
@ -87,11 +102,19 @@ class SerialComIF : public DeviceCommunicationIF, public SystemObject {
/** /**
* @brief With this function the datasize settings are added to the termios options struct. * @brief With this function the datasize settings are added to the termios options struct.
*/ */
void setDatasizeOptions(struct termios* options, SerialCookie* uartCookie); void setDatasizeOptions(struct termios* options, UartCookie* uartCookie);
ReturnValue_t handleCanonicalRead(SerialCookie& uartCookie, UartDeviceMap::iterator& iter, /**
* @brief This functions adds the baudrate specified in the uartCookie to the termios options
* struct.
*/
void configureBaudrate(struct termios* options, UartCookie* uartCookie);
void setUartMode(struct termios* options, UartCookie& uartCookie);
ReturnValue_t handleCanonicalRead(UartCookie& uartCookie, UartDeviceMapIter& iter,
size_t requestLen); size_t requestLen);
ReturnValue_t handleNoncanonicalRead(SerialCookie& uartCookie, UartDeviceMap::iterator& iter, ReturnValue_t handleNoncanonicalRead(UartCookie& uartCookie, UartDeviceMapIter& iter,
size_t requestLen); size_t requestLen);
}; };

View File

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

View File

@ -3,10 +3,50 @@
#include <fsfw/devicehandlers/CookieIF.h> #include <fsfw/devicehandlers/CookieIF.h>
#include <fsfw/objectmanager/SystemObjectIF.h> #include <fsfw/objectmanager/SystemObjectIF.h>
#include <fsfw_hal/linux/serial/helper.h>
#include <string> #include <string>
enum class Parity { NONE, EVEN, ODD };
enum class StopBits { ONE_STOP_BIT, TWO_STOP_BITS };
enum class UartModes { CANONICAL, NON_CANONICAL };
enum class BitsPerWord { BITS_5, BITS_6, BITS_7, BITS_8 };
enum class UartBaudRate {
RATE_50,
RATE_75,
RATE_110,
RATE_134,
RATE_150,
RATE_200,
RATE_300,
RATE_600,
RATE_1200,
RATE_1800,
RATE_2400,
RATE_4800,
RATE_9600,
RATE_19200,
RATE_38400,
RATE_57600,
RATE_115200,
RATE_230400,
RATE_460800,
RATE_500000,
RATE_576000,
RATE_921600,
RATE_1000000,
RATE_1152000,
RATE_1500000,
RATE_2000000,
RATE_2500000,
RATE_3000000,
RATE_3500000,
RATE_4000000
};
/** /**
* @brief Cookie for the UartComIF. There are many options available to configure the UART driver. * @brief Cookie for the UartComIF. There are many options available to configure the UART driver.
* The constructor only requests for common options like the baudrate. Other options can * The constructor only requests for common options like the baudrate. Other options can
@ -14,7 +54,7 @@
* *
* @author J. Meier * @author J. Meier
*/ */
class SerialCookie : public CookieIF { class UartCookie : public CookieIF {
public: public:
/** /**
* @brief Constructor for the uart cookie. * @brief Constructor for the uart cookie.
@ -29,10 +69,10 @@ class SerialCookie : public CookieIF {
* 8 databits (number of bits transfered with one uart frame) * 8 databits (number of bits transfered with one uart frame)
* One stop bit * One stop bit
*/ */
SerialCookie(object_id_t handlerId, std::string deviceFile, UartBaudRate baudrate, UartCookie(object_id_t handlerId, std::string deviceFile, UartBaudRate baudrate,
size_t maxReplyLen, UartModes uartMode = UartModes::NON_CANONICAL); size_t maxReplyLen, UartModes uartMode = UartModes::NON_CANONICAL);
virtual ~SerialCookie(); virtual ~UartCookie();
UartBaudRate getBaudrate() const; UartBaudRate getBaudrate() const;
size_t getMaxReplyLen() const; size_t getMaxReplyLen() const;

View File

@ -0,0 +1,3 @@
target_sources(${LIB_FSFW_NAME} PUBLIC
UioMapper.cpp
)

View File

@ -1,7 +1,6 @@
#include "UioMapper.h" #include "UioMapper.h"
#include <fcntl.h> #include <fcntl.h>
#include <sys/stat.h>
#include <unistd.h> #include <unistd.h>
#include <filesystem> #include <filesystem>
@ -14,38 +13,22 @@ const char UioMapper::UIO_PATH_PREFIX[] = "/sys/class/uio/";
const char UioMapper::MAP_SUBSTR[] = "/maps/map"; const char UioMapper::MAP_SUBSTR[] = "/maps/map";
const char UioMapper::SIZE_FILE_PATH[] = "/size"; const char UioMapper::SIZE_FILE_PATH[] = "/size";
UioMapper::UioMapper(std::string uioFile, int mapNum) : mapNum(mapNum) { UioMapper::UioMapper(std::string uioFile, int mapNum) : uioFile(uioFile), mapNum(mapNum) {}
struct stat buf;
lstat(uioFile.c_str(), &buf);
if (S_ISLNK(buf.st_mode)) {
char* res = realpath(uioFile.c_str(), nullptr);
if (res) {
this->uioFile = res;
free(res);
} else {
#if FSFW_CPP_OSTREAM_ENABLED == 1
sif::error << "Could not resolve real path of UIO file " << uioFile << std::endl;
#endif
}
} else {
this->uioFile = std::move(uioFile);
}
}
UioMapper::~UioMapper() {} UioMapper::~UioMapper() {}
ReturnValue_t UioMapper::getMappedAdress(uint32_t** address, Permissions permissions) { ReturnValue_t UioMapper::getMappedAdress(uint32_t** address, Permissions permissions) {
ReturnValue_t result = returnvalue::OK; ReturnValue_t result = HasReturnvaluesIF::RETURN_OK;
int fd = open(uioFile.c_str(), O_RDWR | O_SYNC); int fd = open(uioFile.c_str(), O_RDWR);
if (fd < 1) { if (fd < 1) {
#if FSFW_CPP_OSTREAM_ENABLED == 1 #if FSFW_CPP_OSTREAM_ENABLED == 1
sif::error << "UioMapper::getMappedAdress: Invalid UIO device file " << uioFile << std::endl; sif::error << "PtmeAxiConfig::initialize: Invalid UIO device file" << std::endl;
#endif #endif
return returnvalue::FAILED; return HasReturnvaluesIF::RETURN_FAILED;
} }
size_t size = 0; size_t size = 0;
result = getMapSize(&size); result = getMapSize(&size);
if (result != returnvalue::OK) { if (result != HasReturnvaluesIF::RETURN_OK) {
return result; return result;
} }
*address = static_cast<uint32_t*>( *address = static_cast<uint32_t*>(
@ -56,9 +39,9 @@ ReturnValue_t UioMapper::getMappedAdress(uint32_t** address, Permissions permiss
sif::error << "UioMapper::getMappedAdress: Failed to map physical address of uio device " sif::error << "UioMapper::getMappedAdress: Failed to map physical address of uio device "
<< uioFile.c_str() << " and map" << static_cast<int>(mapNum) << std::endl; << uioFile.c_str() << " and map" << static_cast<int>(mapNum) << std::endl;
#endif #endif
return returnvalue::FAILED; return HasReturnvaluesIF::RETURN_FAILED;
} }
return returnvalue::OK; return HasReturnvaluesIF::RETURN_OK;
} }
ReturnValue_t UioMapper::getMapSize(size_t* size) { ReturnValue_t UioMapper::getMapSize(size_t* size) {
@ -71,7 +54,7 @@ ReturnValue_t UioMapper::getMapSize(size_t* size) {
#if FSFW_CPP_OSTREAM_ENABLED == 1 #if FSFW_CPP_OSTREAM_ENABLED == 1
sif::error << "UioMapper::getMapSize: Failed to open file " << namestream.str() << std::endl; sif::error << "UioMapper::getMapSize: Failed to open file " << namestream.str() << std::endl;
#endif #endif
return returnvalue::FAILED; return HasReturnvaluesIF::RETURN_FAILED;
} }
char hexstring[SIZE_HEX_STRING] = ""; char hexstring[SIZE_HEX_STRING] = "";
int items = fscanf(fp, "%s", hexstring); int items = fscanf(fp, "%s", hexstring);
@ -83,7 +66,7 @@ ReturnValue_t UioMapper::getMapSize(size_t* size) {
<< namestream.str() << std::endl; << namestream.str() << std::endl;
#endif #endif
fclose(fp); fclose(fp);
return returnvalue::FAILED; return HasReturnvaluesIF::RETURN_FAILED;
} }
uint32_t sizeTmp = 0; uint32_t sizeTmp = 0;
items = sscanf(hexstring, "%x", &sizeTmp); items = sscanf(hexstring, "%x", &sizeTmp);
@ -96,8 +79,8 @@ ReturnValue_t UioMapper::getMapSize(size_t* size) {
<< "size of map" << mapNum << " to integer" << std::endl; << "size of map" << mapNum << " to integer" << std::endl;
#endif #endif
fclose(fp); fclose(fp);
return returnvalue::FAILED; return HasReturnvaluesIF::RETURN_FAILED;
} }
fclose(fp); fclose(fp);
return returnvalue::OK; return HasReturnvaluesIF::RETURN_OK;
} }

View File

@ -5,7 +5,7 @@
#include <string> #include <string>
#include "fsfw/returnvalues/returnvalue.h" #include "fsfw/returnvalues/HasReturnvaluesIF.h"
/** /**
* @brief Class to help opening uio device files and mapping the physical addresses into the user * @brief Class to help opening uio device files and mapping the physical addresses into the user

View File

@ -2,4 +2,6 @@ add_subdirectory(spi)
add_subdirectory(gpio) add_subdirectory(gpio)
add_subdirectory(devicetest) add_subdirectory(devicetest)
target_sources(${LIB_FSFW_NAME} PRIVATE dma.cpp) target_sources(${LIB_FSFW_NAME} PRIVATE
dma.cpp
)

View File

@ -0,0 +1,3 @@
target_sources(${LIB_FSFW_NAME} PRIVATE
GyroL3GD20H.cpp
)

View File

@ -84,7 +84,7 @@ ReturnValue_t GyroL3GD20H::initialize() {
spiHandle->Init.Mode = SPI_MODE_MASTER; spiHandle->Init.Mode = SPI_MODE_MASTER;
if (HAL_SPI_Init(spiHandle) != HAL_OK) { if (HAL_SPI_Init(spiHandle) != HAL_OK) {
sif::printWarning("Error initializing SPI\n"); sif::printWarning("Error initializing SPI\n");
return returnvalue::FAILED; return HasReturnvaluesIF::RETURN_FAILED;
} }
delete mspCfg; delete mspCfg;
@ -106,11 +106,11 @@ ReturnValue_t GyroL3GD20H::initialize() {
return handlePollingTransferInit(); return handlePollingTransferInit();
} }
default: { default: {
return returnvalue::FAILED; return HasReturnvaluesIF::RETURN_FAILED;
} }
} }
return returnvalue::OK; return HasReturnvaluesIF::RETURN_OK;
} }
ReturnValue_t GyroL3GD20H::performOperation() { ReturnValue_t GyroL3GD20H::performOperation() {
@ -125,10 +125,10 @@ ReturnValue_t GyroL3GD20H::performOperation() {
return handleInterruptSensorRead(); return handleInterruptSensorRead();
} }
default: { default: {
return returnvalue::FAILED; return HasReturnvaluesIF::RETURN_FAILED;
} }
} }
return returnvalue::OK; return HasReturnvaluesIF::RETURN_OK;
} }
ReturnValue_t GyroL3GD20H::handleDmaTransferInit() { ReturnValue_t GyroL3GD20H::handleDmaTransferInit() {
@ -162,10 +162,10 @@ ReturnValue_t GyroL3GD20H::handleDmaTransferInit() {
case (TransferStates::FAILURE): { case (TransferStates::FAILURE): {
sif::printWarning("Transfer failure\n"); sif::printWarning("Transfer failure\n");
transferState = TransferStates::FAILURE; transferState = TransferStates::FAILURE;
return returnvalue::FAILED; return HasReturnvaluesIF::RETURN_FAILED;
} }
default: { default: {
return returnvalue::FAILED; return HasReturnvaluesIF::RETURN_FAILED;
} }
} }
@ -194,10 +194,10 @@ ReturnValue_t GyroL3GD20H::handleDmaTransferInit() {
case (TransferStates::FAILURE): { case (TransferStates::FAILURE): {
sif::printWarning("GyroL3GD20H::initialize: Configuration transfer failure\n"); sif::printWarning("GyroL3GD20H::initialize: Configuration transfer failure\n");
transferState = TransferStates::FAILURE; transferState = TransferStates::FAILURE;
return returnvalue::FAILED; return HasReturnvaluesIF::RETURN_FAILED;
} }
default: { default: {
return returnvalue::FAILED; return HasReturnvaluesIF::RETURN_FAILED;
} }
} }
@ -228,13 +228,13 @@ ReturnValue_t GyroL3GD20H::handleDmaTransferInit() {
case (TransferStates::FAILURE): { case (TransferStates::FAILURE): {
sif::printWarning("GyroL3GD20H::initialize: Configuration transfer failure\n"); sif::printWarning("GyroL3GD20H::initialize: Configuration transfer failure\n");
transferState = TransferStates::FAILURE; transferState = TransferStates::FAILURE;
return returnvalue::FAILED; return HasReturnvaluesIF::RETURN_FAILED;
} }
default: { default: {
return returnvalue::FAILED; return HasReturnvaluesIF::RETURN_FAILED;
} }
} }
return returnvalue::OK; return HasReturnvaluesIF::RETURN_OK;
} }
ReturnValue_t GyroL3GD20H::handleDmaSensorRead() { ReturnValue_t GyroL3GD20H::handleDmaSensorRead() {
@ -259,13 +259,13 @@ ReturnValue_t GyroL3GD20H::handleDmaSensorRead() {
case (TransferStates::FAILURE): { case (TransferStates::FAILURE): {
sif::printWarning("GyroL3GD20H::handleDmaSensorRead: Sensor read failure\n"); sif::printWarning("GyroL3GD20H::handleDmaSensorRead: Sensor read failure\n");
transferState = TransferStates::FAILURE; transferState = TransferStates::FAILURE;
return returnvalue::FAILED; return HasReturnvaluesIF::RETURN_FAILED;
} }
default: { default: {
return returnvalue::FAILED; return HasReturnvaluesIF::RETURN_FAILED;
} }
} }
return returnvalue::OK; return HasReturnvaluesIF::RETURN_OK;
} }
HAL_StatusTypeDef GyroL3GD20H::performDmaTransfer(size_t sendSize) { HAL_StatusTypeDef GyroL3GD20H::performDmaTransfer(size_t sendSize) {
@ -298,14 +298,14 @@ ReturnValue_t GyroL3GD20H::handlePollingTransferInit() {
} }
case (HAL_TIMEOUT): { case (HAL_TIMEOUT): {
sif::printDebug("GyroL3GD20H::initialize: Polling transfer timeout\n"); sif::printDebug("GyroL3GD20H::initialize: Polling transfer timeout\n");
return returnvalue::FAILED; return HasReturnvaluesIF::RETURN_FAILED;
} }
case (HAL_ERROR): { case (HAL_ERROR): {
sif::printDebug("GyroL3GD20H::initialize: Polling transfer failure\n"); sif::printDebug("GyroL3GD20H::initialize: Polling transfer failure\n");
return returnvalue::FAILED; return HasReturnvaluesIF::RETURN_FAILED;
} }
default: { default: {
return returnvalue::FAILED; return HasReturnvaluesIF::RETURN_FAILED;
} }
} }
@ -323,14 +323,14 @@ ReturnValue_t GyroL3GD20H::handlePollingTransferInit() {
} }
case (HAL_TIMEOUT): { case (HAL_TIMEOUT): {
sif::printDebug("GyroL3GD20H::initialize: Polling transfer timeout\n"); sif::printDebug("GyroL3GD20H::initialize: Polling transfer timeout\n");
return returnvalue::FAILED; return HasReturnvaluesIF::RETURN_FAILED;
} }
case (HAL_ERROR): { case (HAL_ERROR): {
sif::printDebug("GyroL3GD20H::initialize: Polling transfer failure\n"); sif::printDebug("GyroL3GD20H::initialize: Polling transfer failure\n");
return returnvalue::FAILED; return HasReturnvaluesIF::RETURN_FAILED;
} }
default: { default: {
return returnvalue::FAILED; return HasReturnvaluesIF::RETURN_FAILED;
} }
} }
@ -353,17 +353,17 @@ ReturnValue_t GyroL3GD20H::handlePollingTransferInit() {
} }
case (HAL_TIMEOUT): { case (HAL_TIMEOUT): {
sif::printDebug("GyroL3GD20H::initialize: Polling transfer timeout\n"); sif::printDebug("GyroL3GD20H::initialize: Polling transfer timeout\n");
return returnvalue::FAILED; return HasReturnvaluesIF::RETURN_FAILED;
} }
case (HAL_ERROR): { case (HAL_ERROR): {
sif::printDebug("GyroL3GD20H::initialize: Polling transfer failure\n"); sif::printDebug("GyroL3GD20H::initialize: Polling transfer failure\n");
return returnvalue::FAILED; return HasReturnvaluesIF::RETURN_FAILED;
} }
default: { default: {
return returnvalue::FAILED; return HasReturnvaluesIF::RETURN_FAILED;
} }
} }
return returnvalue::OK; return HasReturnvaluesIF::RETURN_OK;
} }
ReturnValue_t GyroL3GD20H::handlePollingSensorRead() { ReturnValue_t GyroL3GD20H::handlePollingSensorRead() {
@ -380,17 +380,17 @@ ReturnValue_t GyroL3GD20H::handlePollingSensorRead() {
} }
case (HAL_TIMEOUT): { case (HAL_TIMEOUT): {
sif::printDebug("GyroL3GD20H::initialize: Polling transfer timeout\n"); sif::printDebug("GyroL3GD20H::initialize: Polling transfer timeout\n");
return returnvalue::FAILED; return HasReturnvaluesIF::RETURN_FAILED;
} }
case (HAL_ERROR): { case (HAL_ERROR): {
sif::printDebug("GyroL3GD20H::initialize: Polling transfer failure\n"); sif::printDebug("GyroL3GD20H::initialize: Polling transfer failure\n");
return returnvalue::FAILED; return HasReturnvaluesIF::RETURN_FAILED;
} }
default: { default: {
return returnvalue::FAILED; return HasReturnvaluesIF::RETURN_FAILED;
} }
} }
return returnvalue::OK; return HasReturnvaluesIF::RETURN_OK;
} }
ReturnValue_t GyroL3GD20H::handleInterruptTransferInit() { ReturnValue_t GyroL3GD20H::handleInterruptTransferInit() {
@ -416,7 +416,7 @@ ReturnValue_t GyroL3GD20H::handleInterruptTransferInit() {
case (HAL_ERROR): case (HAL_ERROR):
case (HAL_TIMEOUT): { case (HAL_TIMEOUT): {
sif::printDebug("GyroL3GD20H::initialize: Initialization failure using interrupts\n"); sif::printDebug("GyroL3GD20H::initialize: Initialization failure using interrupts\n");
return returnvalue::FAILED; return HasReturnvaluesIF::RETURN_FAILED;
} }
} }
@ -438,7 +438,7 @@ ReturnValue_t GyroL3GD20H::handleInterruptTransferInit() {
case (HAL_ERROR): case (HAL_ERROR):
case (HAL_TIMEOUT): { case (HAL_TIMEOUT): {
sif::printDebug("GyroL3GD20H::initialize: Initialization failure using interrupts\n"); sif::printDebug("GyroL3GD20H::initialize: Initialization failure using interrupts\n");
return returnvalue::FAILED; return HasReturnvaluesIF::RETURN_FAILED;
} }
} }
@ -465,10 +465,10 @@ ReturnValue_t GyroL3GD20H::handleInterruptTransferInit() {
case (HAL_ERROR): case (HAL_ERROR):
case (HAL_TIMEOUT): { case (HAL_TIMEOUT): {
sif::printDebug("GyroL3GD20H::initialize: Initialization failure using interrupts\n"); sif::printDebug("GyroL3GD20H::initialize: Initialization failure using interrupts\n");
return returnvalue::FAILED; return HasReturnvaluesIF::RETURN_FAILED;
} }
} }
return returnvalue::OK; return HasReturnvaluesIF::RETURN_OK;
} }
ReturnValue_t GyroL3GD20H::handleInterruptSensorRead() { ReturnValue_t GyroL3GD20H::handleInterruptSensorRead() {
@ -489,10 +489,10 @@ ReturnValue_t GyroL3GD20H::handleInterruptSensorRead() {
case (HAL_ERROR): case (HAL_ERROR):
case (HAL_TIMEOUT): { case (HAL_TIMEOUT): {
sif::printDebug("GyroL3GD20H::initialize: Sensor read failure using interrupts\n"); sif::printDebug("GyroL3GD20H::initialize: Sensor read failure using interrupts\n");
return returnvalue::FAILED; return HasReturnvaluesIF::RETURN_FAILED;
} }
} }
return returnvalue::OK; return HasReturnvaluesIF::RETURN_OK;
} }
void GyroL3GD20H::prepareConfigRegs(uint8_t *configRegs) { void GyroL3GD20H::prepareConfigRegs(uint8_t *configRegs) {

View File

@ -6,14 +6,10 @@
#include "../spi/mspInit.h" #include "../spi/mspInit.h"
#include "../spi/spiDefinitions.h" #include "../spi/spiDefinitions.h"
#include "fsfw/returnvalues/returnvalue.h" #include "fsfw/returnvalues/HasReturnvaluesIF.h"
#include "stm32h7xx_hal.h" #include "stm32h7xx_hal.h"
#include "stm32h7xx_hal_spi.h" #include "stm32h7xx_hal_spi.h"
#ifndef STM_USE_PERIPHERAL_TX_BUFFER_MPU_PROTECTION
#define STM_USE_PERIPHERAL_TX_BUFFER_MPU_PROTECTION 1
#endif
enum class TransferStates { IDLE, WAIT, SUCCESS, FAILURE }; enum class TransferStates { IDLE, WAIT, SUCCESS, FAILURE };
class GyroL3GD20H { class GyroL3GD20H {

View File

@ -0,0 +1,3 @@
target_sources(${LIB_FSFW_NAME} PRIVATE
gpio.cpp
)

View File

@ -0,0 +1,2 @@
target_sources(${LIB_FSFW_NAME} PRIVATE
)

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